Skip to content

Commit a866df9

Browse files
committed
Implement initial run-if-changed with commander and cosmiconfig
1 parent 70effb9 commit a866df9

File tree

3 files changed

+70
-1
lines changed

3 files changed

+70
-1
lines changed

bin/git-run-if-changed.sh

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
#!/usr/bin/env bash
2+
3+
if [ $# -lt 2 ]; then
4+
>&2 echo "usage: git-run-if-changed.sh <file> <commands...>"
5+
exit 1
6+
fi
7+
8+
9+
git diff-tree --name-only --no-commit-id HEAD@{1} HEAD | grep --quiet "$1" 2> /dev/null
10+
11+
if [ $? -eq 0 ]; then
12+
echo "$1 changed:"
13+
shift
14+
while (($#)); do
15+
echo "Running '$1'..."
16+
eval "$1"
17+
shift
18+
done
19+
20+
fi

index.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#!/usr/bin/env node
2+
3+
4+
const cli = require('commander');
5+
const util = require('util');
6+
const process = require('process');
7+
const cosmiconfig = require('cosmiconfig');
8+
const exec = util.promisify(require('child_process').exec);
9+
const pkg = require('./package.json');
10+
11+
cli
12+
.version(pkg.version, '-v, --version')
13+
.parse(process.argv);
14+
15+
async function runCommandsIfFileChanged(fileToCheck, commandsList) {
16+
const commandsString = commandsList.map(x => `"${x}"`).join(' ');
17+
const command = `./bin/git-run-if-changed.sh "${fileToCheck}" ${commandsString}`;
18+
const response = await exec(command);
19+
const { stdout, stderr } = response;
20+
if (stdout) {
21+
console.log(stdout);
22+
}
23+
if (response instanceof Error) {
24+
console.error('There was an error executing script:');
25+
}
26+
if (stderr) {
27+
console.error(stderr);
28+
}
29+
}
30+
31+
const configResult = cosmiconfig(pkg.name).searchSync();
32+
33+
if (!configResult || configResult.isEmpty) {
34+
process.exit(0);
35+
}
36+
37+
const { config } = configResult;
38+
39+
Object.entries(config).forEach(([file, commands]) => {
40+
if (commands.length === 0) {
41+
return;
42+
}
43+
44+
runCommandsIfFileChanged(file, commands);
45+
});

package.json

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,9 @@
66
"main": "index.js",
77
"repository": "https://github.com/hkdobrev/run-if-changed",
88
"author": "Haralan Dobrev <hkdobrev@gmail.com>",
9-
"license": "MIT"
9+
"license": "MIT",
10+
"dependencies": {
11+
"commander": "^2.19.0",
12+
"cosmiconfig": "^5.0.7"
13+
}
1014
}

0 commit comments

Comments
 (0)