UNPKG

9.45 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const tslib_1 = require("tslib");
4const fs = require("fs-extra");
5const os = require("os");
6const path = require("path");
7const stream = require("stream");
8const through2 = require("through2");
9const safe = require("./safe");
10tslib_1.__exportStar(require("fs-extra"), exports);
11var safe_1 = require("./safe");
12exports.statSafe = safe_1.stat;
13exports.readdirSafe = safe_1.readdir;
14async function readdirp(dir, { filter, onError, walkerOptions } = {}) {
15 return new Promise((resolve, reject) => {
16 const items = [];
17 let rs = walk(dir, walkerOptions);
18 if (filter) {
19 rs = rs.pipe(through2.obj(function (obj, enc, cb) {
20 if (!filter || filter(obj)) {
21 this.push(obj);
22 }
23 cb();
24 }));
25 }
26 rs
27 .on('error', (err) => onError ? onError(err) : reject(err))
28 .on('data', (item) => items.push(item.path))
29 .on('end', () => resolve(items));
30 });
31}
32exports.readdirp = readdirp;
33/**
34 * Compile and return a file tree structure.
35 *
36 * This function walks a directory structure recursively, building a nested
37 * object structure in memory that represents it. When finished, the root
38 * directory node is returned.
39 *
40 * @param dir The root directory from which to compile the file tree
41 */
42async function getFileTree(dir, { onError, onFileNode = n => n, onDirectoryNode = n => n, walkerOptions } = {}) {
43 const fileMap = new Map([]);
44 const getOrCreateParent = (item) => {
45 const parentPath = path.dirname(item.path);
46 const parent = fileMap.get(parentPath);
47 if (parent && parent.type === "directory" /* DIRECTORY */) {
48 return parent;
49 }
50 return onDirectoryNode({ path: parentPath, type: "directory" /* DIRECTORY */, children: [] });
51 };
52 const createFileNode = (item, parent) => {
53 const node = { path: item.path, parent };
54 return item.stats.isDirectory() ?
55 onDirectoryNode({ ...node, type: "directory" /* DIRECTORY */, children: [] }) :
56 onFileNode({ ...node, type: "file" /* FILE */ });
57 };
58 return new Promise((resolve, reject) => {
59 dir = path.resolve(dir);
60 const rs = walk(dir, walkerOptions);
61 rs
62 .on('error', err => onError ? onError(err) : reject(err))
63 .on('data', item => {
64 const parent = getOrCreateParent(item);
65 const node = createFileNode(item, parent);
66 parent.children.push(node);
67 fileMap.set(item.path, node);
68 fileMap.set(parent.path, parent);
69 })
70 .on('end', () => {
71 const root = fileMap.get(dir);
72 if (!root) {
73 return reject(new Error('No root node found after walking directory structure.'));
74 }
75 delete root.parent;
76 resolve(root);
77 });
78 });
79}
80exports.getFileTree = getFileTree;
81async function fileToString(filePath) {
82 try {
83 return await fs.readFile(filePath, { encoding: 'utf8' });
84 }
85 catch (e) {
86 if (e.code === 'ENOENT' || e.code === 'ENOTDIR') {
87 return '';
88 }
89 throw e;
90 }
91}
92exports.fileToString = fileToString;
93async function getFileChecksum(filePath) {
94 const crypto = await Promise.resolve().then(() => require('crypto'));
95 return new Promise((resolve, reject) => {
96 const hash = crypto.createHash('md5');
97 const input = fs.createReadStream(filePath);
98 input.on('error', (err) => {
99 reject(err);
100 });
101 hash.once('readable', () => {
102 const fullChecksum = hash.read().toString('hex');
103 resolve(fullChecksum);
104 });
105 input.pipe(hash);
106 });
107}
108exports.getFileChecksum = getFileChecksum;
109/**
110 * Return true and cached checksums for a file by its path.
111 *
112 * Cached checksums are stored as `.md5` files next to the original file. If
113 * the cache file is missing, the cached checksum is undefined.
114 *
115 * @param p The file path
116 * @return Promise<[true checksum, cached checksum or undefined if cache file missing]>
117 */
118async function getFileChecksums(p) {
119 return Promise.all([
120 getFileChecksum(p),
121 (async () => {
122 try {
123 const md5 = await fs.readFile(`${p}.md5`, { encoding: 'utf8' });
124 return md5.trim();
125 }
126 catch (e) {
127 if (e.code !== 'ENOENT') {
128 throw e;
129 }
130 }
131 })(),
132 ]); // TODO: https://github.com/microsoft/TypeScript/issues/33752
133}
134exports.getFileChecksums = getFileChecksums;
135/**
136 * Store a cache file containing the source file's md5 checksum hash.
137 *
138 * @param p The file path
139 * @param checksum The checksum. If excluded, the checksum is computed
140 */
141async function cacheFileChecksum(p, checksum) {
142 const md5 = await getFileChecksum(p);
143 await fs.writeFile(`${p}.md5`, md5, { encoding: 'utf8' });
144}
145exports.cacheFileChecksum = cacheFileChecksum;
146function writeStreamToFile(stream, destination) {
147 return new Promise((resolve, reject) => {
148 const dest = fs.createWriteStream(destination);
149 stream.pipe(dest);
150 dest.on('error', reject);
151 dest.on('finish', resolve);
152 });
153}
154exports.writeStreamToFile = writeStreamToFile;
155async function pathAccessible(filePath, mode) {
156 try {
157 await fs.access(filePath, mode);
158 }
159 catch (e) {
160 return false;
161 }
162 return true;
163}
164exports.pathAccessible = pathAccessible;
165async function pathExists(filePath) {
166 return pathAccessible(filePath, fs.constants.F_OK);
167}
168exports.pathExists = pathExists;
169async function pathReadable(filePath) {
170 return pathAccessible(filePath, fs.constants.R_OK);
171}
172exports.pathReadable = pathReadable;
173async function pathWritable(filePath) {
174 return pathAccessible(filePath, fs.constants.W_OK);
175}
176exports.pathWritable = pathWritable;
177async function pathExecutable(filePath) {
178 return pathAccessible(filePath, fs.constants.X_OK);
179}
180exports.pathExecutable = pathExecutable;
181async function isExecutableFile(filePath) {
182 const [stats, executable] = await Promise.all([
183 safe.stat(filePath),
184 pathExecutable(filePath),
185 ]); // TODO: https://github.com/microsoft/TypeScript/issues/33752
186 return !!stats && (stats.isFile() || stats.isSymbolicLink()) && executable;
187}
188exports.isExecutableFile = isExecutableFile;
189/**
190 * Find the base directory based on the path given and a marker file to look for.
191 */
192async function findBaseDirectory(dir, file) {
193 if (!dir || !file) {
194 return;
195 }
196 for (const d of compilePaths(dir)) {
197 const results = await safe.readdir(d);
198 if (results.includes(file)) {
199 return d;
200 }
201 }
202}
203exports.findBaseDirectory = findBaseDirectory;
204/**
205 * Generate a random file path within the computer's temporary directory.
206 *
207 * @param prefix Optionally provide a filename prefix.
208 */
209function tmpfilepath(prefix) {
210 const rn = Math.random().toString(16).substring(2, 8);
211 const p = path.resolve(os.tmpdir(), prefix ? `${prefix}-${rn}` : rn);
212 return p;
213}
214exports.tmpfilepath = tmpfilepath;
215/**
216 * Given an absolute system path, compile an array of paths working backwards
217 * one directory at a time, always ending in the root directory.
218 *
219 * For example, `'/some/dir'` => `['/some/dir', '/some', '/']`
220 *
221 * @param filePath Absolute system base path.
222 */
223function compilePaths(filePath) {
224 filePath = path.normalize(filePath);
225 if (!path.isAbsolute(filePath)) {
226 throw new Error(`${filePath} is not an absolute path`);
227 }
228 const parsed = path.parse(filePath);
229 if (filePath === parsed.root) {
230 return [filePath];
231 }
232 return filePath
233 .slice(parsed.root.length)
234 .split(path.sep)
235 .map((segment, i, array) => parsed.root + path.join(...array.slice(0, array.length - i)))
236 .concat(parsed.root);
237}
238exports.compilePaths = compilePaths;
239class Walker extends stream.Readable {
240 constructor(p, options = {}) {
241 super({ objectMode: true });
242 this.p = p;
243 this.options = options;
244 this.paths = [this.p];
245 }
246 _read() {
247 const p = this.paths.shift();
248 const { pathFilter } = this.options;
249 if (!p) {
250 this.push(null); // tslint:disable-line:no-null-keyword
251 return;
252 }
253 fs.lstat(p, (err, stats) => {
254 if (err) {
255 this.emit('error', err);
256 return;
257 }
258 const item = { path: p, stats };
259 if (stats.isDirectory()) {
260 fs.readdir(p, (err, contents) => {
261 if (err) {
262 this.emit('error', err);
263 return;
264 }
265 let paths = contents.map(file => path.join(p, file));
266 if (pathFilter) {
267 paths = paths.filter(p => pathFilter(p.substring(this.p.length + 1)));
268 }
269 this.paths.push(...paths);
270 this.push(item);
271 });
272 }
273 else {
274 this.push(item);
275 }
276 });
277 }
278}
279exports.Walker = Walker;
280function walk(p, options = {}) {
281 return new Walker(p, options);
282}
283exports.walk = walk;