-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
executable file
·211 lines (179 loc) · 5.96 KB
/
index.js
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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
#!/usr/bin/env node
const { execSync } = require("child_process");
const { confirm } = require("@inquirer/prompts");
const select = require("@inquirer/select").default;
const { Command, Option } = require("commander");
const ora = require("ora");
const path = require("path");
const fs = require("fs");
const os = require("os");
const crypto = require("crypto");
const https = require("https");
const CLI_VERSION = require("./package.json").version;
const { downloadFile, unzip } = require("./lib/download.js");
const program = new Command();
program
.name("Create Radfish App")
.description("The CLI to bootstrap a radfish app!")
.version(CLI_VERSION);
let examples = [];
(async function run(argsv) {
examples = await getExamples();
await bootstrap(program);
program.parse(argsv);
})(process.argv);
function getExamples() {
return new Promise((resolve, reject) => {
const requestUrl = new URL(
"https://api.github.com/repos/nmfs-radfish/boilerplate/contents/examples",
);
const options = {
hostname: requestUrl.hostname,
path: requestUrl.pathname,
headers: {
Accept: "application/vnd.github+json",
"User-Agent": `radfish-cli/${CLI_VERSION}`,
"X-GitHub-Api-Version": "2022-11-28",
},
};
https.get(options, function (response) {
if (response.statusCode >= 400) {
return reject(new Error("Failed to download file"));
}
if (response.statusCode === 200) {
let data = "";
response.on("data", (chunk) => {
data += chunk;
});
response.on("end", () => {
const examples = JSON.parse(data);
resolve(examples.filter((example) => example.type === "dir"));
});
}
});
});
}
async function bootstrap(program) {
program
.addOption(new Option("--template [name]", "specified template").choices(["react-javascript"]))
.addOption(
new Option("--example [name]", "specified example")
.choices(examples.map((example) => example.name))
.conflicts("template"),
);
// program options
program.argument("<projectDirectoryPath>");
program.action((projectDirectoryPath) => {
scaffoldRadFishApp(projectDirectoryPath);
});
}
async function selectExample(examples) {
return await select({
message: "Select an example",
choices: examples.map((example) => ({ name: example.name, value: example.name })),
});
}
async function scaffoldRadFishApp(projectDirectoryPath) {
const targetDirectory = `${projectDirectoryPath.trim().replace(/\s+/g, "-")}`; // replace whitespaces in the filepath
const targetDirectoryPath = path.resolve(process.cwd(), targetDirectory);
async function confirmConfiguration() {
return await confirm({
message: `You are about to scaffold an application in the following project directory: ${targetDirectoryPath}
Okay to proceed?`,
});
}
async function bootstrapApp(options) {
const spinner = ora("Setting up application").start();
const ref = "latest";
try {
const temporaryDirectoryPath = await new Promise((resolve, reject) => {
fs.mkdtemp(path.join(os.tmpdir(), "radfish-"), (err, folder) => {
if (err) {
return reject(err);
}
resolve(folder);
});
});
const uuid = crypto.createHash("sha256").update(crypto.randomBytes(255)).digest("hex");
const tarballFileName = `${uuid}.tar.gz`;
const tarballFilePath = path.join(temporaryDirectoryPath, tarballFileName);
await new Promise((resolve, reject) => {
downloadFile(
`https://api.github.com/repos/NMFS-RADFish/boilerplate/tarball/${encodeURIComponent(
ref,
)}`,
tarballFilePath,
(err, res) => {
if (err) {
return reject(err);
}
resolve(res);
},
);
});
await new Promise((resolve, reject) => {
fs.mkdir(targetDirectoryPath, (err) => {
if (err) {
return reject(err);
}
resolve();
});
});
let sourceType = "templates";
let sourceProjectDirectory = "react-javascript";
if (options.template) {
sourceType = "templates";
sourceProjectDirectory = options.template;
} else if (options.example) {
sourceType = "examples";
sourceProjectDirectory = options.example;
}
const sourcePath = path.join(sourceType, sourceProjectDirectory);
await new Promise((resolve, reject) => {
unzip(
tarballFilePath,
{ outputDirectoryPath: targetDirectoryPath, sourcePath: sourcePath },
(err, res) => {
if (err) {
return reject(err);
}
resolve(res);
},
);
});
console.log(`\nProject successfully created.`);
} catch (error) {
console.error(error);
console.error(`Error cloning repository: ${error.message}`);
process.exit(1);
}
// Run an npm script (replace 'your-script-name' with the actual npm script name)
try {
execSync("npm install", { stdio: "inherit", cwd: targetDirectoryPath });
console.log(`node modules successfully installed.`);
} catch (error) {
console.error(`Error running npm script: ${error.message}`);
process.exit(1);
}
try {
console.log(`Success! Created ${targetDirectory} at ${targetDirectoryPath}`);
console.log(`\nWe suggest that you begin by typing:`);
console.log(` cd ${targetDirectory}`);
console.log(` npm start\n`);
process.exit(0);
} catch (error) {
console.error(`Error running npm script: ${error.message}`);
process.exit(1);
}
spinner.stop();
}
const options = program.opts();
let example = options.example;
if (example === true) {
example = await selectExample(examples);
}
const confirmation = await confirmConfiguration();
if (confirmation) {
await bootstrapApp({ ...options, example });
}
}