@mailwoman/core 10.5.0 → 10.7.0

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.
Files changed (50) hide show
  1. package/lib/fs/zip.ts +52 -11
  2. package/lib/geocode/result.ts +46 -0
  3. package/lib/git.ts +357 -55
  4. package/lib/layers/manifest.ts +31 -0
  5. package/lib/layers/schema.ts +14 -0
  6. package/lib/license/obligations.ts +7 -0
  7. package/lib/process.ts +320 -0
  8. package/lib/resources/git.ts +9 -5
  9. package/lib/utils/events.ts +23 -0
  10. package/out/fs/zip.d.ts +14 -1
  11. package/out/fs/zip.d.ts.map +1 -1
  12. package/out/fs/zip.js +45 -10
  13. package/out/fs/zip.js.map +1 -1
  14. package/out/geocode/result.d.ts +25 -0
  15. package/out/geocode/result.d.ts.map +1 -1
  16. package/out/geocode/result.js +40 -0
  17. package/out/geocode/result.js.map +1 -1
  18. package/out/git.d.ts +180 -4
  19. package/out/git.d.ts.map +1 -1
  20. package/out/git.js +227 -37
  21. package/out/git.js.map +1 -1
  22. package/out/layers/manifest.d.ts +19 -0
  23. package/out/layers/manifest.d.ts.map +1 -1
  24. package/out/layers/manifest.js +12 -0
  25. package/out/layers/manifest.js.map +1 -1
  26. package/out/layers/schema.d.ts +10 -0
  27. package/out/layers/schema.d.ts.map +1 -1
  28. package/out/layers/schema.js +4 -0
  29. package/out/layers/schema.js.map +1 -1
  30. package/out/license/obligations.d.ts.map +1 -1
  31. package/out/license/obligations.js +7 -0
  32. package/out/license/obligations.js.map +1 -1
  33. package/out/process.d.ts +146 -0
  34. package/out/process.d.ts.map +1 -1
  35. package/out/process.js +158 -0
  36. package/out/process.js.map +1 -1
  37. package/out/resources/git.d.ts +5 -1
  38. package/out/resources/git.d.ts.map +1 -1
  39. package/out/resources/git.js +8 -5
  40. package/out/resources/git.js.map +1 -1
  41. package/out/tools/download/libpostal-resources.d.ts +2 -2
  42. package/out/tools/download/libpostal-resources.d.ts.map +1 -1
  43. package/out/tools/download/libpostal-resources.js +4 -4
  44. package/out/tools/download/libpostal-resources.js.map +1 -1
  45. package/out/utils/events.d.ts +13 -0
  46. package/out/utils/events.d.ts.map +1 -1
  47. package/out/utils/events.js +19 -0
  48. package/out/utils/events.js.map +1 -1
  49. package/package.json +7 -7
  50. package/tools/download/libpostal-resources.ts +4 -4
package/lib/fs/zip.ts CHANGED
@@ -44,8 +44,12 @@ async function openStreamingArchive(
44
44
  ): Promise<StreamingArchive & AsyncDisposable> {
45
45
  // `decodeStrings: false` returns the central directory's raw name bytes.
46
46
  // This lets the caller read a name when the archive does not declare its encoding.
47
- // See {@link ZipNameOptions}.
48
- const archive = await openArchive(archivePath.toString(), options?.filenameEncoding ? { decodeStrings: false } : {})
47
+ // See {@link ZipNameOptions}. yauzl's own name check is off because it throws on a
48
+ // leading slash. {@link memberPath} checks every name instead.
49
+ const archive = await openArchive(archivePath.toString(), {
50
+ validateFilenames: false,
51
+ ...(options?.filenameEncoding ? { decodeStrings: false } : {}),
52
+ })
49
53
 
50
54
  return Object.assign(archive, { [Symbol.asyncDispose]: () => archive.close() })
51
55
  }
