mirror of
https://github.com/SukkaW/Surge.git
synced 2026-01-28 17:41:54 +08:00
Chore: migrate fileEqual to use foxts util
This commit is contained in:
@@ -5,80 +5,9 @@ import picocolors from 'picocolors';
|
||||
import type { Span } from '../trace';
|
||||
import { readFileByLine } from './fetch-text-by-line';
|
||||
import { writeFile } from './misc';
|
||||
import { invariant } from 'foxts/guard';
|
||||
import { createCompareSource, fileEqualWithCommentComparator } from 'foxts/compare-source';
|
||||
|
||||
export async function fileEqual(linesA: string[], source: AsyncIterable<string> | Iterable<string>): Promise<boolean> {
|
||||
if (linesA.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const aLen = linesA.length;
|
||||
|
||||
const maxIndexA = aLen - 1;
|
||||
let index = -1;
|
||||
|
||||
const iterator = Symbol.asyncIterator in source
|
||||
? source[Symbol.asyncIterator]()
|
||||
: (
|
||||
Symbol.iterator in source
|
||||
? source[Symbol.iterator]()
|
||||
: null
|
||||
);
|
||||
|
||||
invariant(iterator, 'source must be iterable or async iterable');
|
||||
|
||||
let result = await iterator.next();
|
||||
let lineB: string = result.value;
|
||||
|
||||
while (!result.done) {
|
||||
index++;
|
||||
|
||||
// b become bigger
|
||||
if (index === aLen) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const lineA = linesA[index];
|
||||
|
||||
if (lineA.length === 0) {
|
||||
if (lineB.length === 0) {
|
||||
// eslint-disable-next-line no-await-in-loop -- sequential
|
||||
result = await iterator.next();
|
||||
lineB = result.value;
|
||||
continue;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const aFirstChar = lineA.charCodeAt(0);
|
||||
if (aFirstChar !== lineB.charCodeAt(0)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Now both line has the same first char
|
||||
// We only need to compare one of them
|
||||
if (
|
||||
aFirstChar === 35 // #
|
||||
|| aFirstChar === 33 // !
|
||||
) {
|
||||
// eslint-disable-next-line no-await-in-loop -- sequential
|
||||
result = await iterator.next();
|
||||
lineB = result.value;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (lineA !== lineB) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line no-await-in-loop -- sequential
|
||||
result = await iterator.next();
|
||||
lineB = result.value;
|
||||
}
|
||||
|
||||
// b is not smaller than a
|
||||
return index === maxIndexA;
|
||||
}
|
||||
export const fileEqual = createCompareSource(fileEqualWithCommentComparator);
|
||||
|
||||
export async function compareAndWriteFile(span: Span, linesA: string[], filePath: string) {
|
||||
const isEqual = await span.traceChildAsync(`compare ${filePath}`, async () => {
|
||||
|
||||
Reference in New Issue
Block a user