browser-plugin-creator
Version:
A modern scaffolding tool for creating browser extensions with ease
113 lines (112 loc) • 3.76 kB
JavaScript
import path from 'path';
import os from 'os';
import fs from 'fs-extra';
export class ConfigManager {
constructor() {
this.configPath = path.join(os.homedir(), '.browser-plugin-creator', 'config.json');
this.config = this.loadConfig();
}
loadConfig() {
try {
if (fs.existsSync(this.configPath)) {
return fs.readJsonSync(this.configPath);
}
}
catch (error) {
console.warn('无法加载配置文件,使用默认配置');
}
// 默认配置
return {
templatesPath: path.join(__dirname, '../../templates'),
defaultAuthor: this.getDefaultAuthor(),
defaultEmail: this.getDefaultEmail(),
packageManager: 'npm',
gitInit: true,
typescript: true,
autoInstall: true,
browserSupport: ['chrome', 'firefox', 'edge', 'safari'],
theme: 'light',
language: 'en'
};
}
getDefaultAuthor() {
try {
const { execSync } = require('child_process');
return execSync('git config --global user.name', { encoding: 'utf8' }).trim();
}
catch {
return os.userInfo().username;
}
}
getDefaultEmail() {
try {
const { execSync } = require('child_process');
return execSync('git config --global user.email', { encoding: 'utf8' }).trim();
}
catch {
return '';
}
}
getConfig() {
return { ...this.config };
}
async setConfig(key, value) {
this.config[key] = value;
await this.saveConfig();
}
async updateConfig(updates) {
this.config = { ...this.config, ...updates };
await this.saveConfig();
}
async saveConfig() {
try {
await fs.ensureDir(path.dirname(this.configPath));
await fs.writeJson(this.configPath, this.config, { spaces: 2 });
}
catch (error) {
console.error('保存配置文件失败:', error);
}
}
async resetConfig() {
this.config = {
templatesPath: path.join(__dirname, '../../templates'),
defaultAuthor: this.getDefaultAuthor(),
defaultEmail: this.getDefaultEmail(),
packageManager: 'npm',
gitInit: true,
typescript: true,
autoInstall: true,
browserSupport: ['chrome', 'firefox', 'edge', 'safari'],
theme: 'light',
language: 'en'
};
await this.saveConfig();
}
getTemplatePath(templateName) {
return path.join(this.config.templatesPath || path.join(__dirname, '../../templates'), templateName);
}
async listTemplates() {
try {
const templatesDir = this.config.templatesPath || path.join(__dirname, '../../templates');
if (await fs.pathExists(templatesDir)) {
const items = await fs.readdir(templatesDir);
const templates = [];
for (const item of items) {
const itemPath = path.join(templatesDir, item);
const stat = await fs.stat(itemPath);
if (stat.isDirectory()) {
const manifestPath = path.join(itemPath, 'manifest.json');
if (await fs.pathExists(manifestPath)) {
templates.push(item);
}
}
}
return templates.sort();
}
}
catch (error) {
console.error('读取模板列表失败:', error);
}
return [];
}
}