UNPKG

1.54 kBPlain TextView Raw
1import * as os from "os";
2import * as crypto from "crypto";
3import * as fse from "fs-extra";
4
5const originalCwd = process.cwd();
6const createdDirectories: string[] = [];
7
8process.on("exit", () => {
9 // In case something went wrong and some temp
10 // directories are still on the disk.
11 createdDirectories.forEach(path => {
12 fse.removeSync(path);
13 });
14});
15
16const setCleanTestCwd = () => {
17 const random = crypto.randomBytes(16).toString("hex");
18 const path = `${os.tmpdir()}/fs-jetpack-test-${random}`;
19 fse.mkdirSync(path);
20 createdDirectories.push(path);
21 process.chdir(path);
22};
23
24const switchBackToCorrectCwd = () => {
25 const path = createdDirectories.pop();
26 process.chdir(originalCwd);
27 try {
28 fse.removeSync(path);
29 } catch (err) {
30 // On Windows platform sometimes removal of the directory leads to error:
31 // Error: ENOTEMPTY: directory not empty, rmdir
32 // Let's retry the attempt.
33 fse.removeSync(path);
34 }
35};
36
37const parseMode = (modeAsNumber: number) => {
38 const mode = modeAsNumber.toString(8);
39 return mode.substring(mode.length - 3);
40};
41
42// Converts paths to windows or unix formats depending on platform running.
43function osSep(path: string): string;
44function osSep(path: string[]): string[];
45function osSep(path: any): any {
46 if (Array.isArray(path)) {
47 return path.map(osSep);
48 }
49
50 if (process.platform === "win32") {
51 return path.replace(/\//g, "\\");
52 }
53 return path.replace(/\\/g, "/");
54}
55
56export default {
57 setCleanTestCwd,
58 switchBackToCorrectCwd,
59 parseMode,
60 osSep
61};