MCPcopy
hub / github.com/SukkaW/Surge / compareAndWriteFile

Function compareAndWriteFile

Build/lib/create-file.ts:13–55  ·  view source on GitHub ↗
(span: Span, linesA: string[], filePath: string)

Source from the content-addressed store, hash-verified

11export const fileEqual = createCompareSource(fileEqualWithCommentComparator);
12
13export async function compareAndWriteFile(span: Span, linesA: string[], filePath: string) {
14 // readFileByLine will not include last empty line. So we always pop the linesA for comparison purpose
15 if (linesA.length > 0 && linesA[linesA.length - 1] === '') {
16 linesA.pop();
17 }
18
19 const isEqual = await span.traceChildAsync(`compare ${filePath}`, async () => {
20 if (fs.existsSync(filePath)) {
21 return fileEqual(linesA, readFileByLine(filePath));
22 }
23
24 console.log(`${filePath} does not exists, writing...`);
25 return false;
26 });
27
28 if (isEqual) {
29 console.log(picocolors.gray(picocolors.dim(`same content, bail out writing: ${filePath}`)));
30 return;
31 }
32
33 return span.traceChildAsync<void>(`writing ${filePath}`, async () => {
34 const linesALen = linesA.length;
35
36 // The default highwater mark is normally 16384,
37 // So we make sure direct write to file if the content is
38 // most likely less than 250 lines
39 if (linesALen < 250) {
40 return writeFile(filePath, fastStringArrayJoin(linesA, '\n'));
41 }
42
43 const writeStream = fs.createWriteStream(filePath);
44 for (let i = 0; i < linesALen; i++) {
45 const p = asyncWriteToStream(writeStream, linesA[i] + '\n');
46 // eslint-disable-next-line no-await-in-loop -- stream high water mark
47 if (p) await p;
48 }
49 await new Promise<void>(resolve => {
50 // Since we previously poped the last empty line for comparison, we need to add it back here to ensure final EOF line
51 writeStream.end(resolve);
52 });
53 await promisify(writeStream.close.bind(writeStream))();
54 });
55}

Calls 2

readFileByLineFunction · 0.90
writeFileFunction · 0.90

Tested by

no test coverage detected