use-multiple-gits
Version:
CLI tool to manage multiple git configurations (user.name, user.email, SSH keys) with easy switching between identities
178 lines ⢠7.93 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.addCommand = void 0;
const inquirer_1 = __importDefault(require("inquirer"));
const chalk_1 = __importDefault(require("chalk"));
const path = __importStar(require("path"));
const scriptGenerator_1 = require("../utils/scriptGenerator");
const zshrc_1 = require("../utils/zshrc");
const configStorage_1 = require("../utils/configStorage");
const fs_1 = require("../utils/fs");
const paths_1 = require("../utils/paths");
const init_1 = require("./init");
const errors_1 = require("../utils/errors");
const sshKeyGenerator_1 = require("../utils/sshKeyGenerator");
const addCommand = async (name, options) => {
try {
if (!name) {
console.log(chalk_1.default.red('Error: Configuration name is required'));
console.log(chalk_1.default.yellow('Usage: multiGit add <name>'));
process.exit(1);
}
const initialized = await (0, configStorage_1.isInitialized)();
if (!initialized) {
console.log(chalk_1.default.yellow('â ď¸ Multi-Git not initialized. Running init...\n'));
await (0, init_1.initCommand)();
}
console.log(chalk_1.default.blue(`\nđ Adding configuration: ${name}\n`));
const existingConfigs = await (0, configStorage_1.getAllConfigs)();
const existingConfig = existingConfigs.find(c => c.name === name);
if (existingConfig) {
const { overwrite } = await inquirer_1.default.prompt([
{
type: 'confirm',
name: 'overwrite',
message: `Configuration "${name}" already exists. Overwrite?`,
default: false,
},
]);
if (!overwrite) {
console.log(chalk_1.default.yellow('Cancelled.'));
return;
}
}
const questions = [
{
type: 'input',
name: 'displayName',
message: 'Display name (e.g., "Work", "Personal", "Company"):',
default: name.charAt(0).toUpperCase() + name.slice(1),
},
{
type: 'input',
name: 'userName',
message: 'Git user.name:',
validate: (input) => input.trim().length > 0 || 'User name is required',
},
{
type: 'input',
name: 'userEmail',
message: 'Git user.email:',
validate: (input) => {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(input) || 'Valid email is required';
},
},
{
type: 'input',
name: 'sshKeyName',
message: 'SSH key filename (e.g., id_ed25519_work):',
default: `id_ed25519_${name}`,
validate: (input) => {
const keyPath = path.join(paths_1.SSH_DIR, input);
if (!(0, fs_1.fileExists)(keyPath)) {
if (options?.generateSshKey) {
// Will generate key later
return true;
}
return `SSH key not found at ${keyPath}. Use --generate-ssh-key to create it automatically.`;
}
return true;
},
},
];
const answers = await inquirer_1.default.prompt(questions);
// Generate SSH key if needed
let sshKeyName = answers.sshKeyName;
const keyPath = path.join(paths_1.SSH_DIR, sshKeyName);
if (!(0, fs_1.fileExists)(keyPath) && options?.generateSshKey) {
console.log(chalk_1.default.blue(`\nđ Generating SSH key: ${sshKeyName}...\n`));
try {
await (0, sshKeyGenerator_1.generateSSHKey)({
email: answers.userEmail,
keyName: sshKeyName,
keyType: 'ed25519',
});
console.log(chalk_1.default.green(`â
SSH key generated successfully!\n`));
console.log(chalk_1.default.cyan('Public key:'));
const { getPublicKey } = require('../utils/sshKeyGenerator');
const publicKey = await getPublicKey(keyPath);
console.log(chalk_1.default.gray(publicKey));
console.log(chalk_1.default.yellow('\nâ ď¸ Add this key to your GitHub/GitLab account!\n'));
}
catch (error) {
console.error(chalk_1.default.red(`\nâ Failed to generate SSH key: ${error.message}\n`));
process.exit(1);
}
}
const config = {
name,
displayName: answers.displayName,
userName: answers.userName,
userEmail: answers.userEmail,
sshKeyName,
};
await (0, scriptGenerator_1.generateScript)(config);
await (0, configStorage_1.addConfig)(config);
const allConfigs = await (0, configStorage_1.getAllConfigs)();
await (0, zshrc_1.addAliases)(allConfigs);
console.log(chalk_1.default.green(`\nâ
Configuration "${name}" added successfully!\n`));
console.log(chalk_1.default.cyan('Next steps:'));
console.log(` 1. Reload shell: source ~/.zshrc`);
console.log(` 2. Use: use-${name}`);
console.log(` 3. Add SSH public key to GitHub/GitLab:`);
console.log(chalk_1.default.gray(` cat ~/.ssh/${answers.sshKeyName}.pub\n`));
}
catch (error) {
if (error instanceof errors_1.SSHKeyNotFoundError) {
console.error(chalk_1.default.red(`\nâ ${error.message}`));
console.log(chalk_1.default.yellow(` Please generate it first with:`));
console.log(chalk_1.default.gray(` ssh-keygen -t ed25519 -C "your.email@domain.com" -f ~/.ssh/${error.message.split(' ').pop()}\n`));
}
else if (error instanceof errors_1.FileSystemError) {
console.error(chalk_1.default.red(`\nâ ${error.message}\n`));
}
else {
console.error(chalk_1.default.red(`\nâ Error: ${error.message}\n`));
}
process.exit(1);
}
};
exports.addCommand = addCommand;
//# sourceMappingURL=add.js.map