-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmgit.ts
More file actions
394 lines (371 loc) · 13.7 KB
/
mgit.ts
File metadata and controls
394 lines (371 loc) · 13.7 KB
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
import * as c from "https://deno.land/std@0.215.0/fmt/colors.ts";
import { walk } from "https://deno.land/std@0.215.0/fs/walk.ts";
import * as path from "https://deno.land/std@0.215.0/path/mod.ts";
import $ from "https://deno.land/x/dax@0.39.0/mod.ts";
import * as JSONC from "https://deno.land/std@0.215.0/jsonc/mod.ts";
// these are typically used by consumers of this library so make them accessible
export * as colors from "https://deno.land/std@0.215.0/fmt/colors.ts";
export * as fs from "https://deno.land/std@0.215.0/fs/mod.ts";
export * as JSONC from "https://deno.land/std@0.215.0/jsonc/mod.ts";
export * as path from "https://deno.land/std@0.215.0/path/mod.ts";
export * as dax from "https://deno.land/x/dax@0.39.0/mod.ts";
export { $ } from "https://deno.land/x/dax@0.39.0/mod.ts";
/**
* TODO: document all interfaces, fields, and functions so that VS Code editor
* can act as our primary documentation for `ws-ensure.ts` scripts
*/
export interface WorkspaceContext {
readonly workspaceFsHome: string;
readonly handled: WorkspaceRepo[];
readonly vsCodeWsPathMatchers: RegExp[];
readonly debug?: boolean;
}
export interface WorkspaceRepo {
readonly wsContext: WorkspaceContext;
readonly repoUrlWithoutScheme: string;
readonly repoURL: URL;
readonly repoFsHomeAbs: string;
readonly repoFsHomeRel: string;
readonly pp: path.ParsedPath;
readonly stat?: Deno.FileInfo;
}
export function defaultWorkspaceFsHome() {
return Deno.env.get("MANAGED_GIT_WORKSPACES_HOME") || Deno.cwd();
}
export function strictVsCodeWsPathMatchers() {
return [/.mgit.code-workspace$/];
}
export function relaxedVsCodeWsPathMatchers() {
return [/.code-workspace$/];
}
/**
* Prepare a workspace context to track work across multiple mGit repos in the
* same workspace.
* @param workspaceFsHome absolute path of the managed workspaces root
* @param vsCodeWsPathMatchers the regEx's that will determine whether a file is candidate mGit VS Code `.code-workspace` file
* @param handled which repos have already been handled (so we don't end up with recursive loops in case repos depend on each other)
* @returns workspace context that should be passed into {@link workspaceRepo} function
*/
export function workspaceContext(
workspaceFsHome = defaultWorkspaceFsHome(),
vsCodeWsPathMatchers = strictVsCodeWsPathMatchers(),
handled: WorkspaceRepo[] = [],
): WorkspaceContext {
return { workspaceFsHome, vsCodeWsPathMatchers, handled };
}
/**
* Prepare a workspace repo instance that can be passed to other functions like {@link ensureRepo}.
* @param repoUrlWithoutScheme a URL-like string (e.g. "github.com/org/repo")
* @param wsContext the workspace context in which we're operating
* @returns a workspace repo instance
*/
export async function workspaceRepo(
repoUrlWithoutScheme: string,
wsContext = workspaceContext(),
) {
const repoFsHomeAbs = path.join(
wsContext.workspaceFsHome,
repoUrlWithoutScheme,
);
const pp = path.parse(repoFsHomeAbs);
const result: WorkspaceRepo = {
wsContext,
repoUrlWithoutScheme,
repoURL: new URL(`https://${repoUrlWithoutScheme}`),
repoFsHomeAbs,
repoFsHomeRel: path.relative(wsContext.workspaceFsHome, repoFsHomeAbs),
pp,
};
try {
const stat = await Deno.stat(repoFsHomeAbs);
return { ...result, stat };
} catch (_err) {
return result;
}
}
/**
* Either `git clone` or `git pull` a repo to ensure that it exists in the local file system.
* @param repo the repo we want to prepare
* @param options how we want to prepare the repo
* @returns
*/
export async function ensureRepo(
repo: WorkspaceRepo,
options?: {
/** if the repo already exists, don't do a pull and instead delete the existing repo without confirmation and then do a fresh clone */
readonly force?: boolean;
/** if set, we won't try to find `*.code-workspace` files to symlink them in the workspace home */
readonly skipMgitVsCodeWsAutoDetect?: boolean;
/** if set, we will find dependent repos by looking in `*.code-workspace` files' `.folders[].path` configuration */
readonly ensureVscWsDepsFolders?: boolean;
/** if set, define the patterns that will be used to find `*.code-workspace` files */
readonly vsCodeWsPathMatchers?: RegExp[];
},
) {
if (
repo.wsContext.handled.find((r) => r.repoFsHomeAbs == repo.repoFsHomeAbs)
) {
// deno-fmt-ignore
if (repo.wsContext.debug) console.debug(c.dim(`[ensureRepo] already preparing ${c.underline(repo.repoUrlWithoutScheme)} ${JSON.stringify(options)}, popping stack`));
return;
}
repo.wsContext.handled.push(repo);
// deno-fmt-ignore
if (repo.wsContext.debug) console.debug(c.dim(`[ensureRepo] preparing ${c.underline(repo.repoUrlWithoutScheme)} ${JSON.stringify(options)}`));
if (repo.stat?.isDirectory) {
if (options?.force) {
// deno-fmt-ignore
console.info(`${c.yellow(repo.repoUrlWithoutScheme)} found, forcing re-create by removing ${c.red(repo.repoFsHomeRel)}`);
await Deno.remove(repo.repoFsHomeAbs, { recursive: true });
} else {
// deno-fmt-ignore
console.info(`${c.yellow(repo.repoUrlWithoutScheme)} found, pulling latest in ${c.green(repo.repoFsHomeRel)}`);
await $`git -C ${repo.repoFsHomeAbs} pull --quiet`;
if (!options?.skipMgitVsCodeWsAutoDetect) {
await symlinkMgitVsCodeWs(repo, options);
}
if (options?.ensureVscWsDepsFolders) {
await ensureRepos(repo, options);
}
return true;
}
}
await Deno.mkdir(repo.pp.dir, { recursive: true });
try {
await $`git clone ${repo.repoURL} ${repo.repoFsHomeAbs} --quiet`;
// deno-fmt-ignore
console.log(`${c.yellow(repo.repoUrlWithoutScheme)} not found, cloned ${c.magenta(repo.repoFsHomeRel)}`);
if (!options?.skipMgitVsCodeWsAutoDetect) {
await symlinkMgitVsCodeWs(repo, options);
}
if (options?.ensureVscWsDepsFolders) {
await ensureRepos(repo, options);
}
return true;
} catch (error) {
// deno-fmt-ignore
console.error(`${c.yellow(repo.repoURL.toString())}${c.red(' is not a valid managed Git URL')}`);
console.log(c.dim(error));
return false;
}
}
export async function symlinkMgitVsCodeWs(
repo: WorkspaceRepo,
options?: { readonly vsCodeWsPathMatchers?: RegExp[] },
) {
for await (
const we of walk(repo.repoFsHomeAbs, {
match: options?.vsCodeWsPathMatchers ||
repo.wsContext.vsCodeWsPathMatchers,
})
) {
const relMgitWsPathInRepo = path.relative(
repo.wsContext.workspaceFsHome,
we.path,
);
const mgitWsSymlinkPath = path.join(
repo.wsContext.workspaceFsHome,
we.name,
);
// deno-fmt-ignore
console.log(` ${c.dim("symlink'd")} ${c.magenta(we.name)} ➡️ ${c.green(relMgitWsPathInRepo)}`);
try {
await Deno.remove(mgitWsSymlinkPath);
} catch (error) {
if (error instanceof Deno.errors.NotFound) {
// it's OK if the symlink didn't already exist
} else {
// otherwise re-throw
throw error;
}
}
await Deno.symlink(relMgitWsPathInRepo, mgitWsSymlinkPath);
}
}
export function isValidVscWorkspaceDepsSupplier(
vscWorkspaceCandidate: unknown,
): vscWorkspaceCandidate is {
readonly folders: { readonly path: string; readonly name?: string }[];
} {
const isValidFolder = (
folderCandidate: unknown,
): folderCandidate is { readonly path: string; readonly name?: string } => {
if (folderCandidate && typeof folderCandidate === "object") {
const folder: { name?: string; path?: string } = folderCandidate;
if (folder.path && typeof folder.path === "string") {
return true;
}
}
return false;
};
if (vscWorkspaceCandidate && typeof vscWorkspaceCandidate === "object") {
const vscWorkspace: { readonly folders?: unknown[] } =
vscWorkspaceCandidate;
if (vscWorkspace.folders && Array.isArray(vscWorkspace.folders)) {
for (const folder of vscWorkspace.folders) {
if (!isValidFolder(folder)) return false;
}
return true;
}
}
return false;
}
export async function ensureVsCodeWsDepRepos(
vscWorkspaceFsPath: string,
wsContext = workspaceContext(),
options?: {
readonly force?: boolean;
readonly skipMgitVsCodeWsAutoDetect?: boolean;
readonly ensureVscWsDepsFolders?: boolean;
},
) {
// deno-fmt-ignore
if (wsContext.debug) console.debug(c.dim(`[ensureVsCodeWsDepRepos] preparing ${c.underline(vscWorkspaceFsPath)} ${JSON.stringify(options)}`));
try {
const vscWorkspace = JSONC.parse(
await Deno.readTextFile(vscWorkspaceFsPath),
);
if (isValidVscWorkspaceDepsSupplier(vscWorkspace)) {
// deno-fmt-ignore
if (wsContext.debug) console.log(`${c.dim('Determining dependent repos in')} ${c.dim(c.underline(vscWorkspaceFsPath))}`)
for await (const folder of vscWorkspace.folders) {
// deno-fmt-ignore
if (wsContext.debug) console.log(`${c.dim(' found dependent repo ')} ${c.dim(c.underline(folder.path))}`)
await ensureRepo(
await workspaceRepo(folder.path, wsContext),
options,
);
}
} else {
// deno-fmt-ignore
console.log(`${c.dim(' no `folders` found in ')} ${c.dim(c.underline(vscWorkspaceFsPath))}`)
}
} catch (error) {
// deno-fmt-ignore
console.error(`${c.red('Error determining dependent repos in')} ${c.yellow(vscWorkspaceFsPath)}:`)
console.error(c.dim(error.toString()));
}
}
export async function ensureRepos(
repo: WorkspaceRepo,
options?: {
readonly vsCodeWsPathMatchers?: RegExp[];
readonly force?: boolean;
readonly skipMgitVsCodeWsAutoDetect?: boolean;
readonly skipMgitVsCodeWsDepReposEnsure?: boolean;
},
) {
// deno-fmt-ignore
if (repo.wsContext.debug) console.debug(c.dim(`[ensureRepos] preparing ${c.underline(repo.repoUrlWithoutScheme)} ${JSON.stringify(options)}`));
for await (
const we of walk(repo.repoFsHomeAbs, {
match: options?.vsCodeWsPathMatchers ||
repo.wsContext.vsCodeWsPathMatchers,
})
) {
const relMgitWsPathInRepo = path.relative(
repo.wsContext.workspaceFsHome,
we.path,
);
await ensureVsCodeWsDepRepos(
relMgitWsPathInRepo,
repo.wsContext,
options,
);
}
}
export async function inspect(
wsContext: WorkspaceContext,
options?: {
readonly vsCodeWsPathMatchers?: RegExp[];
},
) {
const allRepos = new Set<string>();
const gitManagers = new Set<string>();
for await (
const we of walk(wsContext.workspaceFsHome, {
match: options?.vsCodeWsPathMatchers ||
wsContext.vsCodeWsPathMatchers,
})
) {
const relMgitWsPathInRepo = path.relative(
wsContext.workspaceFsHome,
we.path,
);
try {
const vscWorkspace = JSONC.parse(
await Deno.readTextFile(relMgitWsPathInRepo),
);
if (isValidVscWorkspaceDepsSupplier(vscWorkspace)) {
for (const folder of vscWorkspace.folders) {
const repoPath = folder.path == "."
? path.dirname(path.relative(wsContext.workspaceFsHome, we.path))
: folder.path;
allRepos.add(repoPath);
const pathItems = repoPath.split(path.SEP);
if (pathItems.length > 0) {
gitManagers.add(pathItems[0]);
}
}
}
} catch (error) {
// deno-fmt-ignore
console.error(`${c.red('Error determining dependent repos in')} ${c.yellow(relMgitWsPathInRepo)}:`)
console.error(c.dim(error.toString()));
}
}
console.log(
`${c.dim("Git Managers")} ${
Array.from(gitManagers.values()).sort().join(", ")
}`,
);
console.log(
`${c.dim("All mGit repos from *.code-workspace folder entries:")}\n - ${
Array.from(allRepos.values()).sort().join("\n - ")
}`,
);
// TODO:
// # List file counts for all folders in a VS Code *.code-workspace file
// cat $vscws | jq -r '.folders[] | "FC=`find \(.path)/* -type f | wc -l`; echo \"$FC\t\(.path)\""' | sh
// # List path sizes for all folders in a VS Code *.code-workspace file
// cat $vscws | jq -r '.folders[] | "du -s \(.path)"' | sh
}
export async function mGitStatus(wsContext: WorkspaceContext): Promise<void> {
try {
for await (const entry of walk(wsContext.workspaceFsHome)) {
if (entry.name === ".git" && entry.isDirectory) {
const projDir = entry.path.slice(0, -4); // Remove '.git' from path
if (projDir.includes("$RECYCLE.BIN")) continue; // this only happens on Windows
// Check for various git statuses
const { stdout: statusStdout } =
await $`git --git-dir=${projDir}/.git --work-tree=${projDir} status`
.stdout("piped").stderr("piped");
const { stdout: stashStdout } =
await $`git --git-dir=${projDir}/.git --work-tree=${projDir} stash list`
.stdout("piped").stderr("piped");
const locked = statusStdout.includes("index.lock");
const uncommitted = statusStdout.includes(
"Changes not staged for commit",
);
const untracked = statusStdout.includes("Untracked files");
const needsPush = statusStdout.includes("Your branch is ahead");
const needsPull = statusStdout.includes("Your branch is behind");
const hasStashes = stashStdout.trim().length > 0;
// Output results with colors
console.log(`Repository: ${projDir}`);
if (locked) console.log(c.red(" Locked"));
if (uncommitted) console.log(c.red(" Uncommitted changes"));
if (untracked) console.log(c.cyan(" Untracked files"));
if (needsPush) console.log(c.yellow(" Needs push"));
if (needsPull) console.log(c.blue(" Needs pull"));
if (hasStashes) {
console.log(
c.magenta(`${stashStdout.trim().split("\n").length} stashes`),
);
}
}
}
} catch (err) {
// usually 'PermissionDenied' do we can ignore
}
}