Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions Taskfile.yml
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ tasks:
- versions bump -by 'task spin:bump' spin "{{.RELEASE}}"

contract:spin:
desc: Hold src/cli/contract.ts's error codes and actions to errorActions in spin's cmd/cli/cmd/errcode.go at the release versions.yaml pins (hack/errcodes), read from spin's repository over git - with GH_TOKEN as git's credentials when it is set, since spin is private. The Bump spin workflow runs it after the bump, so a release that adds or drops a code is a red bump, not an envelope read as internal.
desc: Hold src/cli/contract.ts's error codes and actions to failureKinds in spin's cmd/cli/cmd package at the release versions.yaml pins (hack/errcodes), read from spin's repository over git - with GH_TOKEN as git's credentials when it is set, since spin is private. The Bump spin workflow runs it after the bump, so a release that adds or drops a code is a red bump, not an envelope read as internal.
vars:
SPIN:
sh: versions version spin
Expand All @@ -241,9 +241,9 @@ tasks:
set -eu
dir=$(mktemp -d)
trap 'rm -rf "$dir"' EXIT
git clone --quiet --depth 1 --branch {{.SPIN}} --filter=blob:none --no-checkout https://github.com/spin-stack/spin "$dir/spin"
git -C "$dir/spin" show HEAD:cmd/cli/cmd/errcode.go > "$dir/errcode.go"
go run ./hack/errcodes -spin "$dir/errcode.go" -contract src/cli/contract.ts
git -c advice.detachedHead=false clone --quiet --depth 1 --branch {{.SPIN}} --filter=blob:none --sparse https://github.com/spin-stack/spin "$dir/spin"
git -C "$dir/spin" sparse-checkout set cmd/cli/cmd
go run ./hack/errcodes -spin "$dir/spin/cmd/cli/cmd" -contract src/cli/contract.ts

spin:propose:
desc: Commit versions.yaml's spin at RELEASE, with package.json at the next patch when its version is tagged already, push it to spin/next and open or rewrite the pull request there, as the app GH_TOKEN and APP_SLUG name (hack/spinpropose) - the Bump spin workflow's last step, after task ci and task package:all.
Expand Down
100 changes: 64 additions & 36 deletions hack/errcodes/main.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
// Command errcodes holds the extension's error codes to the spin CLI's: every code, and the action
// it pairs with, in errorActions of spin's cmd/cli/cmd/errcode.go is ACTION_OF in
// it pairs with, in failureKinds of spin's cmd/cli/cmd package is ACTION_OF in
// src/cli/contract.ts, and nothing else is. A code spin adds or drops is a failure here, not an
// envelope the extension quietly reads as internal (task contract:spin reads spin's file at the
// release versions.yaml pins):
// envelope the extension quietly reads as internal (task contract:spin reads spin's package at the
// release versions.yaml pins). The whole package is read, not a file: the codes and the table that
// pairs them live in files of their own, and have moved between them before.
//
// go run ./hack/errcodes -spin errcode.go -contract src/cli/contract.ts
// go run ./hack/errcodes -spin <spin>/cmd/cli/cmd -contract src/cli/contract.ts
package main

