git-bolt
Version:
Git utilities for faster development
47 lines (42 loc) • 1.66 kB
JavaScript
import chalk from 'chalk';
import fs from 'fs';
import git from 'isomorphic-git';
async function branchCommand(name, options) {
try {
if (options.list || (!name && !options.create)) {
// List all branches
const branches = await git.listBranches({ fs, dir: '.' });
const currentBranch = await git.currentBranch({ fs, dir: '.' });
console.log(chalk.blue('Branches:'));
for (const branch of branches) {
if (branch === currentBranch) {
console.log(chalk.green(`* ${branch} (current)`));
} else {
console.log(` ${branch}`);
}
}
} else if (options.create) {
// Create a new branch
if (!name) {
console.error(chalk.red('Error: Branch name is required for creation'));
console.log('Use: npx git-bolt branch -c <branch-name>');
process.exit(1);
}
await git.branch({ fs, dir: '.', ref: name });
console.log(chalk.green(`Created branch: ${name}`));
} else if (name) {
// Checkout a branch
await git.checkout({ fs, dir: '.', ref: name });
console.log(chalk.green(`Switched to branch: ${name}`));
}
} catch (error) {
console.error(chalk.red(`Error during branch operation:`), error.message);
if (error.message.includes('already exists')) {
console.error(chalk.yellow(`Branch '${name}' already exists. To switch to it, don't use the -c option.`));
} else if (error.message.includes('does not exist')) {
console.error(chalk.yellow(`Branch '${name}' does not exist. Create it first with -c option.`));
}
process.exit(1);
}
}
export { branchCommand };