-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathutils.ts
44 lines (42 loc) · 1.06 KB
/
utils.ts
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
/**
* @ignore
*/
import { createHash } from 'crypto'
import { constants, createReadStream } from 'fs'
import { access } from 'fs/promises'
import { pipeline } from 'stream/promises'
/** @internal */
export function exists(file: string) {
return access(file, constants.F_OK).then(() => true, () => false)
}
/**
* Validate the sha1 value of the file
* @internal
*/
export async function validateSha1(target: string, hash?: string, strict = false) {
if (await access(target).then(() => false, () => true)) { return false }
if (!hash) { return !strict }
const sha1 = await checksum(target, 'sha1')
return sha1 === hash
}
/**
* Return the sha1 of a file
* @internal
*/
export async function checksum(target: string, algorithm: string) {
const hash = createHash(algorithm).setEncoding('hex')
try {
await pipeline(createReadStream(target), hash)
} catch (e) {
if ((e as any).code === 'ENOENT') {
return undefined
}
}
return hash.read()
}
/**
* @internal
*/
export function isNotNull<T>(v: T | undefined): v is T {
return v !== undefined
}