dir-analysis-tool 3.4.0 → 3.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -715,1207 +715,1254 @@ function emptyTypeStats() {
715
715
  }
716
716
  };
717
717
  }
718
- // src/core/duplicates.ts
719
- /** Files up to this size are read in one call and hashed in full straight away. */
720
- const SAMPLE_THRESHOLD = 262144;
721
- /** Bytes read from each end of a larger file for its sample hash. */
722
- const SAMPLE_BYTES = 65536;
723
- const READ_BUFFER_BYTES = 524288;
724
- const ALGORITHM = "sha256";
718
+ // src/core/limiter.ts
725
719
  /**
726
- * Finds files with identical contents among groups of same-sized files.
727
- *
728
- * Work is staged so most files are never read in full:
729
- * 1. Only sizes shared by at least two distinct inodes are considered.
730
- * 2. Large files are first compared by a sample hash of their first and
731
- * last 64 KiB, which separates almost all non-duplicates cheaply.
732
- * 3. Survivors (and small files) get a full SHA-256.
720
+ * A tiny concurrency limiter for filesystem work.
733
721
  *
734
- * Groups are hashed independently and finished as soon as their last member
735
- * is done, so memory holds only the groups in flight plus the results.
722
+ * Tasks run at most `concurrency` at a time. Pending tasks are taken
723
+ * last-in-first-out, which makes a directory walk proceed depth-first and
724
+ * keeps the pending queue small even on very wide trees.
736
725
  */
