forked from shah/vscode-team
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproject.ts
555 lines (499 loc) · 15.8 KB
/
project.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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
import { fs, path } from "./deps.ts";
import * as dl from "./download.ts";
import * as vscConfig from "./vscode-settings.ts";
export type FsPathOnly = string;
export type AbsoluteFsPath = FsPathOnly;
export type RelativeFsPath = FsPathOnly;
export type FsPathAndFileName = FsPathOnly & string;
export type FsPathAndFileNameOrUrl = FsPathAndFileName | URL;
export type FileExtension = string;
export type FileGlobPattern = string;
export type AbsoluteFsPathAndFileName = AbsoluteFsPath & string;
export type RecoverableErrorHandlerResult = "recovered" | "unrecoverrable";
export interface PathFinder {
(target: FsPathAndFileName, search: FsPathOnly[]): FsPathAndFileName | false;
}
export function findInPath(
target: FsPathAndFileName,
search: FsPathOnly[],
): FsPathAndFileName | false {
for (const searchPath of search) {
const tryPath = path.join(searchPath, target);
if (fs.existsSync(tryPath)) return tryPath;
}
return false;
}
export interface ProjectPathEnricher {
(ctx: { absProjectPath: FsPathAndFileName }, pp: ProjectPath): ProjectPath;
}
export interface ProjectPath {
readonly isProjectPath: true;
readonly absProjectPath: FsPathAndFileName;
readonly absProjectPathExists: boolean;
}
export function isProjectPath(o: unknown): o is ProjectPath {
return o && typeof o === "object" && "isProjectPath" in o;
}
/**
* Prepare a project path.
* @param ctx the enrichment context
* @returns the new ProjectPath
*/
export function prepareProjectPath(
ctx: { absProjectPath: FsPathAndFileName },
): ProjectPath {
const absPath = path.isAbsolute(ctx.absProjectPath)
? ctx.absProjectPath
: path.join(Deno.cwd(), ctx.absProjectPath);
return {
isProjectPath: true,
absProjectPath: absPath,
absProjectPathExists: fs.existsSync(absPath),
};
}
const defaultEnrichers: ProjectPathEnricher[] = [
enrichVsCodeWorkTree,
enrichGitWorkTree,
enrichDenoProjectByVsCodePlugin,
enrichNpmProject,
enrichTypeScriptProject,
];
/**
* Take a ProjectPath and enrich it with polyglot detection.
* @param ctx the enrichment context
* @returns the enriched ProjectPath
*/
export function enrichProjectPath(
ctx: { absProjectPath: FsPathAndFileName },
pp: ProjectPath = prepareProjectPath(ctx),
enrichers?: (suggested: ProjectPathEnricher[]) => ProjectPathEnricher[],
): ProjectPath {
const transformers = enrichers
? enrichers(defaultEnrichers)
: defaultEnrichers;
let result = pp;
for (const tr of transformers) {
result = tr(ctx, result);
}
return result;
}
export interface VsCodeProjectWorkTree extends ProjectPath {
readonly isVsCodeProjectWorkTree: true;
readonly vsCodeConfig: {
absConfigPath: AbsoluteFsPath;
settingsFileName: AbsoluteFsPathAndFileName;
extensionsFileName: AbsoluteFsPathAndFileName;
configPathExists: () => boolean;
settingsExists: () => boolean;
extensionsExists: () => boolean;
writeSettings: (settings: vscConfig.Settings) => void;
writeExtensions: (extensions: vscConfig.Extension[]) => void;
};
}
export function isVsCodeProjectWorkTree(
o: unknown,
): o is VsCodeProjectWorkTree {
return o && typeof o === "object" && "isVsCodeProjectWorkTree" in o;
}
/**
* Take a ProjectPath and enrich it as a Visual Studio Code work tree
* @param ctx the enrichment context
* @param pp The ProjectPath we want to enrich as a VS Code work tree
* @returns the enriched ProjectPath
*/
export function enrichVsCodeWorkTree(
ctx: { absProjectPath: FsPathAndFileName },
pp: ProjectPath,
): ProjectPath | GitWorkTree {
if (isVsCodeProjectWorkTree(pp)) return pp;
if (!pp.absProjectPathExists) return pp;
const configPath = `${pp.absProjectPath}/.vscode`;
const configSettingsFileName = `${configPath}/settings.json`;
const configExtnFileName = `${configPath}/extensions.json`;
const result: VsCodeProjectWorkTree = {
...pp,
isVsCodeProjectWorkTree: true,
vsCodeConfig: {
absConfigPath: configPath,
settingsFileName: configSettingsFileName,
extensionsFileName: configExtnFileName,
configPathExists: (): boolean => {
return fs.existsSync(configPath);
},
settingsExists: (): boolean => {
return fs.existsSync(configSettingsFileName);
},
extensionsExists: (): boolean => {
return fs.existsSync(configExtnFileName);
},
writeSettings: (settings: vscConfig.Settings): void => {
// we check first in case .vscode is an existing symlink
if (!fs.existsSync(configPath)) fs.ensureDirSync(configPath);
Deno.writeTextFileSync(
configSettingsFileName,
JSON.stringify(settings, undefined, 2),
);
},
writeExtensions: (extensions: vscConfig.Extension[]) => {
// we check first in case .vscode is an existing symlink
if (!fs.existsSync(configPath)) fs.ensureDirSync(configPath);
Deno.writeTextFileSync(
configExtnFileName,
JSON.stringify(
vscConfig.extnRecommendations(extensions),
undefined,
2,
),
);
},
},
};
return result;
}
export interface GitWorkTree extends ProjectPath {
readonly isGitWorkTree: true;
readonly gitWorkTree: FsPathOnly;
readonly gitDir: FsPathOnly;
}
export function isGitWorkTree(o: unknown): o is GitWorkTree {
return o && typeof o === "object" && "isGitWorkTree" in o;
}
/**
* Take a ProjectPath and enrich it as a Git work tree if appropriate.
* @param ctx the enrichment context
* @param pp The ProjectPath we want to enrich as a Git work tree
* @returns the enriched ProjectPath
*/
export function enrichGitWorkTree(
ctx: { absProjectPath: FsPathAndFileName },
pp: ProjectPath,
): ProjectPath | GitWorkTree {
if (isGitWorkTree(pp)) return pp;
if (!pp.absProjectPathExists) return pp;
const workingTreePath = pp.absProjectPath;
const gitTreePath = path.join(workingTreePath, ".git");
if (fs.existsSync(gitTreePath)) {
const result: GitWorkTree = {
...pp,
isGitWorkTree: true,
gitDir: gitTreePath,
gitWorkTree: workingTreePath,
};
return result;
}
return pp;
}
export interface PolyglotFile {
readonly fileName: AbsoluteFsPathAndFileName;
readonly fileExtn: FileExtension;
readonly fileExists: boolean;
readonly relativeTo: (to: FsPathOnly) => RelativeFsPath;
}
export interface JsonFile extends PolyglotFile {
readonly isJsonFile: true;
readonly content: () => unknown;
}
export class TypicalJsonFile implements JsonFile {
readonly isJsonFile = true;
constructor(readonly fileName: string) {
}
content(): unknown {
if (this.fileExists) {
return JSON.parse(Deno.readTextFileSync(this.fileName));
}
return undefined;
}
contentDict(): Record<string, unknown> | undefined {
const content = this.content();
if (content) {
return content as Record<string, unknown>;
}
return undefined;
}
get fileExists(): boolean {
return fs.existsSync(this.fileName);
}
get fileExtn(): FileExtension {
return path.extname(this.fileName);
}
relativeTo(to: FsPathOnly): RelativeFsPath {
return path.relative(to, this.fileName);
}
}
export function guessPolyglotFile(fn: AbsoluteFsPathAndFileName): PolyglotFile {
const extn = path.extname(fn);
switch (extn) {
case ".json":
return new TypicalJsonFile(fn);
default:
return {
fileName: fn,
fileExists: fs.existsSync(fn),
fileExtn: extn,
relativeTo: (to: FsPathOnly): RelativeFsPath => {
return path.relative(to, fn);
},
};
}
}
export function guessPolyglotFiles(glob: FileGlobPattern): PolyglotFile[] {
const results: PolyglotFile[] = [];
for (const we of fs.expandGlobSync(glob)) {
if (we.isFile) {
results.push(guessPolyglotFile(we.path));
}
}
return results;
}
export interface TypeScriptProject extends ProjectPath {
readonly isTypeScriptProject: true;
readonly tsConfigFileName?: FsPathAndFileName;
}
export function isTypeScriptProject(o: unknown): o is TypeScriptProject {
return o && typeof o === "object" && "isTypeScriptProject" in o;
}
/**
* Take a ProjectPath and enrich it as a TypeScript project
* if it has a tsconfig.json file at its root location.
* @param ctx the enrichment context
* @param pp The ProjectPath we want to enrich as a Git work tree
* @returns the enriched ProjectPath
*/
export function enrichTypeScriptProject(
ctx: { absProjectPath: FsPathAndFileName },
pp: ProjectPath,
): ProjectPath | TypeScriptProject {
if (isTypeScriptProject(pp)) return pp;
if (!pp.absProjectPathExists) return pp;
const projectPath = pp.absProjectPath;
const tsConfigPath = path.join(projectPath, "tsconfig.json");
if (!fs.existsSync(tsConfigPath)) return pp;
const result: TypeScriptProject = {
...pp,
isTypeScriptProject: true,
tsConfigFileName: tsConfigPath,
};
return result;
}
export interface DenoProject extends ProjectPath, TypeScriptProject {
readonly isDenoProject: true;
readonly updateDepsCandidates: () => PolyglotFile[];
}
export function isDenoProject(o: unknown): o is DenoProject {
return o && typeof o === "object" && "isDenoProject" in o;
}
export interface DenoProjectByVsCodePlugin extends DenoProject {
readonly isDenoProjectByVsCodePlugin: true;
}
export function isDenoProjectByVsCodePlugin(
o: unknown,
): o is DenoProjectByVsCodePlugin {
return o && typeof o === "object" && "isDenoProjectByVsCodePlugin" in o;
}
export interface DenoProjectByConvention extends DenoProject {
readonly isDenoProjectByConvention: true;
}
export function isDenoProjectByConvention(
o: unknown,
): o is DenoProjectByConvention {
return o && typeof o === "object" && "isDenoProjectByConvention" in o;
}
/**
* Take a ProjectPath and enrich it as a Deno project.
* @param pp The ProjectPath we want to enrich as a Deno project
* @returns the enriched ProjectPath
*/
export function forceDenoProject(pp: ProjectPath): DenoProject {
const projectPath = pp.absProjectPath;
const tsConfigFileName = path.join(projectPath, "tsconfig.json");
const result: DenoProject = {
...pp,
isTypeScriptProject: true,
tsConfigFileName: fs.existsSync(tsConfigFileName)
? tsConfigFileName
: undefined,
isDenoProject: true,
updateDepsCandidates: (): PolyglotFile[] => {
return [
...guessPolyglotFiles(path.join(projectPath, "**", "mod.ts")),
...guessPolyglotFiles(path.join(projectPath, "**", "deps.ts")),
...guessPolyglotFiles(
path.join(projectPath, "**", "deps-test.ts"),
),
];
},
};
return result;
}
/**
* Take a ProjectPath and enrich it as a Deno project if appropriate.
* @param ctx the enrichment context
* @param pp The ProjectPath we want to enrich as a Deno project
* @returns the enriched ProjectPath
*/
export function enrichDenoProjectByVsCodePlugin(
ctx: { absProjectPath: FsPathAndFileName },
pp: ProjectPath,
): ProjectPath | DenoProjectByVsCodePlugin {
if (isDenoProjectByVsCodePlugin(pp)) return pp;
if (!pp.absProjectPathExists) return pp;
if (isVsCodeProjectWorkTree(pp)) {
if (pp.vsCodeConfig.configPathExists()) {
const settingsJSON = new TypicalJsonFile(
pp.vsCodeConfig.settingsFileName,
);
if (settingsJSON.fileExists) {
const contentDict = settingsJSON.contentDict();
if (contentDict && contentDict["deno.enable"]) {
const result: DenoProjectByVsCodePlugin = {
...forceDenoProject(pp),
isDenoProjectByVsCodePlugin: true,
};
return result;
}
}
}
}
return pp;
}
// TODO: this is incomplete, needs implementation - it's designed to convert
// a Deno project from a polyrepo into a monorepo by making all imports
// local instead of remote.
// # To make the libraries "local" monorepo
// "https://denopkg.com/gov-suite/(.*?)(@.*?)/(.*?)/mod.ts"
// ../../../$1/$3/mod.ts
// # To make the libraries back to polyrepos
// "https://denopkg.com/gov-suite/$1/mod.ts"
export async function denoRewriteImportsAsMonoRepo(
ctx: { projectHome: string },
depsGlob = "**/*/deps{-test,}.ts",
): Promise<true | void> {
const matchURL = "https://denopkg.com/gov-suite/\\(.*\\)\\(@.*\\)/";
for (const we of fs.expandGlobSync(depsGlob)) {
if (we.isFile) {
const relative = path.relative(ctx.projectHome, we.path);
const relativeDirName = path.dirname(relative);
const monoRepoLocalDest = "../".repeat(
relativeDirName.split(path.sep).length + 1,
);
console.log(
`sed -i 's!${matchURL}!${monoRepoLocalDest}\\1!g' ${relative}`,
);
}
}
}
export class NpmPackageConfig extends TypicalJsonFile {
get isValid(): boolean {
return this.fileExists;
}
get isPublishable(): boolean {
const packageDict = this.contentDict();
if (packageDict) {
const scripts = packageDict.scripts as Record<string, string>;
return scripts.prepublishOnly ? true : false;
}
return false;
}
}
export interface NpmProject extends ProjectPath {
readonly isNpmProject: true;
readonly npmPackageConfig: NpmPackageConfig;
}
export function isNpmProject(o: unknown): o is NpmProject {
return o && typeof o === "object" && "isNpmProject" in o;
}
export interface NpmPublishableProject extends NpmProject {
readonly isNpmPublishableProject: true;
}
export function isNpmPublishableProject(
o: unknown,
): o is NpmPublishableProject {
return o && typeof o === "object" && "isNpmPublishableProject" in o;
}
/**
* Take a ProjectPath and enrich it as a NodeJS NPM project if appropriate.
* @param ctx the enrichment context
* @param pp The ProjectPath we want to enrich as a NodeJS NPM project
* @returns the enriched ProjectPath
*/
export function enrichNpmProject(
ctx: { absProjectPath: FsPathAndFileName },
pp: ProjectPath,
): ProjectPath | NpmProject | NpmPublishableProject {
if (isNpmProject(pp)) return pp;
if (!pp.absProjectPathExists) return pp;
const projectPath = pp.absProjectPath;
const npmPkgConfig = new NpmPackageConfig(
path.join(projectPath, "package.json"),
);
if (!npmPkgConfig.isValid) return pp;
let regular: NpmProject = {
...pp,
isNpmProject: true,
npmPackageConfig: npmPkgConfig,
};
if (npmPkgConfig.isPublishable) {
const publishable: NpmPublishableProject = {
...regular,
isNpmPublishableProject: true,
};
return publishable;
}
return regular;
}
function isURL(text: string | URL): boolean {
if (typeof text === "string") {
const pattern = new RegExp(
"^(https?:\\/\\/)?" + // protocol
"((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|" + // domain name
"((\\d{1,3}\\.){3}\\d{1,3}))" + // OR ip (v4) address
"(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*" + // port and path
"(\\?[;&a-z\\d%_.~+=-]*)?" + // query string
"(\\#[-a-z\\d_]*)?$", // fragment locator
"i",
);
return !!pattern.test(text);
}
return true;
}
export async function copySourceToDest(
sources: FsPathAndFileNameOrUrl[],
dest: FsPathAndFileName,
{ dryRun, verbose }: {
readonly dryRun: boolean;
readonly verbose: boolean;
},
): Promise<void> {
if (!fs.existsSync(dest)) {
if (dryRun) {
console.log("mkdir", dest);
} else {
if (verbose) console.log(`Creating directory ${dest}`);
Deno.mkdirSync(dest);
}
}
if (fs.existsSync(dest)) {
for (const src of sources) {
if (verbose) {
console.log(`Copying ${src} to ${dest}`);
}
if (isURL(src)) {
if (dryRun) {
console.log(`Download ${src} ${dest}`);
} else {
await dl.download(src, { dir: dest }, {
redirect: "follow",
});
}
} else {
if (dryRun) {
console.log(`cp ${src} ${dest}`);
} else {
fs.copySync(src as string, dest, { overwrite: true });
}
}
}
} else {
console.error(`${dest} does not exist (and unable to create it)`);
}
}