-
Notifications
You must be signed in to change notification settings - Fork 0
/
validator.js
94 lines (85 loc) · 2.24 KB
/
validator.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import fs from 'fs'
import path from 'path'
import _ from 'lodash'
import argv from 'minimist'
import md5F from 'md5-file'
import Promise from 'bluebird'
Promise.promisifyAll(fs)
const md5File = Promise.promisify(md5F)
const arg = argv(process.argv.slice(2))
const manifest = arg.manifest || arg.m
const format = arg.format || arg.f
const patchDir = arg.path || arg.p
const validate = arg.validate || arg.v
// stop right here if no manifest file was supplied
if (!manifest) {
throw new Error('Specify path to manifest via --manifest|m option')
}
fs.readFileAsync(manifest, 'utf-8')
.then(data => {
return JSON.parse(data)
})
.then(json => {
return (format) ? formatJSON(json, 'filemd5') : json
})
.then(json => {
return (format) ? saveJSON(manifest, json) : json
})
.then(json => {
return (validate) ? validateAllFiles(json) : json
})
.catch(err => {
throw err
})
/**
* Filter non-unique entries and sort array
* @param {Array} json manifest data
* @param {String} key key to perform unique sort on
* @return {Array}
*/
function formatJSON (json, key) {
if (json.constructor !== Array) {
throw new Error('Manifest file should contain an Array of Objects')
} else {
return _.chain(json).unique(key).sort((a, b) => {
return (a.start - b.start) || (a.end - b.end)
})
}
}
/**
* Save JSON to file
* @param {String} file path to file
* @param {Array} json manifest data
* @param {Number} spaces number of spaces to indent
* @return {Promise}
*/
function saveJSON (file, json, spaces = 2) {
let str = JSON.stringify(json, null, spaces)
return fs.writeFile(file, str)
}
/**
* Validate file against given hash
* @param {String} fileName file name
* @param {String} hash md5 hash
* @return {Promise}
*/
function validateFile (fileName, hash) {
let file = path.join(patchDir, fileName)
return md5File(file)
.then(fileHash => {
return fileHash === hash
})
.catch(err => {
throw err
})
}
/**
* Validate all files agains given hash
* @param {Array} json manifest data
* @return {Promise}
*/
function validateAllFiles (json) {
return Promise.all(json.forEach(patch => {
return validateFile(patch.file_name, patch.filemd5)
}))
}