@@ -88,9 +92,44 @@ export interface ZipNameOptions {
88
92
  function entryName(entry: Entry, options?: ZipNameOptions): string {
89
93
  const raw = entry.filename as unknown
90
94
 
91
- if (typeof raw === "string") return raw
95
+ if (typeof raw === "string") return memberPath(raw)
96
+
97
+ return memberPath(iconv.decode(Buffer.from(raw as Uint8Array), options?.filenameEncoding ?? "utf8"))
98
+ }
99
+
100
+ /**
101
+ * A member name as a path relative to the archive root.
102
+ * Every reader here matches and writes this form.
103
+ *
104
+ * Backslashes become forward slashes and leading slashes are removed, as `unzip` does when it extracts.
105
+ * OS Open Roads' GML archive stores `/data/`, `/doc/licence.txt` and `/readme.txt`
106
+ * beside `data/OSOpenRoads_HP.gml`.
107
+ * A reader that refused a leading slash refused that archive.
108
+ *
109
+ * @throws When the name has a drive letter or a `..` segment, so no member is
110
+ * written outside the extraction directory.
111
+ */
112
+ export function memberPath(name: string): string {
113
+ const relative = name.replaceAll("\\", "/").replace(/^\/+/, "")
114
+
115
+ if (/^[a-z]:/i.test(relative)) {
116
+ throw new Error(`Zip member '${name}' names a drive`)
117
+ }
118
+
119
+ if (relative.split("/").includes("..")) {
120
+ throw new Error(`Zip member '${name}' has a .. segment, so it would extract outside its directory`)
121
+ }
92
122
 
93
- return iconv.decode(Buffer.from(raw as Uint8Array), options?.filenameEncoding ?? "utf8")
123
+ return relative
124
+ }
125
+
126
+ /**
127
+ * Whether a member name, already passed through {@link memberPath}, is a directory entry.
128
+ *
129
+ * The root itself, a stored `/`, normalizes to the empty name.
130
+ */
131
+ function isDirectoryMember(name: string): boolean {
132
+ return name === "" || name.endsWith("/")
94
133
  }
95
134
 
96
135
  /**
@@ -185,7 +224,7 @@ export type ZipEntrySelector = string | RegExp
185
224
  */
186
225
  export interface ZipEntryInfo {
187
226
  /**
188
- * The archive-internal path, e.g. `it/countrywide.csv`.
227
+ * The archive-internal path, e.g. `it/countrywide.csv`, as {@link memberPath} normalizes it.
189
228
  *
190
229
  * Directory entries keep their trailing slash.
191
230
  */
@@ -265,7 +304,7 @@ export async function extractZipEntry(
265
304
  await using archive = await openStreamingArchive(archivePath)
266
305
 
267
306
  for await (const entry of archive) {
268
- if (!selectorMatches(selector, entry.filename)) continue
307
+ if (!selectorMatches(selector, entryName(entry))) continue
269
308
 
270
309
  await pipeline(await entry.openReadStream(), openWriteStream(destinationPath))
271
310
 
@@ -317,11 +356,13 @@ export async function extractZipEntries(
317
356
  const written: string[] = []
318
357
 
319
358
  for await (const entry of archive) {
320
- if (entry.filename.endsWith("/")) continue
359
+ const name = entryName(entry)
360
+
361
+ if (isDirectoryMember(name)) continue
321
362
 
322
- if (selector && !selectorMatches(selector, entry.filename)) continue
363
+ if (selector && !selectorMatches(selector, name)) continue
323
364
 
324
- const relative = flatten ? basename(entry.filename) : entry.filename
365
+ const relative = flatten ? basename(name) : name
325
366
  const destination = resolvePath(destinationDirectory, relative)
326
367
 
327
368
  if (!flatten) {
@@ -334,7 +375,7 @@ export async function extractZipEntries(
334
375
  await pipeline(await entry.openReadStream(), openWriteStream(destination))
335
376
  }
336
377
 
337
- written.push(entry.filename)
378
+ written.push(name)
338
379
  }
339
380
 
340
381
  return written
@@ -361,7 +402,7 @@ export async function verifyZipIntegrity(archivePath: PathBuilderLike): Promise<
361
402
  let checked = 0
362
403
 
363
404
  for await (const entry of archive) {
364
- if (entry.filename.endsWith("/")) continue
405
+ if (isDirectoryMember(entryName(entry))) continue
365
406
 
366
407
  await using contents = await openEntryStream(entry, { validateCrc32: false })
367
408
  let checksum = 0
@@ -165,6 +165,43 @@ export const RooftopSchema = z.object({ localityNorm: z.string().nullable(), pos
165
165
 
166
166
  export type Rooftop = z.infer<typeof RooftopSchema>
167
167
 
168
+ /**
169
+ * The register row that supplied an `address_point` or `interpolated` coordinate,
170
+ * as the row itself records it.
171
+ */
172
+ export const CoordinateSourceSchema = z
173
+ .object({
174
+ /**
175
+ * The row's provenance stamp, verbatim: `openstreetmap:nz` for a row an operator built
176
+ * from an OpenStreetMap extract, `overture:NAD` for an Overture row, and so on.
177
+ */
178
+ source: z.string(),
179
+ /**
180
+ * The data release the row came from, as the row records it, or null when the resolved
181
+ * tree carries none, as a tree a client sent to `/v1/resolve` may not.
182
+ */
183
+ release: z.string().nullable(),
184
+ })
185
+ .meta({ id: "CoordinateSource", description: "The register row that supplied the coordinate." })
186
+
187
+ export type CoordinateSource = z.infer<typeof CoordinateSourceSchema>
188
+
189
+ /**
190
+ * The service-level credit the OpenStreetMap Foundation's Geocoding Guideline asks
191
+ * of a public geocoder that serves OpenStreetMap data.
192
+ */
193
+ export const OPENSTREETMAP_CREDIT = "© OpenStreetMap contributors, ODbL 1.0, https://www.openstreetmap.org/copyright"
194
+
195
+ /**
196
+ * Whether a row's provenance stamp names an OpenStreetMap-derived row.
197
+ *
198
+ * `@mailwoman/osm` stamps every row it builds `openstreetmap:<cc>`, and a row the
199
+ * street-recovery pass placed `openstreetmap:<cc>#recovered`, so the prefix decides.
200
+ */
201
+ export function isOpenStreetMapSource(source: string | null | undefined): boolean {
202
+ return typeof source === "string" && source.startsWith("openstreetmap:")
203
+ }
204
+
168
205
  /**
169
206
  * The poi.db entity that supplied a `venue`-tier coordinate.
170
207
  */
@@ -236,6 +273,15 @@ export const GeocodeResultSchema = z
236
273
  */
237
274
  rooftop: RooftopSchema.nullable(),
238
275
 
276
+ /**
277
+ * The register row that supplied the coordinate, with its provenance stamp and release.
278
+ *
279
+ * Set on the `address_point` and `interpolated` tiers, whose coordinate comes from one register row.
280
+ * It is null on every other tier, including a coordinate a later pass moved to a venue
281
+ * or a plus code, because that coordinate no longer comes from the row.
282
+ */
283
+ coordinate_source: CoordinateSourceSchema.nullable(),
284
+
239
285
  /**
240
286
  * The uncertainty radius in meters, or null when the tier reports none.
241
287
  */
package/lib/git.ts CHANGED
@@ -2,18 +2,343 @@
2
2
  * @copyright Sister Software
3
3
  * @license AGPL-3.0
4
4
  * @author Teffen Ellis, et al.
5
- * @file The working tree's own git state: head, the current branch, dirty tracked files, tracked paths.
5
+ * @file The one home for running git: {@linkcode GitClient} and the readers built on it.
6
6
  *
7
- * Every reader here is one `git` invocation with its output shaped for the caller, so the seven sites that each
8
- * spelled `git rev-parse head` through their own wrapper share one. A resource repository clone and pull is a
9
- * different concern and lives in `resources/git.ts`.
7
+ * A `GitClient` is bound to one directory. Short reads such as `rev-parse` answer their stdout.
8
+ * Long transfers such as `clone` and `fetch` run as a {@linkcode ProcessTask} with `--progress`,
9
+ * and the client re-dispatches each parsed progress line, so a command renders one stream for every repository it touches.
10
+ * Disposing the client stops every git process it started.
11
+ *
12
+ * The free functions below are the same readers for a caller that needs one answer about the working tree.
10
13
  */
11
14
 
15
+ import { asyncInit } from "async-init"
12
16
  import type { PathBuilderLike } from "path-ts"
13
17
  import { TextSpliterator } from "spliterator"
14
18
 
19
+ import type { IRuntimeLogger } from "#logging"
15
20
  import { repoRootPathBuilder } from "#paths"
16
- import { runFile } from "#process"
21
+ import {
22
+ type ProcessProgress,
23
+ type ProcessResult,
24
+ ProcessTask,
25
+ type ProcessTaskOptions,
26
+ runFile,
27
+ runFileSync,
28
+ } from "#process"
29
+ import { TypedEventTarget } from "#utils/events"
30
+
31
+ /**
32
+ * The stdout ceiling for a git read that lists paths or history.
33
+ */
34
+ const LISTING_MAX_BUFFER = 64 * 1024 * 1024
35
+
36
+ /**
37
+ * Git's progress meter, as it writes one redraw to stderr under `--progress`:
38
+ * `Receiving objects: 45% (450/1000), 1.20 MiB | 2.40 MiB/s`, or the same line
39
+ * prefixed with `remote: ` when the server reports it.
40
+ */
41
+ const GIT_PROGRESS_PATTERN = /^(?:remote: )?([A-Z][A-Za-z ]+):\s+(\d{1,3})% \((\d+)\/(\d+)\)/u
42
+
43
+ /**
44
+ * Read one stderr line of a git transfer as progress, or `null` for any other line.
45
+ */
46
+ export function parseGitProgress(line: string): ProcessProgress | null {
47
+ const match = GIT_PROGRESS_PATTERN.exec(line)
48
+
49
+ if (!match) return null
50
+
51
+ return {
52
+ stage: match[1]!,
53
+ percent: Number(match[2]),
54
+ processed: Number(match[3]),
55
+ total: Number(match[4]),
56
+ }
57
+ }
58
+
59
+ /**
60
+ * One progress step from a git transfer, with the command line it came from.
61
+ */
62
+ export interface GitProgress extends ProcessProgress {
63
+ command: string
64
+ }
65
+
66
+ /**
67
+ * The events a {@linkcode GitClient} dispatches, keyed by type, with each event's `detail`.
68
+ */
69
+ export interface GitClientEventMap {
70
+ progress: GitProgress
71
+ }
72
+
73
+ /**
74
+ * Options for {@linkcode GitClient}.
75
+ */
76
+ export interface GitClientOptions {
77
+ /**
78
+ * The directory git runs in.
79
+ *
80
+ * @defaultValue the repository root
81
+ */
82
+ cwd?: PathBuilderLike
83
+ logger?: IRuntimeLogger
84
+ /**
85
+ * Aborting the signal stops every git process the client started.
86
+ */
87
+ signal?: AbortSignal
88
+ }
89
+
90
+ /**
91
+ * Options for a single git read.
92
+ */
93
+ export interface GitReadOptions {
94
+ /**
95
+ * The stdout ceiling in bytes.
96
+ *
97
+ * A read past it rejects rather than answering a truncated listing.
98
+ */
99
+ maxBuffer?: number
100
+ /**
101
+ * Whether to remove surrounding whitespace from stdout.
102
+ *
103
+ * Porcelain output starts with a status column that may be a space, so a porcelain read passes `false`.
104
+ *
105
+ * @defaultValue `true`
106
+ */
107
+ trim?: boolean
108
+ }
109
+
110
+ /**
111
+ * Options for a git transfer.
112
+ */
113
+ export interface GitTransferOptions extends Pick<ProcessTaskOptions, "stdin" | "stdout" | "rawStdout"> {
114
+ /**
115
+ * Whether a non-zero exit rejects the transfer.
116
+ *
117
+ * @defaultValue `true`
118
+ */
119
+ reject?: boolean
120
+ }
121
+
122
+ /**
123
+ * A git runner bound to one directory, modeled on `APIClient`.
124
+ *
125
+ * Its reads answer stdout with the trailing newline removed.
126
+ * Its transfers report progress as `progress` events.
127
+ *
128
+ * Disposal stops every process the client started and waits for each to exit.
129
+ *
130
+ * Initialize it with `construct(GitClient, options)` from `async-init` to resolve
131
+ * {@linkcode GitClient.root} and {@linkcode GitClient.commonDirectory} before use.
132
+ * A client that will clone into a directory that does not exist yet is used without initialization.
133
+ */
134
+ export class GitClient extends TypedEventTarget<GitClientEventMap> implements AsyncDisposable {
135
+ public readonly cwd: PathBuilderLike
136
+ public readonly logger: IRuntimeLogger | undefined
137
+
138
+ /**
139
+ * The working-tree root, set by initialization.
140
+ */
141
+ public root: string | null = null
142
+ /**
143
+ * The shared `.git` directory, set by initialization.
144
+ *
145
+ * The main checkout and each of its worktrees report the same directory.
146
+ */
147
+ public commonDirectory: string | null = null
148
+
149
+ readonly #shutdown = new AbortController()
150
+ readonly #tasks = new Set<ProcessTask>()
151
+ #disposePromise: Promise<void> | null = null
152
+
153
+ constructor(options: GitClientOptions = {}) {
154
+ super()
155
+
156
+ this.cwd = options.cwd ?? repoRootPathBuilder
157
+ this.logger = options.logger
158
+
159
+ options.signal?.addEventListener("abort", () => void this[Symbol.asyncDispose](), { once: true })
160
+ }
161
+
162
+ public async [asyncInit](): Promise<void> {
163
+ this.root = await this.read(["rev-parse", "--show-toplevel"])
164
+ this.commonDirectory = await this.read(["rev-parse", "--path-format=absolute", "--git-common-dir"])
165
+ }
166
+
167
+ /**
168
+ * Run git to completion and answer stdout with surrounding whitespace removed.
169
+ *
170
+ * A non-zero exit rejects with a `ProcessError` carrying git's stderr.
171
+ */
172
+ public async read(args: string | readonly string[], options: GitReadOptions = {}): Promise<string> {
173
+ this.#shutdown.signal.throwIfAborted()
174
+
175
+ const argumentList = typeof args === "string" ? [args] : args
176
+
177
+ this.logger?.debug(`$ git ${argumentList.join(" ")}`)
178
+
179
+ const { stdout } = await runFile("git", argumentList, {
180
+ cwd: this.cwd,
181
+ maxBuffer: options.maxBuffer,
182
+ signal: this.#shutdown.signal,
183
+ })
184
+
185
+ return options.trim === false ? stdout : stdout.trim()
186
+ }
187
+
188
+ /**
189
+ * Start git as a {@linkcode ProcessTask} whose parsed progress lines the client re-dispatches.
190
+ *
191
+ * The caller passes `--progress` where the subcommand accepts it.
192
+ * Git writes the meter only to a terminal unless asked.
193
+ */
194
+ public start(args: readonly string[], options: GitTransferOptions = {}): ProcessTask {
195
+ this.#shutdown.signal.throwIfAborted()
196
+
197
+ const task = new ProcessTask("git", args, {
198
+ stdin: options.stdin,
199
+ stdout: options.stdout,
200
+ rawStdout: options.rawStdout,
201
+ cwd: this.cwd,
202
+ logger: this.logger,
203
+ reject: options.reject,
204
+ signal: this.#shutdown.signal,
205
+ progress: parseGitProgress,
206
+ })
207
+
208
+ this.#tasks.add(task)
209
+
210
+ task.on("progress", (step) => this.emit("progress", { ...step, command: task.command }))
211
+ void task.result.finally(() => this.#tasks.delete(task)).catch(() => undefined)
212
+
213
+ return task
214
+ }
215
+
216
+ /**
217
+ * Clone `url` into `directory`, shallow when `depth` is given.
218
+ */
219
+ public clone(
220
+ url: string,
221
+ directory: PathBuilderLike,
222
+ options: GitTransferOptions & { depth?: number } = {}
223
+ ): Promise<ProcessResult> {
224
+ const depth = options.depth === undefined ? [] : ["--depth", String(options.depth)]
225
+
226
+ return this.start(["clone", "--progress", ...depth, url, directory.toString()], options).result
227
+ }
228
+
229
+ /**
230
+ * Fetch `remote` into the client's repository.
231
+ */
232
+ public fetch(remote = "origin", options: GitTransferOptions = {}): Promise<ProcessResult> {
233
+ return this.start(["fetch", "--progress", remote], options).result
234
+ }
235
+
236
+ /**
237
+ * Pull the current branch's upstream into the client's repository.
238
+ */
239
+ public pull(options: GitTransferOptions = {}): Promise<ProcessResult> {
240
+ return this.start(["pull", "--progress"], options).result
241
+ }
242
+
243
+ /**
244
+ * The commit `HEAD` refers to, as a full SHA or, with `short`, git's abbreviation.
245
+ */
246
+ public head(options: { short?: boolean } = {}): Promise<string> {
247
+ return this.read(options.short ? ["rev-parse", "--short", "HEAD"] : ["rev-parse", "HEAD"])
248
+ }
249
+
250
+ /**
251
+ * The checked-out branch name, or `HEAD` when the tree is detached.
252
+ */
253
+ public currentBranch(): Promise<string> {
254
+ return this.read(["rev-parse", "--abbrev-ref", "HEAD"])
255
+ }
256
+
257
+ /**
258
+ * `git status --porcelain` lines, narrowed by pathspecs.
259
+ *
260
+ * Untracked files are included unless `untracked` is `false`.
261
+ */
262
+ public async status(pathspecs: readonly string[] = [], options: { untracked?: boolean } = {}): Promise<string[]> {
263
+ const scope = pathspecs.length ? ["--", ...pathspecs] : []
264
+ const untracked = options.untracked === false ? ["--untracked-files=no"] : []
265
+ const output = await this.read(["status", "--porcelain", ...untracked, ...scope], { trim: false })
266
+
267
+ // `trim: false` keeps the status column, whose first character is a space for an unstaged change.
268
+ return TextSpliterator.from(output, { trim: false })
269
+ .map((line) => line.trimEnd())
270
+ .filter((line) => line.length)
271
+ .toArray()
272
+ }
273
+
274
+ /**
275
+ * Run git and split its NUL-delimited stdout into the non-empty fields.
276
+ */
277
+ public async readNulDelimited(args: readonly string[]): Promise<string[]> {
278
+ const output = await this.read(args, { maxBuffer: LISTING_MAX_BUFFER })
279
+
280
+ return output.split("\0").filter((field) => field.length)
281
+ }
282
+
283
+ /**
284
+ * Run git and answer its stdout's non-empty lines.
285
+ */
286
+ public async readLines(args: readonly string[]): Promise<string[]> {
287
+ const output = await this.read(args, { maxBuffer: LISTING_MAX_BUFFER })
288
+
289
+ return TextSpliterator.from(output)
290
+ .map((line) => line.trimEnd())
291
+ .filter((line) => line.length)
292
+ .toArray()
293
+ }
294
+
295
+ /**
296
+ * Disposal stops every git process the client started and waits for each to exit.
297
+ * Repeated calls return the same promise.
298
+ */
299
+ public [Symbol.asyncDispose](): Promise<void> {
300
+ if (this.#disposePromise) return this.#disposePromise
301
+
302
+ this.#shutdown.abort(new Error(`git client for ${this.cwd} is disposed`))
303
+
304
+ this.#disposePromise = Promise.all([...this.#tasks].map((task) => task[Symbol.asyncDispose]())).then(
305
+ () => undefined
306
+ )
307
+
308
+ return this.#disposePromise
309
+ }
310
+ }
311
+
312
+ /**
313
+ * Options for {@linkcode gitSync}.
314
+ */
315
+ export interface GitSyncOptions {
316
+ cwd?: PathBuilderLike
317
+ env?: NodeJS.ProcessEnv
318
+ /**
319
+ * Whether to remove surrounding whitespace from stdout.
320
+ *
321
+ * @defaultValue `true`
322
+ */
323
+ trim?: boolean
324
+ }
325
+
326
+ /**
327
+ * Run git synchronously and answer stdout, for a slot whose caller is synchronous.
328
+ *
329
+ * Git's stderr is captured rather than written to the terminal.
330
+ * A non-zero exit throws the builtin's error, which carries that stderr.
331
+ */
332
+ export function gitSync(args: readonly string[], options: GitSyncOptions = {}): string {
333
+ const stdout = runFileSync("git", args, {
334
+ cwd: options.cwd ?? repoRootPathBuilder,
335
+ env: options.env,
336
+ stdio: "pipe",
337
+ maxBuffer: LISTING_MAX_BUFFER,
338
+ })
339
+
340
+ return options.trim === false ? stdout : stdout.trim()
341
+ }
17
342
 
18
343
  /**
19
344
  * Run a git command in the given repository.
@@ -25,11 +350,7 @@ export async function git(
25
350
  repoRoot: PathBuilderLike = repoRootPathBuilder,
26
351
  maxBuffer?: number
27
352
  ): Promise<string> {
28
- const argumentList = Array.isArray(args) ? args : [args]
29
-
30
- const { stdout } = await runFile("git", argumentList, { cwd: repoRoot, encoding: "utf8", maxBuffer })
31
-
32
- return stdout.trim()
353
+ return new GitClient({ cwd: repoRoot }).read(args, { maxBuffer })
33
354
  }
34
355
 
35
356
  /**
@@ -39,16 +360,14 @@ export async function gitHead(
39
360
  repoRoot: PathBuilderLike = repoRootPathBuilder,
40
361
  options: { short?: boolean } = {}
41
362
  ): Promise<string> {
42
- const args = options.short ? ["rev-parse", "--short", "HEAD"] : ["rev-parse", "HEAD"]
43
-
44
- return git(args, repoRoot)
363
+ return new GitClient({ cwd: repoRoot }).head(options)
45
364
  }
46
365
 
47
366
  /**
48
367
  * The checked-out branch name, or `head` when the tree is detached.
49
368
  */
50
369
  export async function currentBranch(repoRoot: PathBuilderLike = repoRootPathBuilder): Promise<string> {
51
- return git(["rev-parse", "--abbrev-ref", "HEAD"], repoRoot)
370
+ return new GitClient({ cwd: repoRoot }).currentBranch()
52
371
  }
53
372
 
54
373
  /**
@@ -79,13 +398,7 @@ export async function dirtyTrackedFiles(
79
398
  repoRoot: PathBuilderLike = repoRootPathBuilder,
80
399
  pathspecs: string[] = []
81
400
  ): Promise<string[]> {
82
- const scope = pathspecs.length ? ["--", ...pathspecs] : []
83
- const output = await git(["status", "--porcelain", "--untracked-files=no", ...scope], repoRoot)
84
-
85
- return TextSpliterator.from(output)
86
- .map((line) => line.trimEnd())
87
- .filter((line) => line.length)
88
- .toArray()
401
+ return new GitClient({ cwd: repoRoot }).status(pathspecs, { untracked: false })
89
402
  }
90
403
 
91
404
  /**
@@ -103,13 +416,7 @@ export async function workingTreeStatus(
103
416
  repoRoot: PathBuilderLike = repoRootPathBuilder,
104
417
  pathspecs: string[] = []
105
418
  ): Promise<string[]> {
106
- const scope = pathspecs.length ? ["--", ...pathspecs] : []
107
- const output = await git(["status", "--porcelain", ...scope], repoRoot)
108
-
109
- return TextSpliterator.from(output)
110
- .map((line) => line.trimEnd())
111
- .filter((line) => line.length)
112
- .toArray()
419
+ return new GitClient({ cwd: repoRoot }).status(pathspecs)
113
420
  }
114
421
 
115
422
  /**
@@ -124,9 +431,7 @@ export async function changedFiles(
124
431
  base: string,
125
432
  head: string
126
433
  ): Promise<string[]> {
127
- const output = await git(["diff", "--name-only", "-z", base, head], repoRoot, 64 * 1024 * 1024)
128
-
129
- return output.split("\0").filter((path) => path.length)
434
+ return new GitClient({ cwd: repoRoot }).readNulDelimited(["diff", "--name-only", "-z", base, head])
130
435
  }
131
436
 
132
437
  /**
@@ -139,7 +444,7 @@ export async function renamesSince(
139
444
  ref: string,
140
445
  repoRoot: PathBuilderLike = repoRootPathBuilder
141
446
  ): Promise<Array<{ from: string; to: string }>> {
142
- const fields = (await git(["diff", "--name-status", "-M", "-z", ref], repoRoot, 64 * 1024 * 1024)).split("\0")
447
+ const fields = (await git(["diff", "--name-status", "-M", "-z", ref], repoRoot, LISTING_MAX_BUFFER)).split("\0")
143
448
  const renames: Array<{ from: string; to: string }> = []
144
449
 
145
450
  for (let index = 0; index < fields.length;) {
@@ -165,9 +470,7 @@ export async function renamesSince(
165
470
  * Every path `ref` tracks, repo-relative, read NUL-delimited.
166
471
  */
167
472
  export async function filesAtRef(ref: string, repoRoot: PathBuilderLike = repoRootPathBuilder): Promise<string[]> {
168
- const output = await git(["ls-tree", "-r", "--name-only", "-z", ref], repoRoot, 64 * 1024 * 1024)
169
-
170
- return output.split("\0").filter((path) => path.length)
473
+ return new GitClient({ cwd: repoRoot }).readNulDelimited(["ls-tree", "-r", "--name-only", "-z", ref])
171
474
  }
172
475
 
173
476
  /**
@@ -180,9 +483,7 @@ export async function trackedFiles(
180
483
  repoRoot: PathBuilderLike = repoRootPathBuilder,
181
484
  pathspecs: string[] = []
182
485
  ): Promise<string[]> {
183
- const output = await git(["ls-files", "-z", ...pathspecs], repoRoot, 64 * 1024 * 1024)
184
-
185
- return output.split("\0").filter((path) => path.length)
486
+ return new GitClient({ cwd: repoRoot }).readNulDelimited(["ls-files", "-z", ...pathspecs])
186
487
  }
187
488
 
188
489
  /**
@@ -200,13 +501,14 @@ export async function workingTreeFiles(
200
501
  pathspecs: string[] = [],
201
502
  repoRoot: PathBuilderLike = repoRootPathBuilder
202
503
  ): Promise<string[]> {
203
- const output = await git(
204
- ["ls-files", "-z", "--cached", "--others", "--exclude-standard", ...pathspecs],
205
- repoRoot,
206
- 64 * 1024 * 1024
207
- )
208
-
209
- return output.split("\0").filter((path) => path.length)
504
+ return new GitClient({ cwd: repoRoot }).readNulDelimited([
505
+ "ls-files",
506
+ "-z",
507
+ "--cached",
508
+ "--others",
509
+ "--exclude-standard",
510
+ ...pathspecs,
511
+ ])
210
512
  }
211
513
 
212
514
  /**
@@ -229,14 +531,14 @@ export async function workingTreeFiles(
229
531
  * against 11,483 for the reading that answers the wrong set.
230
532
  */
231
533
  export async function movedAwayPaths(repoRoot: PathBuilderLike = repoRootPathBuilder): Promise<Set<string>> {
232
- const output = await git(
233
- ["log", "--all", "--no-renames", "--diff-filter=D", "--name-only", "--format="],
234
- repoRoot,
235
- 64 * 1024 * 1024
236
- )
237
-
238
- return TextSpliterator.from(output)
239
- .map((line) => line.trimEnd())
240
- .filter((line) => line.length)
241
- .toSet()
534
+ const lines = await new GitClient({ cwd: repoRoot }).readLines([
535
+ "log",
536
+ "--all",
537
+ "--no-renames",
538
+ "--diff-filter=D",
539
+ "--name-only",
540
+ "--format=",
541
+ ])
542
+
543
+ return new Set(lines)
242
544
  }