Skip to content
Myr

glob.ts

This file

Path

packages/gate/src/glob.ts

65 lines · 1.9 KiB · TypeScript

Last changed by

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

History of this file

Take it

The walk stopped after 200 commits: lines older than 678c8b8 point at it.

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

line 1why, one step back
1/**

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

lines 2–5why, one step back
2 * Globs read as `.gitignore` reads them: a glob with a `/` before its end is
3 * anchored at the root, and one with none matches a file's name at any depth.4 * The gate keeps its own matcher rather than importing `@repo/checks`' (it5 * takes no checks dependency); both read the same globs.

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 6–65why, one step back
6 */
78// The characters a RegExp reads as syntax, which a glob means literally.9const SYNTAX = new Set("\\^$.|+()[]{}");1011const sourceOf = (glob: string) => {12 let source = "";13 let at = 0;1415 while (at < glob.length) {16 if (glob.startsWith("**/", at)) {17 // Any number of whole folders, none included.18 source += "(?:.*/)?";19 at += 3;20 } else if (glob.startsWith("/**", at) && at + 3 === glob.length) {21 // The folder itself, or anything under it.22 source += "(?:/.*)?";23 at += 3;24 } else if (glob.startsWith("**", at)) {25 source += ".*";26 at += 2;27 } else {28 const char = glob.charAt(at);2930 if (char === "*") {31 source += "[^/]*";32 } else if (char === "?") {33 source += "[^/]";34 } else {35 source += SYNTAX.has(char) ? `\\${char}` : char;36 }3738 at += 1;39 }40 }4142 return `^${source}$`;43};4445/**46 * The glob as one anchored at the root, by `.gitignore`'s rules. Whether it47 * is anchored is read before a trailing `/` becomes `/**`, so `generated/`48 * is every folder of that name.49 */50const anchored = (glob: string) => {51 const folder = glob.endsWith("/") ? `${glob}**` : glob;5253 if (folder.startsWith("/")) {54 return folder.slice(1);55 }5657 return glob.slice(0, -1).includes("/") ? folder : `**/${folder}`;58};5960export const matchGlob = (glob: string, path: string): boolean =>61 new RegExp(sourceOf(anchored(glob)), "u").test(path);6263export const matchAny = (globs: readonly string[], path: string): boolean =>64 globs.some((glob) => !glob.startsWith("!") && matchGlob(glob, path)) &&65 !globs.some((glob) => glob.startsWith("!") && matchGlob(glob.slice(1), path));