get-file-details.ts
1.83 KB
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
/*
Copyright 2021 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
import glob from 'glob';
import upath from 'upath';
import {errors} from './errors';
import {getFileSize} from './get-file-size';
import {getFileHash} from './get-file-hash';
import {GlobPartial} from '../types';
interface FileDetails {
file: string;
hash: string;
size: number;
}
export function getFileDetails({
globDirectory,
globFollow,
globIgnores,
globPattern,
globStrict,
}: Omit<GlobPartial, 'globDirectory' | 'globPatterns' | 'templatedURLs'> & {
// This will only be called when globDirectory is not undefined.
globDirectory: string;
globPattern: string;
}): {
globbedFileDetails: Array<FileDetails>;
warning: string;
} {
let globbedFiles: Array<string>;
let warning = '';
try {
globbedFiles = glob.sync(globPattern, {
cwd: globDirectory,
follow: globFollow,
ignore: globIgnores,
strict: globStrict,
});
} catch (err) {
throw new Error(
errors['unable-to-glob-files'] +
` '${err instanceof Error && err.message ? err.message : ''}'`,
);
}
if (globbedFiles.length === 0) {
warning =
errors['useless-glob-pattern'] +
' ' +
JSON.stringify({globDirectory, globPattern, globIgnores}, null, 2);
}
const globbedFileDetails: Array<FileDetails> = [];
for (const file of globbedFiles) {
const fullPath = upath.join(globDirectory, file);
const fileSize = getFileSize(fullPath);
if (fileSize !== null) {
const fileHash = getFileHash(fullPath);
globbedFileDetails.push({
file: `${upath.relative(globDirectory, fullPath)}`,
hash: fileHash,
size: fileSize,
});
}
}
return {globbedFileDetails, warning};
}