forked from jupyterlab/jupyterlab
/
utils.ts
376 lines (347 loc) · 9.72 KB
/
utils.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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
import path = require('path');
import glob = require('glob');
import fs = require('fs-extra');
import childProcess = require('child_process');
import { DepGraph } from 'dependency-graph';
import sortPackageJson = require('sort-package-json');
import coreutils = require('@lumino/coreutils');
type Dict<T> = { [key: string]: T };
const backSlash = /\\/g;
/**
* Get all of the lerna package paths.
*/
export function getLernaPaths(basePath = '.'): string[] {
basePath = path.resolve(basePath);
let packages;
try {
let baseConfig = require(path.join(basePath, 'package.json'));
if (baseConfig.workspaces) {
packages = baseConfig.workspaces.packages || baseConfig.workspaces;
} else {
baseConfig = require(path.join(basePath, 'lerna.json'));
packages = baseConfig.packages;
}
} catch (e) {
if (e.code === 'MODULE_NOT_FOUND') {
throw new Error(
`No yarn workspace / lerna package list found in ${basePath}`
);
}
throw e;
}
let paths: string[] = [];
for (let config of packages) {
paths = paths.concat(glob.sync(path.join(basePath, config)));
}
return paths.filter(pkgPath => {
return fs.existsSync(path.join(pkgPath, 'package.json'));
});
}
/**
* Get all of the core package paths.
*/
export function getCorePaths(): string[] {
let spec = path.resolve(path.join('.', 'packages', '*'));
return glob.sync(spec);
}
/**
* Write a package.json if necessary.
*
* @param data - The package data.
*
* @oaram pkgJsonPath - The path to the package.json file.
*
* @returns Whether the file has changed.
*/
export function writePackageData(pkgJsonPath: string, data: any): boolean {
let text = JSON.stringify(sortPackageJson(data), null, 2) + '\n';
let orig = fs
.readFileSync(pkgJsonPath, 'utf8')
.split('\r\n')
.join('\n');
if (text !== orig) {
fs.writeFileSync(pkgJsonPath, text, 'utf8');
return true;
}
return false;
}
/**
* Read a json file.
*/
export function readJSONFile(filePath: string): any {
try {
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
} catch (e) {
throw `Cannot read JSON for path ${filePath}: ${e}`;
}
}
/**
* Write a json file.
*/
export function writeJSONFile(filePath: string, data: any): boolean {
function sortObjByKey(value: any): any {
// https://stackoverflow.com/a/35810961
return typeof value === 'object'
? Array.isArray(value)
? value.map(sortObjByKey)
: Object.keys(value)
.sort()
.reduce((o: any, key) => {
const v = value[key];
o[key] = sortObjByKey(v);
return o;
}, {})
: value;
}
let text = JSON.stringify(data, sortObjByKey(data), 2) + '\n';
let orig = {};
try {
orig = readJSONFile(filePath);
} catch (e) {
// no-op
}
if (!coreutils.JSONExt.deepEqual(data, orig)) {
fs.writeFileSync(filePath, text, 'utf8');
return true;
}
return false;
}
/**
* Simple template substitution for template vars of the form {{name}}
*
* @param templ: the template string.
* Ex: `This header generated by {{funcName}}`
*
* @param subs: an object in which the parameter keys are the template
* variables and the parameter values are the substitutions.
*
* @param options: function options.
*
* @param options.autoindent: default = true. If true, will try to match
* indentation level of {{var}} in substituted template.
*
* @param options.end: default = '\n'. Inserted at the end of
* a template post-substitution and post-trim.
*
* @returns the input template with all {{vars}} substituted, then `.trim`-ed.
*/
export function fromTemplate(
templ: string,
subs: Dict<string>,
options: { autoindent?: boolean; end?: string } = {}
) {
// default options values
const autoindent =
options.autoindent === undefined ? true : options.autoindent;
const end = options.end === undefined ? '\n' : options.end;
Object.keys(subs).forEach(key => {
const val = subs[key];
if (autoindent) {
// try to match the indentation level of the {{var}} in the input template.
templ = templ.split(`{{${key}}}`).reduce((acc, cur) => {
// Regex: 0 or more non-newline whitespaces followed by end of string
let indentRe = acc.match(/([^\S\r\n]*).*$/);
let indent = indentRe ? indentRe[1] : '';
return acc + val.split('\n').join('\n' + indent) + cur;
});
} else {
templ = templ.split(`{{${key}}}`).join(val);
}
});
return templ.trim() + end;
}
/**
*
* Call a command, checking its status.
*/
export function checkStatus(cmd: string) {
const data = childProcess.spawnSync(cmd, { shell: true });
return data.status;
}
/**
* Get the current version of JupyterLab
*/
export function getPythonVersion() {
const cmd = 'python setup.py --version';
return run(cmd, { stdio: 'pipe' }, true);
}
/**
* Get the current version of a package
*/
export function getJSVersion(pkg: string) {
const filePath = path.resolve(
path.join('.', 'packages', pkg, 'package.json')
);
const data = readJSONFile(filePath);
return data.version;
}
/**
* Pre-bump.
*/
export function prebump() {
// Ensure bump2version is installed (active fork of bumpversion)
run('python -m pip install bump2version');
// Make sure we start in a clean git state.
let status = run('git status --porcelain', {
stdio: 'pipe',
encoding: 'utf8'
});
if (status.length > 0) {
throw new Error(
`Must be in a clean git state with no untracked files.
Run "git status" to see the issues.
${status}`
);
}
}
/**
* Post-bump.
*/
export function postbump() {
// Get the current version.
const curr = getPythonVersion();
// Update the dev mode version.
let filePath = path.resolve(path.join('.', 'dev_mode', 'package.json'));
let data = readJSONFile(filePath);
data.jupyterlab.version = curr;
writeJSONFile(filePath, data);
}
/**
* Run a command with terminal output.
*
* @param cmd - The command to run.
*/
export function run(
cmd: string,
options: childProcess.ExecSyncOptions = {},
quiet?: boolean
): string {
options = options || {};
options['stdio'] = options.stdio || 'inherit';
if (!quiet) {
console.log('>', cmd);
}
const value = childProcess.execSync(cmd, options);
if (value === null) {
return '';
}
return value
.toString()
.replace(/(\r\n|\n)$/, '')
.trim();
}
/**
* Get a graph that has all of the package data for the local packages and their
* first order dependencies.
*/
export function getPackageGraph(): DepGraph<Dict<any>> {
// Pick up all the package versions.
const paths = getLernaPaths();
const locals: Dict<any> = {};
// These two are not part of the workspaces but should be
// considered part of the dependency graph.
paths.push('./jupyterlab/tests/mock_packages/extension');
paths.push('./jupyterlab/tests/mock_packages/mimeextension');
// Gather all of our package data.
paths.forEach(pkgPath => {
// Read in the package.json.
let data: any;
try {
data = readJSONFile(path.join(pkgPath, 'package.json'));
} catch (e) {
console.error(e);
return;
}
locals[data.name] = data;
});
// Build up a dependency graph from all our local packages and
// their first order dependencies.
const graph = new DepGraph();
Object.keys(locals).forEach(name => {
const data = locals[name];
graph.addNode(name, data);
const deps: Dict<Array<string>> = data.dependencies || {};
Object.keys(deps).forEach(depName => {
if (!graph.hasNode(depName)) {
let depData: any;
// get data from locals if available, otherwise from
// third party library.
if (depName in locals) {
depData = locals[depName];
} else {
depData = requirePackage(name, depName);
}
graph.addNode(depName, depData);
}
graph.addDependency(data.name, depName);
});
});
return graph;
}
/**
* Resolve a `package.json` in the `module` starting at resolution from the `parentModule`.
*
* We could just use "require(`${depName}/package.json`)", however this won't work for modules
* that are not hoisted to the top level.
*/
function requirePackage(parentModule: string, module: string) {
const packagePath = `${module}/package.json`;
let parentModulePath: string;
// This will fail when the parent module cannot be loaded, like `@jupyterlab/test-root`
try {
parentModulePath = require.resolve(parentModule);
} catch {
return require(packagePath);
}
const requirePath = require.resolve(packagePath, {
paths: [parentModulePath]
});
return require(requirePath);
}
/**
* Ensure the given path uses '/' as path separator.
*/
export function ensureUnixPathSep(source: string) {
if (path.sep === '/') {
return source;
}
return source.replace(backSlash, '/');
}
/**
* Get the last portion of a path, without its extension (if any).
*
* @param path - The file path.
*
* @returns the last part of the path, sans extension.
*/
export function stem(path: string): string {
return path
.split('\\')
.pop()
.split('/')
.pop()
.split('.')
.shift();
}
/**
* Given a 'snake-case', 'snake_case', or 'snake case' string,
* will return the camel case version: 'snakeCase'.
*
* @param str: the snake-case input string.
*
* @param upper: default = false. If true, the first letter of the
* returned string will be capitalized.
*
* @returns the camel case version of the input string.
*/
export function camelCase(str: string, upper: boolean = false): string {
return str.replace(/(?:^\w|[A-Z]|\b\w|\s+|-+|_+)/g, function(match, index) {
if (+match === 0 || match[0] === '-') {
return '';
} else if (index === 0 && !upper) {
return match.toLowerCase();
} else {
return match.toUpperCase();
}
});
}