@yaks/git 0.0.0-stage → 0.2.36

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 (183) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +754 -2
  3. package/_dist/address.d.ts +6 -0
  4. package/_dist/address.d.ts.map +1 -0
  5. package/_dist/checkout_vocab.d.ts +3 -0
  6. package/_dist/checkout_vocab.d.ts.map +1 -0
  7. package/_dist/cites.d.ts +48 -0
  8. package/_dist/cites.d.ts.map +1 -0
  9. package/_dist/commit.d.ts +36 -0
  10. package/_dist/commit.d.ts.map +1 -0
  11. package/_dist/comp.d.ts +29 -0
  12. package/_dist/comp.d.ts.map +1 -0
  13. package/_dist/door.d.ts +29 -0
  14. package/_dist/door.d.ts.map +1 -0
  15. package/_dist/format.d.ts +2 -0
  16. package/_dist/format.d.ts.map +1 -0
  17. package/_dist/hold.d.ts +6 -0
  18. package/_dist/hold.d.ts.map +1 -0
  19. package/_dist/host.d.ts +126 -0
  20. package/_dist/host.d.ts.map +1 -0
  21. package/_dist/http.d.ts +33 -0
  22. package/_dist/http.d.ts.map +1 -0
  23. package/_dist/import.d.ts +13 -0
  24. package/_dist/import.d.ts.map +1 -0
  25. package/_dist/index.d.ts +80 -0
  26. package/_dist/index.d.ts.map +1 -0
  27. package/_dist/land.d.ts +77 -0
  28. package/_dist/land.d.ts.map +1 -0
  29. package/_dist/mod.d.ts +73 -0
  30. package/_dist/mod.d.ts.map +1 -0
  31. package/_dist/objects.d.ts +40 -0
  32. package/_dist/objects.d.ts.map +1 -0
  33. package/_dist/oid.d.ts +24 -0
  34. package/_dist/oid.d.ts.map +1 -0
  35. package/_dist/pack-store.d.ts +9 -0
  36. package/_dist/pack-store.d.ts.map +1 -0
  37. package/_dist/pack.d.ts +26 -0
  38. package/_dist/pack.d.ts.map +1 -0
  39. package/_dist/pkt.d.ts +14 -0
  40. package/_dist/pkt.d.ts.map +1 -0
  41. package/_dist/placement.d.ts +4 -0
  42. package/_dist/placement.d.ts.map +1 -0
  43. package/_dist/plugin.d.ts +43 -0
  44. package/_dist/plugin.d.ts.map +1 -0
  45. package/_dist/project.d.ts +20 -0
  46. package/_dist/project.d.ts.map +1 -0
  47. package/_dist/push.d.ts +42 -0
  48. package/_dist/push.d.ts.map +1 -0
  49. package/_dist/refs.d.ts +81 -0
  50. package/_dist/refs.d.ts.map +1 -0
  51. package/_dist/rewrite.d.ts +35 -0
  52. package/_dist/rewrite.d.ts.map +1 -0
  53. package/_dist/service.d.ts +35 -0
  54. package/_dist/service.d.ts.map +1 -0
  55. package/_dist/sha1.d.ts +11 -0
  56. package/_dist/sha1.d.ts.map +1 -0
  57. package/_dist/source.d.ts +12 -0
  58. package/_dist/source.d.ts.map +1 -0
  59. package/_dist/tools.d.ts +11 -0
  60. package/_dist/tools.d.ts.map +1 -0
  61. package/_dist/tree.d.ts +28 -0
  62. package/_dist/tree.d.ts.map +1 -0
  63. package/_dist/unpack.d.ts +5 -0
  64. package/_dist/unpack.d.ts.map +1 -0
  65. package/_dist/vocab.d.ts +8 -0
  66. package/_dist/vocab.d.ts.map +1 -0
  67. package/_dist/workspace.d.ts +17 -0
  68. package/_dist/workspace.d.ts.map +1 -0
  69. package/address.js +9 -0
  70. package/address.js.map +1 -0
  71. package/address.ts +15 -0
  72. package/cache.js +9 -0
  73. package/cache.js.map +1 -0
  74. package/cache.ts +6 -0
  75. package/checkout.js +18 -0
  76. package/checkout.js.map +1 -0
  77. package/checkout.ts +24 -0
  78. package/checkout_vocab.js +14 -0
  79. package/checkout_vocab.js.map +1 -0
  80. package/checkout_vocab.ts +11 -0
  81. package/cites.js +189 -0
  82. package/cites.js.map +1 -0
  83. package/cites.ts +206 -0
  84. package/commit.js +128 -0
  85. package/commit.js.map +1 -0
  86. package/commit.ts +183 -0
  87. package/comp.js +94 -0
  88. package/comp.js.map +1 -0
  89. package/comp.ts +111 -0
  90. package/deno.json +1 -0
  91. package/door.js +88 -0
  92. package/door.js.map +1 -0
  93. package/door.ts +142 -0
  94. package/format.js +43 -0
  95. package/format.js.map +1 -0
  96. package/format.ts +49 -0
  97. package/hold.js +17 -0
  98. package/hold.js.map +1 -0
  99. package/hold.ts +21 -0
  100. package/host.js +1024 -0
  101. package/host.js.map +1 -0
  102. package/host.ts +1140 -0
  103. package/http.js +268 -0
  104. package/http.js.map +1 -0
  105. package/http.ts +329 -0
  106. package/import.js +141 -0
  107. package/import.js.map +1 -0
  108. package/import.ts +128 -0
  109. package/index.js +496 -0
  110. package/index.js.map +1 -0
  111. package/index.ts +634 -0
  112. package/land.js +788 -0
  113. package/land.js.map +1 -0
  114. package/land.ts +871 -0
  115. package/mod.js +73 -0
  116. package/mod.js.map +1 -0
  117. package/mod.ts +74 -0
  118. package/objects.js +331 -0
  119. package/objects.js.map +1 -0
  120. package/objects.ts +390 -0
  121. package/oid.js +50 -0
  122. package/oid.js.map +1 -0
  123. package/oid.ts +83 -0
  124. package/pack-index.js +103 -0
  125. package/pack-index.js.map +1 -0
  126. package/pack-index.ts +104 -0
  127. package/pack-store.js +216 -0
  128. package/pack-store.js.map +1 -0
  129. package/pack-store.ts +292 -0
  130. package/pack.js +121 -0
  131. package/pack.js.map +1 -0
  132. package/pack.ts +146 -0
  133. package/package.json +78 -4
  134. package/pkt.js +73 -0
  135. package/pkt.js.map +1 -0
  136. package/pkt.ts +93 -0
  137. package/placement.js +44 -0
  138. package/placement.js.map +1 -0
  139. package/placement.ts +38 -0
  140. package/plugin.js +66 -0
  141. package/plugin.js.map +1 -0
  142. package/plugin.ts +88 -0
  143. package/process-cwd.py +57 -0
  144. package/project.js +142 -0
  145. package/project.js.map +1 -0
  146. package/project.ts +151 -0
  147. package/push.js +401 -0
  148. package/push.js.map +1 -0
  149. package/push.ts +451 -0
  150. package/refs.js +176 -0
  151. package/refs.js.map +1 -0
  152. package/refs.ts +285 -0
  153. package/rewrite.js +176 -0
  154. package/rewrite.js.map +1 -0
  155. package/rewrite.ts +173 -0
  156. package/service.js +104 -0
  157. package/service.js.map +1 -0
  158. package/service.ts +194 -0
  159. package/sha1.js +115 -0
  160. package/sha1.js.map +1 -0
  161. package/sha1.ts +146 -0
  162. package/source.js +100 -0
  163. package/source.js.map +1 -0
  164. package/source.ts +116 -0
  165. package/spare.js +108 -0
  166. package/spare.js.map +1 -0
  167. package/spare.ts +94 -0
  168. package/tools.js +278 -0
  169. package/tools.js.map +1 -0
  170. package/tools.ts +310 -0
  171. package/tree.js +105 -0
  172. package/tree.js.map +1 -0
  173. package/tree.ts +132 -0
  174. package/unpack.js +207 -0
  175. package/unpack.js.map +1 -0
  176. package/unpack.ts +210 -0
  177. package/vocab.js +20 -0
  178. package/vocab.js.map +1 -0
  179. package/vocab.json +386 -0
  180. package/vocab.ts +22 -0
  181. package/workspace.js +449 -0
  182. package/workspace.js.map +1 -0
  183. package/workspace.ts +445 -0
