This repository was archived by the owner on Feb 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
Copy pathunbox.ts
166 lines (143 loc) · 4.56 KB
/
unbox.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
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
import fse from "fs-extra";
import path from "path";
import download from "download-git-repo";
import axios from "axios";
import vcsurl from "vcsurl";
import { parse as parseURL } from "url";
import { spawnSync } from "child_process";
import inquirer from "inquirer";
import type { Question } from "inquirer";
import type { boxConfig, unboxOptions } from "typings";
import { promisify } from "util";
import ignore from "ignore";
function verifyLocalPath(localPath: string) {
const configPath = path.join(localPath, "truffle-box.json");
fse.access(configPath).catch(_e => {
throw new Error(`Truffle Box at path ${localPath} doesn't exist.`);
});
}
async function verifyVCSURL(url: string) {
// Next let's see if the expected repository exists. If it doesn't, ghdownload
// will fail spectacularly in a way we can't catch, so we have to do it ourselves.
const configURL = parseURL(
`${vcsurl(url)
.replace("github.com", "raw.githubusercontent.com")
.replace(/#.*/, "")}/master/truffle-box.json`
);
const repoUrl = `https://${configURL.host}${configURL.path}`;
try {
await axios.head(repoUrl, { maxRedirects: 50 });
} catch (error) {
if (error.response && error.response.status === 404) {
throw new Error(
`Truffle Box at URL ${url} doesn't exist. If you believe this is an error, please contact Truffle support.`
);
} else {
const prefix = `Error connecting to ${repoUrl}. Please check your internet connection and try again.`;
error.message = `${prefix}\n\n${error.message || ""}`;
throw error;
}
}
}
async function verifySourcePath(sourcePath: string) {
if (sourcePath.startsWith("/")) {
return verifyLocalPath(sourcePath);
}
return verifyVCSURL(sourcePath);
}
async function gitIgnoreFilter(sourcePath: string) {
const ignoreFilter = ignore();
try {
const gitIgnore = await fse.readFile(
path.join(sourcePath, ".gitignore"),
"utf8"
);
ignoreFilter.add(gitIgnore.split(/\r?\n/).map(p => p.replace(/\/$/, "")));
} catch (err) {}
return ignoreFilter;
}
async function fetchRepository(sourcePath: string, dir: string) {
if (sourcePath.startsWith("/")) {
const filter = await gitIgnoreFilter(sourcePath);
return fse.copy(sourcePath, dir, {
filter: file =>
sourcePath === file || !filter.ignores(path.relative(sourcePath, file))
});
}
return promisify(download)(sourcePath, dir);
}
function prepareToCopyFiles(tempDir: string, { ignore }: boxConfig) {
const needingRemoval = ignore;
// remove box config file
needingRemoval.push("truffle-box.json");
needingRemoval.push("truffle-init.json");
needingRemoval
.map((fileName: string) => path.join(tempDir, fileName))
.forEach((filePath: string) => fse.removeSync(filePath));
}
async function promptOverwrites(
contentCollisions: Array<string>,
logger = console
) {
const overwriteContents = [];
for (const file of contentCollisions) {
logger.log(`${file} already exists in this directory...`);
const overwriting: Question[] = [
{
type: "confirm",
name: "overwrite",
message: `Overwrite ${file}?`,
default: false
}
];
const { overwrite } = await inquirer.prompt(overwriting);
if (overwrite) {
fse.removeSync(file);
overwriteContents.push(file);
}
}
return overwriteContents;
}
async function copyTempIntoDestination(
tmpDir: string,
destination: string,
options: unboxOptions
) {
fse.ensureDirSync(destination);
const { force, logger } = options;
const boxContents = fse.readdirSync(tmpDir);
const destinationContents = fse.readdirSync(destination);
const newContents = boxContents.filter(
filename => !destinationContents.includes(filename)
);
const contentCollisions = boxContents.filter(filename =>
destinationContents.includes(filename)
);
let shouldCopy;
if (force) {
shouldCopy = boxContents;
} else {
const overwriteContents = await promptOverwrites(contentCollisions, logger);
shouldCopy = [...newContents, ...overwriteContents];
}
for (const file of shouldCopy) {
fse.copySync(`${tmpDir}/${file}`, `${destination}/${file}`);
}
}
function installBoxDependencies({ hooks }: boxConfig, destination: string) {
const postUnpack = hooks["post-unpack"];
if (postUnpack.length === 0) return;
spawnSync(postUnpack, {
cwd: destination,
shell: true,
stdio: ["ignore", process.stdout, process.stderr]
});
}
export = {
copyTempIntoDestination,
fetchRepository,
installBoxDependencies,
prepareToCopyFiles,
verifySourcePath,
verifyVCSURL
};