-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmain.js
79 lines (68 loc) · 2.1 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
const fs = require('fs')
const path = require('path')
const crypto = require('crypto')
const execSync = require('child_process').execSync
// hashes a given file and returns the hex digest
const hashFile = (filepath) => {
const hashSum = crypto.createHash('md5')
const contents = fs.readFileSync(filepath, 'utf-8')
const packageBlob = JSON.parse(contents)
const dependencies = {
dependencies: packageBlob['dependencies'] || {},
devDependencies: packageBlob['devDependencies'] || {}
}
const depsJson = JSON.stringify(dependencies)
hashSum.update(Buffer.from(depsJson))
return hashSum.digest('hex')
}
const findPackageJson = () => {
let current = process.cwd()
let last = current
do {
const search = path.join(current, 'package.json')
if (fs.existsSync(search)) {
return search
}
last = current
current = path.dirname(current)
} while (current !== last)
}
// returns whether or not npm install should be executed
const watchFile = ({
hashFilename = 'packagehash.txt',
installCommand = 'npm install',
isHashOnly = false
}) => {
const packagePath = findPackageJson()
if (!packagePath) {
console.error('Cannot find package.json. Travelling up from current working directory')
}
const packageHashPath = path.join(path.dirname(packagePath), hashFilename)
const recentDigest = hashFile(packagePath)
// if the hash file doesn't exist
// or if it does and the hash is different
if (!fs.existsSync(packageHashPath) || fs.readFileSync(packageHashPath, 'utf-8') !== recentDigest) {
console.log('package.json has been modified.')
if (isHashOnly) {
console.log('Updating hash only because --hash-only is true.')
return true
}
console.log('Installing and updating hash.')
try {
execSync(
installCommand,
{
stdio: 'inherit'
}
)
fs.writeFileSync(packageHashPath, recentDigest) // write to hash to file for future use
}
catch (error) {
console.log(error)
}
return true
}
console.log('package.json has not been modified.')
return false
}
module.exports = watchFile