4 Commits
Author SHA1 Message Date
simonfrankenandClaude Opus 5.5 99f1ba2bec Mention branch attach of restore in the README
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 19:18:12 +02:00
simonfrankenandClaude Opus 5.5 651b0c2e69 Restore puts submodules on a branch at their pin
A restored submodule whose pin is a branch tip ends on that branch instead
of a detached HEAD: the local branch tracking the ref, else the ref created
as a tracking branch, else another local branch, else another remote branch
at the pin. No branch is moved; in-sync submodules are included (D28).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 19:17:26 +02:00
simonfranken 2aeebfe3b1 updates screenshot for readme 2026-10-23 18:48:58 +02:00
simonfrankenandClaude Sonnet 5.5 4ac29c04d0 Offer "quit and update" in the footer, check for updates on every start
The update check ran at most once a day and only printed a line after the
TUI exited. Now the registry is asked on every start (in the background,
3 s timeout, no cache) and the result reaches the TUI as a message.

With a newer release, the footer shows `q quit and update to vX` right of
help and quit, on a highlighted background (Theme.Highlight). `q` quits
and `main` installs the release once the terminal is restored, sharing
the code of `submarine update`; plain quit moves to `Q`, ctrl+c never
updates.

Drop LatestCached and CheckInterval. Add D27 and F58.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-23 18:43:17 +02:00
20 changed files with 663 additions and 82 deletions
+5 -3
View File
@@ -103,8 +103,10 @@ clipboard, ready for `cd <paste>`. It works over SSH too (OSC 52; in tmux,
Select a submodule (or the header for the whole superproject) and press `x`. Select a submodule (or the header for the whole superproject) and press `x`.
Its worktree becomes exactly what git records, and so do all submodules Its worktree becomes exactly what git records, and so do all submodules
below it: changes are reset, untracked files removed, merges and rebases below it: changes are reset, untracked files removed, merges and rebases
ended, missing submodules cloned. Staged pins are kept. If something would be ended, missing submodules cloned. Staged pins are kept. A submodule whose pin
lost, you are asked first: is a branch tip ends on that branch instead of a detached HEAD (a missing
local branch is created from the remote one; no branch is ever moved). If
something would be lost, you are asked first:
``` ```
Restore src/app? Discards 7 changed files in 3 repositories. y restore · n cancel Restore src/app? Discards 7 changed files in 3 repositories. y restore · n cancel
@@ -157,7 +159,7 @@ files.
| `x` | Restore: make the worktree exactly what git records (asks if work would be lost) | | `x` | Restore: make the worktree exactly what git records (asks if work would be lost) |
| `f` / `r` | Fetch / reload | | `f` / `r` | Fetch / reload |
| `?` | Full help | | `?` | Full help |
| `q` | Quit | | `q` | Quit. If a newer release exists, the footer offers `q quit and update to vX` (highlighted) and plain quit moves to `Q` |
The mouse works too: click to select, click `▸` to toggle, wheel to move. In The mouse works too: click to select, click `▸` to toggle, wheel to move. In
the branch popup, click a branch to switch to it, use the wheel to move, and the branch popup, click a branch to switch to it, use the wheel to move, and
+25 -25
View File
@@ -6,7 +6,6 @@ import (
"flag" "flag"
"fmt" "fmt"
"os" "os"
"path/filepath"
"time" "time"
tea "github.com/charmbracelet/bubbletea" tea "github.com/charmbracelet/bubbletea"
@@ -71,42 +70,38 @@ func main() {
zone.NewGlobal() zone.NewGlobal()
defer zone.Close() defer zone.Close()
notice := checkForUpdate(ctx, *useMock) var opts []tui.Option
if !*useMock && update.Release(version) && os.Getenv("SUBMARINE_NO_UPDATE_CHECK") == "" {
opts = append(opts, tui.WithUpdateCheck(latestRelease))
}
p := tea.NewProgram(tui.New(ctx, provider), tea.WithAltScreen(), tea.WithMouseCellMotion()) p := tea.NewProgram(tui.New(ctx, provider, opts...), tea.WithAltScreen(), tea.WithMouseCellMotion())
if _, err := p.Run(); err != nil { final, err := p.Run()
if err != nil {
fmt.Fprintln(os.Stderr, err) fmt.Fprintln(os.Stderr, err)
os.Exit(1) os.Exit(1)
} }
select { // The user chose "quit and update": the terminal is restored by now.
case v := <-notice: if m, ok := final.(tui.Model); ok && m.UpdateTo() != "" {
if v != "" { fmt.Printf("updating to %s…\n", m.UpdateTo())
fmt.Fprintf(os.Stderr, "submarine %s is available (you have %s), run: submarine update\n", v, version) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
if code := install(ctx, update.New(), m.UpdateTo()); code != 0 {
os.Exit(code)
} }
default:
} }
} }
// checkForUpdate looks for a newer release in the background (at most once a // latestRelease returns the version of a newer release, or "" if there is
// day, cached) and delivers its version, or "" when there is none. Disabled // none or the registry can't be reached within a few seconds.
// for dev builds, --mock and SUBMARINE_NO_UPDATE_CHECK. func latestRelease(ctx context.Context) string {
func checkForUpdate(ctx context.Context, off bool) <-chan string {
out := make(chan string, 1)
cache, err := os.UserCacheDir()
if off || err != nil || !update.Release(version) || os.Getenv("SUBMARINE_NO_UPDATE_CHECK") != "" {
out <- ""
return out
}
go func() {
ctx, cancel := context.WithTimeout(ctx, 3*time.Second) ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel() defer cancel()
v, err := update.New().LatestCached(ctx, filepath.Join(cache, "submarine", "latest-version")) v, err := update.New().Latest(ctx)
if err != nil || !update.Newer(version, v) { if err != nil || !update.Newer(version, v) {
v = "" return ""
} }
out <- v return v
}()
return out
} }
func runUpdate(args []string) int { func runUpdate(args []string) int {
@@ -135,6 +130,11 @@ func runUpdate(args []string) int {
fmt.Fprintf(os.Stderr, "submarine: this is a %q build; use --force to replace it with %s\n", version, latest) fmt.Fprintf(os.Stderr, "submarine: this is a %q build; use --force to replace it with %s\n", version, latest)
return 1 return 1
} }
return install(ctx, c, latest)
}
// install replaces the running binary with release latest.
func install(ctx context.Context, c *update.Client, latest string) int {
exe, err := c.Install(ctx, latest) exe, err := c.Install(ctx, latest)
if err != nil { if err != nil {
fmt.Fprintln(os.Stderr, "submarine: update failed:", err) fmt.Fprintln(os.Stderr, "submarine: update failed:", err)
+37 -4
View File
@@ -86,7 +86,8 @@ After a successful restore of repository R with target T:
any depth. any depth.
So the subtree shows `in sync` everywhere, except for states restore does So the subtree shows `in sync` everywhere, except for states restore does
not change: `unpushed`, behind/ahead of the ref, and `detached HEAD on pin`. not change: `unpushed`, behind/ahead of the ref, and `detached HEAD on pin`
where no branch is at the pin (see [Branches](#branches)).
The recursion follows **T**, not the tree loaded in the UI. A submodule that The recursion follows **T**, not the tree loaded in the UI. A submodule that
is only in T (for example, after switching branches) is initialized. A is only in T (for example, after switching branches) is initialized. A
@@ -100,8 +101,25 @@ submodule that is only on disk is deleted as an untracked directory.
the branch stays checked out. the branch stays checked out.
- **Submodule off the pin:** HEAD is detached at the target. The branch that - **Submodule off the pin:** HEAD is detached at the target. The branch that
was checked out is **not moved**, so its commits stay on it. was checked out is **not moved**, so its commits stay on it.
- **Submodule detached at the target** (after the step above, or because it
was already so, also when it was in sync): HEAD is put on a branch whose
tip is the target, the first that fits of ([D28](decisions.md)):
1. a local branch tracking the ref the UI shows (or named like it), e.g.
local `main` tracking `origin/main`, also when the pin is behind or
ahead of the ref;
2. the ref itself, if its tip is the target and no local branch has its
name: the local branch is created, tracking it;
3. any other local branch, the first alphabetically;
4. any other remote branch whose name no local branch has, created as a
tracking branch; the ref's remote first, then alphabetically.
Restore never moves, creates or deletes a branch. If git refuses one (checked out in another worktree, a name conflict),
the next is tried. If none fits, HEAD stays detached.
Restore never moves or deletes a branch. A local branch that is behind or
ahead of its remote branch is no candidate and is not fast-forwarded. The
only branches restore creates are tracking branches for remote branches at
the target, in steps 2 and 4.
### What can be lost ### What can be lost
@@ -187,6 +205,14 @@ submodule update --init --checkout --force -- <not yet initialized children>
`--checkout` overrides `submodule.<name>.update`, and the explicit paths `--checkout` overrides `submodule.<name>.update`, and the explicit paths
override `submodule.<name>.active`, so no child module is skipped. override `submodule.<name>.active`, so no child module is skipped.
For a submodule, after `submodule sync`, `attachBranch` puts a detached HEAD
on a branch: `symbolic-ref -q HEAD` (on a branch: done), `for-each-ref
--points-at=T refs/heads refs/remotes` (no branch at T: done), then the ref
is resolved like `Status` does, and the first candidate (see
[Branches](#branches)) that `switch` / `switch -c <local> --track <remote>`
accepts wins. The branch checked out before the restore is passed to the
ref resolution. A child's `.gitmodules` branch is read once per parent.
With `c` the parent's index gets the committed pin first (`update-index With `c` the parent's index gets the committed pin first (`update-index
--cacheinfo` in the parent). --cacheinfo` in the parent).
@@ -261,7 +287,9 @@ restore or switch runs at a time.
`git.Provider.Switch` (`internal/submodule/git/switch.go`): verify the ref is `git.Provider.Switch` (`internal/submodule/git/switch.go`): verify the ref is
still `T`; `update-index --cacheinfo` in the parent; `restoreRepo` (see still `T`; `update-index --cacheinfo` in the parent; `restoreRepo` (see
restore); then `switch` / `switch -c <local> --track <remote-branch>`. restore); then `switch` / `switch -c <local> --track <remote-branch>`. The restore leaves HEAD of the
switched repository alone (Switch puts it on the chosen branch); the
submodules below it are attached as in a restore.
`SwitchLoss` is `lossOf` with `T` as the target. `Branches` is one `SwitchLoss` is `lossOf` with `T` as the target. `Branches` is one
`for-each-ref`, without the `origin/HEAD` symref. `for-each-ref`, without the `origin/HEAD` symref.
@@ -337,7 +365,12 @@ action, hence `x`.
not moved, ignored files survive, a merge and a rebase in progress end, a not moved, ignored files survive, a merge and a rebase in progress end, a
standalone clone and a removed submodule's directory are deleted, a missing standalone clone and a removed submodule's directory are deleted, a missing
submodule is cloned again, `update = none` and inactive submodules are submodule is cloned again, `update = none` and inactive submodules are
restored, an unavailable commit is reported. The loss is empty for off pin, restored, an unavailable commit is reported. A detached submodule ends on
the local branch tracking the ref, else on the ref created as a tracking
branch (before other branches at the pin), else on the first local
branch; a local branch elsewhere is not moved; a checked-out branch stays;
a branch of another worktree is skipped; nested submodules are attached
too. The loss is empty for off pin,
missing and unpushed submodules, counts files, nested changes, merges, missing and unpushed submodules, counts files, nested changes, merges,
detached commits (not those on a branch) and standalone repositories. detached commits (not those on a branch) and standalone repositories.
- UI (`internal/tui/restore_test.go`): restores at once without a loss, asks - UI (`internal/tui/restore_test.go`): restores at once without a loss, asks
+6 -4
View File
@@ -221,10 +221,12 @@ No CI runner: releases are built and published from a developer machine.
`VERSION`, downloads the asset for the running platform, verifies the `VERSION`, downloads the asset for the running platform, verifies the
checksum and atomically replaces the real executable (symlinks resolved, checksum and atomically replaces the real executable (symlinks resolved,
so `sub` works too). `SUBMARINE_UPDATE_URL` overrides the registry. so `sub` works too). `SUBMARINE_UPDATE_URL` overrides the registry.
- After the TUI exits, a one-line notice is printed if a newer release - On every start the TUI looks for a newer release in the background (3 s
exists. The check runs in the background at startup, at most once a day timeout, no cache, no blocking). `main` passes `tui.WithUpdateCheck` and
(cached in the user cache dir) and is off for dev builds, the TUI gets the result as a message; the footer then offers `q quit and
`--mock` and `SUBMARINE_NO_UPDATE_CHECK=1`. update to vX`. That key quits, and `main` installs the release once the
terminal is restored (the same code as `submarine update`). The check is off
for dev builds, `--mock` and `SUBMARINE_NO_UPDATE_CHECK=1`.
## Testing ## Testing
+51 -2
View File
@@ -200,7 +200,8 @@ package so versions stay clean.
**Consequences.** Integrity is a sha256 from the same host: it catches **Consequences.** Integrity is a sha256 from the same host: it catches
corrupt or partial downloads, not a compromised registry (no signatures). corrupt or partial downloads, not a compromised registry (no signatures).
The update check is a deliberate, outside-the-provider network use: only The update check is a deliberate, outside-the-provider network use: only
on `update` and a once-a-day background check that can be disabled. on `update` and a background check at startup that can be disabled (it
was once a day; see D27).
## Copy path with `c` via OSC 52 ## Copy path with `c` via OSC 52
@@ -326,7 +327,8 @@ the same for every submodule of the target tree, initializing missing ones.
- *Ignored files stay* (`clean` without `-x`): `.env`, `node_modules` and - *Ignored files stay* (`clean` without `-x`): `.env`, `node_modules` and
IDE settings are not "additional files" worth deleting in every submodule. IDE settings are not "additional files" worth deleting in every submodule.
- *Branches never move.* A checkout that is not on the target is detached - *Branches never move.* A checkout that is not on the target is detached
first, so commits stay on their branch. first, so commits stay on their branch. (A submodule is then put on a
branch at the target if there is one, see D28.)
- *It asks only if something is lost* (changed or untracked files, - *It asks only if something is lost* (changed or untracked files,
operations in progress, commits on no ref, standalone repositories). operations in progress, commits on no ref, standalone repositories).
Never asking would delete repositories that exist nowhere else; always Never asking would delete repositories that exist nowhere else; always
@@ -481,3 +483,50 @@ and the name is what people know. Long names are cut at 16 columns, so the
label column cannot grow without bound. In a label every role word has its label column cannot grow without bound. In a label every role word has its
own style, and `you` is bold in the default color: it was lost between the own style, and `you` is bold in the default color: it was lost between the
muted words, and it is the one the user looks for. muted words, and it is the one the user looks for.
## D27 — Update check on every start, offered as "quit and update"
**Decision.** The registry is asked on every start, in the background, with
no cache. A newer release shows up in the footer as `q quit and update to
vX`, right of help and quit, on a highlighted background (black on cyan).
While it is shown, `q` quits and updates, and plain quit is `Q`. `ctrl+c`
always quits without updating. The update runs after the TUI has exited.
**Rationale.** A once-a-day check with a notice printed after exit was
easy to miss. The hint is only useful where the user is looking, and the
key they use to leave is the natural place. Running the install after the
TUI exits keeps the terminal clean and reuses `submarine update`'s code.
**Consequences.** Every start makes one small request to the registry (3 s
timeout, failures are silent), which supersedes the once-a-day rule of D21.
N1 still holds: the TUI never waits for it. `q` changes meaning while an
update is available, so muscle memory that exits with `q` now updates; the
bar says so. Typing `q` in the filter or a popup is unchanged.
## D28 — Restore puts a submodule on a branch at its pin
**Context.** After a restore (for example after the superproject's branch
changed) every submodule was a detached HEAD, so IDEs showed only hashes.
**Decision.** Amends D23. After restoring a submodule, at any depth, a
detached HEAD is put on a branch whose tip is the pin, in this order: (1) a
local branch tracking the shown ref (or named like it), (2) the ref itself
as a new local tracking branch, if no local branch has its name, (3) any
other local branch, alphabetically, (4) any other remote branch whose name
no local branch has, as a new tracking branch, the ref's remote first. A
HEAD already on a branch stays there. If git refuses a branch (checked out
in another worktree, a name conflict), the next one is tried; if none fits,
HEAD stays detached and the restore still succeeds. Submodules that were in
sync are included. The superproject is not affected.
**Rationale.** Attaching a branch whose tip is the pin changes no commit and
no file, so nothing can be lost and the loss question stays the same. The
ref comes first because it is what the UI shows; a local branch beats a new
one so restore adds as few branches as possible.
**Alternatives.** Fast-forwarding a local branch that is behind its remote
branch at the pin: rejected, restore still never moves a branch. Staying
detached when several branches fit: rejected, the order above always gives
one answer, the same on every run.
**Consequences.** Restore now may create local branches (only for remote
branches at the pin whose name has none). Per detached submodule it costs a
`symbolic-ref` and one `for-each-ref --points-at`; only if a branch is at
the pin, the ref is resolved (as for `Status`) and one `switch` runs. No
network. `detached HEAD on pin` is now left only where no branch is at the
pin. Switch keeps its own rule for the repository it switches; the
submodules below it follow this one.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 420 KiB

After

Width:  |  Height:  |  Size: 143 KiB

+8 -1
View File
@@ -145,7 +145,8 @@ commit hashes. It doesn't answer the questions users actually have:
the header is selected): its worktree becomes exactly what git records, and the header is selected): its worktree becomes exactly what git records, and
so do all submodules below it, recursively. Staged pins are kept at every so do all submodules below it, recursively. Staged pins are kept at every
depth. For a submodule with a staged pin it asks whether to restore to the depth. For a submodule with a staged pin it asks whether to restore to the
staged or the committed pin (the latter unstages it). It asks for staged or the committed pin (the latter unstages it). A restored submodule
whose pin is a branch tip ends on that branch, not detached. It asks for
confirmation only if something would be lost. See [actions.md](actions.md#restore). confirmation only if something would be lost. See [actions.md](actions.md#restore).
- **F57** `b` opens a popup in the middle of the screen with a search line - **F57** `b` opens a popup in the middle of the screen with a search line
@@ -164,6 +165,12 @@ submarine [dir] # the repository containing dir (default: current directory)
submarine --mock # built-in mock data submarine --mock # built-in mock data
``` ```
- **F58** On every start the tool looks for a newer release in the
background (never blocking, silent on failure; off for dev builds,
`--mock` and `SUBMARINE_NO_UPDATE_CHECK=1`). If there is one, the footer
shows `q quit and update to vX` right of help and quit, highlighted; `q`
then quits and installs the release, and plain quit is `Q`.
## Non-functional requirements ## Non-functional requirements
- **N1** Startup must not block on the network. The tool shows the local - **N1** Startup must not block on the network. The tool shows the local
+8 -3
View File
@@ -42,7 +42,10 @@
Keys come in three groups (`keyMap.Navigation`, `.Submodule`, `.Global`): Keys come in three groups (`keyMap.Navigation`, `.Submodule`, `.Global`):
- **Navigation** (move, fold, toggle): left in the footer. - **Navigation** (move, fold, toggle): left in the footer.
- **Global** (`?`, `q`): right-aligned in the footer, always kept. - **Global** (`?`, `q`): right-aligned in the footer, always kept. If a newer
release exists, `q quit and update to vX` follows them as the right-most
item, on a highlighted background (`Theme.Highlight`: black on Primary), and
plain quit is `Q` (see D27).
- **Submodule** (act on the selected one, e.g. `c`): a palette on the last - **Submodule** (act on the selected one, e.g. `c`): a palette on the last
line of the detail pane. It is left out if the pane is shorter than 12 line of the detail pane. It is left out if the pane is shorter than 12
lines. Whenever the palette isn't shown (pane hidden or too short), these lines. Whenever the palette isn't shown (pane hidden or too short), these
@@ -250,6 +253,7 @@ colors in components.
| Bar | adaptive 254 (light) / 235 (dark) | header background | | Bar | adaptive 254 (light) / 235 (dark) | header background |
| Selected | adaptive 253 (light) / 237 (dark) | selected row background | | Selected | adaptive 253 (light) / 237 (dark) | selected row background |
| Backdrop | adaptive 252 (light) / 238 (dark) | the screen behind a popup | | Backdrop | adaptive 252 (light) / 238 (dark) | the screen behind a popup |
| Highlight | ANSI `0` black, bold, on Primary | the `quit and update` hint in the footer |
- Background shades have no ANSI-16 equivalent, so they use `AdaptiveColor`. - Background shades have no ANSI-16 equivalent, so they use `AdaptiveColor`.
The background is detected once in `main` before Bubble Tea starts. The background is detected once in `main` before Bubble Tea starts.
@@ -283,7 +287,7 @@ colors in components.
| `home` / `g`, `end` / `G` | Header (superproject) / last submodule | | `home` / `g`, `end` / `G` | Header (superproject) / last submodule |
| `pgup`, `pgdn` | Move by one screen | | `pgup`, `pgdn` | Move by one screen |
| `?` | Toggle full help | | `?` | Toggle full help |
| `q`, `ctrl+c` | Quit | | `q`, `ctrl+c` | Quit. With a newer release: `q` quits and updates, `Q` and `ctrl+c` quit |
| `f` | Fetch all repositories (does nothing while a fetch runs) | | `f` | Fetch all repositories (does nothing while a fetch runs) |
| `r` | Reload everything (e.g. after editing files) | | `r` | Reload everything (e.g. after editing files) |
| `c` | Copy the absolute directory of the selected submodule to the clipboard (OSC 52, so it also works over SSH; needs terminal support, in tmux `set -g set-clipboard on`). The footer confirms with `copied <path>`. Without a local provider (mock) the path relative to the superproject is copied | | `c` | Copy the absolute directory of the selected submodule to the clipboard (OSC 52, so it also works over SSH; needs terminal support, in tmux `set -g set-clipboard on`). The footer confirms with `copied <path>`. Without a local provider (mock) the path relative to the superproject is copied |
@@ -413,7 +417,8 @@ where the palette can't be shown, see [Key bar and palette](#key-bar-and-palette
| `/` | Filter | Global | Help | | `/` | Filter | Global | Help |
| `!` | Problems only (toggle) | Global | Help | | `!` | Problems only (toggle) | Global | Help |
| `?` | Toggle full help | Global | Bar, Help | | `?` | Toggle full help | Global | Bar, Help |
| `q`, `ctrl+c` | Quit | Global | Bar, Help | | `q`, `ctrl+c` | Quit (`Q`, `ctrl+c` while an update is offered) | Global | Bar, Help |
| `q` | Quit and update to the newer release (only if there is one) | Global | Bar (highlighted), Help |
### Mouse ### Mouse
+18 -8
View File
@@ -327,17 +327,10 @@ func pinState(ctx context.Context, in info, st *submodule.Status, pin, head, bra
return fmt.Errorf("pinned commit %.7s not fetched", pin) return fmt.Errorf("pinned commit %.7s not fetched", pin)
} }
// remote branches containing the pin, oldest tip first containing, err := remoteContaining(ctx, in.dir, pin)
out, err := run(ctx, in.dir, "for-each-ref", "--contains", pin, "--sort=committerdate", "--format=%(refname)", "refs/remotes")
if err != nil { if err != nil {
return err return err
} }
var containing []string
for _, r := range strings.Fields(out) {
if !strings.HasSuffix(r, "/HEAD") {
containing = append(containing, strings.TrimPrefix(r, "refs/remotes/"))
}
}
st.Pin.Pushed = len(containing) > 0 st.Pin.Pushed = len(containing) > 0
var ref string var ref string
@@ -359,6 +352,7 @@ func pinState(ctx context.Context, in info, st *submodule.Status, pin, head, bra
return err return err
} }
st.CheckedOut = st.Pinned st.CheckedOut = st.Pinned
var out string
if head != pin { if head != pin {
if st.CheckedOut, err = commit(ctx, in.dir, head); err != nil { if st.CheckedOut, err = commit(ctx, in.dir, head); err != nil {
return err return err
@@ -417,6 +411,22 @@ func pinState(ctx context.Context, in info, st *submodule.Status, pin, head, bra
return nil return nil
} }
// remoteContaining lists the remote branches containing pin, oldest tip
// first, without the origin/HEAD symref.
func remoteContaining(ctx context.Context, dir, pin string) ([]string, error) {
out, err := run(ctx, dir, "for-each-ref", "--contains", pin, "--sort=committerdate", "--format=%(refname)", "refs/remotes")
if err != nil {
return nil, err
}
var containing []string
for _, r := range strings.Fields(out) {
if !strings.HasSuffix(r, "/HEAD") {
containing = append(containing, strings.TrimPrefix(r, "refs/remotes/"))
}
}
return containing, nil
}
// resolve finds the ref the pin is compared with, following the order in // resolve finds the ref the pin is compared with, following the order in
// docs/state-model.md: the target (see targetRef) if the pin is on it, else the // docs/state-model.md: the target (see targetRef) if the pin is on it, else the
// branch containing the pin that is closest to it, else the target anyway, // branch containing the pin that is closest to it, else the target anyway,
+154 -4
View File
@@ -6,7 +6,9 @@ import (
"fmt" "fmt"
"io/fs" "io/fs"
"os" "os"
"path"
"path/filepath" "path/filepath"
"slices"
"strings" "strings"
"sync" "sync"
"time" "time"
@@ -45,7 +47,7 @@ func (p *Provider) RestoreLoss(ctx context.Context, path string, to submodule.Re
// submodule is cloned and missing commits are fetched; git never prompts. // submodule is cloned and missing commits are fetched; git never prompts.
func (p *Provider) Restore(ctx context.Context, path string, to submodule.RestoreTarget) error { func (p *Provider) Restore(ctx context.Context, path string, to submodule.RestoreTarget) error {
if path == "" { if path == "" {
return p.restoreRepo(ctx, p.root, "HEAD") return p.restoreRepo(ctx, p.root, "HEAD", nil)
} }
p.mu.RLock() p.mu.RLock()
in, ok := p.mods[path] in, ok := p.mods[path]
@@ -67,7 +69,7 @@ func (p *Provider) Restore(ctx context.Context, path string, to submodule.Restor
return fmt.Errorf("%s: %w", path, err) return fmt.Errorf("%s: %w", path, err)
} }
} }
return p.restoreRepo(ctx, in.dir, pin) return p.restoreRepo(ctx, in.dir, pin, &in)
} }
// restoreTarget returns the directory and the commit path is restored to: // restoreTarget returns the directory and the commit path is restored to:
@@ -123,7 +125,9 @@ func pinOf(ctx context.Context, in info, to submodule.RestoreTarget) (string, er
// or "HEAD") and then every submodule its index records. Branches are never // or "HEAD") and then every submodule its index records. Branches are never
// moved: a checkout that is not on target is detached first. If the checkout // moved: a checkout that is not on target is detached first. If the checkout
// stays on target, its staged pins are kept and are the submodules' targets. // stays on target, its staged pins are kept and are the submodules' targets.
func (p *Provider) restoreRepo(ctx context.Context, dir, target string) error { // For a submodule (in is not nil) a detached HEAD is then put on a branch at
// target if there is one, see attachBranch; the submodules below always are.
func (p *Provider) restoreRepo(ctx context.Context, dir, target string, in *info) error {
env := p.networkEnv() env := p.networkEnv()
g := func(args ...string) (string, error) { g := func(args ...string) (string, error) {
return p.exec(ctx, dir, env, append(append([]string{}, restoreArgs...), args...)...) return p.exec(ctx, dir, env, append(append([]string{}, restoreArgs...), args...)...)
@@ -138,6 +142,7 @@ func (p *Provider) restoreRepo(ctx context.Context, dir, target string) error {
if gitDir, _, err := gitDirs(dir); err == nil { if gitDir, _, err := gitDirs(dir); err == nil {
p.clearOperations(ctx, dir, gitDir) p.clearOperations(ctx, dir, gitDir)
} }
prev, _, _ := try(ctx, dir, "symbolic-ref", "--short", "-q", "HEAD") // for the ref, see attachBranch
var keep []gitlink var keep []gitlink
if head, err := g("rev-parse", "--verify", "-q", "HEAD"); err != nil || head != sha { if head, err := g("rev-parse", "--verify", "-q", "HEAD"); err != nil || head != sha {
if _, err := g("checkout", "--force", "--detach", sha); err != nil { if _, err := g("checkout", "--force", "--detach", sha); err != nil {
@@ -161,6 +166,11 @@ func (p *Provider) restoreRepo(ctx context.Context, dir, target string) error {
if _, err := g("submodule", "sync", "-q"); err != nil { if _, err := g("submodule", "sync", "-q"); err != nil {
return err return err
} }
if in != nil {
if err := p.attachBranch(ctx, *in, sha, prev); err != nil {
return err
}
}
links, err := indexGitlinks(ctx, dir) links, err := indexGitlinks(ctx, dir)
if err != nil { if err != nil {
@@ -178,6 +188,16 @@ func (p *Provider) restoreRepo(ctx context.Context, dir, target string) error {
} }
} }
// the .gitmodules branch of each child, for its ref
branches := map[string]string{}
if out, ok, err := try(ctx, dir, "config", "-f", ".gitmodules", "--get-regexp", `^submodule\..*\.(path|branch)$`); err != nil {
return err
} else if ok {
for _, m := range parseGitmodules(out) {
branches[path.Clean(m.path)] = m.branch
}
}
// the children are independent repositories // the children are independent repositories
var wg sync.WaitGroup var wg sync.WaitGroup
errs := make([]error, len(links)) errs := make([]error, len(links))
@@ -185,7 +205,8 @@ func (p *Provider) restoreRepo(ctx context.Context, dir, target string) error {
wg.Add(1) wg.Add(1)
go func() { go func() {
defer wg.Done() defer wg.Done()
if err := p.restoreRepo(ctx, filepath.Join(dir, filepath.FromSlash(l.path)), l.sha); err != nil { child := info{superDir: dir, dir: filepath.Join(dir, filepath.FromSlash(l.path)), relPath: l.path, branch: branches[l.path]}
if err := p.restoreRepo(ctx, child.dir, l.sha, &child); err != nil {
errs[i] = err errs[i] = err
} }
}() }()
@@ -194,6 +215,135 @@ func (p *Provider) restoreRepo(ctx context.Context, dir, target string) error {
return errors.Join(errs...) return errors.Join(errs...)
} }
// attachBranch puts the detached HEAD of the restored submodule in on a
// branch whose tip is sha, the first that git accepts of, in this order:
//
// 1. a local branch tracking the ref the UI shows (see resolve), or named
// like it;
// 2. the ref itself, as a new local branch tracking it, if no local branch
// has its name;
// 3. any other local branch, alphabetically;
// 4. any other remote branch whose name no local branch has, as a new
// tracking branch; the ref's remote first, then alphabetically.
//
// A HEAD that is on a branch stays there. No branch is moved: a local branch
// elsewhere is no candidate, and its remote branch neither. If nothing fits,
// HEAD stays detached; only a context error is returned. prev is the branch
// checked out before the restore; the ref depends on it.
func (p *Provider) attachBranch(ctx context.Context, in info, sha, prev string) error {
if _, onBranch, err := try(ctx, in.dir, "symbolic-ref", "-q", "HEAD"); err != nil || onBranch {
return err
}
out, ok, err := try(ctx, in.dir, "for-each-ref", "--points-at="+sha,
"--format=%(refname)%00%(upstream)%00%(symref)", "refs/heads", "refs/remotes")
if err != nil || !ok {
return err
}
var locals, remotes []string // alphabetical, as for-each-ref sorts them
upstreams := map[string]string{}
for _, line := range strings.Split(out, "\n") {
f := strings.Split(line, "\x00")
if len(f) != 3 || f[2] != "" { // a symref is origin/HEAD
continue
}
if name, ok := strings.CutPrefix(f[0], "refs/heads/"); ok {
locals = append(locals, name)
upstreams[name] = strings.TrimPrefix(f[1], "refs/remotes/")
} else if name, ok := strings.CutPrefix(f[0], "refs/remotes/"); ok {
remotes = append(remotes, name)
}
}
if len(locals)+len(remotes) == 0 {
return nil
}
// the ref, if it is a remote branch
var ref string
containing, err := remoteContaining(ctx, in.dir, sha)
if err != nil {
return err
}
if r, source, _, err := resolve(ctx, in, sha, prev, containing); err != nil {
return err
} else if source != submodule.RefFromTag && source != submodule.RefFromSHA {
ref = r
}
localOf := func(remote string) string { _, l, _ := strings.Cut(remote, "/"); return l }
hasLocal := func(name string) (bool, error) {
_, ok, err := try(ctx, in.dir, "rev-parse", "--verify", "-q", "refs/heads/"+name)
return ok, err
}
type candidate struct{ local, remote string } // remote: create local, tracking it
var cands []candidate
addRemote := func(r string) error {
l := localOf(r)
if l == "" {
return nil
}
exists, err := hasLocal(l)
if err == nil && !exists {
cands = append(cands, candidate{l, r})
}
return err
}
if ref != "" {
for _, l := range locals {
if upstreams[l] == ref {
cands = append(cands, candidate{local: l})
}
}
if l := localOf(ref); slices.Contains(locals, l) {
cands = append(cands, candidate{local: l})
}
if slices.Contains(remotes, ref) {
if err := addRemote(ref); err != nil {
return err
}
}
}
for _, l := range locals {
cands = append(cands, candidate{local: l})
}
preferred, _, _ := strings.Cut(ref, "/")
if preferred == "" {
if preferred, err = remoteName(ctx, in.dir); err != nil {
return err
}
}
slices.SortStableFunc(remotes, func(a, b string) int {
ap, bp := strings.HasPrefix(a, preferred+"/"), strings.HasPrefix(b, preferred+"/")
switch {
case ap && !bp:
return -1
case bp && !ap:
return 1
}
return 0
})
for _, r := range remotes {
if r != ref {
if err := addRemote(r); err != nil {
return err
}
}
}
for _, c := range cands {
args := append(append([]string{}, restoreArgs...), "switch", "-q", c.local)
if c.remote != "" {
args = append(append([]string{}, restoreArgs...), "switch", "-q", "-c", c.local, "--track", c.remote)
}
if _, err := p.exec(ctx, in.dir, nil, args...); err == nil {
return nil
} else if ctx.Err() != nil {
return ctx.Err()
}
// e.g. checked out in another worktree: try the next one
}
return nil
}
// networkEnv is the environment of commands that may clone or fetch. // networkEnv is the environment of commands that may clone or fetch.
func (p *Provider) networkEnv() []string { func (p *Provider) networkEnv() []string {
return append(append([]string{}, p.sshEnv...), p.extraEnv...) return append(append([]string{}, p.sshEnv...), p.extraEnv...)
+127
View File
@@ -332,3 +332,130 @@ func TestRestoreLossCountsStagedPinsOfAMovingRepository(t *testing.T) {
t.Errorf("loss %+v, want 1 staged pin and the 2 detached nested commits", l) t.Errorf("loss %+v, want 1 staged pin and the 2 detached nested commits", l)
} }
} }
// restoreSub restores the submodule path and returns the branch its HEAD is
// on ("" if detached).
func restoreSub(t *testing.T, p *Provider, super, path string) string {
t.Helper()
if err := p.Restore(context.Background(), path, submodule.RestoreStaged); err != nil {
t.Fatal(err)
}
return out(t, filepath.Join(super, filepath.FromSlash(path)), "branch", "--show-current")
}
func TestRestoreAttachesTheLocalBranchTrackingTheRef(t *testing.T) {
p, root := ownFixture(t)
super := filepath.Join(root, "super")
// src/ui: in sync, the pin is behind origin/main, local main is at the pin
git(t, filepath.Join(super, "src", "ui"), "checkout", "-q", "--detach")
git(t, filepath.Join(super, "src", "ui"), "branch", "aaa") // alphabetically first, but no ref
if got := restoreSub(t, p, super, "src/ui"); got != "main" {
t.Errorf("branch = %q, want main", got)
}
}
func TestRestoreCreatesTheRefBranchBeforeOtherBranches(t *testing.T) {
p, root := ownFixture(t)
super := filepath.Join(root, "super")
log := filepath.Join(super, "libs", "log")
// libs/log: the pin is the tip of origin/main and origin/archive
git(t, log, "checkout", "-q", "--detach")
git(t, log, "branch", "-D", "main")
if got := restoreSub(t, p, super, "libs/log"); got != "main" {
t.Errorf("branch = %q, want main", got)
}
if up := out(t, log, "rev-parse", "--abbrev-ref", "main@{upstream}"); up != "origin/main" {
t.Errorf("upstream = %q, want origin/main", up)
}
if out(t, log, "branch", "--list", "archive") != "" {
t.Error("archive must not be created")
}
}
func TestRestoreCreatesARemoteFeatureBranch(t *testing.T) {
p, root := ownFixture(t)
super := filepath.Join(root, "super")
topic := filepath.Join(super, "libs", "topic")
mainTip := out(t, topic, "rev-parse", "main")
// libs/topic: detached at the tip of origin/feat/search, local main elsewhere
if got := restoreSub(t, p, super, "libs/topic"); got != "feat/search" {
t.Errorf("branch = %q, want feat/search", got)
}
if got := out(t, topic, "rev-parse", "main"); got != mainTip {
t.Errorf("main moved: %s -> %s", mainTip, got)
}
}
func TestRestorePrefersLocalBranchesAlphabetically(t *testing.T) {
p, root := ownFixture(t)
super := filepath.Join(root, "super")
feature := filepath.Join(super, "libs", "feature")
// libs/feature: the pin is on no branch tip
git(t, feature, "branch", "zz")
git(t, feature, "branch", "aa")
if got := restoreSub(t, p, super, "libs/feature"); got != "aa" {
t.Errorf("branch = %q, want aa", got)
}
}
func TestRestoreNeverMovesALocalBranchToAttach(t *testing.T) {
p, root := ownFixture(t)
super := filepath.Join(root, "super")
topic := filepath.Join(super, "libs", "topic")
git(t, topic, "branch", "feat/search", "origin/main") // same name, elsewhere
before := out(t, topic, "rev-parse", "feat/search")
if got := restoreSub(t, p, super, "libs/topic"); got != "" {
t.Errorf("branch = %q, want detached", got)
}
if after := out(t, topic, "rev-parse", "feat/search"); after != before {
t.Errorf("feat/search moved: %s -> %s", before, after)
}
}
func TestRestoreKeepsTheCheckedOutBranch(t *testing.T) {
p, root := ownFixture(t)
super := filepath.Join(root, "super")
log := filepath.Join(super, "libs", "log")
git(t, log, "switch", "-q", "-c", "zz") // at the pin, like main
if got := restoreSub(t, p, super, "libs/log"); got != "zz" {
t.Errorf("branch = %q, want zz kept", got)
}
}
func TestRestoreSkipsABranchOfAnotherWorktree(t *testing.T) {
p, root := ownFixture(t)
super := filepath.Join(root, "super")
log := filepath.Join(super, "libs", "log")
git(t, log, "checkout", "-q", "--detach")
git(t, log, "worktree", "add", "-q", filepath.Join(root, "wt"), "main")
if got := restoreSub(t, p, super, "libs/log"); got == "main" {
t.Error("main is checked out in another worktree")
}
}
func TestRestoreSuperprojectAttachesNestedSubmodules(t *testing.T) {
p, root := ownFixture(t)
super := filepath.Join(root, "super")
nested := filepath.Join(super, "libs", "log", "modules", "nested")
git(t, nested, "checkout", "-q", "--detach")
if err := p.Restore(context.Background(), "", submodule.RestoreStaged); err != nil {
t.Fatal(err)
}
if got := out(t, nested, "branch", "--show-current"); got != "main" {
t.Errorf("nested branch = %q, want main", got)
}
if got := out(t, filepath.Join(super, "libs", "topic"), "branch", "--show-current"); got != "feat/search" {
t.Errorf("libs/topic branch = %q, want feat/search", got)
}
if got := out(t, super, "branch", "--show-current"); got != "main" {
t.Errorf("superproject branch = %q, want main", got)
}
}
+1 -1
View File
@@ -107,7 +107,7 @@ func (p *Provider) Switch(ctx context.Context, path string, b submodule.Branch)
return "", err return "", err
} }
} }
if err := p.restoreRepo(ctx, dir, b.SHA); err != nil { if err := p.restoreRepo(ctx, dir, b.SHA, nil); err != nil { // HEAD goes on b below
return "", err return "", err
} }
+41 -2
View File
@@ -61,11 +61,28 @@ type Model struct {
pickerPath string // the repository the picker is for pickerPath string // the repository the picker is for
notice string // an error to show above the footer until the next key notice string // an error to show above the footer until the next key
checkUpdate func(context.Context) string // looks for a newer release, nil if off
update string // the newer release found, "" if none
updateTo string // the release to quit and update to, "" if not chosen
width, height int width, height int
showDetail bool showDetail bool
} }
func New(ctx context.Context, p submodule.Provider) Model { // Option configures New.
type Option func(*Model)
// WithUpdateCheck looks for a newer release at startup, in the background.
// check returns its version, or "" if there is none. With one, the footer
// offers to quit and update.
func WithUpdateCheck(check func(context.Context) string) Option {
return func(m *Model) { m.checkUpdate = check }
}
// UpdateTo returns the release the user chose to quit and update to, or "".
func (m Model) UpdateTo() string { return m.updateTo }
func New(ctx context.Context, p submodule.Provider, opts ...Option) Model {
t := theme.Default() t := theme.Default()
k := defaultKeys() k := defaultKeys()
sp := spinner.New(spinner.WithSpinner(spinner.MiniDot)) sp := spinner.New(spinner.WithSpinner(spinner.MiniDot))
@@ -90,12 +107,22 @@ func New(ctx context.Context, p submodule.Provider) Model {
} }
m.fetcher, _ = p.(submodule.Fetcher) m.fetcher, _ = p.(submodule.Fetcher)
m.watcher, _ = p.(submodule.Watcher) m.watcher, _ = p.(submodule.Watcher)
for _, o := range opts {
o(&m)
}
return m return m
} }
func (m Model) Init() tea.Cmd { func (m Model) Init() tea.Cmd {
m.loads.start(treeKey) m.loads.start(treeKey)
return tea.Batch(m.loadTree(), m.spinner.Tick) return tea.Batch(m.loadTree(), m.spinner.Tick, m.lookForUpdate())
}
func (m Model) lookForUpdate() tea.Cmd {
if m.checkUpdate == nil {
return nil
}
return func() tea.Msg { return updateMsg{m.checkUpdate(m.ctx)} }
} }
func (m Model) loadTree() tea.Cmd { func (m Model) loadTree() tea.Cmd {
@@ -187,6 +214,15 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.layout() m.layout()
return m, nil return m, nil
case updateMsg:
if msg.version != "" {
m.update = msg.version
m.keys.SetUpdate(msg.version)
m.footer.SetKeys(m.keys)
m.layout()
}
return m, nil
case treeLoadedMsg: case treeLoadedMsg:
return m.treeLoaded(msg) return m.treeLoaded(msg)
@@ -361,6 +397,9 @@ func (m Model) handleKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
m.closeFilter() m.closeFilter()
case key.Matches(msg, k.Quit): case key.Matches(msg, k.Quit):
return m, tea.Quit return m, tea.Quit
case key.Matches(msg, k.QuitUpdate):
m.updateTo = m.update
return m, tea.Quit
case key.Matches(msg, k.Help): case key.Matches(msg, k.Help):
m.footer.ToggleHelp() m.footer.ToggleHelp()
m.layout() m.layout()
+13 -1
View File
@@ -19,13 +19,15 @@ const flashDuration = 2 * time.Second
type clearFlashMsg struct{ id int } type clearFlashMsg struct{ id int }
// Keys provides the key groups. The short bar shows Navigation (and // Keys provides the key groups. The short bar shows Navigation (and
// Submodule, if requested) on the left and Global on the right; full help // Submodule, if requested) on the left, Global and then Highlight (on a
// highlighted background) on the right; full help
// shows FullHelp. // shows FullHelp.
type Keys interface { type Keys interface {
help.KeyMap help.KeyMap
Navigation() []key.Binding Navigation() []key.Binding
Submodule() []key.Binding Submodule() []key.Binding
Global() []key.Binding Global() []key.Binding
Highlight() []key.Binding
} }
type Model struct { type Model struct {
@@ -42,6 +44,9 @@ func New(t theme.Theme, keys Keys) Model {
return Model{theme: t, help: theme.NewHelp(t), keys: keys} return Model{theme: t, help: theme.NewHelp(t), keys: keys}
} }
// SetKeys replaces the key groups, e.g. if bindings changed.
func (m *Model) SetKeys(k Keys) { m.keys = k }
// SetActions shows the submodule bindings in the short bar. Set it if the // SetActions shows the submodule bindings in the short bar. Set it if the
// detail pane doesn't show them. // detail pane doesn't show them.
func (m *Model) SetActions(on bool) { m.actions = on } func (m *Model) SetActions(on bool) { m.actions = on }
@@ -85,6 +90,13 @@ func (m Model) shortBar(w int) string {
h := m.help h := m.help
h.Width = 0 h.Width = 0
right := h.ShortHelpView(m.keys.Global()) right := h.ShortHelpView(m.keys.Global())
if hl := m.keys.Highlight(); len(hl) > 0 {
var parts []string
for _, b := range hl {
parts = append(parts, b.Help().Key+" "+b.Help().Desc)
}
right += " " + m.theme.Highlight().Render(" "+strings.Join(parts, " ")+" ")
}
left := m.keys.Navigation() left := m.keys.Navigation()
if m.actions { if m.actions {
left = append(left[:len(left):len(left)], m.keys.Submodule()...) left = append(left[:len(left):len(left)], m.keys.Submodule()...)
+54
View File
@@ -0,0 +1,54 @@
package footer
import (
"strings"
"testing"
"github.com/charmbracelet/bubbles/key"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/x/ansi"
"submarine/internal/tui/theme"
)
type testKeys struct{ highlight []key.Binding }
func bind(k, desc string) key.Binding { return key.NewBinding(key.WithKeys(k), key.WithHelp(k, desc)) }
func (testKeys) ShortHelp() []key.Binding { return nil }
func (testKeys) FullHelp() [][]key.Binding { return nil }
func (testKeys) Navigation() []key.Binding {
return []key.Binding{bind("j", "move"), bind("h", "fold")}
}
func (testKeys) Submodule() []key.Binding { return nil }
func (testKeys) Global() []key.Binding { return []key.Binding{bind("?", "help"), bind("Q", "quit")} }
func (k testKeys) Highlight() []key.Binding { return k.highlight }
func bar(w int, hl ...key.Binding) string {
m := New(theme.Default(), testKeys{hl})
m.SetWidth(w)
return ansi.Strip(m.View())
}
func TestUpdateIsRightmost(t *testing.T) {
got := strings.TrimRight(bar(80, bind("q", "quit and update to v1.2.3")), " ")
if !strings.HasSuffix(got, "? help • Q quit q quit and update to v1.2.3") {
t.Errorf("order must be help, quit, quit and update:\n%q", got)
}
if w := lipgloss.Width(bar(80, bind("q", "quit and update to v1.2.3"))); w != 80 {
t.Errorf("bar is %d wide, want 80", w)
}
}
func TestNoUpdate(t *testing.T) {
if got := bar(80); strings.Contains(got, "update") {
t.Errorf("unexpected update hint:\n%q", got)
}
}
func TestNavigationGivesWayToUpdate(t *testing.T) {
got := bar(50, bind("q", "quit and update to v1.2.3"))
if !strings.Contains(got, "q quit and update to v1.2.3") || !strings.Contains(got, "Q quit") {
t.Errorf("the right group must be kept:\n%q", got)
}
}
+30 -3
View File
@@ -1,6 +1,8 @@
package tui package tui
import "github.com/charmbracelet/bubbles/key" import (
"github.com/charmbracelet/bubbles/key"
)
type keyMap struct { type keyMap struct {
Up, Down, Left, Right, Toggle key.Binding Up, Down, Left, Right, Toggle key.Binding
@@ -8,7 +10,7 @@ type keyMap struct {
Home, End, PageUp, PageDown key.Binding Home, End, PageUp, PageDown key.Binding
Fetch, Reload, Filter, Issues key.Binding Fetch, Reload, Filter, Issues key.Binding
Copy, Restore, Switch key.Binding Copy, Restore, Switch key.Binding
Help, Quit key.Binding Help, Quit, QuitUpdate key.Binding
} }
func defaultKeys() keyMap { func defaultKeys() keyMap {
@@ -33,9 +35,17 @@ func defaultKeys() keyMap {
Copy: key.NewBinding(key.WithKeys("c"), key.WithHelp("c", "copy path")), Copy: key.NewBinding(key.WithKeys("c"), key.WithHelp("c", "copy path")),
Help: key.NewBinding(key.WithKeys("?"), key.WithHelp("?", "help")), Help: key.NewBinding(key.WithKeys("?"), key.WithHelp("?", "help")),
Quit: key.NewBinding(key.WithKeys("q", "ctrl+c"), key.WithHelp("q", "quit")), Quit: key.NewBinding(key.WithKeys("q", "ctrl+c"), key.WithHelp("q", "quit")),
QuitUpdate: key.NewBinding(key.WithKeys("q"), key.WithHelp("q", "quit and update"), key.WithDisabled()),
} }
} }
// SetUpdate announces the newer release v: q quits and updates to it, and the
// plain quit moves to Q (ctrl+c always quits without updating).
func (k *keyMap) SetUpdate(v string) {
k.Quit = key.NewBinding(key.WithKeys("Q", "ctrl+c"), key.WithHelp("Q", "quit"))
k.QuitUpdate = key.NewBinding(key.WithKeys("q"), key.WithHelp("q", "quit and update to "+v))
}
// Navigation returns the bindings that move the selection or fold the tree. // Navigation returns the bindings that move the selection or fold the tree.
func (k keyMap) Navigation() []key.Binding { func (k keyMap) Navigation() []key.Binding {
move := key.NewBinding(key.WithKeys("up"), key.WithHelp("↑↓/jk", "move")) move := key.NewBinding(key.WithKeys("up"), key.WithHelp("↑↓/jk", "move"))
@@ -51,6 +61,23 @@ func (k keyMap) Submodule() []key.Binding { return []key.Binding{k.Copy, k.Switc
// Global returns the bindings that don't depend on the selection. // Global returns the bindings that don't depend on the selection.
func (k keyMap) Global() []key.Binding { return []key.Binding{k.Help, k.Quit} } func (k keyMap) Global() []key.Binding { return []key.Binding{k.Help, k.Quit} }
// fullUpdate is Highlight with a short description, for the full help.
func (k keyMap) fullUpdate() []key.Binding {
if !k.QuitUpdate.Enabled() {
return nil
}
return []key.Binding{key.NewBinding(key.WithKeys("q"), key.WithHelp("q", "quit and update"))}
}
// Highlight returns the bindings that are shown after Global on a highlighted
// background: quit and update, if there is an update.
func (k keyMap) Highlight() []key.Binding {
if !k.QuitUpdate.Enabled() {
return nil
}
return []key.Binding{k.QuitUpdate}
}
func (k keyMap) ShortHelp() []key.Binding { func (k keyMap) ShortHelp() []key.Binding {
return append(append(k.Navigation(), k.Submodule()...), k.Global()...) return append(append(k.Navigation(), k.Submodule()...), k.Global()...)
} }
@@ -62,6 +89,6 @@ func (k keyMap) FullHelp() [][]key.Binding {
{k.Home, k.End, k.PageUp, k.PageDown}, {k.Home, k.End, k.PageUp, k.PageDown},
{k.Copy, k.Switch, k.Restore}, {k.Copy, k.Switch, k.Restore},
{k.Fetch, k.Reload, k.Filter, k.Issues}, {k.Fetch, k.Reload, k.Filter, k.Issues},
{k.Help, k.Quit}, append([]key.Binding{k.Help, k.Quit}, k.fullUpdate()...),
} }
} }
+4
View File
@@ -26,3 +26,7 @@ type changeMsg struct {
change submodule.Change change submodule.Change
closed bool // the watcher stopped closed bool // the watcher stopped
} }
// updateMsg carries the result of the startup update check; version is ""
// if there is no newer release.
type updateMsg struct{ version string }
+10 -1
View File
@@ -1,6 +1,9 @@
package theme package theme
import "github.com/charmbracelet/bubbles/help" import (
"github.com/charmbracelet/bubbles/help"
"github.com/charmbracelet/lipgloss"
)
// NewHelp returns a help renderer in the theme's colors. // NewHelp returns a help renderer in the theme's colors.
func NewHelp(t Theme) help.Model { func NewHelp(t Theme) help.Model {
@@ -13,3 +16,9 @@ func NewHelp(t Theme) help.Model {
h.Styles.FullSeparator = h.Styles.ShortSeparator h.Styles.FullSeparator = h.Styles.ShortSeparator
return h return h
} }
// Highlight is the style of a key hint that should catch the eye: dark text
// on the accent color, on the whole hint including its key.
func (t Theme) Highlight() lipgloss.Style {
return lipgloss.NewStyle().Foreground(lipgloss.Color("0")).Background(t.Primary).Bold(true)
}
+68
View File
@@ -0,0 +1,68 @@
package tui
import (
"context"
"strings"
"testing"
tea "github.com/charmbracelet/bubbletea"
"submarine/internal/submodule/mock"
)
func newUpdateModel(version string) tea.Model {
check := func(context.Context) string { return version }
var m tea.Model = New(context.Background(), mock.New(), WithUpdateCheck(check))
m, _ = m.Update(tea.WindowSizeMsg{Width: 120, Height: 30})
return m
}
func isQuit(cmd tea.Cmd) bool {
if cmd == nil {
return false
}
_, ok := cmd().(tea.QuitMsg)
return ok
}
func TestUpdateCheckDeliversMessage(t *testing.T) {
m := New(context.Background(), mock.New(), WithUpdateCheck(func(context.Context) string { return "v9.9.9" }))
if m.lookForUpdate() == nil {
t.Fatal("no update check was started")
}
if msg := m.lookForUpdate()(); msg != (updateMsg{"v9.9.9"}) {
t.Errorf("got %v", msg)
}
if New(context.Background(), mock.New()).lookForUpdate() != nil {
t.Error("an update check was started without the option")
}
}
func TestQuitWithoutUpdate(t *testing.T) {
m := newUpdateModel("")
m, _ = m.Update(updateMsg{""})
m, cmd := press(m, "q")
if !isQuit(cmd) || m.(Model).UpdateTo() != "" {
t.Errorf("q must quit without updating, got update to %q", m.(Model).UpdateTo())
}
}
func TestQuitAndUpdate(t *testing.T) {
m := newUpdateModel("v9.9.9")
m, _ = m.Update(updateMsg{"v9.9.9"})
if bar := m.(Model).footer.View(); !strings.Contains(bar, "q quit and update to v9.9.9") {
t.Errorf("the footer does not offer the update:\n%s", bar)
}
m2, cmd := press(m, "q")
if !isQuit(cmd) || m2.(Model).UpdateTo() != "v9.9.9" {
t.Errorf("q must quit and update, got update to %q", m2.(Model).UpdateTo())
}
m2, cmd = press(m, "Q")
if !isQuit(cmd) || m2.(Model).UpdateTo() != "" {
t.Errorf("Q must quit without updating, got update to %q", m2.(Model).UpdateTo())
}
m2, cmd = pressKey(m, tea.KeyCtrlC)
if !isQuit(cmd) || m2.(Model).UpdateTo() != "" {
t.Errorf("ctrl+c must quit without updating, got update to %q", m2.(Model).UpdateTo())
}
}
-17
View File
@@ -209,20 +209,3 @@ func (l *limitWriter) Write(p []byte) (int, error) {
} }
return l.w.Write(p) return l.w.Write(p)
} }
// CheckInterval is how often the passive check may hit the network.
const CheckInterval = 24 * time.Hour
// LatestCached is Latest with a file cache: within CheckInterval it returns
// the cached answer without any network access. A failed lookup is cached too,
// so an unreachable registry is not retried on every start.
func (c *Client) LatestCached(ctx context.Context, cacheFile string) (string, error) {
if fi, err := os.Stat(cacheFile); err == nil && time.Since(fi.ModTime()) < CheckInterval {
b, _ := os.ReadFile(cacheFile)
return strings.TrimSpace(string(b)), nil
}
v, err := c.Latest(ctx)
_ = os.MkdirAll(filepath.Dir(cacheFile), 0o755)
_ = os.WriteFile(cacheFile, []byte(v), 0o644) // v is "" on failure
return v, err
}