-
Notifications
You must be signed in to change notification settings - Fork 15
/
localShadowRepo.ts
568 lines (498 loc) · 21.5 KB
/
localShadowRepo.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
556
557
558
559
560
561
562
563
564
565
566
567
568
/*
* Copyright (c) 2020, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import path from 'node:path';
import * as os from 'node:os';
import * as fs from 'graceful-fs';
import { NamedPackageDir, Lifecycle, Logger, SfError } from '@salesforce/core';
import { env } from '@salesforce/kit';
// @ts-expect-error isogit has both ESM and CJS exports but node16 module/resolution identifies it as ESM
import git, { Walker } from 'isomorphic-git';
import { Performance } from '@oclif/core';
import {
RegistryAccess,
MetadataResolver,
VirtualTreeContainer,
SourceComponent,
} from '@salesforce/source-deploy-retrieve';
import { chunkArray, excludeLwcLocalOnlyTest, folderContainsPath } from './functions';
import { sourceComponentGuard } from './guards';
/** returns the full path to where we store the shadow repo */
const getGitDir = (orgId: string, projectPath: string): string =>
path.join(projectPath, '.sf', 'orgs', orgId, 'localSourceTracking');
// filenames were normalized when read from isogit
const toFilenames = (rows: StatusRow[]): string[] => rows.map((row) => row[FILE]);
// catch isogit's `InternalError` to avoid people report CLI issues in isogit repo.
// See: https://github.com/forcedotcom/cli/issues/2416
const redirectToCliRepoError = (e: unknown): never => {
if (e instanceof git.Errors.InternalError) {
const error = new SfError(
`An internal error caused this command to fail. isomorphic-git error:${os.EOL}${e.data.message}`,
e.name
);
throw error;
}
throw e;
};
type FileInfo = { filename: string; hash: string; basename: string };
type StringMap = Map<string, string>;
type AddAndDeleteMaps = { addedMap: StringMap; deletedMap: StringMap };
type ShadowRepoOptions = {
orgId: string;
projectPath: string;
packageDirs: NamedPackageDir[];
registry: RegistryAccess;
};
// https://isomorphic-git.org/docs/en/statusMatrix#docsNav
type StatusRow = [file: string, head: number, workdir: number, stage: number];
// array members for status results
const FILE = 0;
const HEAD = 1;
const WORKDIR = 2;
// We don't use STAGE (StatusRow[3]). Changes are added and committed in one step
type CommitRequest = {
deployedFiles?: string[];
deletedFiles?: string[];
message?: string;
needsUpdatedStatus?: boolean;
};
export class ShadowRepo {
private static instanceMap = new Map<string, ShadowRepo>();
public gitDir: string;
public projectPath: string;
private packageDirs!: NamedPackageDir[];
private status!: StatusRow[];
private logger!: Logger;
private readonly isWindows: boolean;
private readonly registry: RegistryAccess;
/** do not try to add more than this many files at a time through isogit. You'll hit EMFILE: too many open files even with graceful-fs */
private readonly maxFileAdd: number;
private constructor(options: ShadowRepoOptions) {
this.gitDir = getGitDir(options.orgId, options.projectPath);
this.projectPath = options.projectPath;
this.packageDirs = options.packageDirs;
this.isWindows = os.type() === 'Windows_NT';
this.registry = options.registry;
this.maxFileAdd = env.getNumber(
'SF_SOURCE_TRACKING_BATCH_SIZE',
env.getNumber('SFDX_SOURCE_TRACKING_BATCH_SIZE', this.isWindows ? 8000 : 15_000)
);
}
// think of singleton behavior but unique to the projectPath
public static async getInstance(options: ShadowRepoOptions): Promise<ShadowRepo> {
if (!ShadowRepo.instanceMap.has(options.projectPath)) {
const newInstance = new ShadowRepo(options);
await newInstance.init();
ShadowRepo.instanceMap.set(options.projectPath, newInstance);
}
return ShadowRepo.instanceMap.get(options.projectPath) as ShadowRepo;
}
public async init(): Promise<void> {
this.logger = await Logger.child('ShadowRepo');
// initialize the shadow repo if it doesn't exist
if (!fs.existsSync(this.gitDir)) {
this.logger.debug('initializing git repo');
await this.gitInit();
}
}
/**
* Initialize a new source tracking shadow repo. Think of git init
*
*/
public async gitInit(): Promise<void> {
this.logger.trace(`initializing git repo at ${this.gitDir}`);
await fs.promises.mkdir(this.gitDir, { recursive: true });
try {
await git.init({ fs, dir: this.projectPath, gitdir: this.gitDir, defaultBranch: 'main' });
} catch (e) {
redirectToCliRepoError(e);
}
}
/**
* Delete the local tracking files
*
* @returns the deleted directory
*/
public async delete(): Promise<string> {
if (typeof fs.promises.rm === 'function') {
await fs.promises.rm(this.gitDir, { recursive: true, force: true });
} else {
await fs.promises.rm(this.gitDir, { recursive: true });
}
return this.gitDir;
}
/**
* If the status already exists, return it. Otherwise, set the status before returning.
* It's kinda like a cache
*
* @params noCache: if true, force a redo of the status using FS even if it exists
*
* @returns StatusRow[]
*/
public async getStatus(noCache = false): Promise<StatusRow[]> {
this.logger.trace(`start: getStatus (noCache = ${noCache})`);
if (!this.status || noCache) {
const marker = Performance.mark('@salesforce/source-tracking', 'localShadowRepo.getStatus#withoutCache');
// iso-git uses relative, posix paths
// but packageDirs has already resolved / normalized them
// so we need to make them project-relative again and convert if windows
const pkgDirs = this.packageDirs.map(packageDirToRelativePosixPath(this.isWindows)(this.projectPath));
try {
// status hasn't been initialized yet
this.status = await git.statusMatrix({
fs,
dir: this.projectPath,
gitdir: this.gitDir,
filepaths: pkgDirs,
ignored: true,
filter: (f) =>
// no hidden files
!f.includes(`${path.sep}.`) &&
// no lwc tests
excludeLwcLocalOnlyTest(f) &&
// no gitignore files
!f.endsWith('.gitignore') &&
// isogit uses `startsWith` for filepaths so it's possible to get a false positive
pkgDirs.some(folderContainsPath(f)),
});
// Check for moved files and update local git status accordingly
if (env.getBoolean('SF_BETA_TRACK_FILE_MOVES') === true) {
await Lifecycle.getInstance().emitTelemetry({ eventName: 'moveFileDetectionEnabled' });
await this.detectMovedFiles();
} else {
// Adding this telemetry for easier tracking of how many users are using the beta feature
// This telemetry even will remain when the feature is GA and we switch to opt-out
await Lifecycle.getInstance().emitTelemetry({ eventName: 'moveFileDetectionDisabled' });
}
} catch (e) {
redirectToCliRepoError(e);
}
// isomorphic-git stores things in unix-style tree. Convert to windows-style if necessary
if (this.isWindows) {
this.status = this.status.map((row) => [path.normalize(row[FILE]), row[HEAD], row[WORKDIR], row[3]]);
}
marker?.stop();
}
this.logger.trace(`done: getStatus (noCache = ${noCache})`);
return this.status;
}
/**
* returns any change (add, modify, delete)
*/
public async getChangedRows(): Promise<StatusRow[]> {
return (await this.getStatus()).filter((file) => file[HEAD] !== file[WORKDIR]);
}
/**
* returns any change (add, modify, delete)
*/
public async getChangedFilenames(): Promise<string[]> {
return toFilenames(await this.getChangedRows());
}
public async getDeletes(): Promise<StatusRow[]> {
return (await this.getStatus()).filter(isDeleted);
}
public async getDeleteFilenames(): Promise<string[]> {
return toFilenames(await this.getDeletes());
}
/**
* returns adds and modifies but not deletes
*/
public async getNonDeletes(): Promise<StatusRow[]> {
return (await this.getStatus()).filter((file) => file[WORKDIR] === 2);
}
/**
* returns adds and modifies but not deletes
*/
public async getNonDeleteFilenames(): Promise<string[]> {
return toFilenames(await this.getNonDeletes());
}
public async getAdds(): Promise<StatusRow[]> {
return (await this.getStatus()).filter(isAdded);
}
public async getAddFilenames(): Promise<string[]> {
return toFilenames(await this.getAdds());
}
/**
* returns files that were not added or deleted, but changed locally
*/
public async getModifies(): Promise<StatusRow[]> {
return (await this.getStatus()).filter((file) => file[HEAD] === 1 && file[WORKDIR] === 2);
}
public async getModifyFilenames(): Promise<string[]> {
return toFilenames(await this.getModifies());
}
/**
* Look through status and stage all changes, then commit
*
* @param fileList list of files to commit (full paths)
* @param message: commit message (include org username and id)
*
* @returns sha (string)
*/
public async commitChanges({
deployedFiles = [],
deletedFiles = [],
message = 'sfdx source tracking',
needsUpdatedStatus = true,
}: CommitRequest = {}): Promise<string | undefined> {
// if no files are specified, commit all changes
if (deployedFiles.length === 0 && deletedFiles.length === 0) {
// this is valid, might not be an error
return 'no files to commit';
}
const marker = Performance.mark('@salesforce/source-tracking', 'localShadowRepo.commitChanges', {
deployedFiles: deployedFiles.length,
deletedFiles: deletedFiles.length,
});
if (deployedFiles.length) {
const chunks = chunkArray(
// these are stored in posix/style/path format. We have to convert inbound stuff from windows
[...new Set(this.isWindows ? deployedFiles.map(normalize).map(ensurePosix) : deployedFiles)],
this.maxFileAdd
);
for (const chunk of chunks) {
try {
this.logger.debug(`adding ${chunk.length} files of ${deployedFiles.length} deployedFiles to git`);
// these need to be done sequentially (it's already batched) because isogit manages file locking
// eslint-disable-next-line no-await-in-loop
await git.add({
fs,
dir: this.projectPath,
gitdir: this.gitDir,
filepath: chunk,
force: true,
});
} catch (e) {
if (e instanceof git.Errors.MultipleGitError) {
this.logger.error(`${e.errors.length} errors on git.add, showing the first 5:`, e.errors.slice(0, 5));
throw SfError.create({
message: e.message,
name: e.name,
data: e.errors.map((err) => err.message),
cause: e,
actions: [
`One potential reason you're getting this error is that the number of files that source tracking is batching exceeds your user-specific file limits. Increase your hard file limit in the same session by executing 'ulimit -Hn ${this.maxFileAdd}'. Or set the 'SFDX_SOURCE_TRACKING_BATCH_SIZE' environment variable to a value lower than the output of 'ulimit -Hn'.\nNote: Don't set this environment variable too close to the upper limit or your system will still hit it. If you continue to get the error, lower the value of the environment variable even more.`,
],
});
}
redirectToCliRepoError(e);
}
}
}
if (deletedFiles.length) {
// Using a cache here speeds up the performance by ~24.4%
let cache = {};
const deleteMarker = Performance.mark('@salesforce/source-tracking', 'localShadowRepo.commitChanges#delete', {
deletedFiles: deletedFiles.length,
});
for (const filepath of [
...new Set(this.isWindows ? deletedFiles.map(normalize).map(ensurePosix) : deletedFiles),
]) {
try {
// these need to be done sequentially because isogit manages file locking. Isogit remove does not support multiple files at once
// eslint-disable-next-line no-await-in-loop
await git.remove({ fs, dir: this.projectPath, gitdir: this.gitDir, filepath, cache });
} catch (e) {
redirectToCliRepoError(e);
}
}
// clear cache
cache = {};
deleteMarker?.stop();
}
try {
this.logger.trace('start: commitChanges git.commit');
const sha = await git.commit({
fs,
dir: this.projectPath,
gitdir: this.gitDir,
message,
author: { name: 'sfdx source tracking' },
});
// status changed as a result of the commit. This prevents users from having to run getStatus(true) to avoid cache
if (needsUpdatedStatus) {
await this.getStatus(true);
}
this.logger.trace('done: commitChanges git.commit');
return sha;
} catch (e) {
redirectToCliRepoError(e);
}
marker?.stop();
}
private async detectMovedFiles(): Promise<void> {
const { addedFilenamesWithMatches, deletedFilenamesWithMatches } = getMatches(await this.getStatus()) ?? {};
if (!addedFilenamesWithMatches || !deletedFilenamesWithMatches) return;
const movedFilesMarker = Performance.mark('@salesforce/source-tracking', 'localShadowRepo.detectMovedFiles');
// Track how long it takes to gather the oid information from the git trees
const getInfoMarker = Performance.mark('@salesforce/source-tracking', 'localShadowRepo.detectMovedFiles#getInfo', {
addedFiles: addedFilenamesWithMatches.length,
deletedFiles: deletedFilenamesWithMatches.length,
});
const getInfo = async (targetTree: Walker, filenameSet: Set<string>): Promise<FileInfo[]> =>
// Unable to properly type the return value of git.walk without using "as", ignoring linter
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
git.walk({
fs,
dir: this.projectPath,
gitdir: this.gitDir,
trees: [targetTree],
map: async (filename, [tree]) =>
filenameSet.has(filename) && (await tree?.type()) === 'blob'
? {
filename,
hash: await tree?.oid(),
basename: path.basename(filename),
}
: undefined,
});
// We found file adds and deletes with the same basename
// The have likely been moved, confirm by comparing their hashes (oids)
const [addedInfo, deletedInfo] = await Promise.all([
getInfo(git.WORKDIR(), new Set(addedFilenamesWithMatches)),
getInfo(git.TREE({ ref: 'HEAD' }), new Set(deletedFilenamesWithMatches)),
]);
getInfoMarker?.stop();
const matchingNameAndHashes = compareHashes(await buildMaps(addedInfo, deletedInfo));
if (matchingNameAndHashes.size === 0) {
return movedFilesMarker?.stop();
}
const matches = removeNonMatches(matchingNameAndHashes, this.registry, this.isWindows);
if (matches.size === 0) {
return movedFilesMarker?.stop();
}
this.logger.debug(
[
'Files have moved. Committing moved files:',
[...matches.entries()].map(([add, del]) => `- File ${del} was moved to ${add}`).join(os.EOL),
].join(os.EOL)
);
movedFilesMarker?.addDetails({ filesMoved: matches.size });
// Commit the moved files and refresh the status
await this.commitChanges({
deletedFiles: [...matches.values()],
deployedFiles: [...matches.keys()],
message: 'Committing moved files',
});
movedFilesMarker?.stop();
}
}
const packageDirToRelativePosixPath =
(isWindows: boolean) =>
(projectPath: string) =>
(packageDir: NamedPackageDir): string =>
isWindows
? ensurePosix(path.relative(projectPath, packageDir.fullPath))
: path.relative(projectPath, packageDir.fullPath);
const normalize = (filepath: string): string => path.normalize(filepath);
const ensureWindows = (filepath: string): string => path.win32.normalize(filepath);
const ensurePosix = (filepath: string): string => filepath.split(path.sep).join(path.posix.sep);
const buildMap = (info: FileInfo[]): StringMap[] => {
const map: StringMap = new Map();
const ignore: StringMap = new Map();
info.forEach((i) => {
const key = `${i.hash}#${i.basename}`;
// If we find a duplicate key, we need to remove it and ignore it in the future.
// Finding duplicate hash#basename means that we cannot accurately determine where it was moved to or from
if (map.has(key) || ignore.has(key)) {
map.delete(key);
ignore.set(key, i.filename);
} else {
map.set(key, i.filename);
}
});
return [map, ignore];
};
/** compare delete and adds from git.status, matching basenames of the files. returns early when there's nothing to match */
const getMatches = (
status: StatusRow[]
): { deletedFilenamesWithMatches: string[]; addedFilenamesWithMatches: string[] } | undefined => {
// We check for moved files in incremental steps and exit as early as we can to avoid any performance degradation
// Deleted files will be more rare than added files, so we'll check them first and exit early if there are none
const deletedFiles = status.filter(isDeleted);
if (!deletedFiles.length) return;
const addedFiles = status.filter(isAdded);
if (!addedFiles.length) return;
// Both arrays have contents, look for matching basenames
const addedFilenames = toFilenames(addedFiles);
const deletedFilenames = toFilenames(deletedFiles);
// Build Sets of basenames for added and deleted files for quick lookups
const addedBasenames = new Set(addedFilenames.map((filename) => path.basename(filename)));
const deletedBasenames = new Set(deletedFilenames.map((filename) => path.basename(filename)));
// Again, we filter over the deleted files first and exit early if there are no filename matches
const deletedFilenamesWithMatches = deletedFilenames.filter((f) => addedBasenames.has(path.basename(f)));
if (!deletedFilenamesWithMatches.length) return;
const addedFilenamesWithMatches = addedFilenames.filter((f) => deletedBasenames.has(path.basename(f)));
if (!addedFilenamesWithMatches.length) return;
return { addedFilenamesWithMatches, deletedFilenamesWithMatches };
};
const isDeleted = (status: StatusRow): boolean => status[WORKDIR] === 0;
const isAdded = (status: StatusRow): boolean => status[HEAD] === 0 && status[WORKDIR] === 2;
/** build maps of the add/deletes with filenames, returning the matches Logs if non-matches */
const buildMaps = async (addedInfo: FileInfo[], deletedInfo: FileInfo[]): Promise<AddAndDeleteMaps> => {
const [addedMap, addedIgnoredMap] = buildMap(addedInfo);
const [deletedMap, deletedIgnoredMap] = buildMap(deletedInfo);
// If we detected any files that have the same basename and hash, emit a warning and send telemetry
// These files will still show up as expected in the `sf project deploy preview` output
// We could add more logic to determine and display filepaths that we ignored...
// but this is likely rare enough to not warrant the added complexity
// Telemetry will help us determine how often this occurs
if (addedIgnoredMap.size || deletedIgnoredMap.size) {
const message = 'Files were found that have the same basename and hash. Skipping the commit of these files';
const logger = Logger.childFromRoot('ShadowRepo.compareHashes');
logger.warn(message);
const lifecycle = Lifecycle.getInstance();
await Promise.all([
lifecycle.emitWarning(message),
lifecycle.emitTelemetry({ eventName: 'moveFileHashBasenameCollisionsDetected' }),
]);
}
return { addedMap, deletedMap };
};
/** builds a map of the values from both maps */
const compareHashes = ({ addedMap, deletedMap }: AddAndDeleteMaps): StringMap => {
const matches: StringMap = new Map();
for (const [addedKey, addedValue] of addedMap) {
const deletedValue = deletedMap.get(addedKey);
if (deletedValue) {
matches.set(addedValue, deletedValue);
}
}
return matches;
};
const resolveType = (resolver: MetadataResolver, filenames: string[]): SourceComponent[] =>
filenames
.flatMap((filename) => {
try {
return resolver.getComponentsFromPath(filename);
} catch (e) {
const logger = Logger.childFromRoot('ShadowRepo.compareTypes');
logger.warn(`unable to resolve ${filename}`);
return undefined;
}
})
.filter(sourceComponentGuard);
const removeNonMatches = (matches: StringMap, registry: RegistryAccess, isWindows: boolean): StringMap => {
const addedFiles = isWindows ? [...matches.keys()].map(ensureWindows) : [...matches.keys()];
const deletedFiles = isWindows ? [...matches.values()].map(ensureWindows) : [...matches.values()];
const resolverAdded = new MetadataResolver(registry, VirtualTreeContainer.fromFilePaths(addedFiles));
const resolverDeleted = new MetadataResolver(registry, VirtualTreeContainer.fromFilePaths(deletedFiles));
return new Map(
[...matches.entries()].filter(([addedFile, deletedFile]) => {
// we're only ever using the first element of the arrays
const [resolvedAdded] = resolveType(resolverAdded, isWindows ? [ensureWindows(addedFile)] : [addedFile]);
const [resolvedDeleted] = resolveType(resolverDeleted, isWindows ? [ensureWindows(deletedFile)] : [deletedFile]);
return (
// they could match, or could both be undefined (because unresolved by SDR)
resolvedAdded?.type.name === resolvedDeleted?.type.name &&
// parent names match, if resolved and there are parents
resolvedAdded?.parent?.name === resolvedDeleted?.parent?.name &&
// parent types match, if resolved and there are parents
resolvedAdded?.parent?.type.name === resolvedDeleted?.parent?.type.name
);
})
);
};