Skip to content
6 changes: 3 additions & 3 deletions Taskfile.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,9 @@ includes:
flatten: true
vars:
GO_TOOLS: 'go run ./cmd/'
GATE_WORKFLOW: ci.yml
GATE_JOBS: Gate
RELEASE_FILES: _output/release/*.tar.gz _output/release/checksums.txt
# release.yml runs `task release` once ci.yml's Gate has passed on the commit.
RELEASE:
map: {proof: ci.yml, jobs: Gate, files: _output/release/*.tar.gz _output/release/checksums.txt}
# The others are the pins go tool sfw and go tool exposure embed for every repository.
VERSIONS_FILES: versions.yaml cmd/sfw/versions.yaml cmd/exposure/versions.yaml
# The site's CI page shows this workflow for a repository to copy.
Expand Down
119 changes: 96 additions & 23 deletions cmd/versions/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,39 @@ import (

func main() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
err := run(ctx, os.Args[1:])
err := run(ctx, os.Args[1:]) // mutate-exempt: the process's own arguments; run is what the tests drive
stop()
if err != nil && !errors.Is(err, flag.ErrHelp) {
// The package names itself in its errors already; this names the rest.
msg := err.Error()
if !strings.HasPrefix(msg, "versions: ") {
msg = "versions: " + msg
}
if msg, code := failure(err); code != 0 { // mutate-exempt: the process's exit; failure is what the tests drive
fmt.Fprintln(os.Stderr, msg)
os.Exit(1)
os.Exit(code)
}
}

// failure is what a command that failed says and the status it exits with: nothing and 0 for one
// that did not, and for a help that was asked for.
func failure(err error) (string, int) {
if err == nil || errors.Is(err, flag.ErrHelp) {
return "", 0
}
// The package names itself in its errors already; this names the rest.
msg := err.Error()
if !strings.HasPrefix(msg, "versions: ") {
msg = "versions: " + msg
}
return msg, status(err)
}

// unread is check's failure when it could not read a row: another exit status than a row behind,
// so that what a script reads as "nothing to bump" is never a file it was not shown.
type unread struct{ error }

// status is the exit status of a failure: 2 for rows check could not read, 1 for any other, a
// row behind among them - as diff answers 1 for a difference and 2 for a file it could not read.
func status(err error) int {
if errors.As(err, &unread{}) {
return 2
}
return 1
}

const usage = `versions - what versions.yaml pins
Expand All @@ -49,9 +71,14 @@ Usage:
versions url <name> a download's URL, at its version
versions fetch <name> <dir> a download in dir, only as the bytes it pins, and its path
versions newer <name> <version> <version> when it is newer than the pin, nothing when not
versions check what is behind its upstream; exits 1 when anything is
versions check what is behind its upstream; exits 1 when anything is,
and 2 when an entry could not be read, which may be
behind (-task: its last line names the task that
moves one, for a run through the common tasks)
versions bump <name> [version] pin an entry at a version, the newest by default, and
every entry tracked with it at the same
every entry tracked with it at the same; never at an
older version or commit than the pin's, unless -back,
and not an entry whose bump: names another command
versions refresh <name>... bump each to its newest, a commit each, and say what moved
and what is a new major, left for a person;
-propose pushes them as refresh/<label>-<sum> and opens
Expand All @@ -78,6 +105,8 @@ func run(ctx context.Context, argv []string) error {
propose := fs.Bool("propose", false, "refresh: open a pull request of what moved")
label := fs.String("label", "versions", "refresh: the name of the branches it proposes")
base := fs.String("base", "main", "refresh: the branch the pull request is into")
byTask := fs.Bool("task", false, "check: name the common task that moves an entry, as a repository runs it")
back := fs.Bool("back", false, "bump: move the pin to an older version or commit too")
if err := fs.Parse(argv); err != nil {
if errors.Is(err, flag.ErrHelp) {
fmt.Print(usage)
Expand Down Expand Up @@ -115,9 +144,9 @@ func run(ctx context.Context, argv []string) error {
if len(names) != 0 {
return errors.New("check: takes no names; it checks every entry")
}
return check(ctx, v)
return check(os.Stdout, upstream.Check(ctx, v), *byTask)
case "bump":
return bump(ctx, v, *file, names)
return bump(ctx, v, *file, names, *back)
case "refresh":
r := refresher{file: *file, git: runGit, label: *label, base: *base, out: os.Stdout, now: time.Now()}
return refresh(ctx, r, *propose, names)
Expand Down Expand Up @@ -188,8 +217,9 @@ func newer(w io.Writer, v *versions.Versions, names []string) error {
return err
}

// bump pins an entry at a version, the newest by default, and writes the file.
func bump(ctx context.Context, v *versions.Versions, file string, names []string) error {
// bump pins an entry at a version, the newest by default, and writes the file. back is a person
// saying the version is older than the pin and meant: without it that is refused.
func bump(ctx context.Context, v *versions.Versions, file string, names []string, back bool) error {
if len(names) < 1 || len(names) > 2 {
return errors.New("bump: <name> [version]")
}
Expand All @@ -201,7 +231,14 @@ func bump(ctx context.Context, v *versions.Versions, file string, names []string
if err != nil {
return err
}
_, out, err := upstream.Bump(ctx, v, was.Name, version)
if err := anothers(was); err != nil {
return err
}
to := upstream.Bump
if back {
to = upstream.BumpBackwards
}
_, out, err := to(ctx, v, was.Name, version)
if err != nil {
return err
}
Expand All @@ -221,6 +258,16 @@ func bump(ctx context.Context, v *versions.Versions, file string, names []string
return nil
}

// anothers refuses an entry whose file says another command moves it, and names the command:
// what that command checks, waits for or writes besides the pin is not something this one does.
func anothers(e versions.Entry) error {
if e.Bump == "" {
return nil
}
return fmt.Errorf("versions: %s is moved by `%s`, as its entry says (bump:), and not by this command: "+
"that one knows what a bump of %s needs", e.Name, e.Bump, e.Name)
}

// pins is each KEY=value the entries named are handed over as, after prefix, sorted: the same
// entries are the same command line, which is what a comparison of two of them relies on.
func pins(v *versions.Versions, names []string, prefix string) ([]string, error) {
Expand All @@ -238,22 +285,48 @@ func pins(v *versions.Versions, names []string, prefix string) ([]string, error)
return out, nil
}

func check(ctx context.Context, v *versions.Versions) error {
tw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
// check prints where each entry stands and fails when one is behind, or could not be read. The
// two are counted apart and fail apart: a row not read - a private upstream asked without a token
// answers 404 - may be behind, so a count of what is behind says "of those read" beside it.
// The last line names the command that moves an entry as the person who ran this would type it:
// the task every repository has when byTask says that is what ran it, and this command otherwise.
func check(w io.Writer, rows []upstream.Status, byTask bool) error {
// mutate-exempt: of the three zeros, a minimum width of one is under every cell's, a tab's width is unused where the padding is spaces, and the flag that edit sets reads HTML entities, which no row has
tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
_, _ = fmt.Fprintln(tw, "NAME\tPINNED\tNEWEST\t")
behind := 0
for _, st := range upstream.Check(ctx, v) {
behind, unreadRows, anothers := 0, 0, false
for _, st := range rows {
mark := ""
if st.Behind {
switch {
case st.Unread:
mark, unreadRows = "not read:", unreadRows+1
case st.Behind:
mark, behind = "behind", behind+1
anothers = anothers || st.Entry.Bump != ""
}
note := st.Note
if st.Entry.Bump != "" {
note = strings.TrimSpace("moved by `" + st.Entry.Bump + "` " + note)
}
_, _ = fmt.Fprintf(tw, "%s\t%s\t%s\t%s %s\n", st.Entry.Name, st.Entry.Version, st.Newest, mark, st.Note)
_, _ = fmt.Fprintf(tw, "%s\t%s\t%s\t%s %s\n", st.Entry.Name, st.Entry.Version, st.Newest, mark, note)
}
if err := tw.Flush(); err != nil {
return err
}
if behind > 0 {
return fmt.Errorf("%d behind; versions bump <name> moves one", behind)
switch {
case unreadRows > 0:
return unread{fmt.Errorf("%d not read, and %d behind of the %d that were: a row not read may be behind, and says why "+
"(GITHUB_TOKEN or GH_TOKEN reads a private repository, and more than sixty requests an hour)", unreadRows, behind, len(rows)-unreadRows)}
case behind > 0:
also := ""
if anothers {
also = ", and the command a row names moves that one"
}
bump := "versions bump <name>"
if byTask {
bump = "go tool task bump NAME=<name>"
}
return fmt.Errorf("%d behind; %s moves one%s", behind, bump, also)
}
return nil
}
141 changes: 141 additions & 0 deletions cmd/versions/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@ import (
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"

"github.com/spin-stack/go-tools/versions"
"github.com/spin-stack/go-tools/versions/upstream"
)

// stdout is what f printed to os.Stdout.
Expand Down Expand Up @@ -206,3 +208,142 @@ func TestABumpSaysEveryEntryItMoved(t *testing.T) {
err = run(t.Context(), []string{"bump", "-file", file, "snapshot", today, "x"})
assert.ErrorContains(t, err, "bump: <name> [version]")
}

// check counts what is behind and what it could not read apart, and fails apart for them: a row
// not read may be behind, so its failure is another exit status and its message says how many
// rows the count of what is behind is of. Each file here is answered without a network: an entry
// with another in the file, and a track check does not know, which is a row it cannot read.
func TestCheckCountsARowItCouldNotReadAndFailsApartForIt(t *testing.T) {
const lead = "- name: lead\n kind: date\n version: v2\n track: branch\n"
const behind = "- name: behind\n kind: date\n version: v1\n track: with lead\n"
const unknown = "- name: unknown\n kind: date\n version: v1\n track: rumour\n"
for name, tc := range map[string]struct {
file string
argv []string
rows []string
says string
status int
}{
"nothing behind": {file: lead, rows: []string{"lead v2 v2"}}, //nolint:dupword // a row: its pin, then its newest
"one behind": {file: lead + behind, rows: []string{"behind v1 v2 behind"},
says: "1 behind; versions bump <name> moves one", status: 1},
"one behind, through the task": {file: lead + behind, argv: []string{"-task"},
says: "1 behind; go tool task bump NAME=<name> moves one", status: 1},
"one behind that another command moves": {file: lead + behind + " bump: spin-os upgrade\n", rows: []string{"behind v1 v2 behind moved by `spin-os upgrade`"},
says: "1 behind; versions bump <name> moves one, and the command a row names moves that one", status: 1},
"one that another command moves, not behind": {file: lead + " bump: spin-os upgrade\n", rows: []string{"lead v2 v2 moved by `spin-os upgrade`"}}, //nolint:dupword // a row: its pin, then its newest
"one behind, and another that another command moves": {file: lead + " bump: spin-os upgrade\n" + behind,
says: "1 behind; versions bump <name> moves one", status: 1},
"one not read": {file: lead + unknown, rows: []string{"unknown v1 not read: versions: unknown tracks \"rumour\", which check does not know"},
says: "1 not read, and 0 behind of the 1 that were: a row not read may be behind", status: 2},
"one behind and two not read": {file: lead + behind + unknown + "- name: other\n kind: date\n version: v1\n track: gossip\n",
says: "2 not read, and 1 behind of the 2 that were: a row not read may be behind", status: 2},
} {
t.Run(name, func(t *testing.T) {
file := filepath.Join(t.TempDir(), "versions.yaml")
require.NoError(t, os.WriteFile(file, []byte(tc.file), 0o600))
var err error
out := stdout(t, func() { err = run(t.Context(), append(append([]string{"check"}, tc.argv...), "-file", file)) })
// A row's columns, whatever the widest entry made their width.
var rows []string
for line := range strings.Lines(out) {
rows = append(rows, strings.Join(strings.Fields(line), " "))
}
for _, row := range tc.rows {
assert.Contains(t, rows, row)
}
msg, code := failure(err)
assert.Equal(t, tc.status, code)
if tc.says == "" {
require.NoError(t, err)
assert.Empty(t, msg)
return
}
require.ErrorContains(t, err, tc.says)
assert.True(t, strings.HasPrefix(msg, "versions: "+tc.says), msg)
})
}
}

type roundTrip func(*http.Request) (*http.Response, error)

func (f roundTrip) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }

// latestRelease answers GitHub's latest release of o/tool with tag, for the test.
func latestRelease(t *testing.T, tag string) {
t.Helper()
before := http.DefaultClient.Transport
http.DefaultClient.Transport = roundTrip(func(r *http.Request) (*http.Response, error) {
status, body := http.StatusNotFound, ""
if r.URL.String() == "https://api.github.com/repos/o/tool/releases/latest" {
status, body = http.StatusOK, `{"tag_name": "`+tag+`"}`
}
return &http.Response{StatusCode: status, Body: io.NopCloser(strings.NewReader(body)), Request: r, Header: http.Header{}}, nil
})
t.Cleanup(func() { http.DefaultClient.Transport = before })
}

// aheadFile is an entry pinned past what its upstream calls its latest release.
const aheadFile = "- name: tool\n kind: date\n version: v2.0.0\n track: github-release https://github.com/o/tool\n"

// A bump to an older version is refused and writes nothing, named or found; -back is the same
// bump meant.
func TestABumpBackwardsIsRefusedUnlessMeant(t *testing.T) {
latestRelease(t, "v1.9.0")
file := filepath.Join(t.TempDir(), "versions.yaml")
require.NoError(t, os.WriteFile(file, []byte(aheadFile), 0o600))
for _, argv := range [][]string{{"bump", "-file", file, "tool"}, {"bump", "-file", file, "tool", "v1.9.0"}, {"bump", "-file", file, "tool", "v1.0.0"}} {
var err error
out := stdout(t, func() { err = run(t.Context(), argv) })
require.ErrorContains(t, err, "a bump does not move a pin backwards", "%v", argv)
assert.Empty(t, out)
raw, err := os.ReadFile(file) //nolint:gosec // the test's own file
require.NoError(t, err)
assert.Equal(t, aheadFile, string(raw), "%v", argv)
}
var err error
out := stdout(t, func() { err = run(t.Context(), []string{"bump", "-file", file, "-back", "tool", "v1.0.0"}) })
require.NoError(t, err)
assert.Equal(t, "tool: v2.0.0 -> v1.0.0 \n", out)
out = stdout(t, func() { err = run(t.Context(), []string{"bump", "-file", file, "-back", "tool"}) })
require.NoError(t, err)
assert.Equal(t, "tool: v1.0.0 -> v1.9.0 \n", out)
}

// An entry whose file names another command for its bump is not moved by this one, with a version
// or without, told to go backwards or not: the refusal names the command, and the file is as it was.
func TestABumpOfAnEntryAnotherCommandMovesIsRefused(t *testing.T) {
const theirs = "- name: spin\n kind: date\n version: 20260101T000000Z\n track: today\n bump: go tool task sources:bump\n"
file := filepath.Join(t.TempDir(), "versions.yaml")
require.NoError(t, os.WriteFile(file, []byte(theirs), 0o600))
for _, argv := range [][]string{{"bump", "-file", file, "spin"}, {"bump", "-file", file, "spin", "20270101T000000Z"}, {"bump", "-file", file, "-back", "spin", "20250101T000000Z"}} {
var err error
out := stdout(t, func() { err = run(t.Context(), argv) })
require.ErrorContains(t, err, "spin is moved by `go tool task sources:bump`, as its entry says (bump:), and not by this command", "%v", argv)
assert.Empty(t, out)
raw, err := os.ReadFile(file) //nolint:gosec // the test's own file
require.NoError(t, err)
assert.Equal(t, theirs, string(raw), "%v", argv)
}
}

// A failure is said once under the command's name, whoever worded it, and a help that was asked
// for is no failure. The table's columns are two spaces apart.
func TestAFailureIsSaidUnderTheCommandsName(t *testing.T) {
msg, code := failure(run(t.Context(), nil))
assert.Equal(t, "versions: no command given", msg)
assert.Equal(t, 1, code)
msg, code = failure(run(t.Context(), []string{"version", "-file", filepath.Join(t.TempDir(), "none"), "kernel"}))
assert.True(t, strings.HasPrefix(msg, "versions: open "), msg)
assert.Equal(t, 1, code)
var err error
stdout(t, func() { err = run(t.Context(), []string{"version", "-h"}) })
require.Error(t, err)
msg, code = failure(err)
assert.Empty(t, msg)
assert.Zero(t, code)

var table bytes.Buffer
require.NoError(t, check(&table, []upstream.Status{{Entry: versions.Entry{Name: "kernel", Version: "7.2.8"}, Newest: "7.2.8"}}, false))
assert.Equal(t, "NAME PINNED NEWEST \nkernel 7.2.8 7.2.8 \n", table.String())
}
10 changes: 10 additions & 0 deletions cmd/versions/refresh.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,17 @@ func (r refresher) move(ctx context.Context, name string) (m []moved, major bool
if err != nil {
return nil, false, err
}
if named, err := v.Get(name); err != nil {
return nil, false, err
} else if err := anothers(named); err != nil {
return nil, false, err
}
e, out, err := upstream.Bump(ctx, v, name, "")
// Pinned past what its upstream calls the newest - a release candidate, a release its
// publisher has not marked latest: it is at its newest, as far as a schedule is concerned.
if errors.Is(err, upstream.ErrBackwards) {
return nil, false, nil
}
if err != nil {
return nil, false, err
}
Expand Down
Loading