-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.go
More file actions
526 lines (482 loc) · 16.4 KB
/
Copy pathcli.go
File metadata and controls
526 lines (482 loc) · 16.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
package main
import (
"context"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"github.com/aviorstudio/termcade/internal/plugin"
"github.com/aviorstudio/termcade/internal/registry"
"github.com/aviorstudio/termcade/manifest"
)
const usage = `termcade — an arcade in your terminal
usage:
termcade play (marketplace included — press m)
termcade add <author/slug> add a marketplace game to your account and
install it on this machine
termcade remove <id> remove an added game (id is author/slug)
termcade list list the games in your arcade
termcade sync install everything on your account that is
missing here
termcade publish <repo> <tag> [asset]
publish a release: point the marketplace at a
.tcade on one of your GitHub releases
termcade org studios you publish under (list · new · show ·
add · remove)
termcade keys publish keys for CI (list · new · revoke)
termcade whoami who you are and what you can publish under
termcade username <name> claim or rename your handle (or check one is
free, signed out)
termcade account delete <u> delete your account
termcade signup [email] create a marketplace account
termcade login [email] sign in (publishing and your account library)
termcade logout sign out
termcade dev new <id> [dir] start your own game (id is author/slug)
termcade dev build [dir] build a game directory into a .tcade package
termcade dev install <file> install a local .tcade while developing
This arcade is also the whole dev kit: dev new, hack, dev build, dev install,
play. See docs/sdk.md to get started.
`
// runCommand dispatches non-play subcommands; it reports whether it handled
// one (main falls through to the arcade otherwise).
func runCommand(args []string) bool {
if len(args) == 0 {
return false
}
var err error
switch args[0] {
case "add", "install":
err = cmdAdd(args[1:])
case "remove", "uninstall":
err = cmdRemove(args[1:])
case "list":
err = cmdList()
case "sync":
err = cmdSync()
case "login":
err = cmdLogin(args[1:])
case "signup":
err = cmdSignup(args[1:])
case "logout":
err = cmdLogout()
case "publish":
err = cmdPublish(args[1:])
case "keys":
err = cmdKeys(args[1:])
case "org":
err = cmdOrg(args[1:])
case "whoami":
err = cmdWhoami()
case "username":
err = cmdUsername(args[1:])
case "account":
err = cmdAccount(args[1:])
case "dev":
switch {
case len(args) >= 2 && args[1] == "build":
err = cmdDevBuild(args[2:])
case len(args) >= 2 && args[1] == "new":
err = cmdDevNew(args[2:])
case len(args) >= 2 && args[1] == "install":
err = cmdDevInstall(args[2:])
default:
err = fmt.Errorf("unknown dev subcommand; try: termcade dev new <author/slug> · termcade dev build [dir] · termcade dev install <file>")
}
case "version", "-v", "--version":
fmt.Println("termcade", resolveVersion())
case "help", "-h", "--help":
fmt.Print(usage)
default:
fmt.Fprintf(os.Stderr, "termcade: unknown command %q\n\n%s", args[0], usage)
os.Exit(2)
}
if err != nil {
fmt.Fprintln(os.Stderr, "termcade:", err)
os.Exit(1)
}
return true
}
// gameIDRe matches a marketplace id, e.g. "aviorstudio/brickough".
var gameIDRe = regexp.MustCompile(`^[a-z0-9][a-z0-9-]*/[a-z0-9][a-z0-9-]*$`)
// slugOnlyRe matches half of one — "brickough" with the author left off. The
// character class is gameIDRe's without the slash, so nothing with a path, a
// scheme, or a file extension can reach it.
var slugOnlyRe = regexp.MustCompile(`^[a-z0-9][a-z0-9-]*$`)
func cmdAdd(args []string) error {
if len(args) != 1 {
return fmt.Errorf("usage: termcade add <author/slug>")
}
id := args[0]
// Pinning is gone. Someone with the old spelling in their fingers or in a
// script should be told that, not handed a missing-file error for what is
// obviously a marketplace id. Before the account check, because this is
// the command being wrong rather than the caller being anonymous — being
// told to sign in and then told the syntax changed is two trips.
if bare, _, pinned := strings.Cut(id, "@"); pinned && gameIDRe.MatchString(bare) {
return fmt.Errorf("versions cannot be pinned — `termcade add %s` installs what %s currently ships", bare, bare)
}
if slugOnlyRe.MatchString(id) {
return fmt.Errorf("%q is missing an author — marketplace ids look like author/slug, e.g. aviorstudio/%s", id, id)
}
if !gameIDRe.MatchString(id) {
return fmt.Errorf("add installs marketplace ids only; use `termcade dev install <file>` for a local package")
}
session, err := registry.LoadSession()
if err != nil {
return err
}
// Every marketplace install goes through an account. The bundled starter
// pack is what a signed-out arcade has to play; local author iteration is
// the explicit `dev install` path above this product boundary.
if session == nil {
return fmt.Errorf("installing a game requires an account — run `termcade login` (or `termcade signup`)")
}
return addFromRegistry(session, id)
}
// addFromRegistry installs a marketplace id. The session is never nil: cmdAdd
// turns a signed-out install away before it gets here.
func addFromRegistry(session *registry.Session, id string) error {
author, slug, _ := strings.Cut(id, "/")
client := registry.New(registry.URL(session), session.Token)
// The account library is authoritative; the package on this machine is a
// cache of that choice. Record the choice first so a failed download is
// restored by the next sync rather than becoming an untracked install.
if err := client.LibraryAdd(author, slug); err != nil {
return err
}
path, err := client.Download(author, slug)
if errors.Is(err, registry.ErrLoginRequired) {
return fmt.Errorf("your session has expired — run `termcade login`")
}
if err != nil {
return err
}
defer os.Remove(path)
raw, err := os.ReadFile(path)
if err != nil {
return err
}
if err := installPackage(raw); err != nil {
return err
}
return nil
}
// cmdDevInstall is the deliberate local escape hatch for an author iterating
// on a package. Player installs stay behind the marketplace API; development
// bytes never pretend to be account library state.
func cmdDevInstall(args []string) error {
if len(args) != 1 {
return fmt.Errorf("usage: termcade dev install <file.tcade>")
}
raw, err := os.ReadFile(args[0])
if err != nil {
return err
}
return installPackage(raw)
}
// installPackageBytes validates and installs a .tcade without printing, so
// the TUI can call it too: manifest parses, ABI is speakable, the wasm
// compiles and exports the termcade ABI — then an atomic extract into the
// games directory.
func installPackageBytes(raw []byte) (*manifest.Package, string, error) {
pkg, err := manifest.ReadPackage(raw)
if err != nil {
return nil, "", err
}
if !pkg.Manifest.CompatibleABI() {
return nil, "", fmt.Errorf("%s needs ABI v%d; this termcade speaks v%d",
pkg.Manifest.Game.ID, pkg.Manifest.Requirements.ABI, 1)
}
rt := plugin.NewRuntime(context.Background())
defer rt.Close()
if _, err := rt.Compile(pkg.Manifest.Game.ID, pkg.Wasm); err != nil {
return nil, "", err
}
gamesDir, err := plugin.GamesDir()
if err != nil {
return nil, "", err
}
dest, err := pkg.Install(gamesDir)
if err != nil {
return nil, "", err
}
return pkg, dest, nil
}
func installPackage(raw []byte) error {
pkg, dest, err := installPackageBytes(raw)
if err != nil {
return err
}
fmt.Printf("added %s %s → %s\n", pkg.Manifest.Game.ID, pkg.Manifest.Game.Version, dest)
return nil
}
// removeLocal deletes an installed game's directory. Silent, TUI-safe.
func removeLocal(author, slug string) error {
if author == "" || slug == "" ||
strings.ContainsAny(author, `\.`) || strings.ContainsAny(slug, `\.`) {
return fmt.Errorf("id must look like author/slug")
}
gamesDir, err := plugin.GamesDir()
if err != nil {
return err
}
dir := filepath.Join(gamesDir, author, slug)
if _, err := os.Stat(filepath.Join(dir, manifest.FileName)); err != nil {
return fmt.Errorf("%s/%s is not in your arcade", author, slug)
}
return os.RemoveAll(dir)
}
// syncLibraryRemove records a removal in the authoritative account library.
// A package absent from the library is a local/dev/starter package and is
// still removable. Other failures stop the local mutation so clients do not
// silently diverge from the account.
func syncLibraryRemove(author, slug string) error {
session, err := registry.LoadSession()
if err != nil || session == nil {
return nil // purely local when signed out
}
client := registry.New(registry.URL(session), session.Token)
err = client.LibraryRemove(author, slug)
if err == nil || errors.Is(err, registry.ErrNotFound) {
return nil
}
if errors.Is(err, registry.ErrLoginRequired) {
return fmt.Errorf("your session has expired — run `termcade login`")
}
return err
}
func cmdRemove(args []string) error {
if len(args) != 1 {
return fmt.Errorf("usage: termcade remove <author/slug>")
}
author, slug, ok := strings.Cut(args[0], "/")
if !ok {
return fmt.Errorf("id must look like author/slug")
}
if err := syncLibraryRemove(author, slug); err != nil {
return err
}
if err := removeLocal(author, slug); err != nil {
return err
}
fmt.Printf("removed %s\n", args[0])
return nil
}
func cmdList() error {
rt := plugin.NewRuntime(context.Background())
defer rt.Close()
games := discoverGames(rt)
// The TUI has empty states everywhere and the CLI had none, so removing
// your last game made `list` answer with nothing at all — which reads as
// a broken command rather than an empty arcade.
if len(games) == 0 {
fmt.Println("no games installed — run `termcade` and press m for the marketplace")
return nil
}
for _, g := range games {
if g.Err != nil {
fmt.Printf("%-24s %-28s broken: %v\n", g.Info.Title, g.Info.ID, g.Err)
continue
}
fmt.Printf("%-24s %-28s installed\n", g.Info.Title, g.Info.ID)
}
return nil
}
// cmdPublish points the marketplace at a package on a GitHub release. The
// registry fetches it, validates it against the same manifest rules the
// arcade uses, and records its digest — so what is published is decided by
// the package, not by anything asserted here.
//
// This is the signed-in path. Publishing from an author's own CI, with a
// scoped key rather than a session, is a separate credential and is not
// built yet.
func cmdPublish(args []string) error {
if len(args) < 2 || len(args) > 3 {
return fmt.Errorf("usage: termcade publish <repo-url> <tag> [asset]")
}
// TERMCADE_TOKEN is how CI publishes: a scoped key instead of a session,
// on a machine nobody is logged in to. It wins over a stored session so a
// workflow cannot accidentally publish as whoever last used the runner.
session, err := registry.LoadSession()
if err != nil {
return err
}
token := strings.TrimSpace(os.Getenv("TERMCADE_TOKEN"))
switch {
case token != "":
// A key names its own handle, so no session is needed or wanted.
case session != nil:
token = session.Token
default:
return fmt.Errorf(
"publishing requires an account — run `termcade login`, " +
"or set TERMCADE_TOKEN to a publish key (`termcade keys new`)")
}
repo, tag := args[0], args[1]
asset := ""
if len(args) == 3 {
asset = args[2]
} else {
// Default to what `dev build` names its output, read from the game
// directory we are standing in.
raw, err := os.ReadFile(manifest.FileName)
if err != nil {
return fmt.Errorf("no asset name given, and no %s here to infer one from", manifest.FileName)
}
m, err := manifest.Parse(raw)
if err != nil {
return err
}
asset = m.Slug() + ".tcade"
}
out, err := registry.New(registry.URL(session), token).Publish(repo, tag, asset)
if err != nil {
return err
}
fmt.Printf("published %s %s\n", out.ID, out.Version)
fmt.Printf(" from %s @ %s (%s)\n", out.Repo, out.Tag, out.Asset)
fmt.Printf(" sha256 %s\n", out.SHA256)
return nil
}
func cmdDevBuild(args []string) error {
dir := "."
if len(args) == 1 {
dir = args[0]
} else if len(args) > 1 {
return fmt.Errorf("usage: termcade dev build [dir]")
}
manifestRaw, err := os.ReadFile(filepath.Join(dir, manifest.FileName))
if err != nil {
return fmt.Errorf("a game directory needs a %s: %w", manifest.FileName, err)
}
m, err := manifest.Parse(manifestRaw)
if err != nil {
return err
}
wasmPkg := filepath.Join(dir, "cmd", "wasm")
if _, err := os.Stat(wasmPkg); err != nil {
return fmt.Errorf("a game directory needs a cmd/wasm entrypoint: %w", err)
}
tmp, err := os.MkdirTemp("", "termcade-build-*")
if err != nil {
return err
}
defer os.RemoveAll(tmp)
wasmOut := filepath.Join(tmp, manifest.WasmName)
build := exec.Command("go", "build", "-buildmode=c-shared", "-o", wasmOut, "./"+filepath.ToSlash(filepath.Join("cmd", "wasm")))
build.Dir = dir
build.Env = append(os.Environ(), "GOOS=wasip1", "GOARCH=wasm")
if out, err := build.CombinedOutput(); err != nil {
return fmt.Errorf("go build failed: %w\n%s", err, out)
}
wasm, err := os.ReadFile(wasmOut)
if err != nil {
return err
}
// The same validation an install would do, so authors find out now.
rt := plugin.NewRuntime(context.Background())
defer rt.Close()
if _, err := rt.Compile(m.Game.ID, wasm); err != nil {
return err
}
// Output lands inside the game directory, never the invoker's cwd; build
// artifacts stay next to what built them (and out of version control).
buildDir := filepath.Join(dir, "build")
if err := os.MkdirAll(buildDir, 0o755); err != nil {
return err
}
out := filepath.Join(buildDir, m.Slug()+".tcade")
if err := manifest.WritePackage(out, manifestRaw, wasm); err != nil {
return err
}
fmt.Printf("built %s %s → %s\n", m.Game.ID, m.Game.Version, out)
return nil
}
// cmdSync installs everything on your account that is missing from this
// machine.
//
// The library is the half of an account that follows you: adds and removes
// mirror to it from the arcade, the CLI and the app alike, and until now
// nothing brought it back down. A new machine, a reinstall, or a game added
// from your phone all end here.
//
// It only adds. A game installed locally but absent from the library is left
// alone — that is a local file someone installed on purpose, and deleting it
// because a server has not heard of it would be the wrong way round.
func cmdSync() error {
session, err := registry.LoadSession()
if err != nil {
return err
}
if session == nil {
return fmt.Errorf("syncing your library requires an account — run `termcade login`")
}
client := registry.New(registry.URL(session), session.Token)
library, err := client.Library()
if errors.Is(err, registry.ErrLoginRequired) {
return fmt.Errorf("your session has expired — run `termcade login`")
}
if err != nil {
return err
}
if len(library) == 0 {
fmt.Println("nothing in your library yet — add a game and it will follow you")
return nil
}
rt := plugin.NewRuntime(context.Background())
installed := map[string]bool{}
for _, g := range discoverGames(rt) {
installed[g.Info.ID] = true
}
// Closed before installing: a runtime holding compiled modules from the
// games directory has no business being open while that directory is
// written to.
rt.Close()
added, failed := 0, 0
for _, game := range library {
if installed[game.ID] {
continue
}
author, slug, ok := strings.Cut(game.ID, "/")
if !ok {
continue
}
if !game.HasPackage {
fmt.Fprintf(os.Stderr, "skipping %s: nothing published to install yet\n", game.ID)
continue
}
path, err := client.Download(author, slug)
if err != nil {
// One unavailable game must not strand the rest — a deleted
// release is the publisher's doing, not this player's.
fmt.Fprintf(os.Stderr, "could not restore %s: %v\n", game.ID, err)
failed++
continue
}
raw, readErr := os.ReadFile(path)
os.Remove(path)
if readErr != nil {
fmt.Fprintf(os.Stderr, "could not restore %s: %v\n", game.ID, readErr)
failed++
continue
}
if err := installPackage(raw); err != nil {
fmt.Fprintf(os.Stderr, "could not restore %s: %v\n", game.ID, err)
failed++
continue
}
added++
}
switch {
case added == 0 && failed == 0:
fmt.Println("your library is already here")
case failed > 0:
return fmt.Errorf("restored %d game(s); %d could not be installed", added, failed)
default:
fmt.Printf("restored %d game(s)\n", added)
}
return nil
}