|
| 1 | +const cac = require('cac') |
| 2 | +const path = require('path') |
| 3 | +const fs = require('fs') |
| 4 | +const spawn = require('cross-spawn') |
| 5 | +const parseArgs = require('../utils/parseArgs') |
| 6 | +const logger = require('../utils/logger') |
| 7 | + |
| 8 | +module.exports = class Core { |
| 9 | + constructor() { |
| 10 | + this.cwd = process.cwd() |
| 11 | + this.rawArgs = process.argv |
| 12 | + this.args = parseArgs(this.rawArgs.slice(2)) |
| 13 | + |
| 14 | + this.isGitProject() |
| 15 | + |
| 16 | + this.initCli() |
| 17 | + } |
| 18 | + |
| 19 | + initCli() { |
| 20 | + const cli = (this.cli = cac()) |
| 21 | + this.command = cli |
| 22 | + .command('[...branches]') |
| 23 | + .usage('[option]') |
| 24 | + .action(branches => { |
| 25 | + this.deleteBranch(branches) |
| 26 | + }) |
| 27 | + |
| 28 | + cli.version(require('../package.json').version).help() |
| 29 | + |
| 30 | + this.cli.parse(this.rawArgs, { run: false }) |
| 31 | + } |
| 32 | + |
| 33 | + isGitProject() { |
| 34 | + if (!fs.existsSync(path.join(this.cwd, '.git'))) { |
| 35 | + logger.error('Current working directory is not a git project!') |
| 36 | + process.exit(1) |
| 37 | + } |
| 38 | + return true |
| 39 | + } |
| 40 | + |
| 41 | + getBranch() { |
| 42 | + const { stdout } = spawn.sync('git', ['branch']) |
| 43 | + const branch = stdout |
| 44 | + .toString() |
| 45 | + .trimRight() |
| 46 | + .split('\n') |
| 47 | + .map(b => { |
| 48 | + if (!b.includes('*')) { |
| 49 | + return b.trim() |
| 50 | + } |
| 51 | + }) |
| 52 | + .filter(Boolean) |
| 53 | + |
| 54 | + return branch |
| 55 | + } |
| 56 | + |
| 57 | + deleteBranch(branches) { |
| 58 | + const match = require('multimatch') |
| 59 | + const matched = match(this.getBranch(), branches) |
| 60 | + |
| 61 | + matched.forEach(branch => { |
| 62 | + const ps = spawn.sync('git', ['branch', branch, '-D']) |
| 63 | + if (ps.status === 0) { |
| 64 | + logger.success('Deleted branch', `\`${branch}\``) |
| 65 | + } |
| 66 | + }) |
| 67 | + } |
| 68 | + |
| 69 | + run() { |
| 70 | + this.cli.runMatchedCommand() |
| 71 | + } |
| 72 | +} |
0 commit comments