package/tools.ts ADDED
@@ -0,0 +1,310 @@
1
+ // The implementations behind the `tool: true` declarations in ./vocab.json,
2
+ // exported as `@yaks/git/tools`.
3
+ //
4
+ // File tools read the machine running the call. `land` takes its checkout
5
+ // explicitly as `cwd`: the CLI fills its current directory, and an MCP
6
+ // caller names its own, even when sub-agents share the connection.
7
+ //
8
+ // A landing refused for the caller's own state is an expected invocation
9
+ // failure: a moved base is returned as a divergence, which becomes a
10
+ // `CallError` carrying Git's whole account, and a worktree that is dirty,
11
+ // detached or on the base, or a revert the guard caught, is a `LandError`,
12
+ // which is one already. The tool
13
+ // runner records either as a failed call and a command line reports it as
14
+ // exit 1. An unexpected Git command failure escapes as a plain error, for the
15
+ // runner to report as the fault it is.
16
+ //
17
+ // `cites check` is a check — a tool whose verb is `check`, which is all a
18
+ // doctor is (@yaks/tools ./check.ts) — so a citation that moved is a finding
19
+ // in a report, never a refused write. It enforces nothing, on purpose: a
20
+ // document whose code moved is work somebody has to do, not a transaction to
21
+ // reject. `cites verify` is the only thing that writes the `verified` mark,
22
+ // which is what keeps the mark meaning "somebody looked" rather than
23
+ // "somebody edited this".
24
+ //
25
+ import type { Bundle, Comp, Graph } from 'jsr:@yaks/graph@0.2.36'
26
+ import { argsOf } from '@yaks/graph/call'
27
+ import { Refused } from '@yaks/graph/errors'
28
+ import type { Runs } from 'jsr:@yaks/graph@0.2.36/tools'
29
+ import { and, present, want } from '@yaks/query'
30
+ import { human, idsIn, parse, prefixOf } from '@yaks/id'
31
+ import { verify as entityVerify } from '@yaks/kernel'
32
+ import { once } from '@yaks/fp'
33
+ import type { Finding, Level } from 'jsr:@yaks/tools@0.2.36'
34
+ import { CallError } from '@yaks/tools/errors'
35
+ import { checked } from '@yaks/tools/check'
36
+ import { land, type LandOps, run as git } from './land.js'
37
+ import { localFilesystem, locate, repositoryEid } from './host.js'
38
+ import {
39
+ type Checkout,
40
+ CITES,
41
+ FILE,
42
+ LINES,
43
+ REVISION,
44
+ type Status,
45
+ status,
46
+ SYMBOL,
47
+ tracked,
48
+ VERIFIED,
49
+ within,
50
+ } from './cites.js'
51
+
52
+ let str = (v: unknown): string => v == null ? '' : String(v)
53
+ let comp = (b: Bundle | undefined, name: string) =>
54
+ b?.[name] as Comp | undefined
55
+ let count = (v: unknown): number | undefined =>
56
+ typeof v == 'number' && Number.isFinite(v) ? v : undefined
57
+
58
+ // Every citation, with the marks its state is derived from: a read names each
59
+ // component it wants, so one left out reads as never written.
60
+ let citations = async (graph: Graph): Promise<Bundle[]> =>
61
+ await graph.read(
62
+ and(present(CITES), want('edge'), want(VERIFIED), want(REVISION)),
63
+ )
64
+
65
+ // Every entity the citations reach: both ends, the file a cited symbol or
66
+ // place is in, and the root each file is read in.
67
+ let reach = async (graph: Graph, cites: Bundle[]) => {
68
+ let at = new Map<string, Bundle>()
69
+ let add = async (eids: unknown[]) => {
70
+ let more = [...new Set(eids.map(str))].filter((eid) => eid && !at.has(eid))
71
+ if (!more.length) return
72
+ for (let b of await graph.get(more)) at.set(b.entity.eid, b)
73
+ }
74
+ await add(cites.flatMap((b) => [comp(b, 'edge')?.from, comp(b, 'edge')?.to]))
75
+ await add([...at.values()].map(within))
76
+ await add([...at.values()].map((b) => comp(b, FILE)?.root))
77
+ return at
78
+ }
79
+
80
+ let cwdOf = (call: Bundle, verb: string): string => {
81
+ let cwd = comp(call, 'process')?.cwd
82
+ if (!cwd) {
83
+ throw new CallError(
84
+ 'cwd',
85
+ `${verb} reads a checkout, and this graph runs nowhere in particular`,
86
+ )
87
+ }
88
+ return String(cwd)
89
+ }
90
+
91
+ // The checkout holding `cwd`, at its top, and the repository it is a checkout
92
+ // of on this computer's filesystem. Nothing when `cwd` is in no checkout.
93
+ let checkoutOf = async (
94
+ graph: Graph,
95
+ cwd: string,
96
+ ): Promise<Checkout | undefined> => {
97
+ let found = await locate(cwd)
98
+ if (!found) return undefined
99
+ let workspace = (await localFilesystem(graph)).entity.eid
100
+ return { cwd: found.path, repository: repositoryEid(found.common, workspace) }
101
+ }
102
+
103
+ // Where a citation points, in one phrase: the file and the place in it, or the
104
+ // entity it names.
105
+ let where = (
106
+ to: Bundle,
107
+ file: Bundle | undefined,
108
+ id: (b: Bundle) => string,
109
+ ): string => {
110
+ let path = str(comp(file, FILE)?.path)
111
+ if (!path) return id(to)
112
+ let name = str(comp(to, SYMBOL)?.name)
113
+ if (name) return `${path}:${name}`
114
+ let start = count(comp(to, LINES)?.start)
115
+ if (start == null) return path
116
+ return `${path}:${start}-${count(comp(to, LINES)?.end) ?? start}`
117
+ }
118
+
119
+ // How a state reads in a report. A citation that moved is a measured fact, so
120
+ // it fails; one nobody has checked, or one nothing could establish an answer
121
+ // for, is a warning — the check could not vouch either way.
122
+ let verdict = (
123
+ got: Exclude<Status, { state: 'current' }>,
124
+ ): [Level, string] =>
125
+ got.state == 'moved'
126
+ ? [
127
+ 'fail',
128
+ got.changes?.length
129
+ ? `moved by ${got.changes.join(', ')}`
130
+ : 'cited content changed',
131
+ ]
132
+ : got.state == 'unverified'
133
+ ? ['warn', 'never checked']
134
+ : ['warn', `no answer: ${got.why}`]
135
+
136
+ /** Landing with Git supplied at the effect boundary. Each commit that landed
137
+ * is recorded as `commit{target, message}`, its eid the sha, created through
138
+ * the caller's session; its target is the task its first line names. */
139
+ export let landing =
140
+ (run: typeof land, report?: LandOps['report']) =>
141
+ async (call: Bundle, graph?: Graph): Promise<Bundle[]> => {
142
+ let args = argsOf(call)
143
+ let cwd = str(args.cwd)
144
+ // Git's output, exactly as Git wrote it, collected in the order it
145
+ // arrived: what the caller reads is Git's own account, not a summary of
146
+ // it.
147
+ let said: string[] = []
148
+ let outcome = await run({
149
+ cwd,
150
+ allow: str(args['allow-revert']).split(',').filter(Boolean),
151
+ report,
152
+ write: (text) => {
153
+ let line = text.trimEnd()
154
+ if (line) said.push(line)
155
+ },
156
+ })
157
+ if (!('landed' in outcome)) {
158
+ throw new CallError('diverged', said.join('\n'))
159
+ }
160
+ // A graph without commit vocabulary records nothing.
161
+ let landed = graph?.vocab.comp('commit') ? outcome.commits : []
162
+ // The task a commit's first line names (T-12), as the graph addresses it.
163
+ let series = landed.length ? prefixOf(graph!.vocab)('task') : ''
164
+ let named = landed.map((c) =>
165
+ idsIn(c.message.split('\n')[0]).find((id) => parse(id)?.prefix == series)
166
+ )
167
+ let ids = [...new Set(named.filter((id): id is string => !!id))]
168
+ let at = ids.length ? await graph!.address(ids) : new Map<string, string>()
169
+ return [
170
+ {
171
+ entity: { eid: '$landed' },
172
+ content: { body: [...said, `landed ${outcome.landed}`].join('\n') },
173
+ output: { source: call.entity.eid },
174
+ },
175
+ ...landed.map((c, i) => ({
176
+ entity: { eid: c.sha },
177
+ commit: {
178
+ message: c.message,
179
+ ...at.get(named[i] ?? '') ? { target: at.get(named[i]!) } : {},
180
+ },
181
+ })),
182
+ ]
183
+ }
184
+
185
+ /** The implementations of the tools ./vocab.json declares. The host's
186
+ * `report` hears a failure land catches and carries on past. */
187
+ export let runs = (host?: { report?: LandOps['report'] }): Runs => ({
188
+ land: landing(land, host?.report),
189
+
190
+ cites_check: async (call, graph): Promise<Bundle[]> => {
191
+ let args = argsOf(call)
192
+ let cwd = str(comp(call, 'process')?.cwd) || undefined
193
+ let id = human(graph.vocab)
194
+ let of = str(args.of)
195
+ let scope = of || undefined
196
+ let path = str(args.path)
197
+ let cites = await citations(graph)
198
+ let at = await reach(graph, cites)
199
+ // The checkout the call was made in: asked once, and only when a citation
200
+ // of a file needs it.
201
+ let ours = once(async () => cwd ? await checkoutOf(graph, cwd) : undefined)
202
+ // The path names a file of this checkout's repository, when there is one.
203
+ let named = async (file: Bundle | undefined) => {
204
+ if (str(comp(file, FILE)?.path) != path) return false
205
+ let repository = (await ours())?.repository
206
+ return !repository || str(comp(file, FILE)?.root) == repository
207
+ }
208
+ let found: Finding[] = []
209
+ for (let cite of cites) {
210
+ let edge = comp(cite, 'edge')
211
+ let from = at.get(str(edge?.from))
212
+ let to = at.get(str(edge?.to))
213
+ if (!from) continue
214
+ if (scope && from.entity.eid != scope) continue
215
+ if (!to) {
216
+ if (path) continue
217
+ found.push({
218
+ level: 'fail',
219
+ text: `${id(from)} cites ${str(edge?.to)} — cited entity is gone`,
220
+ })
221
+ continue
222
+ }
223
+ let file = tracked(to, (eid) => at.get(eid))
224
+ if (path && !await named(file)) continue
225
+ let checkout = file ? await ours() : undefined
226
+ let got = await status(cite, to, { checkout, vocab: graph.vocab }, file)
227
+ if (got.state == 'current') continue
228
+ let [level, why] = verdict(got)
229
+ found.push({
230
+ level,
231
+ text: `${id(from)} cites ${where(to, file, id)} — ${why}`,
232
+ })
233
+ }
234
+ return checked(call.entity.eid, 'every citation still holds', found)
235
+ },
236
+
237
+ cites_verify: async (call, graph): Promise<Bundle[]> => {
238
+ let args = argsOf(call)
239
+ let cite = str(args.cite)
240
+ let of = str(args.of)
241
+ if (!cite && !of) {
242
+ throw new Refused(
243
+ 'verify needs a citation, or an entity whose citations to verify',
244
+ )
245
+ }
246
+ let asked = cite || of
247
+ let found = cite
248
+ ? (await graph.get([asked])).filter((b) => b[CITES])
249
+ : (await citations(graph))
250
+ .filter((b) => str(comp(b, 'edge')?.from) == asked)
251
+ if (!found.length) {
252
+ throw new Refused(
253
+ cite
254
+ ? `${cite} is not a citation`
255
+ : `${of} makes no citations to verify`,
256
+ )
257
+ }
258
+ let at = await reach(graph, found)
259
+ let toOf = (b: Bundle) => at.get(str(comp(b, 'edge')?.to))
260
+ // The file of a repository a citation is checked against in Git, if any.
261
+ let gitFile = (b: Bundle) => {
262
+ let to = toOf(b)
263
+ return to && tracked(to, (eid) => at.get(eid))
264
+ }
265
+ for (let b of found) {
266
+ let to = toOf(b)
267
+ if (to && comp(to, SYMBOL) && !gitFile(b)) {
268
+ throw new Refused(
269
+ `the cited symbol ${to.entity.eid} has no file to check`,
270
+ )
271
+ }
272
+ }
273
+ let files = found.map(gitFile).filter((f): f is Bundle => !!f)
274
+ let commit = ''
275
+ if (files.length) {
276
+ let cwd = cwdOf(call, 'verifying a file citation')
277
+ let checkout = await checkoutOf(graph, cwd)
278
+ if (!checkout) throw new CallError('cwd', `${cwd} is in no checkout`)
279
+ let other = files.find((f) =>
280
+ str(comp(f, FILE)?.root) != checkout.repository
281
+ )
282
+ if (other) {
283
+ throw new CallError(
284
+ 'cwd',
285
+ `${str(comp(other, FILE)?.path)} is a file of another repository ` +
286
+ 'than this checkout; verify it in a checkout of its own',
287
+ )
288
+ }
289
+ let head = await git(['rev-parse', 'HEAD'], checkout.cwd)
290
+ if (!head.ok) {
291
+ throw new CallError(
292
+ 'head',
293
+ head.err.trim() || 'this checkout is on no commit',
294
+ )
295
+ }
296
+ commit = head.out.trim()
297
+ }
298
+ return found.map((b) => {
299
+ let to = toOf(b)
300
+ if (!to) throw new Refused(`citation ${b.entity.eid} names no entity`)
301
+ return gitFile(b)
302
+ ? {
303
+ entity: { eid: b.entity.eid },
304
+ [VERIFIED]: {},
305
+ [REVISION]: { commit },
306
+ }
307
+ : entityVerify(b, to, graph.vocab)
308
+ })
309
+ },
310
+ })
package/tree.js ADDED
@@ -0,0 +1,105 @@
1
+ // A directory, as Git writes one down: `<mode> <name>\0<raw id>` per child,
2
+ // concatenated in Git's order — and a flat `path → bytes` manifest folded into
3
+ // the nested directories a commit needs.
4
+ //
5
+ // Two details are most of the format, and both are places a hand-written tree
6
+ // usually goes wrong:
7
+ //
8
+ // - **The mode has no leading zero.** A directory is `40000` in the body, even
9
+ // though `git ls-tree` prints `040000`. One byte, and it is a different
10
+ // object.
11
+ // - **A directory sorts as though its name ended in `/`.** So `a.txt` comes
12
+ // before the directory `a`, because `.` (0x2e) is below `/` (0x2f) — the
13
+ // reverse of a plain name sort. Names are compared as UTF-8 bytes, which is
14
+ // what Git compares; JavaScript's own string order is UTF-16 and disagrees
15
+ // above the BMP.
16
+ //
17
+ // The order is not the caller's to choose: {@link treeBody} sorts whatever it
18
+ // is given, so an object id is a function of the entries alone.
19
+ import { bin, concat, hex } from "./oid.js";
20
+ /** A regular file's mode, as a tree body writes it. */ export let FILE = '100644';
21
+ /** A directory's mode — no leading zero, unlike `git ls-tree`'s printing. */ export let DIR = '40000';
22
+ let utf8 = new TextEncoder();
23
+ // Git's order, over UTF-8 bytes, with a directory's name carrying the `/` it
24
+ // is entered through.
25
+ let key = (e)=>utf8.encode(e.mode == DIR ? e.name + '/' : e.name);
26
+ let below = (a, b)=>{
27
+ for(let i = 0; i < Math.min(a.length, b.length); i++){
28
+ if (a[i] != b[i]) return a[i] - b[i];
29
+ }
30
+ return a.length - b.length;
31
+ };
32
+ /** The entries in the order a tree stores them. */ export let sorted = (entries)=>[
33
+ ...entries
34
+ ].sort((a, b)=>below(key(a), key(b)));
35
+ /** A tree object's body: every child, in git's order. */ export let treeBody = (entries)=>concat(sorted(entries).flatMap((e)=>[
36
+ utf8.encode(`${e.mode} ${e.name}\0`),
37
+ bin(e.oid)
38
+ ]));
39
+ /** A tree body's children, in their stored order. `width` is the number of
40
+ * bytes in each raw object id: 20 for SHA-1, 32 for SHA-256. */ export let treeEntries = (body, width = 20)=>{
41
+ let bad = ()=>new Error('git: malformed tree body');
42
+ if (!Number.isInteger(width) || width <= 0) throw bad();
43
+ let text = new TextDecoder('utf-8', {
44
+ fatal: true
45
+ });
46
+ let entries = [];
47
+ for(let at = 0; at < body.length;){
48
+ let space = body.indexOf(32, at);
49
+ let end = body.indexOf(0, at);
50
+ if (space <= at || end <= space + 1 || end + 1 + width > body.length) {
51
+ throw bad();
52
+ }
53
+ let mode, name;
54
+ try {
55
+ mode = text.decode(body.subarray(at, space));
56
+ name = text.decode(body.subarray(space + 1, end));
57
+ } catch {
58
+ throw bad();
59
+ }
60
+ if (!/^[0-7]+$/.test(mode)) throw bad();
61
+ entries.push({
62
+ mode,
63
+ name,
64
+ oid: hex(body.subarray(end + 1, end + 1 + width))
65
+ });
66
+ at = end + 1 + width;
67
+ }
68
+ return entries;
69
+ };
70
+ let dir = ()=>({
71
+ files: new Map(),
72
+ dirs: new Map()
73
+ });
74
+ // A name cannot be a file in one place and a directory in another: the tree
75
+ // would hold it twice, and no reader could tell which one was meant.
76
+ let both = (path)=>new Error(`git: \`${path}\` is both a file and a directory`);
77
+ /**
78
+ * A flat manifest folded into directories: `{'lib/a.js': sha}` becomes a root
79
+ * holding one directory `lib` holding one file `a.js`.
80
+ *
81
+ * Leading and doubled slashes are ignored, `.` means this directory, and `..`
82
+ * is refused: a manifest that points out of its own root has no tree it could
83
+ * become.
84
+ */ export let nest = (files)=>{
85
+ let root = dir();
86
+ for (let [path, sha] of Object.entries(files)){
87
+ let parts = path.split('/').filter((p)=>p && p != '.');
88
+ if (parts.some((p)=>p == '..')) {
89
+ throw new Error(`git: \`${path}\` leaves its own root`);
90
+ }
91
+ let name = parts.pop();
92
+ if (!name) continue;
93
+ let at = root;
94
+ for (let part of parts){
95
+ if (at.files.has(part)) throw both(path);
96
+ let next = at.dirs.get(part) ?? dir();
97
+ at.dirs.set(part, next);
98
+ at = next;
99
+ }
100
+ if (at.dirs.has(name)) throw both(path);
101
+ at.files.set(name, sha);
102
+ }
103
+ return root;
104
+ };
105
+ //# sourceMappingURL=tree.js.map
package/tree.js.map ADDED
@@ -0,0 +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Q,KAAK,KAAK,CAAC,KAAK,MAAM,CAAC,CAAC,IAAM,KAAK,KAAK;IACpD,IAAI,MAAM,IAAI,CAAC,CAAC,IAAM,KAAK,OAAO;MAChC,MAAM,IAAI,MAAM,CAAC,OAAO,EAAE,KAAK,sBAAsB,CAAC;IACxD;IACA,IAAI,OAAO,MAAM,GAAG;IACpB,IAAI,CAAC,MAAM;IACX,IAAI,KAAK;IACT,KAAK,IAAI,QAAQ,MAAO;MACtB,IAAI,GAAG,KAAK,CAAC,GAAG,CAAC,OAAO,MAAM,KAAK;MACnC,IAAI,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,SAAS;MAChC,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM;MAClB,KAAK;IACP;IACA,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,OAAO,MAAM,KAAK;IAClC,GAAG,KAAK,CAAC,GAAG,CAAC,MAAM;EACrB;EACA,OAAO;AACT,EAAC"}
package/tree.ts ADDED
@@ -0,0 +1,132 @@
1
+ // A directory, as Git writes one down: `<mode> <name>\0<raw id>` per child,
2
+ // concatenated in Git's order — and a flat `path → bytes` manifest folded into
3
+ // the nested directories a commit needs.
4
+ //
5
+ // Two details are most of the format, and both are places a hand-written tree
6
+ // usually goes wrong:
7
+ //
8
+ // - **The mode has no leading zero.** A directory is `40000` in the body, even
9
+ // though `git ls-tree` prints `040000`. One byte, and it is a different
10
+ // object.
11
+ // - **A directory sorts as though its name ended in `/`.** So `a.txt` comes
12
+ // before the directory `a`, because `.` (0x2e) is below `/` (0x2f) — the
13
+ // reverse of a plain name sort. Names are compared as UTF-8 bytes, which is
14
+ // what Git compares; JavaScript's own string order is UTF-16 and disagrees
15
+ // above the BMP.
16
+ //
17
+ // The order is not the caller's to choose: {@link treeBody} sorts whatever it
18
+ // is given, so an object id is a function of the entries alone.
19
+
20
+ import { bin, concat, hex } from './oid.js'
21
+
22
+ /** A regular file's mode, as a tree body writes it. */
23
+ export let FILE = '100644'
24
+
25
+ /** A directory's mode — no leading zero, unlike `git ls-tree`'s printing. */
26
+ export let DIR = '40000'
27
+
28
+ /** One child of a tree: its name here, its mode, and its id. The id is
29
+ * whichever of the two ids is being written — a SHA-256 body names its
30
+ * children by their `oid256` (see ./oid.ts). */
31
+ export type Entry = { name: string; mode: string; oid: string }
32
+
33
+ /** A version's files, in the shape a yaks.app deploy manifest already has:
34
+ * the path the app serves the file at, and the SHA-256 of its bytes. */
35
+ export type Files = Record<string, string>
36
+
37
+ /** A directory of a manifest: files by name, and the directories under it. */
38
+ export type Dir = { files: Map<string, string>; dirs: Map<string, Dir> }
39
+
40
+ let utf8 = new TextEncoder()
41
+
42
+ // Git's order, over UTF-8 bytes, with a directory's name carrying the `/` it
43
+ // is entered through.
44
+ let key = (e: Entry): Uint8Array =>
45
+ utf8.encode(e.mode == DIR ? e.name + '/' : e.name)
46
+
47
+ let below = (a: Uint8Array, b: Uint8Array): number => {
48
+ for (let i = 0; i < Math.min(a.length, b.length); i++) {
49
+ if (a[i] != b[i]) return a[i] - b[i]
50
+ }
51
+ return a.length - b.length
52
+ }
53
+
54
+ /** The entries in the order a tree stores them. */
55
+ export let sorted = (entries: Entry[]): Entry[] =>
56
+ [...entries].sort((a, b) => below(key(a), key(b)))
57
+
58
+ /** A tree object's body: every child, in git's order. */
59
+ export let treeBody = (entries: Entry[]): Uint8Array<ArrayBuffer> =>
60
+ concat(
61
+ sorted(entries).flatMap((
62
+ e,
63
+ ) => [utf8.encode(`${e.mode} ${e.name}\0`), bin(e.oid)]),
64
+ )
65
+
66
+ /** A tree body's children, in their stored order. `width` is the number of
67
+ * bytes in each raw object id: 20 for SHA-1, 32 for SHA-256. */
68
+ export let treeEntries = (body: Uint8Array, width = 20): Entry[] => {
69
+ let bad = () => new Error('git: malformed tree body')
70
+ if (!Number.isInteger(width) || width <= 0) throw bad()
71
+ let text = new TextDecoder('utf-8', { fatal: true })
72
+ let entries: Entry[] = []
73
+ for (let at = 0; at < body.length;) {
74
+ let space = body.indexOf(32, at)
75
+ let end = body.indexOf(0, at)
76
+ if (space <= at || end <= space + 1 || end + 1 + width > body.length) {
77
+ throw bad()
78
+ }
79
+ let mode: string, name: string
80
+ try {
81
+ mode = text.decode(body.subarray(at, space))
82
+ name = text.decode(body.subarray(space + 1, end))
83
+ } catch {
84
+ throw bad()
85
+ }
86
+ if (!/^[0-7]+$/.test(mode)) throw bad()
87
+ entries.push({
88
+ mode,
89
+ name,
90
+ oid: hex(body.subarray(end + 1, end + 1 + width)),
91
+ })
92
+ at = end + 1 + width
93
+ }
94
+ return entries
95
+ }
96
+
97
+ let dir = (): Dir => ({ files: new Map(), dirs: new Map() })
98
+
99
+ // A name cannot be a file in one place and a directory in another: the tree
100
+ // would hold it twice, and no reader could tell which one was meant.
101
+ let both = (path: string): Error =>
102
+ new Error(`git: \`${path}\` is both a file and a directory`)
103
+
104
+ /**
105
+ * A flat manifest folded into directories: `{'lib/a.js': sha}` becomes a root
106
+ * holding one directory `lib` holding one file `a.js`.
107
+ *
108
+ * Leading and doubled slashes are ignored, `.` means this directory, and `..`
109
+ * is refused: a manifest that points out of its own root has no tree it could
110
+ * become.
111
+ */
112
+ export let nest = (files: Files): Dir => {
113
+ let root = dir()
114
+ for (let [path, sha] of Object.entries(files)) {
115
+ let parts = path.split('/').filter((p) => p && p != '.')
116
+ if (parts.some((p) => p == '..')) {
117
+ throw new Error(`git: \`${path}\` leaves its own root`)
118
+ }
119
+ let name = parts.pop()
120
+ if (!name) continue
121
+ let at = root
122
+ for (let part of parts) {
123
+ if (at.files.has(part)) throw both(path)
124
+ let next = at.dirs.get(part) ?? dir()
125
+ at.dirs.set(part, next)
126
+ at = next
127
+ }
128
+ if (at.dirs.has(name)) throw both(path)
129
+ at.files.set(name, sha)
130
+ }
131
+ return root
132
+ }