@future-unknown/known 0.0.0-stage → 0.1.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.
@@ -0,0 +1,673 @@
1
+ require("@colors/colors")
2
+ const fs = require("fs")
3
+ const output = require("../output")
4
+ const { getClient, sessionFor, confirm, run, unwrap, actorNames } = require("../helpers")
5
+
6
+ /**
7
+ * `known <org> code` — source trees held in Known.
8
+ *
9
+ * A tree is a site's files, with history, read and written over the API —
10
+ * no filesystem, git or bundler. Every path names its tree with a colon,
11
+ * `hello:src/app.js`, because file names carry dots; `hello:` (or `hello`)
12
+ * is the tree's root. The verbs are the wiki's where the meaning is the
13
+ * same — files are read, written, edited, moved and removed like pages,
14
+ * and a tree's history is its changes — and new only where code means
15
+ * something new: grep, check, pin and unpin, restore.
16
+ *
17
+ * known acme code create hello --starter html --description "A hello world page"
18
+ * known acme code write hello:index.html --file index.html
19
+ * known acme code edit hello:app.js --old "Hello" --new "Hello, Acme"
20
+ * known acme code read hello:app.js --lines 1:40
21
+ * known acme code tree hello:
22
+ * known acme code grep "fetch(" hello:src
23
+ * known acme code pin hello preact
24
+ * known acme code check hello
25
+ * known acme code changes hello:
26
+ * known acme code diff hello:app.js
27
+ * known acme code restore hello: --change 3
28
+ *
29
+ * Every write prints the tree's problems after it — files that do not
30
+ * parse, imports and page references that resolve to nothing, packages
31
+ * not in the import map — and is never refused for them. The safe loop
32
+ * for scripts and agents is the wiki's: change part of a file with `edit`
33
+ * (the exact text you read); to rewrite one, read it with --json, keep
34
+ * `revisionId`, and write back with `--if-revision <id>`.
35
+ */
36
+
37
+ // The largest file a tree takes (the code package's MAX_FILE_BYTES).
38
+ const FILE_MAX = 1024 * 1024
39
+
40
+ const verbs = { read, write, edit, move, rm, tree, grep, deps, pin, unpin, history, diff, changes, restore, check, trees, create, update }
41
+
42
+ module.exports = function (argv, ref, rest) {
43
+ const verb = rest && rest[0]
44
+ if (argv.help) return showMenu(ref)
45
+ if (!verb) return showMenu(ref)
46
+ const handler = verbs[verb]
47
+ if (!handler) {
48
+ output.info(require("../helpers").unknownCommand("code", verb, Object.keys(verbs)).grey)
49
+ return showMenu(ref)
50
+ }
51
+ return handler(argv, ref, rest.slice(1))
52
+ }
53
+
54
+ function showMenu(ref) {
55
+ const org = ref ? ref + " " : ""
56
+ console.log()
57
+ console.log((" known " + org + "code").cyan + " source trees held in Known — every path names its tree (hello:src/app.js)".grey)
58
+ console.log()
59
+ const groups = [
60
+ ["files", [
61
+ [org + "code read <tree>:<path> […]", "print a file, or several one after another (--lines 40:80, --change; --json for its revision)"],
62
+ [org + "code write <tree>:<path>", "write a file whole from --text, --file, or stdin (--if-revision, --message)"],
63
+ [org + "code edit <tree>:<path>", "replace --old with --new; refused unless --old occurs exactly once (--all)"],
64
+ [org + "code move <tree>:<from> <tree>:<to>", "move or rename a file or a folder"],
65
+ [org + "code rm <tree>:<path>", "remove a file (--recursive for a folder)"],
66
+ [org + "code tree <tree>:[dir]", "files and folders (--depth, --change)"],
67
+ [org + "code grep <pattern> <tree>:[dir]", "matching lines as path:line (--regex, --ignore-case, --context, --limit)"]
68
+ ]],
69
+ ["packages", [
70
+ [org + "code deps <tree>", "the packages the import map pins, with their URLs"],
71
+ [org + "code pin <tree> <package>[@<version>]", "pin a package at an exact version (the latest, or what a range or tag means)"],
72
+ [org + "code unpin <tree> <package>", "drop a package from the import map"]
73
+ ]],
74
+ ["history", [
75
+ [org + "code history <tree>:<path>", "a file's revisions, newest first, through moves"],
76
+ [org + "code diff <tree>:[path]", "what the latest change did, as patches (--change, --revision)"],
77
+ [org + "code changes <tree>:[path]", "what changed, newest first, each change with its files (--limit, --before)"],
78
+ [org + "code restore <tree>:[path] --change <id>", "put a file, a folder, or everything back as it stood after a change"]
79
+ ]],
80
+ ["checks", [
81
+ [org + "code check <tree>", "every problem in the tree (--change): files that don't parse, imports and page references to nothing, names a file doesn't export, packages not pinned"]
82
+ ]],
83
+ ["trees", [
84
+ [org + "code trees", "the org's trees: what each is for, its files and latest change"],
85
+ [org + "code create <name>", "make a tree (--starter html, --description, --title)"],
86
+ [org + "code update <tree>", "say what it is for and retitle it (--description, --title)"]
87
+ ]]
88
+ ]
89
+ const width = output.commandWidth(...groups.map(([, rows]) => rows))
90
+ for (const [title, rows] of groups) {
91
+ console.log(" " + title.bold)
92
+ output.commands(rows, width)
93
+ console.log()
94
+ }
95
+ process.exit(0)
96
+ }
97
+
98
+ // ---- files -----------------------------------------------------------------
99
+
100
+ // Several addresses print one after another, each under a `==> address <==`
101
+ // line as `head` prints files, so one call reads a handful of a tree's files.
102
+ function read(argv, ref, rest) {
103
+ return run(async () => {
104
+ const addresses = (rest.length ? rest : [undefined]).map((arg) => fileAddress(arg, "read", "<tree>:<path>"))
105
+ const range = lines(argv.lines)
106
+ const client = clientOf(argv, ref)
107
+ const files = []
108
+ for (const address of addresses) {
109
+ files.push(unwrap(await client.code.read({
110
+ path: address,
111
+ ...range,
112
+ ...(argv.change ? { changeId: intFlag(argv.change, "--change") } : {})
113
+ })))
114
+ }
115
+ if (output.isJson()) return output.data(files.length === 1 ? files[0] : files)
116
+ if (files.length === 1) {
117
+ const [file] = files
118
+ if (file.binary) return process.stdout.write(Buffer.from(file.base64, "base64"))
119
+ return output.raw(file.content)
120
+ }
121
+ files.forEach((file, i) => {
122
+ if (i) output.raw("\n")
123
+ output.raw("==> " + addresses[i] + " <==\n")
124
+ output.raw(file.binary ? "(binary, " + size(Buffer.from(file.base64, "base64").length) + ")\n" : file.content)
125
+ })
126
+ })
127
+ }
128
+
129
+ function write(argv, ref, rest) {
130
+ return run(async () => {
131
+ const address = fileAddress(rest[0], "write", "<tree>:<path>")
132
+ const body = await resolveBody(argv)
133
+ const client = clientOf(argv, ref)
134
+ const res = unwrap(await client.code.write({
135
+ path: address,
136
+ ...body,
137
+ ...(argv.message ? { message: argv.message } : {}),
138
+ ...(argv["if-revision"] ? { ifRevision: argv["if-revision"] } : {})
139
+ }))
140
+ if (output.isJson()) return output.data(res)
141
+ if (!res.changed) output.status("unchanged", res.address, "already this content", "muted")
142
+ else output.status(res.created ? "created" : "updated", res.address, "change " + res.changeId + " · " + problemCount(res.problems))
143
+ printProblems(res.problems)
144
+ })
145
+ }
146
+
147
+ // Change part of a file: one exact string for another, read and written in
148
+ // one step on the server, so a change made meanwhile elsewhere in the file
149
+ // survives. --old must occur exactly once (give more of the text around
150
+ // it), unless --all.
151
+ function edit(argv, ref, rest) {
152
+ return run(async () => {
153
+ const address = fileAddress(rest[0], "edit", "<tree>:<path> --old \"…\" --new \"…\"")
154
+ if (argv.old === undefined || argv.old === "" || argv.new === undefined) {
155
+ throw friendly("say what to replace and with what — `--old \"…\" --new \"…\"` (--new \"\" deletes)")
156
+ }
157
+ const client = clientOf(argv, ref)
158
+ const res = unwrap(await client.code.edit({
159
+ path: address,
160
+ oldString: String(argv.old),
161
+ newString: String(argv.new),
162
+ ...(argv.all ? { replaceAll: true } : {}),
163
+ ...(argv.message ? { message: argv.message } : {}),
164
+ ...(argv["if-revision"] ? { ifRevision: argv["if-revision"] } : {})
165
+ }))
166
+ if (output.isJson()) return output.data(res)
167
+ output.status("edited", res.address, res.replaced + (res.replaced === 1 ? " place" : " places") + " · change " + res.changeId + " · " + problemCount(res.problems))
168
+ printProblems(res.problems)
169
+ })
170
+ }
171
+
172
+ function move(argv, ref, rest) {
173
+ return run(async () => {
174
+ const [from, to] = rest
175
+ if (!from || !to) throw friendly("both addresses are needed — `known <org> code move <tree>:<from> <tree>:<to>`")
176
+ const client = clientOf(argv, ref)
177
+ const res = unwrap(await client.code.move({
178
+ from: String(from),
179
+ to: String(to),
180
+ ...(argv.message ? { message: argv.message } : {}),
181
+ ...(argv["if-revision"] ? { ifRevision: argv["if-revision"] } : {})
182
+ }))
183
+ if (output.isJson()) return output.data(res)
184
+ const files = res.moved.length === 1 ? "" : res.moved.length + " files · "
185
+ output.status("moved", res.to, "from " + res.from + " · " + files + "change " + res.changeId + " · " + problemCount(res.problems))
186
+ printProblems(res.problems)
187
+ })
188
+ }
189
+
190
+ function rm(argv, ref, rest) {
191
+ return run(async () => {
192
+ const address = fileAddress(rest[0], "rm", "<tree>:<path>")
193
+ // A folder goes with everything in it; pause for a person unless --yes
194
+ // or scripted. `restore` brings any of it back.
195
+ if (argv.recursive && !(await confirm("remove " + address + " and everything in it?", argv))) {
196
+ return output.status("kept", address, null, "muted")
197
+ }
198
+ const client = clientOf(argv, ref)
199
+ const res = unwrap(await client.code.remove({
200
+ path: address,
201
+ ...(argv.recursive ? { recursive: true } : {}),
202
+ ...(argv.message ? { message: argv.message } : {}),
203
+ ...(argv["if-revision"] ? { ifRevision: argv["if-revision"] } : {}),
204
+ ...(argv["if-change"] ? { ifChange: intFlag(argv["if-change"], "--if-change") } : {})
205
+ }))
206
+ if (output.isJson()) return output.data(res)
207
+ output.status("removed", res.removed.join(", "), "change " + res.changeId + " · " + problemCount(res.problems), "danger")
208
+ printProblems(res.problems)
209
+ })
210
+ }
211
+
212
+ function tree(argv, ref, rest) {
213
+ return run(async () => {
214
+ const address = treeAddress(rest[0], "tree", "<tree>:[dir]")
215
+ const client = clientOf(argv, ref)
216
+ const root = unwrap(await client.code.tree({
217
+ path: address,
218
+ ...(argv.depth ? { depth: intFlag(argv.depth, "--depth") } : {}),
219
+ ...(argv.change ? { changeId: intFlag(argv.change, "--change") } : {})
220
+ }))
221
+ if (output.isJson()) return output.data(root)
222
+ if (root.type === "file") return output.commands([[root.address, size(root.size)]])
223
+ const rows = [[root.address, root.files + (root.files === 1 ? " file" : " files") + " · change " + root.changeId]]
224
+ walk(root, "")
225
+ function walk(node, prefix) {
226
+ const children = node.children || []
227
+ children.forEach((child, i) => {
228
+ const last = i === children.length - 1
229
+ const name = child.type === "folder" ? child.name + "/" : child.name
230
+ const about = child.type === "folder"
231
+ ? (child.children ? "" : child.files + (child.files === 1 ? " file" : " files"))
232
+ : size(child.size) + (child.binary ? " · binary" : "")
233
+ rows.push([prefix + (last ? "└── " : "├── ") + name, about])
234
+ if (child.type === "folder") walk(child, prefix + (last ? " " : "│ "))
235
+ })
236
+ }
237
+ console.log()
238
+ output.commands(rows)
239
+ console.log()
240
+ })
241
+ }
242
+
243
+ // Matches the way grep prints them, so they read (and paste) as places:
244
+ // `hello:app.js:12: text`, context lines with dashes.
245
+ function grep(argv, ref, rest) {
246
+ return run(async () => {
247
+ const pattern = rest[0]
248
+ if (pattern === undefined || pattern === "") throw friendly("nothing to find — `known <org> code grep <pattern> <tree>:[dir]`")
249
+ const address = treeAddress(rest[1], "grep", "<pattern> <tree>:[dir]")
250
+ const client = clientOf(argv, ref)
251
+ const res = unwrap(await client.code.grep({
252
+ pattern: String(pattern),
253
+ path: address,
254
+ ...(argv.regex ? { regex: true } : {}),
255
+ ...(argv["ignore-case"] ? { ignoreCase: true } : {}),
256
+ ...(argv.context ? { context: intFlag(argv.context, "--context", 0) } : {}),
257
+ ...(argv.limit ? { limit: intFlag(argv.limit, "--limit") } : {})
258
+ }))
259
+ if (output.isJson()) return output.data(res)
260
+ if (!res.matches.length) return output.empty("nothing matches “" + pattern + "” in " + res.files + (res.files === 1 ? " file" : " files"))
261
+ const context = res.matches.some((match) => (match.before || []).length || (match.after || []).length)
262
+ let previous = null
263
+ for (const match of res.matches) {
264
+ if (context && previous) console.log("--".grey)
265
+ ;(match.before || []).forEach((text, i) => console.log((match.address + "-" + (match.line - match.before.length + i) + "-").grey + text))
266
+ console.log((match.address + ":" + match.line + ":").cyan + match.text)
267
+ ;(match.after || []).forEach((text, i) => console.log((match.address + "-" + (match.line + 1 + i) + "-").grey + text))
268
+ previous = match
269
+ }
270
+ if (res.truncated) output.status("more", "matches than shown", "narrow the pattern or the folder, or raise --limit", "muted")
271
+ })
272
+ }
273
+
274
+ // ---- packages --------------------------------------------------------------
275
+
276
+ function deps(argv, ref, rest) {
277
+ return run(async () => {
278
+ const name = treeName(rest[0], "deps", "<tree>")
279
+ const res = unwrap(await clientOf(argv, ref).code.deps({ tree: name }))
280
+ if (output.isJson()) return output.data(res)
281
+ if (!res.packages.length) return output.empty("no packages pinned — `known <org> code pin " + name + " <package>`")
282
+ output.table(res.packages.map((pkg) => ({ package: pkg.name.cyan, version: pkg.version, url: pkg.url.grey })))
283
+ })
284
+ }
285
+
286
+ function pin(argv, ref, rest) {
287
+ return run(async () => {
288
+ const name = treeName(rest[0], "pin", "<tree> <package>[@<version>]")
289
+ const pkg = rest[1]
290
+ if (!pkg) throw friendly("name the package — `known <org> code pin " + name + " <package>[@<version>]`")
291
+ const res = unwrap(await clientOf(argv, ref).code.pin({
292
+ tree: name,
293
+ package: String(pkg),
294
+ ...(argv.version ? { version: String(argv.version) } : {}),
295
+ ...(argv.message ? { message: argv.message } : {})
296
+ }))
297
+ if (output.isJson()) return output.data(res)
298
+ const at = res.package.name + "@" + res.package.version
299
+ if (!res.changed) output.status("unchanged", at, "already pinned", "muted")
300
+ else output.status("pinned", at, res.package.url + " · change " + res.changeId + " · " + problemCount(res.problems))
301
+ printProblems(res.problems)
302
+ })
303
+ }
304
+
305
+ function unpin(argv, ref, rest) {
306
+ return run(async () => {
307
+ const name = treeName(rest[0], "unpin", "<tree> <package>")
308
+ const pkg = rest[1]
309
+ if (!pkg) throw friendly("name the package — `known <org> code unpin " + name + " <package>`")
310
+ const res = unwrap(await clientOf(argv, ref).code.unpin({
311
+ tree: name,
312
+ package: String(pkg),
313
+ ...(argv.message ? { message: argv.message } : {})
314
+ }))
315
+ if (output.isJson()) return output.data(res)
316
+ if (!res.changed) output.status("unchanged", String(pkg), "was not pinned", "muted")
317
+ else output.status("unpinned", String(pkg), "change " + res.changeId + " · " + problemCount(res.problems), "muted")
318
+ printProblems(res.problems)
319
+ })
320
+ }
321
+
322
+ // ---- history ---------------------------------------------------------------
323
+
324
+ function history(argv, ref, rest) {
325
+ return run(async () => {
326
+ const address = fileAddress(rest[0], "history", "<tree>:<path>")
327
+ const client = clientOf(argv, ref)
328
+ const entries = unwrap(await client.code.history({
329
+ path: address,
330
+ ...(argv.limit ? { limit: intFlag(argv.limit, "--limit") } : {})
331
+ }))
332
+ if (output.isJson()) return output.data(entries)
333
+ const by = await actorNames(client, entries.map((entry) => entry.change.actor))
334
+ output.table(entries.map((entry) => ({
335
+ change: String(entry.changeId),
336
+ when: output.timeAgo(new Date(entry.change.createdAt)),
337
+ by: by(entry.change.actor),
338
+ file: actionOf({ ...entry, fromAddress: entry.from ? treeOf(address) + ":" + entry.from : null }, entry.address),
339
+ revision: entry.revisionId.grey,
340
+ note: entry.change.message || "—".grey
341
+ })))
342
+ })
343
+ }
344
+
345
+ // What one change did, as a unified patch per text file: the tree's latest
346
+ // change, or the latest that touched a path (and only that path's part of
347
+ // it), or the one --change names. --revision diffs one revision of a file
348
+ // against the one before it.
349
+ function diff(argv, ref, rest) {
350
+ return run(async () => {
351
+ const address = treeAddress(rest[0], "diff", "<tree>:[path]")
352
+ if (argv.change && argv.revision) throw friendly("pass --change or --revision, not both")
353
+ const name = treeOf(address)
354
+ const path = address.slice(name.length + 1)
355
+ const client = clientOf(argv, ref)
356
+
357
+ if (argv.revision) {
358
+ const revision = unwrap(await client.code.getRevision({ tree: name, revisionId: String(argv.revision) }))
359
+ if (output.isJson()) return output.data(revision)
360
+ const by = await actorNames(client, [revision.change.actor])
361
+ heading(revision.change, by)
362
+ const before = revision.previous
363
+ if (revision.binary || (before && before.binary)) return output.empty(revision.address + " is binary")
364
+ printPatch(createPatch(revision.address, before ? "c" + before.changeId : null, revision.content === null ? null : "c" + revision.changeId,
365
+ before ? before.content : "", revision.content === null ? "" : revision.content))
366
+ return
367
+ }
368
+
369
+ let changeId = argv.change ? intFlag(argv.change, "--change") : null
370
+ if (changeId === null) {
371
+ const [latest] = unwrap(await client.code.changes({ path: address, limit: 1 }))
372
+ if (!latest) return output.empty("nothing has changed at " + address)
373
+ changeId = latest.id
374
+ }
375
+ const change = unwrap(await client.code.getChange({ tree: name, changeId }))
376
+ // A path narrows the change to the files at or under it.
377
+ const within = (p) => !path || p === path || (p && p.startsWith(path + "/"))
378
+ const files = change.files.filter((file) => within(file.path) || within(file.from))
379
+ if (output.isJson()) return output.data({ ...change, files })
380
+ const by = await actorNames(client, [change.actor])
381
+ heading(change, by)
382
+ if (!files.length) return output.empty("change " + change.id + " did not touch " + address)
383
+ for (const file of files) {
384
+ if (file.action === "moved" && !file.patch) console.log("\n " + ("moved " + file.fromAddress + " → " + file.address).grey)
385
+ if (file.binary) console.log("\n " + (file.action + " " + file.address + " (binary)").grey)
386
+ if (file.patch) printPatch(file.patch)
387
+ }
388
+ })
389
+ }
390
+
391
+ function changes(argv, ref, rest) {
392
+ return run(async () => {
393
+ const address = treeAddress(rest[0], "changes", "<tree>:[path]")
394
+ const client = clientOf(argv, ref)
395
+ const entries = unwrap(await client.code.changes({
396
+ path: address,
397
+ ...(argv.limit ? { limit: intFlag(argv.limit, "--limit") } : {}),
398
+ ...(argv.before ? { before: intFlag(argv.before, "--before") } : {})
399
+ }))
400
+ if (output.isJson()) return output.data(entries)
401
+ if (!entries.length) return output.empty("nothing has changed here")
402
+ const by = await actorNames(client, entries.map((entry) => entry.actor))
403
+ output.table(entries.map((entry) => ({
404
+ change: String(entry.id),
405
+ when: output.timeAgo(new Date(entry.createdAt)),
406
+ by: by(entry.actor),
407
+ files: entry.files.map((file) => actionOf(file, file.address)).join(", "),
408
+ note: entry.message || "—".grey
409
+ })))
410
+ const last = entries[entries.length - 1]
411
+ if (argv.limit && entries.length === intFlag(argv.limit, "--limit")) output.status("more", "continue with", "--before " + last.id, "muted")
412
+ })
413
+ }
414
+
415
+ function restore(argv, ref, rest) {
416
+ return run(async () => {
417
+ const address = treeAddress(rest[0], "restore", "<tree>:[path] --change <id>")
418
+ if (!argv.change) throw friendly("say which change to restore to — `known <org> code restore " + address + " --change <id>`")
419
+ const client = clientOf(argv, ref)
420
+ const res = unwrap(await client.code.restore({
421
+ path: address,
422
+ changeId: intFlag(argv.change, "--change"),
423
+ ...(argv["if-change"] ? { ifChange: intFlag(argv["if-change"], "--if-change") } : {}),
424
+ ...(argv.message ? { message: argv.message } : {})
425
+ }))
426
+ if (output.isJson()) return output.data(res)
427
+ if (!res.changed) return output.status("unchanged", res.address, "already as it stood after change " + argv.change, "muted")
428
+ const what = [
429
+ res.restored.length ? res.restored.length + " restored" : null,
430
+ res.removed.length ? res.removed.length + " removed" : null
431
+ ].filter(Boolean).join(", ")
432
+ output.status("restored", res.address, "as after change " + argv.change + " · " + what + " · change " + res.changeId + " · " + problemCount(res.problems))
433
+ printProblems(res.problems)
434
+ })
435
+ }
436
+
437
+ // ---- checks ----------------------------------------------------------------
438
+
439
+ function check(argv, ref, rest) {
440
+ return run(async () => {
441
+ const name = treeName(rest[0], "check", "<tree>")
442
+ const res = unwrap(await clientOf(argv, ref).code.check({
443
+ tree: name,
444
+ ...(argv.change ? { changeId: intFlag(argv.change, "--change") } : {})
445
+ }))
446
+ if (output.isJson()) return output.data(res)
447
+ if (!res.problems.length) return output.status("no problems", name + ":", res.files + (res.files === 1 ? " file" : " files") + " at change " + res.changeId)
448
+ output.status(problemCount(res.problems), name + ":", res.files + (res.files === 1 ? " file" : " files") + " at change " + res.changeId, "danger")
449
+ printProblems(res.problems)
450
+ })
451
+ }
452
+
453
+ // ---- trees -----------------------------------------------------------------
454
+
455
+ function trees(argv, ref, rest) {
456
+ return run(async () => {
457
+ const entries = unwrap(await clientOf(argv, ref).code.list({}))
458
+ if (output.isJson()) return output.data(entries)
459
+ if (!entries.length) return output.empty("no trees yet — `known <org> code create <name> --starter html`")
460
+ output.table(entries.map((entry) => ({
461
+ tree: entry.name.cyan,
462
+ about: entry.description || entry.title || "—".grey,
463
+ files: String(entry.files),
464
+ change: entry.changeId === null ? "—".grey : String(entry.changeId),
465
+ changed: output.timeAgo(new Date(entry.updatedAt))
466
+ })))
467
+ })
468
+ }
469
+
470
+ function create(argv, ref, rest) {
471
+ return run(async () => {
472
+ const name = rest[0]
473
+ if (!name) throw friendly("name the tree — `known <org> code create <name>`")
474
+ if (!TREE_NAME.test(String(name))) throw friendly("tree names are lowercase letters, digits, and hyphens — got “" + name + "”")
475
+ const res = unwrap(await clientOf(argv, ref).code.create({
476
+ name: String(name),
477
+ ...(argv.title ? { title: String(argv.title) } : {}),
478
+ ...(argv.description ? { description: String(argv.description) } : {}),
479
+ ...(argv.starter ? { starter: String(argv.starter) } : {}),
480
+ ...(argv.message ? { message: argv.message } : {})
481
+ }))
482
+ if (output.isJson()) return output.data(res)
483
+ const files = res.tree.files ? res.tree.files + (res.tree.files === 1 ? " file" : " files") + " · change " + res.changeId : "empty"
484
+ output.status("created", res.tree.name + ":", files + " · address its files as " + res.tree.name + ":<path>")
485
+ printProblems(res.problems)
486
+ })
487
+ }
488
+
489
+ function update(argv, ref, rest) {
490
+ return run(async () => {
491
+ const name = treeName(rest[0], "update", "<tree> --description \"…\"")
492
+ const changes = {
493
+ ...(argv.title !== undefined ? { title: String(argv.title) } : {}),
494
+ ...(argv.description !== undefined ? { description: String(argv.description) } : {})
495
+ }
496
+ if (!Object.keys(changes).length) throw friendly("nothing to change — pass --description or --title")
497
+ const res = unwrap(await clientOf(argv, ref).code.update({ tree: name, ...changes }))
498
+ if (output.isJson()) return output.data(res)
499
+ const said = [
500
+ changes.description !== undefined ? "says what it is for" : null,
501
+ changes.title !== undefined ? "is titled " + res.title : null
502
+ ].filter(Boolean)
503
+ output.status("updated", res.name + ":", said.join(", "))
504
+ })
505
+ }
506
+
507
+ // ---- addresses, flags, output ----------------------------------------------
508
+
509
+ const TREE_NAME = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/
510
+
511
+ function clientOf(argv, ref) {
512
+ return getClient(argv, { session: sessionFor(argv, ref) })
513
+ }
514
+
515
+ function treeOf(address) {
516
+ const colon = address.indexOf(":")
517
+ return colon === -1 ? address : address.slice(0, colon)
518
+ }
519
+
520
+ // A file's address: a tree, a colon, a path. Checked before any session is
521
+ // resolved, so a slip reports without credentials.
522
+ function fileAddress(arg, verb, usage) {
523
+ const text = arg == null ? "" : String(arg).trim()
524
+ const colon = text.indexOf(":")
525
+ if (colon === -1 || colon === text.length - 1) {
526
+ // `hello` and `hello:` name a tree; anything else is a path missing one.
527
+ const tree = colon === -1 ? (TREE_NAME.test(text) ? text : null) : text.slice(0, -1)
528
+ throw friendly(text
529
+ ? "name a file in its tree — " + (tree ? tree + ":<path>" : "<tree>:" + text) + " (`known <org> code " + verb + " " + usage + "`)"
530
+ : "name the file — `known <org> code " + verb + " " + usage + "`")
531
+ }
532
+ if (!TREE_NAME.test(text.slice(0, colon))) throw friendly("tree names are lowercase letters, digits, and hyphens — got “" + text.slice(0, colon) + "”")
533
+ return text
534
+ }
535
+
536
+ // A tree, or a folder in it: `hello`, `hello:` or `hello:src`.
537
+ function treeAddress(arg, verb, usage) {
538
+ const text = arg == null ? "" : String(arg).trim()
539
+ if (!text) throw friendly("name the tree — `known <org> code " + verb + " " + usage + "`")
540
+ if (!TREE_NAME.test(treeOf(text))) throw friendly("tree names are lowercase letters, digits, and hyphens — got “" + treeOf(text) + "”")
541
+ return text.includes(":") ? text : text + ":"
542
+ }
543
+
544
+ // A tree named alone: `hello` (a trailing colon is forgiven).
545
+ function treeName(arg, verb, usage) {
546
+ const text = arg == null ? "" : String(arg).trim().replace(/:$/, "")
547
+ if (!text) throw friendly("name the tree — `known <org> code " + verb + " " + usage + "`")
548
+ if (!TREE_NAME.test(text)) throw friendly("name the tree alone, not a path in it — `known <org> code " + verb + " " + usage + "`")
549
+ return text
550
+ }
551
+
552
+ // --lines 40:80 (first and last, counting from 1), 40: (to the end), or 40.
553
+ function lines(value) {
554
+ if (value === undefined) return {}
555
+ const match = /^(\d+)(?::(\d*))?$/.exec(String(value))
556
+ if (!match || Number(match[1]) < 1) throw friendly("--lines takes <first>:<last>, counting from 1 — got “" + value + "”")
557
+ const first = Number(match[1])
558
+ if (match[2] === undefined) return { offset: first, limit: 1 }
559
+ if (match[2] === "") return { offset: first }
560
+ const last = Number(match[2])
561
+ if (last < first) throw friendly("--lines ends before it starts — got “" + value + "”")
562
+ return { offset: first, limit: last - first + 1 }
563
+ }
564
+
565
+ function intFlag(value, name, min = 1) {
566
+ const n = Number(value)
567
+ if (!Number.isInteger(n) || n < min) throw friendly(name + " must be " + (min === 0 ? "a whole number" : "a positive integer"))
568
+ return n
569
+ }
570
+
571
+ function size(bytes) {
572
+ if (bytes < 1024) return bytes + " B"
573
+ if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + " KB"
574
+ return (bytes / 1024 / 1024).toFixed(1) + " MB"
575
+ }
576
+
577
+ function problemCount(problems) {
578
+ if (!problems.length) return "no problems"
579
+ return problems.length + (problems.length === 1 ? " problem" : " problems")
580
+ }
581
+
582
+ // The tree's problems, each at its place (`hello:app.js:2:8`), so the next
583
+ // command can go straight there.
584
+ function printProblems(problems) {
585
+ if (output.isJson() || !problems || !problems.length) return
586
+ for (const problem of problems) {
587
+ const place = problem.address + (problem.line ? ":" + problem.line + (problem.column ? ":" + problem.column : "") : "")
588
+ console.log(" " + place.yellow + " " + problem.message)
589
+ }
590
+ console.log()
591
+ }
592
+
593
+ // One file in a change, as a word and its address.
594
+ function actionOf(file, address) {
595
+ if (file.action === "moved") return "moved " + (file.fromAddress || "") + " → " + address
596
+ if (file.action === "updated") return address
597
+ return file.action + " " + address
598
+ }
599
+
600
+ function heading(change, by) {
601
+ console.log()
602
+ console.log(" change " + change.id + " " + change.createdAt + " " + by(change.actor) + (change.message ? " " + change.message : ""))
603
+ }
604
+
605
+ function createPatch(name, fromLabel, toLabel, fromText, toText) {
606
+ const { createTwoFilesPatch } = require("diff")
607
+ return createTwoFilesPatch(fromLabel ? name + "@" + fromLabel : "/dev/null", toLabel ? name + "@" + toLabel : "/dev/null", fromText, toText, undefined, undefined, { context: 3 })
608
+ }
609
+
610
+ function printPatch(patch) {
611
+ const lines = patch.split("\n").filter((line) => !line.startsWith("====") && !line.startsWith("Index:"))
612
+ console.log()
613
+ for (const line of lines) {
614
+ if (line.startsWith("+++") || line.startsWith("---")) console.log(" " + line.grey)
615
+ else if (line.startsWith("+")) console.log(" " + line.green)
616
+ else if (line.startsWith("-")) console.log(" " + line.red)
617
+ else if (line.startsWith("@@")) console.log(" " + line.cyan)
618
+ else console.log(" " + line)
619
+ }
620
+ }
621
+
622
+ // ---- content input ---------------------------------------------------------
623
+
624
+ // One source of the file's contents, named explicitly: --text, --file, or
625
+ // piped stdin. A file that is not UTF-8 text (an image, a font) goes as
626
+ // base64 and is kept as binary.
627
+ async function resolveBody(argv) {
628
+ const piped = !process.stdin.isTTY
629
+ const given = [
630
+ argv.text !== undefined ? "--text" : null,
631
+ argv.file ? "--file" : null,
632
+ piped && argv.text === undefined && !argv.file ? "stdin" : null
633
+ ].filter(Boolean)
634
+ if (given.length > 1) throw friendly("pass only one of " + given.join(" or ") + " — not both")
635
+
636
+ if (argv.text !== undefined) return { content: String(argv.text) }
637
+ let bytes
638
+ if (argv.file) {
639
+ try {
640
+ bytes = fs.readFileSync(argv.file)
641
+ } catch (e) {
642
+ throw friendly("cannot read " + argv.file + ": " + e.message)
643
+ }
644
+ } else if (piped) {
645
+ bytes = await readStdin()
646
+ } else {
647
+ throw friendly("nothing to write — pass --text \"…\", --file <path>, or pipe content in")
648
+ }
649
+ if (bytes.length > FILE_MAX) throw friendly("the file is " + size(bytes.length) + "; a tree takes files up to " + size(FILE_MAX))
650
+ const text = bytes.toString("utf8")
651
+ const isText = !bytes.includes(0) && Buffer.from(text, "utf8").equals(bytes)
652
+ return isText ? { content: text } : { base64: bytes.toString("base64") }
653
+ }
654
+
655
+ function readStdin() {
656
+ return new Promise((resolve, reject) => {
657
+ const chunks = []
658
+ let length = 0
659
+ process.stdin.on("data", (chunk) => {
660
+ chunks.push(chunk)
661
+ length += chunk.length
662
+ if (length > FILE_MAX) reject(friendly("input is too long — a tree takes files up to " + size(FILE_MAX)))
663
+ })
664
+ process.stdin.on("end", () => resolve(Buffer.concat(chunks)))
665
+ process.stdin.on("error", reject)
666
+ })
667
+ }
668
+
669
+ function friendly(message) {
670
+ const e = new Error(message)
671
+ e.friendly = true
672
+ return e
673
+ }