737
- async function findDuplicates(sizeGroups, options) {
738
- const small = [];
739
- const large = [];
740
- for (const group of sizeGroups) {
741
- const distinct = distinctInodes(group);
742
- if (distinct.length < 2) continue;
743
- (distinct[0].bytes <= SAMPLE_THRESHOLD ? small : large).push(distinct);
726
+ var Limiter = class {
727
+ #concurrency;
728
+ #queue = [];
729
+ #active = 0;
730
+ #failure = void 0;
731
+ #failed = false;
732
+ #idle = null;
733
+ constructor(concurrency) {
734
+ if (!Number.isInteger(concurrency) || concurrency < 1) throw new RangeError(`concurrency must be a positive integer (got ${concurrency})`);
735
+ this.#concurrency = concurrency;
744
736
  }
745
- const buffers = new BufferPool();
746
- const sampled = await hashStage(large, "sample", options, buffers);
747
- for (const group of sampled) small.push(group.members);
748
- return hashStage(small, "full", options, buffers);
749
- }
750
- async function hashStage(groups, stage, options, buffers) {
751
- let total = 0;
752
- for (const group of groups) total += group.length;
753
- const results = [];
754
- if (total === 0) return results;
755
- const { signal, onProgress } = options;
756
- let done = 0;
757
- onProgress?.({
758
- stage,
759
- done,
760
- total
761
- });
762
- const finish = (state) => {
763
- for (const [digest, members] of state.byHash) if (members.length > 1) results.push({
764
- hash: digest,
765
- bytes: state.bytes,
766
- members
767
- });
768
- };
769
- function* tasks() {
770
- for (const group of groups) {
771
- const state = {
772
- bytes: group[0].bytes,
773
- pending: group.length,
774
- byHash: /* @__PURE__ */ new Map()
775
- };
776
- for (const candidate of group) yield async () => {
777
- try {
778
- const path = options.pathOf(candidate);
779
- const digest = stage === "sample" ? await sampleHash(path, candidate.bytes, buffers) : await hashFileOfSize(path, candidate.bytes, buffers);
780
- const members = state.byHash.get(digest);
781
- if (members) members.push(candidate);
782
- else state.byHash.set(digest, [candidate]);
783
- } catch (error) {
784
- options.onError?.(candidate, error);
785
- } finally {
786
- done++;
787
- if (--state.pending === 0) finish(state);
788
- onProgress?.({
789
- stage,
790
- done,
791
- total
792
- });
793
- }
737
+ /** Schedules a task. Tasks are expected to handle their own errors; a thrown error aborts the run. */
738
+ run(task) {
739
+ if (this.#failed) return;
740
+ this.#queue.push(task);
741
+ this.#pump();
742
+ }
743
+ /** Resolves once every scheduled task, including tasks scheduled by tasks, has finished. */
744
+ idle() {
745
+ if (this.#failed) return Promise.reject(this.#failure);
746
+ if (this.#active === 0 && this.#queue.length === 0) return Promise.resolve();
747
+ return new Promise((resolve, reject) => {
748
+ this.#idle = {
749
+ resolve,
750
+ reject
794
751
  };
795
- }
752
+ });
796
753
  }
797
- await runLimited(tasks(), options.concurrency, signal);
798
- return results;
799
- }
800
- /**
801
- * Runs tasks from a lazy iterator with at most `concurrency` in flight, so a
802
- * million-file stage never materializes a million closures up front.
803
- */
804
- async function runLimited(tasks, concurrency, signal) {
805
- if (signal?.aborted) throw new AbortError();
806
- let aborted = false;
807
- const onAbort = () => {
808
- aborted = true;
809
- };
810
- signal?.addEventListener("abort", onAbort, { once: true });
811
- const worker = async () => {
812
- for (;;) {
813
- if (aborted) return;
814
- const next = tasks.next();
815
- if (next.done) return;
816
- await next.value();
817
- }
818
- };
819
- try {
820
- const workers = [];
821
- for (let i = 0; i < concurrency; i++) workers.push(worker());
822
- await Promise.all(workers);
823
- } finally {
824
- signal?.removeEventListener("abort", onAbort);
754
+ /** Stops scheduling new work and rejects `idle()` with `reason`. */
755
+ abort(reason) {
756
+ if (this.#failed) return;
757
+ this.#failed = true;
758
+ this.#failure = reason;
759
+ this.#queue.length = 0;
760
+ this.#idle?.reject(reason);
761
+ this.#idle = null;
825
762
  }
826
- if (aborted) throw new AbortError();
827
- }
828
- /** Streams a file through SHA-256 and returns the hex digest. */
829
- async function hashFile(path, buffer) {
830
- const hasher = createHash(ALGORITHM);
831
- const handle = await open(path, "r");
832
- try {
833
- const chunk = buffer ?? Buffer.allocUnsafe(READ_BUFFER_BYTES);
834
- let position = 0;
835
- for (;;) {
836
- const { bytesRead } = await handle.read(chunk, 0, chunk.length, position);
837
- if (bytesRead === 0) break;
838
- hasher.update(bytesRead === chunk.length ? chunk : chunk.subarray(0, bytesRead));
839
- position += bytesRead;
763
+ #pump() {
764
+ while (this.#active < this.#concurrency && this.#queue.length > 0) {
765
+ const task = this.#queue.pop();
766
+ this.#active++;
767
+ task().then(this.#onDone, this.#onError);
840
768
  }
841
- } finally {
842
- await handle.close();
843
- }
844
- return hasher.digest("hex");
845
- }
846
- /** Hashes a file whose size is known: one read for small files, streaming otherwise. */
847
- async function hashFileOfSize(path, size, buffers) {
848
- if (size <= SAMPLE_THRESHOLD) return hash(ALGORITHM, await readWhole(path), "hex");
849
- const buffer = buffers?.acquire();
850
- try {
851
- return await hashFile(path, buffer);
852
- } finally {
853
- if (buffer) buffers.release(buffer);
854
- }
855
- }
856
- function readWhole(path) {
857
- return new Promise((resolve, reject) => {
858
- readFile(path, (error, data) => error ? reject(error) : resolve(data));
859
- });
860
- }
861
- async function sampleHash(path, size, buffers) {
862
- const hasher = createHash(ALGORITHM);
863
- const buffer = buffers.acquire();
864
- const handle = await open(path, "r");
865
- try {
866
- for (const position of [0, Math.max(0, size - SAMPLE_BYTES)]) {
867
- const { bytesRead } = await handle.read(buffer, 0, SAMPLE_BYTES, position);
868
- hasher.update(buffer.subarray(0, bytesRead));
769
+ if (this.#active === 0 && this.#queue.length === 0 && this.#idle) {
770
+ const idle = this.#idle;
771
+ this.#idle = null;
772
+ idle.resolve();
869
773
  }
870
- } finally {
871
- buffers.release(buffer);
872
- await handle.close();
873
774
  }
874
- return hasher.digest("hex");
775
+ #onDone = () => {
776
+ this.#active--;
777
+ this.#pump();
778
+ };
779
+ #onError = (error) => {
780
+ this.#active--;
781
+ this.abort(error);
782
+ };
783
+ };
784
+ // src/core/paths.ts
785
+ /** Ordinal comparison, so output order never depends on the locale. */
786
+ function comparePaths(a, b) {
787
+ return a < b ? -1 : a > b ? 1 : 0;
875
788
  }
876
- function distinctInodes(group) {
877
- if (group.length < 2) return group;
878
- const seen = /* @__PURE__ */ new Set();
879
- return group.filter((candidate) => {
880
- const key = `${candidate.dev}:${candidate.ino}`;
881
- if (seen.has(key)) return false;
882
- seen.add(key);
883
- return true;
884
- });
789
+ /** Joins an absolute native directory and a `/`-separated relative path. */
790
+ function joinRelative(root, relative) {
791
+ if (!relative) return root;
792
+ const native = sep === "/" ? relative : relative.replaceAll("/", sep);
793
+ return root.endsWith(sep) ? root + native : root + sep + native;
885
794
  }
886
- /** Reuses read buffers so streaming large files allocates a fixed amount of memory. */
887
- var BufferPool = class {
888
- #free = [];
889
- acquire() {
890
- return this.#free.pop() ?? Buffer.allocUnsafe(READ_BUFFER_BYTES);
891
- }
892
- release(buffer) {
893
- this.#free.push(buffer);
894
- }
895
- };
896
- // src/core/gitignore.ts
795
+ const IS_WINDOWS = process.platform === "win32";
897
796
  /**
898
- * The compiled rules of one ignore file.
797
+ * Concurrent directory walker.
899
798
  *
900
- * `test()` returns `true` when the last matching rule ignores the path,
901
- * `false` when it un-ignores it, and `undefined` when no rule matches, so
902
- * several files can be chained with Git's precedence.
799
+ * Reads directories with `readdir({ withFileTypes })` so directory entries
800
+ * never need a `stat`; regular files are `lstat`ed exactly once. All
801
+ * filesystem calls go through one {@link Limiter}, so concurrency stays
802
+ * bounded no matter how wide the tree is. Results are independent of
803
+ * scheduling order: callers sort what they report.
903
804
  */
904
- var GitignoreMatcher = class GitignoreMatcher {
905
- #runs;
906
- #ignoreCase;
907
- constructor(runs, ignoreCase) {
908
- this.#runs = runs;
909
- this.#ignoreCase = ignoreCase;
910
- }
911
- /** True when the file contains at least one rule. */
912
- get hasRules() {
913
- return this.#runs.length > 0;
914
- }
915
- /**
916
- * @param path Path relative to the ignore file's directory, `/`-separated,
917
- * without leading or trailing slashes.
918
- */
919
- test(path, isDirectory) {
920
- const runs = this.#runs;
921
- let name;
922
- let folded;
923
- let foldedPath;
924
- for (let i = runs.length - 1; i >= 0; i--) {
925
- const run = runs[i];
926
- const fast = isDirectory && run.dirFast !== null ? true : run.anyFast !== null;
927
- const byName = run.anyName !== null || isDirectory && run.dirName !== null;
928
- if (fast || byName) {
929
- name ??= path.slice(path.lastIndexOf("/") + 1);
930
- if (fast) {
931
- folded ??= this.#ignoreCase ? name.toLowerCase() : name;
932
- if (run.anyFast?.has(folded) || isDirectory && run.dirFast?.has(folded)) return !run.negated;
933
- }
934
- if (run.anyName?.test(name) || isDirectory && run.dirName?.test(name)) return !run.negated;
935
- }
936
- if (run.anyPath?.test(path) || isDirectory && run.dirPath?.test(path)) return !run.negated;
937
- if (run.globs !== null) {
938
- name ??= path.slice(path.lastIndexOf("/") + 1);
939
- for (const glob of run.globs) {
940
- if (glob.dirOnly && !isDirectory) continue;
941
- if (this.#ignoreCase) {
942
- if (!(glob.nameOnly ? folded ??= name.toLowerCase() : foldedPath ??= path.toLowerCase()).includes(glob.required)) continue;
943
- } else if (!(glob.nameOnly ? name : path).includes(glob.required)) continue;
944
- if (glob.matches(glob.nameOnly ? name : path)) return !run.negated;
945
- }
946
- }
805
+ var Scanner = class {
806
+ dirs = [];
807
+ errors = [];
808
+ counters = {
809
+ files: 0,
810
+ bytes: 0,
811
+ diskBytes: 0,
812
+ directories: 0,
813
+ symlinks: 0,
814
+ hardlinks: 0,
815
+ excluded: 0,
816
+ filtered: 0,
817
+ errors: 0
818
+ };
819
+ #options;
820
+ #visitor;
821
+ #limiter;
822
+ #filtersActive;
823
+ /** `dev:ino` of files with several links (or of every file when following symlinks). */
824
+ #seenInodes = /* @__PURE__ */ new Set();
825
+ /** `dev:ino` of entered directories, tracked only when following symlinks. */
826
+ #seenDirs = /* @__PURE__ */ new Set();
827
+ constructor(options, visitor) {
828
+ this.#options = options;
829
+ this.#visitor = visitor;
830
+ this.#limiter = new Limiter(options.concurrency);
831
+ this.#filtersActive = options.minSize > 0 || options.maxSize < Infinity || options.modifiedAfter > -Infinity || options.modifiedBefore < Infinity;
832
+ }
833
+ async run() {
834
+ const { root, signal, excluder } = this.#options;
835
+ if (signal?.aborted) throw new AbortError();
836
+ const rootStats = await stat(root);
837
+ if (this.#options.followSymlinks) this.#seenDirs.add(await inodeKey(rootStats, root));
838
+ const chain = await excluder.loadAncestorChain(root);
839
+ const index = this.#addDir("", -1, 0);
840
+ const onAbort = () => this.#limiter.abort(new AbortError());
841
+ signal?.addEventListener("abort", onAbort, { once: true });
842
+ try {
843
+ this.#limiter.run(() => this.#scanDir(index, root, chain));
844
+ await this.#limiter.idle();
845
+ } finally {
846
+ signal?.removeEventListener("abort", onAbort);
947
847
  }
948
848
  }
949
- /** Compiles the contents of an ignore file (or a list of patterns). */
950
- static compile(source, options = {}) {
951
- const lines = typeof source === "string" ? splitRuleLines(source) : source;
952
- const ignoreCase = options.ignoreCase === true;
953
- const flags = ignoreCase ? "i" : "";
954
- const runs = [];
955
- let negated = false;
956
- let parts = new RunParts();
957
- const regex = (sources) => sources.length > 0 ? new RegExp(`^(?:${sources.join("|")})$`, flags) : null;
958
- const flush = () => {
959
- const run = {
960
- negated,
961
- anyFast: parts.anyFast.isEmpty ? null : parts.anyFast,
962
- dirFast: parts.dirFast.isEmpty ? null : parts.dirFast,
963
- anyName: regex(parts.anyName),
964
- dirName: regex(parts.dirName),
965
- anyPath: regex(parts.anyPath),
966
- dirPath: regex(parts.dirPath),
967
- globs: parts.globs.length > 0 ? parts.globs : null
968
- };
969
- if (run.anyFast || run.dirFast || run.anyName || run.dirName || run.anyPath || run.dirPath || run.globs) runs.push(run);
970
- parts = new RunParts();
849
+ /** Root-relative path of a directory (or of `name` inside it), with `/` separators. */
850
+ relativePath(dirIndex, name) {
851
+ const parts = name === void 0 ? [] : [name];
852
+ for (let i = dirIndex; i > 0; i = this.dirs[i].parent) parts.push(this.dirs[i].name);
853
+ return parts.toReversed().join("/");
854
+ }
855
+ absolutePath(dirIndex, name) {
856
+ return joinRelative(this.#options.root, this.relativePath(dirIndex, name));
857
+ }
858
+ #addDir(name, parent, depth) {
859
+ const node = {
860
+ name,
861
+ parent,
862
+ depth,
863
+ entries: 0,
864
+ ownFiles: 0,
865
+ ownBytes: 0,
866
+ ownDiskBytes: 0,
867
+ files: 0,
868
+ bytes: 0,
869
+ diskBytes: 0,
870
+ largestChild: 0
971
871
  };
972
- for (const line of lines) {
973
- const rule = parseRule(line);
974
- if (rule === null) continue;
975
- if (rule.negated !== negated) {
976
- flush();
977
- negated = rule.negated;
872
+ const index = this.dirs.push(node) - 1;
873
+ this.counters.directories++;
874
+ this.#visitor.directory?.(index, node);
875
+ return index;
876
+ }
877
+ async #scanDir(index, absPath, inherited) {
878
+ const { excluder } = this.#options;
879
+ let entries;
880
+ try {
881
+ entries = await readdir(absPath, { withFileTypes: true });
882
+ } catch (error) {
883
+ this.dirs[index].entries = -1;
884
+ this.recordError(this.relativePath(index), error);
885
+ return;
886
+ }
887
+ const node = this.dirs[index];
888
+ node.entries = entries.length;
889
+ if (entries.length === 0) return;
890
+ const relDir = excluder.needsPaths ? this.relativePath(index) : "";
891
+ let chain = inherited;
892
+ if (excluder.gitignore && entries.some((e) => e.name === ".gitignore" && !e.isDirectory())) {
893
+ const scope = await excluder.loadScope(joinNative(absPath, ".gitignore"), relDir);
894
+ if (scope) chain = [...inherited, scope];
895
+ }
896
+ const base = absPath.endsWith(sep) ? absPath : absPath + sep;
897
+ const checkExclusion = excluder.active;
898
+ for (const entry of entries) {
899
+ const name = entry.name;
900
+ const isDirectory = entry.isDirectory();
901
+ const isFile = !isDirectory && entry.isFile();
902
+ const isSymlink = !isDirectory && !isFile && entry.isSymbolicLink();
903
+ const isUnknown = !isDirectory && !isFile && !isSymlink && isUnknownType(entry);
904
+ if (!isDirectory && !isFile && !isSymlink && !isUnknown) continue;
905
+ if (checkExclusion) {
906
+ const rel = relDir ? `${relDir}/${name}` : name;
907
+ if (excluder.isExcluded(rel, name, isDirectory, chain)) {
908
+ this.counters.excluded++;
909
+ this.#options.onSkip?.({
910
+ kind: "excluded",
911
+ dir: index,
912
+ name,
913
+ isDirectory,
914
+ chain
915
+ });
916
+ continue;
917
+ }
978
918
  }
979
- if (rule.fast) {
980
- const target = rule.dirOnly ? parts.dirFast : parts.anyFast;
981
- const value = ignoreCase ? rule.fast.value.toLowerCase() : rule.fast.value;
982
- if (rule.fast.kind === "literal") target.literals.add(value);
983
- else target.addSuffix(value);
984
- } else if (rule.wildcards >= LINEAR_GLOB_WILDCARDS) parts.globs.push(new LinearGlob(rule, ignoreCase));
985
- else if (rule.nameOnly) (rule.dirOnly ? parts.dirName : parts.anyName).push(rule.source);
986
- else (rule.dirOnly ? parts.dirPath : parts.anyPath).push(rule.source);
919
+ const fullPath = base + name;
920
+ if (this.#options.directoriesOnly && !isDirectory) continue;
921
+ if (isDirectory && !this.#options.followSymlinks) this.#enterDir(index, name, fullPath, chain);
922
+ else if (isFile) this.#limiter.run(() => this.#statFile(index, name, fullPath));
923
+ else this.#limiter.run(() => this.#resolveEntry(index, name, fullPath, chain, isSymlink, isDirectory));
987
924
  }
988
- flush();
989
- return new GitignoreMatcher(runs, ignoreCase);
990
925
  }
991
- };
992
- /** Exact names and `*suffix` rules of one run, matched with hash lookups. */
993
- var FastNames = class {
994
- literals = /* @__PURE__ */ new Set();
995
- /** Suffixes keyed by their last character, so a name checks only a few. */
996
- #suffixes = /* @__PURE__ */ new Map();
997
- get isEmpty() {
998
- return this.literals.size === 0 && this.#suffixes.size === 0;
999
- }
1000
- addSuffix(suffix) {
1001
- const key = suffix[suffix.length - 1];
1002
- const list = this.#suffixes.get(key);
1003
- if (list) list.push(suffix);
1004
- else this.#suffixes.set(key, [suffix]);
1005
- }
1006
- has(name) {
1007
- if (this.literals.has(name)) return true;
1008
- if (name === "") return false;
1009
- const list = this.#suffixes.get(name[name.length - 1]);
1010
- if (list === void 0) return false;
1011
- for (const suffix of list) if (name.endsWith(suffix)) return true;
1012
- return false;
926
+ #enterDir(parent, name, fullPath, chain) {
927
+ const depth = this.dirs[parent].depth + 1;
928
+ if (depth > this.#options.maxDepth) {
929
+ this.#options.onSkip?.({
930
+ kind: "depth",
931
+ dir: parent,
932
+ name,
933
+ depth
934
+ });
935
+ return;
936
+ }
937
+ const child = this.#addDir(name, parent, depth);
938
+ this.#limiter.run(() => this.#scanDir(child, fullPath, chain));
1013
939
  }
1014
- };
1015
- var RunParts = class {
1016
- anyFast = new FastNames();
1017
- dirFast = new FastNames();
1018
- anyName = [];
1019
- dirName = [];
1020
- anyPath = [];
1021
- dirPath = [];
1022
- globs = [];
1023
- };
1024
- const STAR = { kind: "star" };
1025
- const ALL = { kind: "all" };
1026
- const DIRS = { kind: "dirs" };
1027
- const ANY = { kind: "any" };
1028
- /** Rules with at least this many wildcards use {@link LinearGlob}. */
1029
- const LINEAR_GLOB_WILDCARDS = 2;
1030
- function isWildcard(token) {
1031
- return token.kind === "star" || token.kind === "all" || token.kind === "dirs";
1032
- }
1033
- /** JavaScript's `.` skips line breaks, so these use `[^]`, which matches any character. */
1034
- function tokenSource(token) {
1035
- switch (token.kind) {
1036
- case "char": return escapeRegex(token.char);
1037
- case "class": return token.source;
1038
- case "any": return "[^/]";
1039
- case "star": return "[^/]*";
1040
- case "all": return "[^]*";
1041
- case "dirs": return "(?:[^]*/)?";
940
+ async #statFile(dirIndex, name, fullPath) {
941
+ let stats;
942
+ try {
943
+ stats = await lstat(fullPath);
944
+ } catch (error) {
945
+ this.recordError(this.relativePath(dirIndex, name), error);
946
+ return;
947
+ }
948
+ const pending = this.#acceptFile(dirIndex, name, fullPath, stats);
949
+ if (pending) await pending;
1042
950
  }
1043
- }
1044
- const CHAR = 0;
1045
- const CLASS = 1;
1046
- const ANY_CHAR = 2;
1047
- const ANY_RUN = 3;
1048
- const ALL_RUN = 4;
1049
- const OPCODES = {
1050
- char: CHAR,
1051
- class: CLASS,
1052
- any: ANY_CHAR,
1053
- star: ANY_RUN,
1054
- all: ALL_RUN,
1055
- dirs: 5
1056
- };
1057
- /** The same case folding as a regular expression with the `i` flag. */
1058
- function foldCase(c) {
1059
- const upper = c.toUpperCase();
1060
- if (upper.length !== 1) return c;
1061
- return c.charCodeAt(0) >= 128 && upper.charCodeAt(0) < 128 ? c : upper;
1062
- }
1063
- /** The longest stretch of plain ASCII characters that a glob must match literally. */
1064
- function longestAsciiRun(tokens) {
1065
- let longest = "";
1066
- let run = "";
1067
- for (const token of tokens) if (token.kind === "char" && token.char.charCodeAt(0) < 128) {
1068
- run += token.char;
1069
- if (run.length > longest.length) longest = run;
1070
- } else run = "";
1071
- return longest;
1072
- }
1073
- /**
1074
- * Matches a parsed glob by tracking every position it could be at, one input
1075
- * character at a time. Nothing is ever retried, so the time is bounded by the
1076
- * length of the path times the length of the pattern, whatever the pattern is.
1077
- */
1078
- var LinearGlob = class {
1079
- dirOnly;
1080
- nameOnly;
1081
951
  /**
1082
- * Text every match must contain, in lower case when ignoring case. Only ASCII
1083
- * is used: a regular expression's `i` flag never folds other characters into
1084
- * ASCII, so lower-casing a path cannot hide or invent an occurrence of it.
952
+ * Handles symlinks, entries whose type the filesystem did not report, and
953
+ * (when following symlinks) directories, which then need their identity.
1085
954
  */
1086
- required;
1087
- #ops;
1088
- #chars;
1089
- #classes;
1090
- #accept;
1091
- #ignoreCase;
1092
- #current;
1093
- #next;
1094
- #nextCount = 0;
1095
- /** The step at which each position was last added, so it is added only once per step. */
1096
- #added;
1097
- /** The same for following a wildcard to the position after it. */
1098
- #skipped;
1099
- #step = 0;
1100
- constructor(rule, ignoreCase) {
1101
- const { tokens } = rule;
1102
- this.dirOnly = rule.dirOnly;
1103
- this.nameOnly = rule.nameOnly;
1104
- this.#ignoreCase = ignoreCase;
1105
- const required = longestAsciiRun(tokens);
1106
- this.required = ignoreCase ? required.toLowerCase() : required;
1107
- const size = tokens.length + 1;
1108
- this.#accept = tokens.length;
1109
- this.#ops = Uint8Array.from(tokens, (token) => OPCODES[token.kind]);
1110
- this.#chars = tokens.map((token) => {
1111
- if (token.kind !== "char") return "";
1112
- return ignoreCase ? foldCase(token.char) : token.char;
1113
- });
1114
- this.#classes = tokens.map((token) => token.kind === "class" ? new RegExp(`^${token.source}$`, ignoreCase ? "i" : "") : null);
1115
- this.#current = new Int32Array(size);
1116
- this.#next = new Int32Array(size);
1117
- this.#added = new Float64Array(size);
1118
- this.#skipped = new Float64Array(size);
1119
- }
1120
- matches(text) {
1121
- const ops = this.#ops;
1122
- const chars = this.#chars;
1123
- const accept = this.#accept;
1124
- this.#nextCount = 0;
1125
- this.#step++;
1126
- this.#add(0, true);
1127
- for (let i = 0; i < text.length; i++) {
1128
- const count = this.#nextCount;
1129
- if (count === 0) return false;
1130
- const current = this.#next;
1131
- this.#next = this.#current;
1132
- this.#current = current;
1133
- this.#nextCount = 0;
1134
- this.#step++;
1135
- const c = text[i];
1136
- const folded = this.#ignoreCase ? foldCase(c) : c;
1137
- for (let k = 0; k < count; k++) {
1138
- const position = current[k];
1139
- if (position === accept) continue;
1140
- switch (ops[position]) {
1141
- case CHAR:
1142
- if (folded === chars[position]) this.#add(position + 1, true);
1143
- break;
1144
- case CLASS:
1145
- if (this.#classes[position].test(c)) this.#add(position + 1, true);
1146
- break;
1147
- case ANY_CHAR:
1148
- if (c !== "/") this.#add(position + 1, true);
1149
- break;
1150
- case ANY_RUN:
1151
- if (c !== "/") this.#add(position, true);
1152
- break;
1153
- case ALL_RUN:
1154
- this.#add(position, true);
1155
- break;
1156
- default:
1157
- this.#add(position, false);
1158
- if (c === "/") this.#add(position + 1, true);
955
+ async #resolveEntry(dirIndex, name, fullPath, chain, isSymlink, checkedAsDirectory) {
956
+ let stats;
957
+ try {
958
+ stats = await lstat(fullPath);
959
+ if (stats.isSymbolicLink()) {
960
+ isSymlink = true;
961
+ if (!this.#options.followSymlinks) {
962
+ this.counters.symlinks++;
963
+ this.#options.onSkip?.({
964
+ kind: "symlink",
965
+ dir: dirIndex,
966
+ name
967
+ });
968
+ return;
969
+ }
970
+ stats = await stat(fullPath);
971
+ }
972
+ } catch (error) {
973
+ const code = errorCode(error);
974
+ if (isSymlink && (code === "ENOENT" || code === "ELOOP")) {
975
+ this.counters.symlinks++;
976
+ return;
977
+ }
978
+ this.recordError(this.relativePath(dirIndex, name), error);
979
+ return;
980
+ }
981
+ if (isSymlink) this.counters.symlinks++;
982
+ if (stats.isDirectory()) {
983
+ const { excluder } = this.#options;
984
+ if (excluder.active && !checkedAsDirectory) {
985
+ const rel = this.relativePath(dirIndex, name);
986
+ if (excluder.isExcluded(rel, name, true, chain)) {
987
+ this.counters.excluded++;
988
+ this.#options.onSkip?.({
989
+ kind: "excluded",
990
+ dir: dirIndex,
991
+ name,
992
+ isDirectory: true,
993
+ chain
994
+ });
995
+ return;
1159
996
  }
1160
997
  }
998
+ const key = await inodeKey(stats, fullPath);
999
+ if (this.#seenDirs.has(key)) return;
1000
+ this.#seenDirs.add(key);
1001
+ this.#enterDir(dirIndex, name, fullPath, chain);
1002
+ } else if (stats.isFile()) {
1003
+ const pending = this.#acceptFile(dirIndex, name, fullPath, stats);
1004
+ if (pending) await pending;
1161
1005
  }
1162
- return this.#added[accept] === this.#step;
1163
1006
  }
1164
- #add(position, arriving) {
1165
- const step = this.#step;
1166
- for (let at = position;; at++) {
1167
- if (this.#added[at] !== step) {
1168
- this.#added[at] = step;
1169
- this.#next[this.#nextCount++] = at;
1007
+ /**
1008
+ * Counts a file once per underlying data. Synchronous unless the file's
1009
+ * identity needs an exact (bigint) stat; see `inodeKey`.
1010
+ */
1011
+ #acceptFile(dirIndex, name, fullPath, stats) {
1012
+ if (!this.#options.countHardlinks && (stats.nlink > 1 || this.#options.followSymlinks)) {
1013
+ const key = inodeKey(stats, fullPath);
1014
+ if (typeof key !== "string") return key.then((exact) => this.#acceptKeyedFile(dirIndex, name, stats, exact));
1015
+ this.#acceptKeyedFile(dirIndex, name, stats, key);
1016
+ return;
1017
+ }
1018
+ this.#countFile(dirIndex, name, stats);
1019
+ }
1020
+ #acceptKeyedFile(dirIndex, name, stats, key) {
1021
+ if (this.#seenInodes.has(key)) {
1022
+ if (stats.nlink > 1) this.counters.hardlinks++;
1023
+ return;
1024
+ }
1025
+ this.#seenInodes.add(key);
1026
+ this.#countFile(dirIndex, name, stats);
1027
+ }
1028
+ #countFile(dirIndex, name, stats) {
1029
+ const size = stats.size;
1030
+ if (this.#filtersActive) {
1031
+ const o = this.#options;
1032
+ const mtime = stats.mtimeMs;
1033
+ if (size < o.minSize || size > o.maxSize || mtime < o.modifiedAfter || mtime > o.modifiedBefore) {
1034
+ this.counters.filtered++;
1035
+ o.onSkip?.({
1036
+ kind: "filtered",
1037
+ dir: dirIndex,
1038
+ name,
1039
+ stats
1040
+ });
1041
+ return;
1170
1042
  }
1171
- if (!arriving || at === this.#accept || this.#ops[at] < ANY_RUN) return;
1172
- if (this.#skipped[at] === step) return;
1173
- this.#skipped[at] = step;
1174
1043
  }
1044
+ const diskBytes = IS_WINDOWS || !(stats.blocks >= 0) ? size : stats.blocks * 512;
1045
+ const node = this.dirs[dirIndex];
1046
+ node.ownFiles++;
1047
+ node.ownBytes += size;
1048
+ node.ownDiskBytes += diskBytes;
1049
+ this.counters.files++;
1050
+ this.counters.bytes += size;
1051
+ this.counters.diskBytes += diskBytes;
1052
+ this.#visitor.file(dirIndex, name, stats, diskBytes);
1053
+ }
1054
+ /** Counts an error and keeps its details, up to {@link MAX_ERROR_DETAILS}. */
1055
+ recordError(path, error) {
1056
+ this.counters.errors++;
1057
+ if (this.errors.length >= 100) return;
1058
+ const code = errorCode(error);
1059
+ this.errors.push({
1060
+ path: path || ".",
1061
+ code: code ?? "UNKNOWN",
1062
+ message: (code && ERROR_DESCRIPTIONS[code]) ?? errorMessage(error)
1063
+ });
1175
1064
  }
1176
1065
  };
1177
- /** No wildcards, classes, or escapes: the pattern is a literal name (or suffix). */
1178
- const LITERAL = /^[^*?[\\]+$/;
1179
- /** A line ending; a final CR counts because Git treats the end of a file as a newline. */
1180
- const EOL = /\r?\n|\r$/;
1181
1066
  /**
1182
- * Splits an ignore file into lines as {@link GitignoreMatcher.compile} reads
1183
- * them, so index + 1 is the line number Git reports.
1067
+ * Rolls per-directory totals up the tree. Must run once, after the scan.
1068
+ * Relies on children always having larger indices than their parents.
1184
1069
  */
1185
- function splitRuleLines(source) {
1186
- return source.replace(/^\uFEFF/, "").split(EOL);
1070
+ function rollUp(dirs) {
1071
+ for (let i = dirs.length - 1; i >= 0; i--) {
1072
+ const node = dirs[i];
1073
+ node.files += node.ownFiles;
1074
+ node.bytes += node.ownBytes;
1075
+ node.diskBytes += node.ownDiskBytes;
1076
+ if (node.parent >= 0) {
1077
+ const parent = dirs[node.parent];
1078
+ parent.files += node.files;
1079
+ parent.bytes += node.bytes;
1080
+ parent.diskBytes += node.diskBytes;
1081
+ if (node.bytes > parent.largestChild) parent.largestChild = node.bytes;
1082
+ }
1083
+ }
1187
1084
  }
1188
- /** Removes unescaped trailing spaces. Tabs are significant, as they are in Git. */
1189
- function trimTrailingSpaces(line) {
1190
- let end = line.length;
1191
- let spaces = -1;
1192
- for (let i = 0; i < line.length; i++) if (line[i] === " ") {
1193
- if (spaces === -1) spaces = i;
1194
- } else {
1195
- if (line[i] === "\\") i++;
1196
- spaces = -1;
1085
+ /**
1086
+ * `dev:ino` identity of a file or directory. `Stats.ino` is a Number, which is
1087
+ * exact only up to 2^53; Windows NTFS file IDs keep a sequence number in their
1088
+ * top 16 bits and often exceed that, so neighboring files can round to the
1089
+ * same value. Those few get an exact bigint stat instead. Keys are only taken
1090
+ * for files and directories (a followed symlink is keyed by its target), so
1091
+ * the stat follows links.
1092
+ */
1093
+ function inodeKey(stats, path) {
1094
+ if (Number.isSafeInteger(stats.ino)) return `${stats.dev}:${stats.ino}`;
1095
+ return exactInodeKey(path);
1096
+ }
1097
+ /** `dev:ino` from a bigint stat, exact for any 64-bit file ID. */
1098
+ async function exactInodeKey(path) {
1099
+ const exact = await stat(path, { bigint: true });
1100
+ return `${exact.dev}:${exact.ino}`;
1101
+ }
1102
+ function joinNative(dir, name) {
1103
+ return dir.endsWith(sep) ? dir + name : dir + sep + name;
1104
+ }
1105
+ function isUnknownType(entry) {
1106
+ return !(entry.isBlockDevice() || entry.isCharacterDevice() || entry.isFIFO() || entry.isSocket());
1107
+ }
1108
+ const ERROR_DESCRIPTIONS = {
1109
+ EACCES: "permission denied",
1110
+ EPERM: "operation not permitted",
1111
+ ENOENT: "no longer exists",
1112
+ ELOOP: "too many levels of symbolic links",
1113
+ EMFILE: "too many open files",
1114
+ ENAMETOOLONG: "name too long",
1115
+ EIO: "input/output error",
1116
+ EBUSY: "resource busy"
1117
+ };
1118
+ // src/core/duplicates.ts
1119
+ /** Files up to this size are read in one call and hashed in full straight away. */
1120
+ const SAMPLE_THRESHOLD = 262144;
1121
+ /** Bytes read from each end of a larger file for its sample hash. */
1122
+ const SAMPLE_BYTES = 65536;
1123
+ const READ_BUFFER_BYTES = 524288;
1124
+ const ALGORITHM = "sha256";
1125
+ /**
1126
+ * Finds files with identical contents among groups of same-sized files.
1127
+ *
1128
+ * Work is staged so most files are never read in full:
1129
+ * 1. Only sizes shared by at least two distinct inodes are considered.
1130
+ * 2. Large files are first compared by a sample hash of their first and
1131
+ * last 64 KiB, which separates almost all non-duplicates cheaply.
1132
+ * 3. Survivors (and small files) get a full SHA-256.
1133
+ *
1134
+ * Groups are hashed independently and finished as soon as their last member
1135
+ * is done, so memory holds only the groups in flight plus the results.
1136
+ */
1137
+ async function findDuplicates(sizeGroups, options) {
1138
+ const small = [];
1139
+ const large = [];
1140
+ for (const group of sizeGroups) {
1141
+ const distinct = await distinctInodes(group, options.pathOf);
1142
+ if (distinct.length < 2) continue;
1143
+ (distinct[0].bytes <= SAMPLE_THRESHOLD ? small : large).push(distinct);
1144
+ }
1145
+ const buffers = new BufferPool();
1146
+ const sampled = await hashStage(large, "sample", options, buffers);
1147
+ for (const group of sampled) small.push(group.members);
1148
+ return hashStage(small, "full", options, buffers);
1149
+ }
1150
+ async function hashStage(groups, stage, options, buffers) {
1151
+ let total = 0;
1152
+ for (const group of groups) total += group.length;
1153
+ const results = [];
1154
+ if (total === 0) return results;
1155
+ const { signal, onProgress } = options;
1156
+ let done = 0;
1157
+ onProgress?.({
1158
+ stage,
1159
+ done,
1160
+ total
1161
+ });
1162
+ const finish = (state) => {
1163
+ for (const [digest, members] of state.byHash) if (members.length > 1) results.push({
1164
+ hash: digest,
1165
+ bytes: state.bytes,
1166
+ members
1167
+ });
1168
+ };
1169
+ function* tasks() {
1170
+ for (const group of groups) {
1171
+ const state = {
1172
+ bytes: group[0].bytes,
1173
+ pending: group.length,
1174
+ byHash: /* @__PURE__ */ new Map()
1175
+ };
1176
+ for (const candidate of group) yield async () => {
1177
+ try {
1178
+ const path = options.pathOf(candidate);
1179
+ const digest = stage === "sample" ? await sampleHash(path, candidate.bytes, buffers) : await hashFileOfSize(path, candidate.bytes, buffers);
1180
+ const members = state.byHash.get(digest);
1181
+ if (members) members.push(candidate);
1182
+ else state.byHash.set(digest, [candidate]);
1183
+ } catch (error) {
1184
+ options.onError?.(candidate, error);
1185
+ } finally {
1186
+ done++;
1187
+ if (--state.pending === 0) finish(state);
1188
+ onProgress?.({
1189
+ stage,
1190
+ done,
1191
+ total
1192
+ });
1193
+ }
1194
+ };
1195
+ }
1196
+ }
1197
+ await runLimited(tasks(), options.concurrency, signal);
1198
+ return results;
1199
+ }
1200
+ /**
1201
+ * Runs tasks from a lazy iterator with at most `concurrency` in flight, so a
1202
+ * million-file stage never materializes a million closures up front.
1203
+ */
1204
+ async function runLimited(tasks, concurrency, signal) {
1205
+ if (signal?.aborted) throw new AbortError();
1206
+ let aborted = false;
1207
+ const onAbort = () => {
1208
+ aborted = true;
1209
+ };
1210
+ signal?.addEventListener("abort", onAbort, { once: true });
1211
+ const worker = async () => {
1212
+ for (;;) {
1213
+ if (aborted) return;
1214
+ const next = tasks.next();
1215
+ if (next.done) return;
1216
+ await next.value();
1217
+ }
1218
+ };
1219
+ try {
1220
+ const workers = [];
1221
+ for (let i = 0; i < concurrency; i++) workers.push(worker());
1222
+ await Promise.all(workers);
1223
+ } finally {
1224
+ signal?.removeEventListener("abort", onAbort);
1225
+ }
1226
+ if (aborted) throw new AbortError();
1227
+ }
1228
+ /** Streams a file through SHA-256 and returns the hex digest. */
1229
+ async function hashFile(path, buffer) {
1230
+ const hasher = createHash(ALGORITHM);
1231
+ const handle = await open(path, "r");
1232
+ try {
1233
+ const chunk = buffer ?? Buffer.allocUnsafe(READ_BUFFER_BYTES);
1234
+ let position = 0;
1235
+ for (;;) {
1236
+ const { bytesRead } = await handle.read(chunk, 0, chunk.length, position);
1237
+ if (bytesRead === 0) break;
1238
+ hasher.update(bytesRead === chunk.length ? chunk : chunk.subarray(0, bytesRead));
1239
+ position += bytesRead;
1240
+ }
1241
+ } finally {
1242
+ await handle.close();
1197
1243
  }
1198
- if (spaces !== -1) end = spaces;
1199
- return line.slice(0, end);
1244
+ return hasher.digest("hex");
1200
1245
  }
1201
- /**
1202
- * Turns one gitignore line into a regex fragment. Returns `null` for blanks,
1203
- * comments, and malformed patterns, which Git treats as never matching.
1204
- */
1205
- function parseRule(line) {
1206
- let pattern = trimTrailingSpaces(line);
1207
- if (pattern === "" || pattern.startsWith("#")) return null;
1208
- let negated = false;
1209
- if (pattern.startsWith("!")) {
1210
- negated = true;
1211
- pattern = pattern.slice(1);
1212
- } else if (pattern.startsWith("\\!") || pattern.startsWith("\\#")) pattern = pattern.slice(1);
1213
- if (pattern === "") return null;
1214
- let dirOnly = false;
1215
- if (pattern.endsWith("/")) {
1216
- dirOnly = true;
1217
- pattern = pattern.slice(0, -1);
1218
- if (pattern === "") return null;
1219
- }
1220
- let anchored = false;
1221
- if (pattern.startsWith("/")) {
1222
- anchored = true;
1223
- pattern = pattern.slice(1);
1224
- } else if (pattern.includes("/")) anchored = true;
1225
- if (pattern.startsWith("**/")) {
1226
- anchored = false;
1227
- pattern = pattern.replace(/^(\*\*\/)+/, "");
1246
+ /** Hashes a file whose size is known: one read for small files, streaming otherwise. */
1247
+ async function hashFileOfSize(path, size, buffers) {
1248
+ if (size <= SAMPLE_THRESHOLD) return hash(ALGORITHM, await readWhole(path), "hex");
1249
+ const buffer = buffers?.acquire();
1250
+ try {
1251
+ return await hashFile(path, buffer);
1252
+ } finally {
1253
+ if (buffer) buffers.release(buffer);
1228
1254
  }
1229
- if (pattern === "") return null;
1230
- const body = parseGlob(pattern);
1231
- if (body === null) return null;
1232
- const nameOnly = !anchored && !pattern.includes("/") && !pattern.includes("**");
1233
- const tokens = anchored || nameOnly ? body : [DIRS, ...body];
1234
- const source = tokens.map(tokenSource).join("");
1235
- const wildcards = tokens.filter(isWildcard).length;
1236
- let fast = null;
1237
- if (nameOnly) {
1238
- if (LITERAL.test(pattern)) fast = {
1239
- kind: "literal",
1240
- value: pattern
1241
- };
1242
- else if (pattern.startsWith("*") && LITERAL.test(pattern.slice(1))) fast = {
1243
- kind: "suffix",
1244
- value: pattern.slice(1)
1245
- };
1255
+ }
1256
+ function readWhole(path) {
1257
+ return new Promise((resolve, reject) => {
1258
+ readFile(path, (error, data) => error ? reject(error) : resolve(data));
1259
+ });
1260
+ }
1261
+ async function sampleHash(path, size, buffers) {
1262
+ const hasher = createHash(ALGORITHM);
1263
+ const buffer = buffers.acquire();
1264
+ const handle = await open(path, "r");
1265
+ try {
1266
+ for (const position of [0, Math.max(0, size - SAMPLE_BYTES)]) {
1267
+ const { bytesRead } = await handle.read(buffer, 0, SAMPLE_BYTES, position);
1268
+ hasher.update(buffer.subarray(0, bytesRead));
1269
+ }
1270
+ } finally {
1271
+ buffers.release(buffer);
1272
+ await handle.close();
1246
1273
  }
1247
- return {
1248
- negated,
1249
- dirOnly,
1250
- nameOnly,
1251
- fast,
1252
- source,
1253
- tokens,
1254
- wildcards
1255
- };
1274
+ return hasher.digest("hex");
1256
1275
  }
1257
1276
  /**
1258
- * Parses a gitignore glob (already stripped of anchors and trailing slashes).
1259
- * Returns `null` for a malformed pattern.
1277
+ * Drops extra hard links to the same data. Only files with several links can
1278
+ * share data, and their identity is exact even where `ino` exceeds 2^53
1279
+ * (Windows file IDs); comparing rounded numbers once hid real duplicates.
1260
1280
  */
1261
- function parseGlob(glob) {
1262
- const out = [];
1263
- const n = glob.length;
1264
- for (let i = 0; i < n; i++) {
1265
- const c = glob[i];
1266
- if (c === "\\") {
1267
- if (i + 1 >= n) return null;
1268
- out.push({
1269
- kind: "char",
1270
- char: glob[++i]
1271
- });
1272
- } else if (c === "*") {
1273
- if (glob[i + 1] === "*") {
1274
- let j = i + 1;
1275
- while (glob[j] === "*") j++;
1276
- const atStart = i === 0 || glob[i - 1] === "/";
1277
- if (atStart && j === n) out.push(ALL);
1278
- else if (atStart && glob[j] === "/") {
1279
- out.push(DIRS);
1280
- j++;
1281
- } else out.push(STAR);
1282
- i = j - 1;
1283
- } else out.push(STAR);
1284
- } else if (c === "?") out.push(ANY);
1285
- else if (c === "[") {
1286
- const cls = parseClass(glob, i);
1287
- if (cls === null) return null;
1288
- out.push({
1289
- kind: "class",
1290
- source: cls.source
1291
- });
1292
- i = cls.end;
1293
- } else out.push({
1294
- kind: "char",
1295
- char: c
1296
- });
1281
+ async function distinctInodes(group, pathOf) {
1282
+ if (group.length < 2) return group;
1283
+ const seen = /* @__PURE__ */ new Set();
1284
+ const distinct = [];
1285
+ for (const candidate of group) {
1286
+ if (candidate.nlink > 1) {
1287
+ let key;
1288
+ if (Number.isSafeInteger(candidate.ino)) key = `${candidate.dev}:${candidate.ino}`;
1289
+ else try {
1290
+ key = await exactInodeKey(pathOf(candidate));
1291
+ } catch {
1292
+ distinct.push(candidate);
1293
+ continue;
1294
+ }
1295
+ if (seen.has(key)) continue;
1296
+ seen.add(key);
1297
+ }
1298
+ distinct.push(candidate);
1297
1299
  }
1298
- return out;
1300
+ return distinct;
1299
1301
  }
1302
+ /** Reuses read buffers so streaming large files allocates a fixed amount of memory. */
1303
+ var BufferPool = class {
1304
+ #free = [];
1305
+ acquire() {
1306
+ return this.#free.pop() ?? Buffer.allocUnsafe(READ_BUFFER_BYTES);
1307
+ }
1308
+ release(buffer) {
1309
+ this.#free.push(buffer);
1310
+ }
1311
+ };
1312
+ // src/core/gitignore.ts
1300
1313
  /**
1301
- * Parses a bracket expression starting at `start`, following Git's wildmatch.
1302
- * Returns `null` when it is malformed (not closed, or an unknown POSIX class).
1314
+ * The compiled rules of one ignore file.
1315
+ *
1316
+ * `test()` returns `true` when the last matching rule ignores the path,
1317
+ * `false` when it un-ignores it, and `undefined` when no rule matches, so
1318
+ * several files can be chained with Git's precedence.
1303
1319
  */
1304
- function parseClass(glob, start) {
1305
- let i = start + 1;
1306
- const negate = glob[i] === "!" || glob[i] === "^";
1307
- if (negate) i++;
1308
- let body = "";
1309
- let rangeStart;
1310
- for (let first = true;; i++, first = false) {
1311
- const c = glob[i];
1312
- if (c === void 0) return null;
1313
- if (c === "]" && !first) break;
1314
- if (c === "\\") {
1315
- const escaped = glob[++i];
1316
- if (escaped === void 0) return null;
1317
- body += escapeInClass(escaped);
1318
- rangeStart = escaped;
1319
- } else if (c === "-" && rangeStart !== void 0 && !isClassEnd(glob[i + 1])) {
1320
- let end = glob[++i];
1321
- if (end === "\\") {
1322
- const escaped = glob[++i];
1323
- if (escaped === void 0) return null;
1324
- end = escaped;
1320
+ var GitignoreMatcher = class GitignoreMatcher {
1321
+ #runs;
1322
+ #ignoreCase;
1323
+ constructor(runs, ignoreCase) {
1324
+ this.#runs = runs;
1325
+ this.#ignoreCase = ignoreCase;
1326
+ }
1327
+ /** True when the file contains at least one rule. */
1328
+ get hasRules() {
1329
+ return this.#runs.length > 0;
1330
+ }
1331
+ /**
1332
+ * @param path Path relative to the ignore file's directory, `/`-separated,
1333
+ * without leading or trailing slashes.
1334
+ */
1335
+ test(path, isDirectory) {
1336
+ const runs = this.#runs;
1337
+ let name;
1338
+ let folded;
1339
+ let foldedPath;
1340
+ for (let i = runs.length - 1; i >= 0; i--) {
1341
+ const run = runs[i];
1342
+ const fast = isDirectory && run.dirFast !== null ? true : run.anyFast !== null;
1343
+ const byName = run.anyName !== null || isDirectory && run.dirName !== null;
1344
+ if (fast || byName) {
1345
+ name ??= path.slice(path.lastIndexOf("/") + 1);
1346
+ if (fast) {
1347
+ folded ??= this.#ignoreCase ? name.toLowerCase() : name;
1348
+ if (run.anyFast?.has(folded) || isDirectory && run.dirFast?.has(folded)) return !run.negated;
1349
+ }
1350
+ if (run.anyName?.test(name) || isDirectory && run.dirName?.test(name)) return !run.negated;
1325
1351
  }
1326
- if (rangeStart <= end) body += `${escapeInClass(rangeStart)}-${escapeInClass(end)}`;
1327
- rangeStart = void 0;
1328
- } else if (c === "[" && glob[i + 1] === ":") {
1329
- const close = glob.indexOf("]", i + 2);
1330
- if (close === -1) return null;
1331
- if (glob[close - 1] === ":" && close - 1 >= i + 2) {
1332
- const posix = POSIX_CLASSES[glob.slice(i + 2, close - 1)];
1333
- if (posix === void 0) return null;
1334
- body += posix;
1335
- i = close;
1336
- rangeStart = void 0;
1337
- } else {
1338
- body += escapeInClass(c);
1339
- rangeStart = c;
1352
+ if (run.anyPath?.test(path) || isDirectory && run.dirPath?.test(path)) return !run.negated;
1353
+ if (run.globs !== null) {
1354
+ name ??= path.slice(path.lastIndexOf("/") + 1);
1355
+ for (const glob of run.globs) {
1356
+ if (glob.dirOnly && !isDirectory) continue;
1357
+ if (this.#ignoreCase) {
1358
+ if (!(glob.nameOnly ? folded ??= name.toLowerCase() : foldedPath ??= path.toLowerCase()).includes(glob.required)) continue;
1359
+ } else if (!(glob.nameOnly ? name : path).includes(glob.required)) continue;
1360
+ if (glob.matches(glob.nameOnly ? name : path)) return !run.negated;
1361
+ }
1340
1362
  }
1341
- } else {
1342
- body += escapeInClass(c);
1343
- rangeStart = c;
1344
1363
  }
1345
1364
  }
1346
- return {
1347
- source: `(?!/)[${negate ? "^" : ""}${body}]`,
1348
- end: i
1349
- };
1365
+ /** Compiles the contents of an ignore file (or a list of patterns). */
1366
+ static compile(source, options = {}) {
1367
+ const lines = typeof source === "string" ? splitRuleLines(source) : source;
1368
+ const ignoreCase = options.ignoreCase === true;
1369
+ const flags = ignoreCase ? "i" : "";
1370
+ const runs = [];
1371
+ let negated = false;
1372
+ let parts = new RunParts();
1373
+ const regex = (sources) => sources.length > 0 ? new RegExp(`^(?:${sources.join("|")})$`, flags) : null;
1374
+ const flush = () => {
1375
+ const run = {
1376
+ negated,
1377
+ anyFast: parts.anyFast.isEmpty ? null : parts.anyFast,
1378
+ dirFast: parts.dirFast.isEmpty ? null : parts.dirFast,
1379
+ anyName: regex(parts.anyName),
1380
+ dirName: regex(parts.dirName),
1381
+ anyPath: regex(parts.anyPath),
1382
+ dirPath: regex(parts.dirPath),
1383
+ globs: parts.globs.length > 0 ? parts.globs : null
1384
+ };
1385
+ if (run.anyFast || run.dirFast || run.anyName || run.dirName || run.anyPath || run.dirPath || run.globs) runs.push(run);
1386
+ parts = new RunParts();
1387
+ };
1388
+ for (const line of lines) {
1389
+ const rule = parseRule(line);
1390
+ if (rule === null) continue;
1391
+ if (rule.negated !== negated) {
1392
+ flush();
1393
+ negated = rule.negated;
1394
+ }
1395
+ if (rule.fast) {
1396
+ const target = rule.dirOnly ? parts.dirFast : parts.anyFast;
1397
+ const value = ignoreCase ? rule.fast.value.toLowerCase() : rule.fast.value;
1398
+ if (rule.fast.kind === "literal") target.literals.add(value);
1399
+ else target.addSuffix(value);
1400
+ } else if (rule.wildcards >= LINEAR_GLOB_WILDCARDS) parts.globs.push(new LinearGlob(rule, ignoreCase));
1401
+ else if (rule.nameOnly) (rule.dirOnly ? parts.dirName : parts.anyName).push(rule.source);
1402
+ else (rule.dirOnly ? parts.dirPath : parts.anyPath).push(rule.source);
1403
+ }
1404
+ flush();
1405
+ return new GitignoreMatcher(runs, ignoreCase);
1406
+ }
1407
+ };
1408
+ /** Exact names and `*suffix` rules of one run, matched with hash lookups. */
1409
+ var FastNames = class {
1410
+ literals = /* @__PURE__ */ new Set();
1411
+ /** Suffixes keyed by their last character, so a name checks only a few. */
1412
+ #suffixes = /* @__PURE__ */ new Map();
1413
+ get isEmpty() {
1414
+ return this.literals.size === 0 && this.#suffixes.size === 0;
1415
+ }
1416
+ addSuffix(suffix) {
1417
+ const key = suffix[suffix.length - 1];
1418
+ const list = this.#suffixes.get(key);
1419
+ if (list) list.push(suffix);
1420
+ else this.#suffixes.set(key, [suffix]);
1421
+ }
1422
+ has(name) {
1423
+ if (this.literals.has(name)) return true;
1424
+ if (name === "") return false;
1425
+ const list = this.#suffixes.get(name[name.length - 1]);
1426
+ if (list === void 0) return false;
1427
+ for (const suffix of list) if (name.endsWith(suffix)) return true;
1428
+ return false;
1429
+ }
1430
+ };
1431
+ var RunParts = class {
1432
+ anyFast = new FastNames();
1433
+ dirFast = new FastNames();
1434
+ anyName = [];
1435
+ dirName = [];
1436
+ anyPath = [];
1437
+ dirPath = [];
1438
+ globs = [];
1439
+ };
1440
+ const STAR = { kind: "star" };
1441
+ const ALL = { kind: "all" };
1442
+ const DIRS = { kind: "dirs" };
1443
+ const ANY = { kind: "any" };
1444
+ /** Rules with at least this many wildcards use {@link LinearGlob}. */
1445
+ const LINEAR_GLOB_WILDCARDS = 2;
1446
+ function isWildcard(token) {
1447
+ return token.kind === "star" || token.kind === "all" || token.kind === "dirs";
1350
1448
  }
1351
- function isClassEnd(c) {
1352
- return c === void 0 || c === "]";
1449
+ /** JavaScript's `.` skips line breaks, so these use `[^]`, which matches any character. */
1450
+ function tokenSource(token) {
1451
+ switch (token.kind) {
1452
+ case "char": return escapeRegex(token.char);
1453
+ case "class": return token.source;
1454
+ case "any": return "[^/]";
1455
+ case "star": return "[^/]*";
1456
+ case "all": return "[^]*";
1457
+ case "dirs": return "(?:[^]*/)?";
1458
+ }
1353
1459
  }
1354
- const POSIX_CLASSES = {
1355
- alnum: "a-zA-Z0-9",
1356
- alpha: "a-zA-Z",
1357
- blank: " \\t",
1358
- cntrl: "\\x00-\\x1f\\x7f",
1359
- digit: "0-9",
1360
- graph: "\\x21-\\x7e",
1361
- lower: "a-z",
1362
- print: "\\x20-\\x7e",
1363
- punct: "!-\\/:-@\\[-`{-~",
1364
- space: " \\t\\r\\n\\v\\f",
1365
- upper: "A-Z",
1366
- xdigit: "0-9A-Fa-f"
1460
+ const CHAR = 0;
1461
+ const CLASS = 1;
1462
+ const ANY_CHAR = 2;
1463
+ const ANY_RUN = 3;
1464
+ const ALL_RUN = 4;
1465
+ const OPCODES = {
1466
+ char: CHAR,
1467
+ class: CLASS,
1468
+ any: ANY_CHAR,
1469
+ star: ANY_RUN,
1470
+ all: ALL_RUN,
1471
+ dirs: 5
1367
1472
  };
1368
- function escapeRegex(c) {
1369
- return /[\\^$.*+?()[\]{}|/-]/.test(c) ? `\\${c}` : c;
1473
+ /** The same case folding as a regular expression with the `i` flag. */
1474
+ function foldCase(c) {
1475
+ const upper = c.toUpperCase();
1476
+ if (upper.length !== 1) return c;
1477
+ return c.charCodeAt(0) >= 128 && upper.charCodeAt(0) < 128 ? c : upper;
1370
1478
  }
1371
- function escapeInClass(c) {
1372
- return /[\\\]^[-]/.test(c) ? `\\${c}` : c;
1479
+ /** The longest stretch of plain ASCII characters that a glob must match literally. */
1480
+ function longestAsciiRun(tokens) {
1481
+ let longest = "";
1482
+ let run = "";
1483
+ for (const token of tokens) if (token.kind === "char" && token.char.charCodeAt(0) < 128) {
1484
+ run += token.char;
1485
+ if (run.length > longest.length) longest = run;
1486
+ } else run = "";
1487
+ return longest;
1373
1488
  }
1374
- // src/core/exclude.ts
1375
- /** Directories skipped unless default excludes are turned off. */
1376
- const DEFAULT_EXCLUDES = [
1377
- ".git",
1378
- ".hg",
1379
- ".svn",
1380
- "node_modules"
1381
- ];
1382
- const EMPTY_CHAIN = [];
1383
1489
  /**
1384
- * Decides which entries a scan skips. Combines the default excluded directory
1385
- * names, user patterns (gitignore syntax, relative to the root), and optionally
1386
- * the repository's own `.gitignore` files, evaluated with Git's precedence:
1387
- * deeper files override shallower ones, and later rules override earlier ones.
1490
+ * Matches a parsed glob by tracking every position it could be at, one input
1491
+ * character at a time. Nothing is ever retried, so the time is bounded by the
1492
+ * length of the path times the length of the pattern, whatever the pattern is.
1388
1493
  */
1389
- var Excluder = class {
1390
- gitignore;
1391
- #defaults;
1392
- #user;
1393
- #ignoreCase;
1394
- /** Trimmed, non-empty user patterns, as they were compiled. */
1395
- patterns;
1396
- constructor(options = {}) {
1397
- this.gitignore = options.gitignore ?? false;
1398
- this.#ignoreCase = options.ignoreCase ?? process.platform !== "linux";
1399
- this.#defaults = options.defaultExcludes ?? true ? new Set(DEFAULT_EXCLUDES) : null;
1400
- const patterns = (options.patterns ?? []).map((p) => p.trim()).filter(Boolean);
1401
- this.patterns = patterns;
1402
- const user = patterns.length > 0 ? this.#compile(patterns) : null;
1403
- this.#user = user?.hasRules ? user : null;
1404
- }
1405
- /** Whether rules match case-insensitively. */
1406
- get ignoreCase() {
1407
- return this.#ignoreCase;
1408
- }
1409
- /** Whether the default directory names are excluded. */
1410
- get defaultExcludes() {
1411
- return this.#defaults !== null;
1412
- }
1413
- /** True when at least one rule could exclude something. */
1414
- get active() {
1415
- return this.#defaults !== null || this.#user !== null || this.gitignore;
1416
- }
1417
- /** Whether path-based rules exist (anything beyond default directory names). */
1418
- get needsPaths() {
1419
- return this.#user !== null || this.gitignore;
1420
- }
1421
- /**
1422
- * @param relPath Root-relative path with `/` separators.
1423
- * @param name Entry name (the last segment of `relPath`).
1424
- */
1425
- isExcluded(relPath, name, isDirectory, chain) {
1426
- if (isDirectory && this.#defaults?.has(name)) return true;
1427
- if (this.#user !== null && this.#user.test(relPath, isDirectory) === true) return true;
1428
- return chain.length > 0 && isGitIgnored(chain, relPath, isDirectory);
1429
- }
1494
+ var LinearGlob = class {
1495
+ dirOnly;
1496
+ nameOnly;
1430
1497
  /**
1431
- * Checks a path and each of its ancestors against the default and user
1432
- * rules. Used to filter filesystem events in watch mode.
1498
+ * Text every match must contain, in lower case when ignoring case. Only ASCII
1499
+ * is used: a regular expression's `i` flag never folds other characters into
1500
+ * ASCII, so lower-casing a path cannot hide or invent an occurrence of it.
1433
1501
  */
1434
- isPathExcluded(relPath) {
1435
- const segments = relPath.split("/").filter(Boolean);
1436
- let current = "";
1437
- for (let i = 0; i < segments.length; i++) {
1438
- const segment = segments[i];
1439
- current = current ? `${current}/${segment}` : segment;
1440
- const isLast = i === segments.length - 1;
1441
- if (!isLast && this.isExcluded(current, segment, true, EMPTY_CHAIN)) return true;
1442
- if (isLast) return this.isExcluded(current, segment, false, EMPTY_CHAIN) || (this.#defaults?.has(segment) ?? false);
1443
- }
1444
- return false;
1502
+ required;
1503
+ #ops;
1504
+ #chars;
1505
+ #classes;
1506
+ #accept;
1507
+ #ignoreCase;
1508
+ #current;
1509
+ #next;
1510
+ #nextCount = 0;
1511
+ /** The step at which each position was last added, so it is added only once per step. */
1512
+ #added;
1513
+ /** The same for following a wildcard to the position after it. */
1514
+ #skipped;
1515
+ #step = 0;
1516
+ constructor(rule, ignoreCase) {
1517
+ const { tokens } = rule;
1518
+ this.dirOnly = rule.dirOnly;
1519
+ this.nameOnly = rule.nameOnly;
1520
+ this.#ignoreCase = ignoreCase;
1521
+ const required = longestAsciiRun(tokens);
1522
+ this.required = ignoreCase ? required.toLowerCase() : required;
1523
+ const size = tokens.length + 1;
1524
+ this.#accept = tokens.length;
1525
+ this.#ops = Uint8Array.from(tokens, (token) => OPCODES[token.kind]);
1526
+ this.#chars = tokens.map((token) => {
1527
+ if (token.kind !== "char") return "";
1528
+ return ignoreCase ? foldCase(token.char) : token.char;
1529
+ });
1530
+ this.#classes = tokens.map((token) => token.kind === "class" ? new RegExp(`^${token.source}$`, ignoreCase ? "i" : "") : null);
1531
+ this.#current = new Int32Array(size);
1532
+ this.#next = new Int32Array(size);
1533
+ this.#added = new Float64Array(size);
1534
+ this.#skipped = new Float64Array(size);
1445
1535
  }
1446
- /** Builds the scope for a `.gitignore` found at `rootRelativeDir` (`''` for the root). */
1447
- async loadScope(filePath, rootRelativeDir) {
1448
- const content = await readFile$1(filePath, "utf8").catch(() => null);
1449
- if (content === null) return null;
1450
- const matcher = this.#compile(content);
1451
- if (!matcher.hasRules) return null;
1452
- return {
1453
- matcher,
1454
- prefix: "",
1455
- strip: rootRelativeDir ? rootRelativeDir.length + 1 : 0,
1456
- source: {
1457
- kind: "gitignore",
1458
- file: filePath,
1459
- content
1536
+ matches(text) {
1537
+ const ops = this.#ops;
1538
+ const chars = this.#chars;
1539
+ const accept = this.#accept;
1540
+ this.#nextCount = 0;
1541
+ this.#step++;
1542
+ this.#add(0, true);
1543
+ for (let i = 0; i < text.length; i++) {
1544
+ const count = this.#nextCount;
1545
+ if (count === 0) return false;
1546
+ const current = this.#next;
1547
+ this.#next = this.#current;
1548
+ this.#current = current;
1549
+ this.#nextCount = 0;
1550
+ this.#step++;
1551
+ const c = text[i];
1552
+ const folded = this.#ignoreCase ? foldCase(c) : c;
1553
+ for (let k = 0; k < count; k++) {
1554
+ const position = current[k];
1555
+ if (position === accept) continue;
1556
+ switch (ops[position]) {
1557
+ case CHAR:
1558
+ if (folded === chars[position]) this.#add(position + 1, true);
1559
+ break;
1560
+ case CLASS:
1561
+ if (this.#classes[position].test(c)) this.#add(position + 1, true);
1562
+ break;
1563
+ case ANY_CHAR:
1564
+ if (c !== "/") this.#add(position + 1, true);
1565
+ break;
1566
+ case ANY_RUN:
1567
+ if (c !== "/") this.#add(position, true);
1568
+ break;
1569
+ case ALL_RUN:
1570
+ this.#add(position, true);
1571
+ break;
1572
+ default:
1573
+ this.#add(position, false);
1574
+ if (c === "/") this.#add(position + 1, true);
1575
+ }
1460
1576
  }
1461
- };
1462
- }
1463
- /**
1464
- * When the root sits inside a Git repository, collects the `.gitignore`
1465
- * files of its ancestors up to the repository root, plus
1466
- * `.git/info/exclude`, so a sub-directory scan matches Git's view.
1467
- */
1468
- async loadAncestorChain(root) {
1469
- return (await this.loadAncestors(root)).chain;
1577
+ }
1578
+ return this.#added[accept] === this.#step;
1470
1579
  }
1471
- /** {@link loadAncestorChain}, plus the repository root it found (null outside a repository). */
1472
- async loadAncestors(root) {
1473
- if (!this.gitignore) return {
1474
- chain: EMPTY_CHAIN,
1475
- repoRoot: null
1476
- };
1477
- const ancestors = [];
1478
- let repoRoot = null;
1479
- let current = root;
1480
- for (;;) {
1481
- if (existsSync(join(current, ".git"))) {
1482
- repoRoot = current;
1483
- break;
1580
+ #add(position, arriving) {
1581
+ const step = this.#step;
1582
+ for (let at = position;; at++) {
1583
+ if (this.#added[at] !== step) {
1584
+ this.#added[at] = step;
1585
+ this.#next[this.#nextCount++] = at;
1484
1586
  }
1485
- const parent = dirname(current);
1486
- if (parent === current) break;
1487
- ancestors.push(parent);
1488
- current = parent;
1587
+ if (!arriving || at === this.#accept || this.#ops[at] < ANY_RUN) return;
1588
+ if (this.#skipped[at] === step) return;
1589
+ this.#skipped[at] = step;
1489
1590
  }
1490
- if (repoRoot === null) return {
1491
- chain: EMPTY_CHAIN,
1492
- repoRoot: null
1493
- };
1494
- const scopes = [];
1495
- const outermostFirst = repoRoot === root ? [] : ancestors.reverse();
1496
- const add = async (file, base, kind) => {
1497
- const content = await readFile$1(file, "utf8").catch(() => null);
1498
- if (content === null) return;
1499
- const matcher = this.#compile(content);
1500
- if (!matcher.hasRules) return;
1501
- const prefix = relative(base, root).split(sep).join("/");
1502
- scopes.push({
1503
- matcher,
1504
- prefix: prefix ? `${prefix}/` : "",
1505
- strip: 0,
1506
- source: {
1507
- kind,
1508
- file,
1509
- content
1510
- }
1511
- });
1512
- };
1513
- const infoExclude = await findInfoExclude(repoRoot);
1514
- if (infoExclude !== null) await add(infoExclude, repoRoot, "info-exclude");
1515
- for (const dir of outermostFirst) await add(join(dir, ".gitignore"), dir, "gitignore");
1516
- return {
1517
- chain: scopes,
1518
- repoRoot
1519
- };
1520
- }
1521
- #compile(source) {
1522
- return GitignoreMatcher.compile(source, { ignoreCase: this.#ignoreCase });
1523
1591
  }
1524
1592
  };
1593
+ /** No wildcards, classes, or escapes: the pattern is a literal name (or suffix). */
1594
+ const LITERAL = /^[^*?[\\]+$/;
1595
+ /** A line ending; a final CR counts because Git treats the end of a file as a newline. */
1596
+ const EOL = /\r?\n|\r$/;
1525
1597
  /**
1526
- * Locates `info/exclude`. In a linked worktree or a submodule `.git` is a file
1527
- * naming the real Git directory, and a worktree shares its main repository's
1528
- * exclude file through `commondir`.
1598
+ * Splits an ignore file into lines as {@link GitignoreMatcher.compile} reads
1599
+ * them, so index + 1 is the line number Git reports.
1529
1600
  */
1530
- async function findInfoExclude(repoRoot) {
1531
- const dotGit = join(repoRoot, ".git");
1532
- const pointer = await readFile$1(dotGit, "utf8").catch(() => null);
1533
- if (pointer === null) return join(dotGit, "info", "exclude");
1534
- const gitDir = /^gitdir:\s*(.+?)\s*$/m.exec(pointer)?.[1];
1535
- if (gitDir === void 0) return null;
1536
- const dir = resolve(repoRoot, gitDir);
1537
- const commonDir = await readFile$1(join(dir, "commondir"), "utf8").catch(() => null);
1538
- return join(commonDir === null ? dir : resolve(dir, commonDir.trim()), "info", "exclude");
1601
+ function splitRuleLines(source) {
1602
+ return source.replace(/^\uFEFF/, "").split(EOL);
1539
1603
  }
1540
- function isGitIgnored(chain, relPath, isDirectory) {
1541
- let ignored = false;
1542
- for (const scope of chain) {
1543
- const local = scope.prefix + relPath.slice(scope.strip);
1544
- if (local === "") continue;
1545
- const result = scope.matcher.test(local, isDirectory);
1546
- if (result !== void 0) ignored = result;
1604
+ /** Removes unescaped trailing spaces. Tabs are significant, as they are in Git. */
1605
+ function trimTrailingSpaces(line) {
1606
+ let end = line.length;
1607
+ let spaces = -1;
1608
+ for (let i = 0; i < line.length; i++) if (line[i] === " ") {
1609
+ if (spaces === -1) spaces = i;
1610
+ } else {
1611
+ if (line[i] === "\\") i++;
1612
+ spaces = -1;
1547
1613
  }
1548
- return ignored;
1614
+ if (spaces !== -1) end = spaces;
1615
+ return line.slice(0, end);
1549
1616
  }
1550
- // src/core/limiter.ts
1551
1617
  /**
1552
- * A tiny concurrency limiter for filesystem work.
1553
- *
1554
- * Tasks run at most `concurrency` at a time. Pending tasks are taken
1555
- * last-in-first-out, which makes a directory walk proceed depth-first and
1556
- * keeps the pending queue small even on very wide trees.
1618
+ * Turns one gitignore line into a regex fragment. Returns `null` for blanks,
1619
+ * comments, and malformed patterns, which Git treats as never matching.
1557
1620
  */
1558
- var Limiter = class {
1559
- #concurrency;
1560
- #queue = [];
1561
- #active = 0;
1562
- #failure = void 0;
1563
- #failed = false;
1564
- #idle = null;
1565
- constructor(concurrency) {
1566
- if (!Number.isInteger(concurrency) || concurrency < 1) throw new RangeError(`concurrency must be a positive integer (got ${concurrency})`);
1567
- this.#concurrency = concurrency;
1621
+ function parseRule(line) {
1622
+ let pattern = trimTrailingSpaces(line);
1623
+ if (pattern === "" || pattern.startsWith("#")) return null;
1624
+ let negated = false;
1625
+ if (pattern.startsWith("!")) {
1626
+ negated = true;
1627
+ pattern = pattern.slice(1);
1628
+ } else if (pattern.startsWith("\\!") || pattern.startsWith("\\#")) pattern = pattern.slice(1);
1629
+ if (pattern === "") return null;
1630
+ let dirOnly = false;
1631
+ if (pattern.endsWith("/")) {
1632
+ dirOnly = true;
1633
+ pattern = pattern.slice(0, -1);
1634
+ if (pattern === "") return null;
1568
1635
  }
1569
- /** Schedules a task. Tasks are expected to handle their own errors; a thrown error aborts the run. */
1570
- run(task) {
1571
- if (this.#failed) return;
1572
- this.#queue.push(task);
1573
- this.#pump();
1636
+ let anchored = false;
1637
+ if (pattern.startsWith("/")) {
1638
+ anchored = true;
1639
+ pattern = pattern.slice(1);
1640
+ } else if (pattern.includes("/")) anchored = true;
1641
+ if (pattern.startsWith("**/")) {
1642
+ anchored = false;
1643
+ pattern = pattern.replace(/^(\*\*\/)+/, "");
1574
1644
  }
1575
- /** Resolves once every scheduled task, including tasks scheduled by tasks, has finished. */
1576
- idle() {
1577
- if (this.#failed) return Promise.reject(this.#failure);
1578
- if (this.#active === 0 && this.#queue.length === 0) return Promise.resolve();
1579
- return new Promise((resolve, reject) => {
1580
- this.#idle = {
1581
- resolve,
1582
- reject
1583
- };
1584
- });
1645
+ if (pattern === "") return null;
1646
+ const body = parseGlob(pattern);
1647
+ if (body === null) return null;
1648
+ const nameOnly = !anchored && !pattern.includes("/") && !pattern.includes("**");
1649
+ const tokens = anchored || nameOnly ? body : [DIRS, ...body];
1650
+ const source = tokens.map(tokenSource).join("");
1651
+ const wildcards = tokens.filter(isWildcard).length;
1652
+ let fast = null;
1653
+ if (nameOnly) {
1654
+ if (LITERAL.test(pattern)) fast = {
1655
+ kind: "literal",
1656
+ value: pattern
1657
+ };
1658
+ else if (pattern.startsWith("*") && LITERAL.test(pattern.slice(1))) fast = {
1659
+ kind: "suffix",
1660
+ value: pattern.slice(1)
1661
+ };
1585
1662
  }
1586
- /** Stops scheduling new work and rejects `idle()` with `reason`. */
1587
- abort(reason) {
1588
- if (this.#failed) return;
1589
- this.#failed = true;
1590
- this.#failure = reason;
1591
- this.#queue.length = 0;
1592
- this.#idle?.reject(reason);
1593
- this.#idle = null;
1663
+ return {
1664
+ negated,
1665
+ dirOnly,
1666
+ nameOnly,
1667
+ fast,
1668
+ source,
1669
+ tokens,
1670
+ wildcards
1671
+ };
1672
+ }
1673
+ /**
1674
+ * Parses a gitignore glob (already stripped of anchors and trailing slashes).
1675
+ * Returns `null` for a malformed pattern.
1676
+ */
1677
+ function parseGlob(glob) {
1678
+ const out = [];
1679
+ const n = glob.length;
1680
+ for (let i = 0; i < n; i++) {
1681
+ const c = glob[i];
1682
+ if (c === "\\") {
1683
+ if (i + 1 >= n) return null;
1684
+ out.push({
1685
+ kind: "char",
1686
+ char: glob[++i]
1687
+ });
1688
+ } else if (c === "*") {
1689
+ if (glob[i + 1] === "*") {
1690
+ let j = i + 1;
1691
+ while (glob[j] === "*") j++;
1692
+ const atStart = i === 0 || glob[i - 1] === "/";
1693
+ if (atStart && j === n) out.push(ALL);
1694
+ else if (atStart && glob[j] === "/") {
1695
+ out.push(DIRS);
1696
+ j++;
1697
+ } else out.push(STAR);
1698
+ i = j - 1;
1699
+ } else out.push(STAR);
1700
+ } else if (c === "?") out.push(ANY);
1701
+ else if (c === "[") {
1702
+ const cls = parseClass(glob, i);
1703
+ if (cls === null) return null;
1704
+ out.push({
1705
+ kind: "class",
1706
+ source: cls.source
1707
+ });
1708
+ i = cls.end;
1709
+ } else out.push({
1710
+ kind: "char",
1711
+ char: c
1712
+ });
1594
1713
  }
1595
- #pump() {
1596
- while (this.#active < this.#concurrency && this.#queue.length > 0) {
1597
- const task = this.#queue.pop();
1598
- this.#active++;
1599
- task().then(this.#onDone, this.#onError);
1600
- }
1601
- if (this.#active === 0 && this.#queue.length === 0 && this.#idle) {
1602
- const idle = this.#idle;
1603
- this.#idle = null;
1604
- idle.resolve();
1714
+ return out;
1715
+ }
1716
+ /**
1717
+ * Parses a bracket expression starting at `start`, following Git's wildmatch.
1718
+ * Returns `null` when it is malformed (not closed, or an unknown POSIX class).
1719
+ */
1720
+ function parseClass(glob, start) {
1721
+ let i = start + 1;
1722
+ const negate = glob[i] === "!" || glob[i] === "^";
1723
+ if (negate) i++;
1724
+ let body = "";
1725
+ let rangeStart;
1726
+ for (let first = true;; i++, first = false) {
1727
+ const c = glob[i];
1728
+ if (c === void 0) return null;
1729
+ if (c === "]" && !first) break;
1730
+ if (c === "\\") {
1731
+ const escaped = glob[++i];
1732
+ if (escaped === void 0) return null;
1733
+ body += escapeInClass(escaped);
1734
+ rangeStart = escaped;
1735
+ } else if (c === "-" && rangeStart !== void 0 && !isClassEnd(glob[i + 1])) {
1736
+ let end = glob[++i];
1737
+ if (end === "\\") {
1738
+ const escaped = glob[++i];
1739
+ if (escaped === void 0) return null;
1740
+ end = escaped;
1741
+ }
1742
+ if (rangeStart <= end) body += `${escapeInClass(rangeStart)}-${escapeInClass(end)}`;
1743
+ rangeStart = void 0;
1744
+ } else if (c === "[" && glob[i + 1] === ":") {
1745
+ const close = glob.indexOf("]", i + 2);
1746
+ if (close === -1) return null;
1747
+ if (glob[close - 1] === ":" && close - 1 >= i + 2) {
1748
+ const posix = POSIX_CLASSES[glob.slice(i + 2, close - 1)];
1749
+ if (posix === void 0) return null;
1750
+ body += posix;
1751
+ i = close;
1752
+ rangeStart = void 0;
1753
+ } else {
1754
+ body += escapeInClass(c);
1755
+ rangeStart = c;
1756
+ }
1757
+ } else {
1758
+ body += escapeInClass(c);
1759
+ rangeStart = c;
1605
1760
  }
1606
1761
  }
1607
- #onDone = () => {
1608
- this.#active--;
1609
- this.#pump();
1610
- };
1611
- #onError = (error) => {
1612
- this.#active--;
1613
- this.abort(error);
1762
+ return {
1763
+ source: `(?!/)[${negate ? "^" : ""}${body}]`,
1764
+ end: i
1614
1765
  };
1766
+ }
1767
+ function isClassEnd(c) {
1768
+ return c === void 0 || c === "]";
1769
+ }
1770
+ const POSIX_CLASSES = {
1771
+ alnum: "a-zA-Z0-9",
1772
+ alpha: "a-zA-Z",
1773
+ blank: " \\t",
1774
+ cntrl: "\\x00-\\x1f\\x7f",
1775
+ digit: "0-9",
1776
+ graph: "\\x21-\\x7e",
1777
+ lower: "a-z",
1778
+ print: "\\x20-\\x7e",
1779
+ punct: "!-\\/:-@\\[-`{-~",
1780
+ space: " \\t\\r\\n\\v\\f",
1781
+ upper: "A-Z",
1782
+ xdigit: "0-9A-Fa-f"
1615
1783
  };
1616
- // src/core/paths.ts
1617
- /** Ordinal comparison, so output order never depends on the locale. */
1618
- function comparePaths(a, b) {
1619
- return a < b ? -1 : a > b ? 1 : 0;
1784
+ function escapeRegex(c) {
1785
+ return /[\\^$.*+?()[\]{}|/-]/.test(c) ? `\\${c}` : c;
1620
1786
  }
1621
- /** Joins an absolute native directory and a `/`-separated relative path. */
1622
- function joinRelative(root, relative) {
1623
- if (!relative) return root;
1624
- const native = sep === "/" ? relative : relative.replaceAll("/", sep);
1625
- return root.endsWith(sep) ? root + native : root + sep + native;
1787
+ function escapeInClass(c) {
1788
+ return /[\\\]^[-]/.test(c) ? `\\${c}` : c;
1626
1789
  }
1627
- const IS_WINDOWS = process.platform === "win32";
1790
+ // src/core/exclude.ts
1791
+ /** Directories skipped unless default excludes are turned off. */
1792
+ const DEFAULT_EXCLUDES = [
1793
+ ".git",
1794
+ ".hg",
1795
+ ".svn",
1796
+ "node_modules"
1797
+ ];
1798
+ const EMPTY_CHAIN = [];
1628
1799
  /**
1629
- * Concurrent directory walker.
1630
- *
1631
- * Reads directories with `readdir({ withFileTypes })` so directory entries
1632
- * never need a `stat`; regular files are `lstat`ed exactly once. All
1633
- * filesystem calls go through one {@link Limiter}, so concurrency stays
1634
- * bounded no matter how wide the tree is. Results are independent of
1635
- * scheduling order: callers sort what they report.
1800
+ * Decides which entries a scan skips. Combines the default excluded directory
1801
+ * names, user patterns (gitignore syntax, relative to the root), and optionally
1802
+ * the repository's own `.gitignore` files, evaluated with Git's precedence:
1803
+ * deeper files override shallower ones, and later rules override earlier ones.
1636
1804
  */
1637
- var Scanner = class {
1638
- dirs = [];
1639
- errors = [];
1640
- counters = {
1641
- files: 0,
1642
- bytes: 0,
1643
- diskBytes: 0,
1644
- directories: 0,
1645
- symlinks: 0,
1646
- hardlinks: 0,
1647
- excluded: 0,
1648
- filtered: 0,
1649
- errors: 0
1650
- };
1651
- #options;
1652
- #visitor;
1653
- #limiter;
1654
- #filtersActive;
1655
- /** `dev:ino` of files with several links (or of every file when following symlinks). */
1656
- #seenInodes = /* @__PURE__ */ new Set();
1657
- /** `dev:ino` of entered directories, tracked only when following symlinks. */
1658
- #seenDirs = /* @__PURE__ */ new Set();
1659
- constructor(options, visitor) {
1660
- this.#options = options;
1661
- this.#visitor = visitor;
1662
- this.#limiter = new Limiter(options.concurrency);
1663
- this.#filtersActive = options.minSize > 0 || options.maxSize < Infinity || options.modifiedAfter > -Infinity || options.modifiedBefore < Infinity;
1664
- }
1665
- async run() {
1666
- const { root, signal, excluder } = this.#options;
1667
- if (signal?.aborted) throw new AbortError();
1668
- const rootStats = await stat(root);
1669
- if (this.#options.followSymlinks) this.#seenDirs.add(inodeKey(rootStats));
1670
- const chain = await excluder.loadAncestorChain(root);
1671
- const index = this.#addDir("", -1, 0);
1672
- const onAbort = () => this.#limiter.abort(new AbortError());
1673
- signal?.addEventListener("abort", onAbort, { once: true });
1674
- try {
1675
- this.#limiter.run(() => this.#scanDir(index, root, chain));
1676
- await this.#limiter.idle();
1677
- } finally {
1678
- signal?.removeEventListener("abort", onAbort);
1679
- }
1680
- }
1681
- /** Root-relative path of a directory (or of `name` inside it), with `/` separators. */
1682
- relativePath(dirIndex, name) {
1683
- const parts = name === void 0 ? [] : [name];
1684
- for (let i = dirIndex; i > 0; i = this.dirs[i].parent) parts.push(this.dirs[i].name);
1685
- return parts.toReversed().join("/");
1686
- }
1687
- absolutePath(dirIndex, name) {
1688
- return joinRelative(this.#options.root, this.relativePath(dirIndex, name));
1805
+ var Excluder = class {
1806
+ gitignore;
1807
+ #defaults;
1808
+ #user;
1809
+ #ignoreCase;
1810
+ /** Trimmed, non-empty user patterns, as they were compiled. */
1811
+ patterns;
1812
+ constructor(options = {}) {
1813
+ this.gitignore = options.gitignore ?? false;
1814
+ this.#ignoreCase = options.ignoreCase ?? process.platform !== "linux";
1815
+ this.#defaults = options.defaultExcludes ?? true ? new Set(DEFAULT_EXCLUDES) : null;
1816
+ const patterns = (options.patterns ?? []).map((p) => p.trim()).filter(Boolean);
1817
+ this.patterns = patterns;
1818
+ const user = patterns.length > 0 ? this.#compile(patterns) : null;
1819
+ this.#user = user?.hasRules ? user : null;
1689
1820
  }
1690
- #addDir(name, parent, depth) {
1691
- const node = {
1692
- name,
1693
- parent,
1694
- depth,
1695
- entries: 0,
1696
- ownFiles: 0,
1697
- ownBytes: 0,
1698
- ownDiskBytes: 0,
1699
- files: 0,
1700
- bytes: 0,
1701
- diskBytes: 0,
1702
- largestChild: 0
1703
- };
1704
- const index = this.dirs.push(node) - 1;
1705
- this.counters.directories++;
1706
- this.#visitor.directory?.(index, node);
1707
- return index;
1821
+ /** Whether rules match case-insensitively. */
1822
+ get ignoreCase() {
1823
+ return this.#ignoreCase;
1708
1824
  }
1709
- async #scanDir(index, absPath, inherited) {
1710
- const { excluder } = this.#options;
1711
- let entries;
1712
- try {
1713
- entries = await readdir(absPath, { withFileTypes: true });
1714
- } catch (error) {
1715
- this.dirs[index].entries = -1;
1716
- this.recordError(this.relativePath(index), error);
1717
- return;
1718
- }
1719
- const node = this.dirs[index];
1720
- node.entries = entries.length;
1721
- if (entries.length === 0) return;
1722
- const relDir = excluder.needsPaths ? this.relativePath(index) : "";
1723
- let chain = inherited;
1724
- if (excluder.gitignore && entries.some((e) => e.name === ".gitignore" && !e.isDirectory())) {
1725
- const scope = await excluder.loadScope(joinNative(absPath, ".gitignore"), relDir);
1726
- if (scope) chain = [...inherited, scope];
1727
- }
1728
- const base = absPath.endsWith(sep) ? absPath : absPath + sep;
1729
- const checkExclusion = excluder.active;
1730
- for (const entry of entries) {
1731
- const name = entry.name;
1732
- const isDirectory = entry.isDirectory();
1733
- const isFile = !isDirectory && entry.isFile();
1734
- const isSymlink = !isDirectory && !isFile && entry.isSymbolicLink();
1735
- const isUnknown = !isDirectory && !isFile && !isSymlink && isUnknownType(entry);
1736
- if (!isDirectory && !isFile && !isSymlink && !isUnknown) continue;
1737
- if (checkExclusion) {
1738
- const rel = relDir ? `${relDir}/${name}` : name;
1739
- if (excluder.isExcluded(rel, name, isDirectory, chain)) {
1740
- this.counters.excluded++;
1741
- this.#options.onSkip?.({
1742
- kind: "excluded",
1743
- dir: index,
1744
- name,
1745
- isDirectory,
1746
- chain
1747
- });
1748
- continue;
1749
- }
1750
- }
1751
- const fullPath = base + name;
1752
- if (this.#options.directoriesOnly && !isDirectory) continue;
1753
- if (isDirectory && !this.#options.followSymlinks) this.#enterDir(index, name, fullPath, chain);
1754
- else if (isFile) this.#limiter.run(() => this.#statFile(index, name, fullPath));
1755
- else this.#limiter.run(() => this.#resolveEntry(index, name, fullPath, chain, isSymlink, isDirectory));
1756
- }
1825
+ /** Whether the default directory names are excluded. */
1826
+ get defaultExcludes() {
1827
+ return this.#defaults !== null;
1757
1828
  }
1758
- #enterDir(parent, name, fullPath, chain) {
1759
- const depth = this.dirs[parent].depth + 1;
1760
- if (depth > this.#options.maxDepth) {
1761
- this.#options.onSkip?.({
1762
- kind: "depth",
1763
- dir: parent,
1764
- name,
1765
- depth
1766
- });
1767
- return;
1768
- }
1769
- const child = this.#addDir(name, parent, depth);
1770
- this.#limiter.run(() => this.#scanDir(child, fullPath, chain));
1829
+ /** True when at least one rule could exclude something. */
1830
+ get active() {
1831
+ return this.#defaults !== null || this.#user !== null || this.gitignore;
1771
1832
  }
1772
- async #statFile(dirIndex, name, fullPath) {
1773
- let stats;
1774
- try {
1775
- stats = await lstat(fullPath);
1776
- } catch (error) {
1777
- this.recordError(this.relativePath(dirIndex, name), error);
1778
- return;
1779
- }
1780
- this.#acceptFile(dirIndex, name, stats);
1833
+ /** Whether path-based rules exist (anything beyond default directory names). */
1834
+ get needsPaths() {
1835
+ return this.#user !== null || this.gitignore;
1781
1836
  }
1782
1837
  /**
1783
- * Handles symlinks, entries whose type the filesystem did not report, and
1784
- * (when following symlinks) directories, which then need their identity.
1838
+ * @param relPath Root-relative path with `/` separators.
1839
+ * @param name Entry name (the last segment of `relPath`).
1785
1840
  */
1786
- async #resolveEntry(dirIndex, name, fullPath, chain, isSymlink, checkedAsDirectory) {
1787
- let stats;
1788
- try {
1789
- stats = await lstat(fullPath);
1790
- if (stats.isSymbolicLink()) {
1791
- isSymlink = true;
1792
- if (!this.#options.followSymlinks) {
1793
- this.counters.symlinks++;
1794
- this.#options.onSkip?.({
1795
- kind: "symlink",
1796
- dir: dirIndex,
1797
- name
1798
- });
1799
- return;
1800
- }
1801
- stats = await stat(fullPath);
1802
- }
1803
- } catch (error) {
1804
- const code = errorCode(error);
1805
- if (isSymlink && (code === "ENOENT" || code === "ELOOP")) {
1806
- this.counters.symlinks++;
1807
- return;
1808
- }
1809
- this.recordError(this.relativePath(dirIndex, name), error);
1810
- return;
1841
+ isExcluded(relPath, name, isDirectory, chain) {
1842
+ if (isDirectory && this.#defaults?.has(name)) return true;
1843
+ if (this.#user !== null && this.#user.test(relPath, isDirectory) === true) return true;
1844
+ return chain.length > 0 && isGitIgnored(chain, relPath, isDirectory);
1845
+ }
1846
+ /**
1847
+ * Checks a path and each of its ancestors against the default and user
1848
+ * rules. Used to filter filesystem events in watch mode.
1849
+ */
1850
+ isPathExcluded(relPath) {
1851
+ const segments = relPath.split("/").filter(Boolean);
1852
+ let current = "";
1853
+ for (let i = 0; i < segments.length; i++) {
1854
+ const segment = segments[i];
1855
+ current = current ? `${current}/${segment}` : segment;
1856
+ const isLast = i === segments.length - 1;
1857
+ if (!isLast && this.isExcluded(current, segment, true, EMPTY_CHAIN)) return true;
1858
+ if (isLast) return this.isExcluded(current, segment, false, EMPTY_CHAIN) || (this.#defaults?.has(segment) ?? false);
1811
1859
  }
1812
- if (isSymlink) this.counters.symlinks++;
1813
- if (stats.isDirectory()) {
1814
- const { excluder } = this.#options;
1815
- if (excluder.active && !checkedAsDirectory) {
1816
- const rel = this.relativePath(dirIndex, name);
1817
- if (excluder.isExcluded(rel, name, true, chain)) {
1818
- this.counters.excluded++;
1819
- this.#options.onSkip?.({
1820
- kind: "excluded",
1821
- dir: dirIndex,
1822
- name,
1823
- isDirectory: true,
1824
- chain
1825
- });
1826
- return;
1827
- }
1828
- }
1829
- const key = inodeKey(stats);
1830
- if (this.#seenDirs.has(key)) return;
1831
- this.#seenDirs.add(key);
1832
- this.#enterDir(dirIndex, name, fullPath, chain);
1833
- } else if (stats.isFile()) this.#acceptFile(dirIndex, name, stats);
1860
+ return false;
1834
1861
  }
1835
- #acceptFile(dirIndex, name, stats) {
1836
- if (!this.#options.countHardlinks && (stats.nlink > 1 || this.#options.followSymlinks)) {
1837
- const key = inodeKey(stats);
1838
- if (this.#seenInodes.has(key)) {
1839
- if (stats.nlink > 1) this.counters.hardlinks++;
1840
- return;
1862
+ /** Builds the scope for a `.gitignore` found at `rootRelativeDir` (`''` for the root). */
1863
+ async loadScope(filePath, rootRelativeDir) {
1864
+ const content = await readFile$1(filePath, "utf8").catch(() => null);
1865
+ if (content === null) return null;
1866
+ const matcher = this.#compile(content);
1867
+ if (!matcher.hasRules) return null;
1868
+ return {
1869
+ matcher,
1870
+ prefix: "",
1871
+ strip: rootRelativeDir ? rootRelativeDir.length + 1 : 0,
1872
+ source: {
1873
+ kind: "gitignore",
1874
+ file: filePath,
1875
+ content
1841
1876
  }
1842
- this.#seenInodes.add(key);
1843
- }
1844
- const size = stats.size;
1845
- if (this.#filtersActive) {
1846
- const o = this.#options;
1847
- const mtime = stats.mtimeMs;
1848
- if (size < o.minSize || size > o.maxSize || mtime < o.modifiedAfter || mtime > o.modifiedBefore) {
1849
- this.counters.filtered++;
1850
- o.onSkip?.({
1851
- kind: "filtered",
1852
- dir: dirIndex,
1853
- name,
1854
- stats
1855
- });
1856
- return;
1877
+ };
1878
+ }
1879
+ /**
1880
+ * When the root sits inside a Git repository, collects the `.gitignore`
1881
+ * files of its ancestors up to the repository root, plus
1882
+ * `.git/info/exclude`, so a sub-directory scan matches Git's view.
1883
+ */
1884
+ async loadAncestorChain(root) {
1885
+ return (await this.loadAncestors(root)).chain;
1886
+ }
1887
+ /** {@link loadAncestorChain}, plus the repository root it found (null outside a repository). */
1888
+ async loadAncestors(root) {
1889
+ if (!this.gitignore) return {
1890
+ chain: EMPTY_CHAIN,
1891
+ repoRoot: null
1892
+ };
1893
+ const ancestors = [];
1894
+ let repoRoot = null;
1895
+ let current = root;
1896
+ for (;;) {
1897
+ if (existsSync(join(current, ".git"))) {
1898
+ repoRoot = current;
1899
+ break;
1857
1900
  }
1901
+ const parent = dirname(current);
1902
+ if (parent === current) break;
1903
+ ancestors.push(parent);
1904
+ current = parent;
1858
1905
  }
1859
- const diskBytes = IS_WINDOWS || !(stats.blocks >= 0) ? size : stats.blocks * 512;
1860
- const node = this.dirs[dirIndex];
1861
- node.ownFiles++;
1862
- node.ownBytes += size;
1863
- node.ownDiskBytes += diskBytes;
1864
- this.counters.files++;
1865
- this.counters.bytes += size;
1866
- this.counters.diskBytes += diskBytes;
1867
- this.#visitor.file(dirIndex, name, stats, diskBytes);
1906
+ if (repoRoot === null) return {
1907
+ chain: EMPTY_CHAIN,
1908
+ repoRoot: null
1909
+ };
1910
+ const scopes = [];
1911
+ const outermostFirst = repoRoot === root ? [] : ancestors.reverse();
1912
+ const add = async (file, base, kind) => {
1913
+ const content = await readFile$1(file, "utf8").catch(() => null);
1914
+ if (content === null) return;
1915
+ const matcher = this.#compile(content);
1916
+ if (!matcher.hasRules) return;
1917
+ const prefix = relative(base, root).split(sep).join("/");
1918
+ scopes.push({
1919
+ matcher,
1920
+ prefix: prefix ? `${prefix}/` : "",
1921
+ strip: 0,
1922
+ source: {
1923
+ kind,
1924
+ file,
1925
+ content
1926
+ }
1927
+ });
1928
+ };
1929
+ const infoExclude = await findInfoExclude(repoRoot);
1930
+ if (infoExclude !== null) await add(infoExclude, repoRoot, "info-exclude");
1931
+ for (const dir of outermostFirst) await add(join(dir, ".gitignore"), dir, "gitignore");
1932
+ return {
1933
+ chain: scopes,
1934
+ repoRoot
1935
+ };
1868
1936
  }
1869
- /** Counts an error and keeps its details, up to {@link MAX_ERROR_DETAILS}. */
1870
- recordError(path, error) {
1871
- this.counters.errors++;
1872
- if (this.errors.length >= 100) return;
1873
- const code = errorCode(error);
1874
- this.errors.push({
1875
- path: path || ".",
1876
- code: code ?? "UNKNOWN",
1877
- message: (code && ERROR_DESCRIPTIONS[code]) ?? errorMessage(error)
1878
- });
1937
+ #compile(source) {
1938
+ return GitignoreMatcher.compile(source, { ignoreCase: this.#ignoreCase });
1879
1939
  }
1880
1940
  };
1881
1941
  /**
1882
- * Rolls per-directory totals up the tree. Must run once, after the scan.
1883
- * Relies on children always having larger indices than their parents.
1942
+ * Locates `info/exclude`. In a linked worktree or a submodule `.git` is a file
1943
+ * naming the real Git directory, and a worktree shares its main repository's
1944
+ * exclude file through `commondir`.
1884
1945
  */
1885
- function rollUp(dirs) {
1886
- for (let i = dirs.length - 1; i >= 0; i--) {
1887
- const node = dirs[i];
1888
- node.files += node.ownFiles;
1889
- node.bytes += node.ownBytes;
1890
- node.diskBytes += node.ownDiskBytes;
1891
- if (node.parent >= 0) {
1892
- const parent = dirs[node.parent];
1893
- parent.files += node.files;
1894
- parent.bytes += node.bytes;
1895
- parent.diskBytes += node.diskBytes;
1896
- if (node.bytes > parent.largestChild) parent.largestChild = node.bytes;
1897
- }
1898
- }
1899
- }
1900
- function inodeKey(stats) {
1901
- return `${stats.dev}:${stats.ino}`;
1902
- }
1903
- function joinNative(dir, name) {
1904
- return dir.endsWith(sep) ? dir + name : dir + sep + name;
1946
+ async function findInfoExclude(repoRoot) {
1947
+ const dotGit = join(repoRoot, ".git");
1948
+ const pointer = await readFile$1(dotGit, "utf8").catch(() => null);
1949
+ if (pointer === null) return join(dotGit, "info", "exclude");
1950
+ const gitDir = /^gitdir:\s*(.+?)\s*$/m.exec(pointer)?.[1];
1951
+ if (gitDir === void 0) return null;
1952
+ const dir = resolve(repoRoot, gitDir);
1953
+ const commonDir = await readFile$1(join(dir, "commondir"), "utf8").catch(() => null);
1954
+ return join(commonDir === null ? dir : resolve(dir, commonDir.trim()), "info", "exclude");
1905
1955
  }
1906
- function isUnknownType(entry) {
1907
- return !(entry.isBlockDevice() || entry.isCharacterDevice() || entry.isFIFO() || entry.isSocket());
1956
+ function isGitIgnored(chain, relPath, isDirectory) {
1957
+ let ignored = false;
1958
+ for (const scope of chain) {
1959
+ const local = scope.prefix + relPath.slice(scope.strip);
1960
+ if (local === "") continue;
1961
+ const result = scope.matcher.test(local, isDirectory);
1962
+ if (result !== void 0) ignored = result;
1963
+ }
1964
+ return ignored;
1908
1965
  }
1909
- const ERROR_DESCRIPTIONS = {
1910
- EACCES: "permission denied",
1911
- EPERM: "operation not permitted",
1912
- ENOENT: "no longer exists",
1913
- ELOOP: "too many levels of symbolic links",
1914
- EMFILE: "too many open files",
1915
- ENAMETOOLONG: "name too long",
1916
- EIO: "input/output error",
1917
- EBUSY: "resource busy"
1918
- };
1919
1966
  // src/core/options.ts
1920
1967
  /** Default number of concurrent filesystem operations. */
1921
1968
  const DEFAULT_CONCURRENCY = 32;
@@ -2295,7 +2342,8 @@ var Collector = class {
2295
2342
  name,
2296
2343
  bytes,
2297
2344
  dev: stats.dev,
2298
- ino: stats.ino
2345
+ ino: stats.ino,
2346
+ nlink: stats.nlink
2299
2347
  };
2300
2348
  const existing = this.#bySize.get(bytes);
2301
2349
  if (existing === void 0) this.#bySize.set(bytes, candidate);
@@ -4880,4 +4928,4 @@ function renderSkipsExplanation(result, options = {}) {
4880
4928
  }
4881
4929
  return `${lines.join("\n")}\n`;
4882
4930
  }
4883
- export { errorMessage as $, DEFAULT_LARGE_FILE_THRESHOLD as A, BUDGET_METRICS as B, MAX_EXPLAIN_LIMIT as C, outsideRootError as D, isOutside as E, joinRelative as F, parseSize as G, formatBudgetActual as H, DEFAULT_EXCLUDES as I, parseDuration as J, CATEGORIES as K, Excluder as L, analyze as M, DEFAULT_CONCURRENCY as N, compare as O, listDirectories as P, errorCode as Q, classify as R, EXPLAIN_VERSION as S, explainSkips as T, parseBudget as U, evaluateBudgets as V, formatBytes as W, AbortError as X, parsePointInTime as Y, DatError as Z, findConfigFile as _, renderComparisonCsv as a, validateConfig as b, renderAnalysis as c, escapeControlInLines as d, formatCount as f, CONFIG_FILE_NAMES as g, supportsColor as h, renderAnalysisCsv as i, DEFAULT_STALE_AGE as j, compactAnalysis as k, renderComparison as l, createStyle as m, renderSkipsExplanation as n, renderAnalysisMarkdown as o, stringifyJson as p, VERSION as q, renderAnalysisHtml as r, renderComparisonMarkdown as s, renderPathExplanation as t, escapeControl as u, loadConfig as v, explainPath as w, DEFAULT_EXPLAIN_LIMIT as x, buildJsonSchema as y, extensionOf as z };
4931
+ export { errorMessage as $, DEFAULT_LARGE_FILE_THRESHOLD as A, BUDGET_METRICS as B, MAX_EXPLAIN_LIMIT as C, outsideRootError as D, isOutside as E, DEFAULT_EXCLUDES as F, parseSize as G, formatBudgetActual as H, Excluder as I, parseDuration as J, CATEGORIES as K, joinRelative as L, analyze as M, DEFAULT_CONCURRENCY as N, compare as O, listDirectories as P, errorCode as Q, classify as R, EXPLAIN_VERSION as S, explainSkips as T, parseBudget as U, evaluateBudgets as V, formatBytes as W, AbortError as X, parsePointInTime as Y, DatError as Z, findConfigFile as _, renderComparisonCsv as a, validateConfig as b, renderAnalysis as c, escapeControlInLines as d, formatCount as f, CONFIG_FILE_NAMES as g, supportsColor as h, renderAnalysisCsv as i, DEFAULT_STALE_AGE as j, compactAnalysis as k, renderComparison as l, createStyle as m, renderSkipsExplanation as n, renderAnalysisMarkdown as o, stringifyJson as p, VERSION as q, renderAnalysisHtml as r, renderComparisonMarkdown as s, renderPathExplanation as t, escapeControl as u, loadConfig as v, explainPath as w, DEFAULT_EXPLAIN_LIMIT as x, buildJsonSchema as y, extensionOf as z };