git-bolt
Version:
Git utilities for faster development
83 lines (71 loc) • 2.08 kB
JavaScript
import dotenv from 'dotenv';
import fs from 'fs';
import path, { dirname } from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// Load environment variables
dotenv.config();
/**
* Get GitHub token from environment or config file
* @returns {string|null} GitHub token
*/
function getGitHubToken() {
// Check environment variable first
if (process.env.GITHUB_TOKEN) {
return process.env.GITHUB_TOKEN;
}
// Check for .env file
try {
const envPath = path.join(process.cwd(), '.env');
if (fs.existsSync(envPath)) {
const envContent = fs.readFileSync(envPath, 'utf8');
const match = envContent.match(/GITHUB_TOKEN=([^\n]+)/);
if (match && match[1]) {
return match[1];
}
}
} catch (error) {
// Silently fail and continue to other methods
}
// Check for git-bolt config
try {
const configPath = path.join(process.cwd(), '.git-bolt');
if (fs.existsSync(configPath)) {
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
if (config.token) {
return config.token;
}
}
} catch (error) {
// Silently fail
}
return null;
}
/**
* Save GitHub token for future use
* @param {string} token GitHub token to save
*/
function saveGitHubToken(token) {
if (!token) return;
// Save to .env file
try {
const envPath = path.join(process.cwd(), '.env');
let content = '';
if (fs.existsSync(envPath)) {
content = fs.readFileSync(envPath, 'utf8');
// Replace existing token or add new one
if (content.includes('GITHUB_TOKEN=')) {
content = content.replace(/GITHUB_TOKEN=([^\n]+)/, `GITHUB_TOKEN=${token}`);
} else {
content += `\nGITHUB_TOKEN=${token}\n`;
}
} else {
content = `GITHUB_TOKEN=${token}\n`;
}
fs.writeFileSync(envPath, content, 'utf8');
} catch (error) {
console.error('Error saving token:', error.message);
}
}
export { getGitHubToken, saveGitHubToken };