Skip to content

Commit 8d962fc

Browse files
committed
feat(cli): husky add will append command
1 parent 80a81c0 commit 8d962fc

File tree

4 files changed

+39
-37
lines changed

4 files changed

+39
-37
lines changed

src/bin.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
#!/usr/bin/env node
2-
import { add } from './commands/add'
2+
import { add } from './commands/set_add'
33
import { install } from './commands/install'
44
import { uninstall } from './commands/uninstall'
55
import fs from 'fs'
@@ -27,6 +27,7 @@ function help() {
2727
husky init
2828
husky install [dir] (default: .husky)
2929
husky uninstall
30+
husky set <file> [cmd]
3031
husky add <file> [cmd]
3132
3233
Examples

src/commands/add.ts

Lines changed: 0 additions & 34 deletions
This file was deleted.

src/commands/init.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import fs from 'fs'
22
import { PackageJson } from 'type-fest'
3-
import { add } from './add'
3+
import { set } from './set_add'
44
import { install } from './install'
55

66
const regex = /^[ ]+|\t+/m
@@ -34,5 +34,5 @@ export function init(isYarn2: boolean): void {
3434
install()
3535

3636
// Add pre-commit sample
37-
add('.husky/pre-commit', 'npm test')
37+
set('.husky/pre-commit', 'npm test')
3838
}

src/commands/set_add.ts

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import fs from 'fs'
2+
import path from 'path'
3+
4+
function data(cmd: string) {
5+
return `#!/bin/sh
6+
. "$(dirname "$0")/_/husky.sh"
7+
8+
${cmd}
9+
`
10+
}
11+
12+
function format(file: string): string {
13+
return `${path.dirname(file)}${path.sep}${path.basename(file)}`
14+
}
15+
16+
export function set(file: string, cmd: string): void {
17+
const dir = path.dirname(file)
18+
if (!fs.existsSync(dir)) {
19+
throw new Error(`can't create hook, ${dir} directory doesn't exist`)
20+
}
21+
22+
fs.writeFileSync(file, data(cmd), { mode: 0o0755 })
23+
24+
// Show "./file" instead of just "file"
25+
console.log(`husky - created ${format(file)}`)
26+
}
27+
28+
export function add(file: string, cmd: string): void {
29+
if (fs.existsSync(file)) {
30+
fs.appendFileSync(file, `${cmd}\n`)
31+
console.log(`husky - updated ${format(file)}`)
32+
} else {
33+
set(file, cmd)
34+
}
35+
}

0 commit comments

Comments
 (0)