import (
Expand All @@ -15,25 +16,26 @@ import (
"go/parser"
"go/token"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
)

func main() {
spinPath := flag.String("spin", "", "spin's cmd/cli/cmd/errcode.go")
spinDir := flag.String("spin", "", "spin's cmd/cli/cmd package directory")
contractPath := flag.String("contract", "src/cli/contract.ts", "the extension's contract")
flag.Parse()
if err := check(*spinPath, *contractPath); err != nil {
if err := check(*spinDir, *contractPath); err != nil {
fmt.Fprintln(os.Stderr, "errcodes:", err)
os.Exit(1)
}
fmt.Println("errcodes: the contract's codes are spin's")
}

func check(spinPath, contractPath string) error {
spinSrc, err := os.ReadFile(spinPath)
func check(spinDir, contractPath string) error {
spinSrc, err := packageSources(spinDir)
if err != nil {
return err
}
Expand All @@ -43,7 +45,7 @@ func check(spinPath, contractPath string) error {
}
spin, err := spinActions(spinSrc)
if err != nil {
return fmt.Errorf("%s: %w", spinPath, err)
return fmt.Errorf("%s: %w", spinDir, err)
}
contract, err := contractActions(string(contractSrc))
if err != nil {
Expand All @@ -55,61 +57,87 @@ func check(spinPath, contractPath string) error {
return nil
}

// spinActions reads errorActions: each key a constant of type errorCode, each value its action.
func spinActions(src []byte) (map[string]string, error) {
f, err := parser.ParseFile(token.NewFileSet(), "errcode.go", src, 0)
// packageSources reads each Go file of dir that is not a test, by name.
func packageSources(dir string) (map[string][]byte, error) {
names, err := filepath.Glob(filepath.Join(dir, "*.go"))
if err != nil {
return nil, err
}
srcs := map[string][]byte{}
for _, name := range names {
if strings.HasSuffix(name, "_test.go") {
continue
}
src, err := os.ReadFile(name)
if err != nil {
return nil, err
}
srcs[filepath.Base(name)] = src
}
if len(srcs) == 0 {
return nil, fmt.Errorf("%s holds no Go file", dir)
}
return srcs, nil
}

// spinActions reads failureKinds: each row a constant of type errorCode, its action, and the status
// spin exits with, which the extension does not read. The constants may be in any file.
func spinActions(srcs map[string][]byte) (map[string]string, error) {
codes := map[string]string{}
var table *ast.CompositeLit
for _, decl := range f.Decls {
gen, ok := decl.(*ast.GenDecl)
if !ok {
continue
for name, src := range srcs {
f, err := parser.ParseFile(token.NewFileSet(), name, src, 0)
if err != nil {
return nil, err
}
for _, spec := range gen.Specs {
vs, ok := spec.(*ast.ValueSpec)
for _, decl := range f.Decls {
gen, ok := decl.(*ast.GenDecl)
if !ok {
continue
}
for i, name := range vs.Names {
if i >= len(vs.Values) {
for _, spec := range gen.Specs {
vs, ok := spec.(*ast.ValueSpec)
if !ok {
continue
}
switch gen.Tok {
case token.CONST:
if s, ok := stringLit(vs.Values[i]); ok {
codes[name.Name] = s
for i, name := range vs.Names {
if i >= len(vs.Values) {
continue
}
case token.VAR:
if lit, ok := vs.Values[i].(*ast.CompositeLit); ok && name.Name == "errorActions" {
table = lit
switch gen.Tok {
case token.CONST:
if s, ok := stringLit(vs.Values[i]); ok {
codes[name.Name] = s
}
case token.VAR:
if lit, ok := vs.Values[i].(*ast.CompositeLit); ok && name.Name == "failureKinds" {
table = lit
}
}
}
}
}
}
if table == nil {
return nil, errors.New("no errorActions")
return nil, errors.New("no failureKinds")
}
actions := map[string]string{}
for _, elt := range table.Elts {
kv, ok := elt.(*ast.KeyValueExpr)
if !ok {
return nil, errors.New("errorActions holds an entry that is no key and value")
row, ok := elt.(*ast.CompositeLit)
if !ok || len(row.Elts) < 2 {
return nil, errors.New("failureKinds holds a row that is no {code, action, status}")
}
key, ok := kv.Key.(*ast.Ident)
key, ok := row.Elts[0].(*ast.Ident)
if !ok {
return nil, errors.New("errorActions has a key that is no constant")
return nil, errors.New("failureKinds has a code that is no constant")
}
code, ok := codes[key.Name]
if !ok {
return nil, fmt.Errorf("errorActions names %s, which is no string constant", key.Name)
return nil, fmt.Errorf("failureKinds names %s, which is no string constant", key.Name)
}
action, ok := stringLit(kv.Value)
action, ok := stringLit(row.Elts[1])
if !ok {
return nil, fmt.Errorf("errorActions pairs %s with no string", code)
return nil, fmt.Errorf("failureKinds pairs %s with no string", code)
}
actions[code] = action
}
Expand Down
78 changes: 63 additions & 15 deletions hack/errcodes/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,14 @@ import (
"testing"
)

// spinSrc is errcode.go as spin writes it: the codes, then errorActions.
const spinSrc = `package cmd
// spinSrc is spin's cmd/cli/cmd as it writes the two: the codes in errcode.go, and failureKinds,
// which pairs each with its action and exit status, in exitcodes.go.
var spinSrc = map[string][]byte{
"errcode.go": []byte(errcodeSrc),
"exitcodes.go": []byte(exitcodesSrc),
}

const errcodeSrc = `package cmd

type errorCode string

Expand All @@ -20,14 +26,25 @@ const (
)

const muxPersist = "10m"
`

var errorActions = map[errorCode]string{
codeNotSignedIn: "login",
codeKeyNotEnrolled: "add_key",
codeInternal: "details",
const exitcodesSrc = `package cmd

var failureKinds = []failureKind{
{codeInternal, "details", exitFailed},
{codeNotSignedIn, "login", exitNotAllowed},
{codeKeyNotEnrolled, "add_key", exitNotAllowed},
}
`

// withExitcodes is spinSrc with exitcodes.go's text replaced, old by new.
func withExitcodes(old, new string) map[string][]byte {
return map[string][]byte{
"errcode.go": []byte(errcodeSrc),
"exitcodes.go": []byte(strings.Replace(exitcodesSrc, old, new, 1)),
}
}

const contractSrc = `export type Action = "login" | "add_key" | "details"

export const ACTION_OF = {
Expand All @@ -38,7 +55,7 @@ export const ACTION_OF = {
`

func TestSpinActions(t *testing.T) {
got, err := spinActions([]byte(spinSrc))
got, err := spinActions(spinSrc)
if err != nil {
t.Fatal(err)
}
Expand Down Expand Up @@ -102,7 +119,7 @@ func TestDiff(t *testing.T) {
},
} {
t.Run(tc.name, func(t *testing.T) {
spin, err := spinActions([]byte(spinSrc))
spin, err := spinActions(spinSrc)
if err != nil {
t.Fatal(err)
}
Expand All @@ -119,26 +136,57 @@ func TestDiff(t *testing.T) {
}

func TestRefused(t *testing.T) {
for _, tc := range []struct{ name, spin, contract, want string }{
{"no table in spin", "package cmd\n", contractSrc, "no errorActions"},
{"a key that is no constant", strings.Replace(spinSrc, "codeInternal: \"details\"", "\"internal\": \"details\"", 1), contractSrc, "no constant"},
for _, tc := range []struct {
name string
spin map[string][]byte
contract string
want string
}{
{"no Go file", map[string][]byte{}, contractSrc, "no Go file"},
{"no table in spin", map[string][]byte{"errcode.go": []byte(errcodeSrc)}, contractSrc, "no failureKinds"},
{"a code that is no constant", withExitcodes(`{codeInternal, "details"`, `{"internal", "details"`), contractSrc, "no constant"},
{"a row that is no row", withExitcodes(`{codeInternal, "details", exitFailed},`, `internalKind,`), contractSrc, "no {code"},
{"no table in the contract", spinSrc, "export const X = {}\n", "no ACTION_OF"},
{"an entry that is no pair", spinSrc, strings.Replace(contractSrc, ` internal: "details",`, ` ...MORE,`, 1), "no `code"},
{"a table that does not end", spinSrc, "export const ACTION_OF = {\n internal: \"details\",", "does not end"},
} {
t.Run(tc.name, func(t *testing.T) {
dir := t.TempDir()
spin, contract := filepath.Join(dir, "errcode.go"), filepath.Join(dir, "contract.ts")
if err := os.WriteFile(spin, []byte(tc.spin), 0o600); err != nil {
t.Fatal(err)
for name, src := range tc.spin {
if err := os.WriteFile(filepath.Join(dir, name), src, 0o600); err != nil {
t.Fatal(err)
}
}
contract := filepath.Join(t.TempDir(), "contract.ts")
if err := os.WriteFile(contract, []byte(tc.contract), 0o600); err != nil {
t.Fatal(err)
}
err := check(spin, contract)
err := check(dir, contract)
if err == nil || !strings.Contains(err.Error(), tc.want) {
t.Fatalf("got %v, want an error holding %q", err, tc.want)
}
})
}
}

// A test file of spin's is not its table: a fixture there names codes spin does not write.
func TestTestFilesAreNotRead(t *testing.T) {
dir := t.TempDir()
files := map[string]string{
"errcode.go": errcodeSrc,
"exitcodes.go": exitcodesSrc,
"exitcodes_test.go": "package cmd\n\nvar failureKinds = []failureKind{{codeGone, \"details\", exitFailed}}\n",
}
for name, src := range files {
if err := os.WriteFile(filepath.Join(dir, name), []byte(src), 0o600); err != nil {
t.Fatal(err)
}
}
contract := filepath.Join(t.TempDir(), "contract.ts")
if err := os.WriteFile(contract, []byte(contractSrc), 0o600); err != nil {
t.Fatal(err)
}
if err := check(dir, contract); err != nil {
t.Fatal(err)
}
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "spinbox",
"displayName": "Spinbox",
"description": "Open Spinbox workspaces in VS Code over Remote-SSH, through the spin CLI.",
"version": "0.0.13",
"version": "0.0.14",
"publisher": "spin-stack",
"icon": "images/icon.png",
"galleryBanner": {
Expand Down
6 changes: 3 additions & 3 deletions src/auth/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export class SpinboxAuthProvider implements vscode.AuthenticationProvider, vscod
// installation unreachable) rejects, for the caller to show.
async getSessions(): Promise<vscode.AuthenticationSession[]> {
const v = await this.cli.version()
this.known = v.signed_in ? [session(v, v.user)] : []
this.known = v.signedIn ? [session(v, v.user)] : []
return this.known
}

Expand Down Expand Up @@ -91,8 +91,8 @@ export class SpinboxAuthProvider implements vscode.AuthenticationProvider, vscod
token.onCancellationRequested(() => abort.abort())
return this.cli.login(
(start) => {
progress.report({ message: `enter ${start.user_code} on the page that opened` })
void vscode.env.openExternal(vscode.Uri.parse(start.verification_url))
progress.report({ message: `enter ${start.userCode} on the page that opened` })
void vscode.env.openExternal(vscode.Uri.parse(start.verificationUrl))
},
{ signal: abort.signal },
)
Expand Down
Loading