-
Notifications
You must be signed in to change notification settings - Fork 28
/
index.mjs
executable file
·183 lines (171 loc) · 5.4 KB
/
index.mjs
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
#!/usr/bin/env node
import { promises as fs } from "fs";
import { git } from "./git.mjs";
import { finished, logo, example } from "./messages.mjs";
import path from "path";
import { program } from "commander";
import { Prompts } from "./prompts.mjs";
import pkg from "./package.json" assert { type: "json" };
import { fileURLToPath } from "url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const version = pkg.version;
const tmplDir = __dirname + "/templates/";
// Colors
const { g, gr, r, y, heading } = await import("./theme.mjs");
const chk = g("✔");
async function performGitTasks(collectedData) {
console.info(heading("Performing git tasks"));
let newRepo = "";
if (collectedData.repo !== path.basename(process.cwd())) {
newRepo = collectedData.repo;
}
if (collectedData.needsGitInit) {
const result = await git(`init ${newRepo}`);
if (newRepo) {
process.chdir(`${process.cwd()}/${newRepo}`);
}
console.info(g(` ${chk} ${result.trim()}`));
}
await git.switchBranch(collectedData.mainBranch);
console.info(g(` ${chk} switched to branch ${collectedData.mainBranch}`));
}
function populateTemplate(rawData, collectedData, file) {
// find all {{\w}} and replace them form collectedData
const replaceSet = (rawData.match(/{{\w+}}/gm) || [])
.map((match) => match.replace(/[{{|}}]/g, ""))
.reduce((collector, match) => collector.add(match), new Set());
return Array.from(replaceSet)
.map((match) => {
const key = new RegExp(`{{${match}}}`, "gm");
if (!collectedData[match]) {
console.warn(
`${y("Warning")}: no match for \`${match}\` in template ${file}`
);
}
const value = collectedData[match] || match;
return [key, value];
})
.reduce((rawData, [key, value]) => rawData.replace(key, value), rawData);
}
async function getFilesToInclude(collectedData) {
const excludedFiles = new Set();
switch (collectedData.preprocessor) {
case "bikeshed":
excludedFiles.add("index.html");
break;
case "respec":
excludedFiles.add("index.bs");
break;
}
const dirFiles = await fs.readdir(tmplDir);
return dirFiles
.filter((filename) => !excludedFiles.has(filename))
.map((filename) => [tmplDir + filename, `${process.cwd()}/${filename}`]);
}
async function fileExists(filePath) {
try {
await fs.access(filePath, fs.F_OK);
} catch (err) {
return false;
}
return true;
}
// Uses git to get the name of the repo (cwd)
async function writeTemplates(collectedData) {
console.info(heading("Creating Templates"));
const destinations = await getFilesToInclude(collectedData);
const successfulWrites = [];
for (let [from, to] of destinations) {
if (await fileExists(to)) {
console.warn(
`${y(" ⚠️ skipping")} ${gr(path.basename(to))} (already exists)`
);
continue;
}
const rawData = await fs.readFile(from, "utf8");
const data = populateTemplate(rawData, collectedData, path.basename(from));
try {
await fs.writeFile(to, data);
const basename = path.basename(to);
console.log(` ${chk} ${g("created")} ${gr(basename)}`);
successfulWrites.push(basename);
} catch (err) {
console.error(
` 💥 ${r("error: ")} could not create ${gr(path.basename(to))}`
);
}
}
if (successfulWrites.length) {
await git(`add ${successfulWrites.join(" ")}`);
await git(`commit -am "feat: add WICG files."`);
console.info(
g(`\nCommitted changes to "${collectedData.mainBranch}" branch.`)
);
}
return collectedData;
}
// Tell the user what they should do next.
function postInitialization() {
console.info(finished);
}
async function collectProjectData(name = "") {
console.info(heading("Let's get you set up! (About this WICG project)"));
let repo = "";
let needsGitInit = true;
try {
repo = await git.getRepoName();
needsGitInit = false;
} catch (err) {
const response = await Prompts.askRepoName();
repo = response.trim();
}
// Let's get the name of the project
if (!name) {
name = await Prompts.askProjectName(repo);
}
// Derive the user's name from git config
const userName = await Prompts.askUserName();
const userEmail = await Prompts.askEmail();
// Get the company from the email
const [, affiliationHint] = /(?:@)([\w|-]+)/.exec(userEmail);
const affiliation = await Prompts.askAffiliation(affiliationHint);
let affiliationURL = "";
if (affiliation) {
affiliationURL = await Prompts.askAffiliationURL(userEmail);
}
const mainBranch = await Prompts.askWhichGitBranch();
const preprocessor = await Prompts.askWhichPreProcessor();
return {
affiliation,
affiliationURL,
mainBranch,
name,
needsGitInit,
preprocessor,
repo,
srcfile: preprocessor === "bikeshed" ? "index.bs" : "index.html",
userEmail,
userName,
};
}
program
.version(version)
.command("init [name]")
.description("start a new incubation project")
.action(async (name, options) => {
console.info(logo);
try {
const collectedData = await collectProjectData(name, options);
await performGitTasks(collectedData);
await writeTemplates(collectedData);
} catch (err) {
console.error(`\n 💥 ${r(err.message)}`, err);
}
postInitialization();
});
program.parse(process.argv);
if (!process.argv.slice(2).length) {
program.outputHelp();
console.log(example);
}