-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
201 lines (159 loc) · 5.62 KB
/
index.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
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
#!/usr/bin/env node
import chalk from 'chalk';
import { Command, OptionValues } from 'commander';
import fse from 'fs-extra';
const { copy, createWriteStream, writeFile, readJSON, rm } = fse;
import path from 'path';
import { exec } from 'child_process';
import util from 'util';
import fetch from 'node-fetch';
import extract from 'extract-zip';
import { getTempDownloadFolder, removeTempDownloadFolder } from './src/os-util.js';
const asyncExec = util.promisify(exec); // make exec awaitable
import packageJson from './package.json' assert { type: 'json' };
export interface Opts extends OptionValues {
gitInit?: boolean;
tag?: string;
};
export const repoUrl = 'https://github.com/terrestris/react-geo-client-template';
export const init = () => {
let projectName = '';
let options: Opts = {};
const programName = Object.keys(packageJson?.bin)[0] || packageJson.name;
const program = new Command(programName)
.version(packageJson.version)
.description('Creates a new react-geo project in the given directory based on a comprehensive template')
.arguments('<project-directory>')
.usage(`${chalk.green('<project-directory>')} [options]`)
.action((name: string, opts: any) => {
projectName = name;
options = opts;
})
.option('-g, --git-init', 'Whether to init an empty git repository or not', false)
.option('-t, --tag', 'The react-geo-client-template version/tag', 'main')
.allowUnknownOption()
.on('--help', () => {
console.log(
` Only ${chalk.green('<project-directory>')} is required.`
);
console.log();
})
.parse(process.argv);
if (!projectName) {
console.log(`${chalk.red('ERROR!')} Please specify the project directory:`);
console.log(
` ${chalk.cyan(program.name())} ${chalk.green('<project-directory>')}`
);
console.log();
console.log('For example:');
console.log(
` ${chalk.cyan(program.name())} ${chalk.green('my-react-geo-app')}`
);
console.log();
console.log(
`Run ${chalk.cyan(`${program.name()} --help`)} to see all options.`
);
process.exit(1);
}
createApp(projectName, options);
};
export const createApp = async (projectName: string, opts: Opts) => {
const currentDir = process.cwd();
const projectPath = path.join(currentDir, projectName);
const tempDir = await downloadTemplate(opts);
await copyTemplate(tempDir, projectPath);
await installTemplateDependencies(projectPath);
await prepareTemplatePackage(projectPath, projectName);
if (opts.gitInit) {
await initGitRepository(projectPath);
}
await removeTempDownloadFolder(tempDir);
console.log(`${chalk.greenBright('Done! Enjoy!')}`);
};
const downloadTemplate = async (opts: Opts) => {
try {
console.log('Downloading the template application');
const downloadUrl = `${repoUrl}/archive/refs/heads/${opts.tag}.zip`;
const tmpDir: string = await getTempDownloadFolder();
const targetArchive = path.join(tmpDir, 'package.zip');
await download(downloadUrl, targetArchive);
await extract(targetArchive, { dir: tmpDir });
await rm(targetArchive);
console.log(`${chalk.greenBright('SUCCESS!')}`);
return tmpDir;
} catch (error) {
console.log(`${chalk.bgMagenta('ERROR!')}`);
console.log(`${error}`);
process.exit(1);
}
};
const copyTemplate = async (tempDir: string, projectPath: string) => {
try {
console.log(`Installing the application to ${chalk.italic(projectPath)}`);
await copy(path.join(tempDir, 'react-geo-client-template-main'), projectPath);
console.log(`${chalk.greenBright('SUCCESS!')}`);
} catch (error) {
console.log(`${chalk.bgMagenta('ERROR!')}`);
console.log(`${error}`);
process.exit(1);
}
};
const installTemplateDependencies = async (projectPath: string) => {
try {
console.log(`Running ${chalk.blueBright('npm install')} in ${chalk.italic(projectPath)}`);
process.chdir(projectPath);
await asyncExec('npm install');
console.log(`${chalk.greenBright('SUCCESS!')}`);
} catch (error) {
console.log(`${chalk.bgMagenta('ERROR!')}`);
console.log(`${error}`);
process.exit(1);
}
};
const prepareTemplatePackage = async (projectPath: string, projectName: string) => {
try {
console.log('Preparing the package.json');
const templatePackageJson = await readJSON(path.join(projectPath, 'package.json'), 'utf8');
templatePackageJson.name = projectName;
templatePackageJson.description = 'Bootstrapped with create-react-geo-app';
templatePackageJson.repository = {
url: '',
type: ''
};
await writeFile(path.join(projectPath, 'package.json'), JSON.stringify(templatePackageJson, null, 2), 'utf8');
console.log(`${chalk.greenBright('SUCCESS!')}`);
} catch (error) {
console.log(`${chalk.bgMagenta('ERROR!')}`);
console.log(`${error}`);
process.exit(1);
}
};
const initGitRepository = async (projectPath: string) => {
const currentDir = process.cwd();
process.chdir(projectPath);
try {
console.log('Initializing an empty git repository');
await asyncExec('git init');
console.log(`${chalk.greenBright('SUCCESS!')}`);
} catch (error) {
console.log(`${chalk.bgMagenta('ERROR!')}`);
console.log(`${error}`);
process.exit(1);
} finally {
process.chdir(currentDir);
}
};
const download = async (url: string, name: string) => {
const res = await fetch(url);
await new Promise((resolve, reject) => {
const fileStream = createWriteStream(name);
res.body?.pipe(fileStream);
res.body?.on('error', (err) => {
reject(err);
});
fileStream.on('finish', function() {
resolve(true);
});
});
};
init();