5 Commits
Author SHA1 Message Date
simonfrankenandClaude Opus 5.5 a8133b4884 Make GH_TOKEN the main setting in .env.template
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 22:42:48 +01:00
simonfrankenandClaude Opus 5.5 1ee394cfdf Move releases to GitHub, with one bridge release on Gitea
GitHub has no generic package registry, so releases become GitHub
release assets. The updater and install.sh read releases/latest/download
and releases/download/<v>/, plain redirects with no API rate limit.
make release publishes a draft with all assets, then makes it latest.
make release-gitea publishes the same version to the old Gitea registry
for binaries that still update from there, and refuses until GitHub
serves it. See D33.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 22:38:50 +01:00
simonfrankenandClaude Opus 5.5 c9932932bb Make the screen explain itself: labels, tools, help pages, hints
For developers new to submodules (notes/usability-plan.md, D32):
- x and X read "restore to pin" and "restore committed pins"
- problems only, filter and fetch are shown in the footer
- ? shows every key in titled columns, then a legend of the status
  words, symbols and spine roles; esc closes it
- u reads "pull (fast-forward)" on the superproject
- the detail pane suggests f when the last fetch is old
- a hint above the footer until the first key
- the header says "staged", like the tree

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 23:26:32 +02:00
simonfrankenandClaude Opus 5.5 b205576759 Hard restore with X asks before dropping staged pins
X dropped staged pins without a question, including the selected
submodule's own pin, which the loss check didn't count. A staged pin is
a decision, and X sits one Shift away from x, so dropped staged pins now
count as a loss and make X ask (D31, amends D30).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 23:26:32 +02:00
simonfrankenandClaude Opus 5.5 72500353cd Hard restore with X drops staged pins at every depth
X restores the selection to the committed pins without the staged or
committed question, and resets every restored repository's index to
HEAD, so staged pins below are dropped too. Dropped staged pins alone
don't make it ask; they are listed if something else is lost.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 22:58:08 +02:00
34 changed files with 1305 additions and 211 deletions
+59 -45
View File
@@ -1,23 +1,23 @@
--- ---
name: release name: release
description: Prepare and publish a submarine release. Finds the latest release, picks the next semver from the changes since, runs a release check, creates and pushes the git tag, hands over to the developer for `make release`, then creates the Gitea release with MCP. Use only when the user asks to release. description: Prepare and publish a submarine release. Finds the latest release, picks the next semver from the changes since, runs a release check, creates and pushes the git tag, writes the release notes, hands over to the developer for `make release`, then verifies the GitHub release. Use only when the user asks to release.
disable-model-invocation: true disable-model-invocation: true
--- ---
# Release submarine # Release submarine
A release is built on the developer's machine (`make release`, see A release is built on the developer's machine (`make release`, see
`docs/architecture.md#distribution`). `make release` publishes the binaries `docs/architecture.md#distribution`). `make release` creates the GitHub
of the **clean `vX.Y.Z` tag at HEAD** to the Gitea package registry. This release of the **clean `vX.Y.Z` tag at HEAD**, with the binaries as assets.
skill does everything around it. The developer runs `make release` This skill does everything around it. The developer runs `make release`
themselves, in the middle: you never run it and never read or print `.env` themselves, in the middle: you never run it and never read or print `.env`,
or `GITEA_TOKEN`. `GH_TOKEN` or `GITEA_TOKEN`.
Pushing a tag and creating a release are outward-facing and hard to undo. Pushing a tag and creating a release are outward-facing and hard to undo.
Do them only after the confirmation in step 5, and never force-push, move or Do them only after the confirmation in step 5, and never force-push, move or
delete a tag without asking. delete a tag without asking.
Gitea: owner `simonfranken`, repo `submarine`, `https://git.simon-franken.de`. GitHub: owner `simonfranken`, repo `submarine`, remote `origin`.
## 1. Preconditions ## 1. Preconditions
@@ -29,7 +29,7 @@ git branch --show-current # main
git status --porcelain # empty: make release refuses a dirty tree git status --porcelain # empty: make release refuses a dirty tree
git rev-parse HEAD origin/main # equal: HEAD is pushed, nothing to release from a local-only commit git rev-parse HEAD origin/main # equal: HEAD is pushed, nothing to release from a local-only commit
git tag --points-at HEAD # empty: HEAD is not released yet git tag --points-at HEAD # empty: HEAD is not released yet
grep -q '^GITEA_TOKEN=.\+' .env # exists: only test it, never print it gh auth status >/dev/null 2>&1 || grep -q '^GH_TOKEN=.\+' .env # one holds: only test, never print
``` ```
## 2. Latest release ## 2. Latest release
@@ -38,11 +38,12 @@ grep -q '^GITEA_TOKEN=.\+' .env # exists: only test it, never print i
git tag --list 'v[0-9]*.[0-9]*.[0-9]*' --sort=-v:refname | head -1 git tag --list 'v[0-9]*.[0-9]*.[0-9]*' --sort=-v:refname | head -1
``` ```
Cross-check with the `mcp__gitea__get_latest_release` MCP tool (load it with Cross-check with the `mcp__github__get_latest_release` MCP tool (load it with
ToolSearch first). If the tag and the Gitea release differ (a tag without a ToolSearch first). If the tag and the GitHub release differ (a tag without a
release is normal for the one in progress, a release without a tag is not), release is normal for the one in progress, a release without a tag is not),
tell the user and ask before going on. With no tag at all, the first release tell the user and ask before going on. With no tag at all, the first release
is `v0.1.0`. is `v0.1.0`. While the Makefile has `release-gitea` (step 10), GitHub has
no releases yet: cross-check with `mcp__gitea__get_latest_release` instead.
## 3. Changes since ## 3. Changes since
@@ -55,7 +56,7 @@ No commits since the last tag: stop, there is nothing to release. Read the
commits, and where a subject is not clear, the diff. Sort each change as: commits, and where a subject is not clear, the diff. Sort each change as:
- **breaking**: removes or changes a key, a command or flag, the on-disk or - **breaking**: removes or changes a key, a command or flag, the on-disk or
registry contract (`install.sh`, asset names, `submarine-latest/latest/VERSION`, release contract (`install.sh`, asset names, `latest/download/VERSION`,
`submarine update`), or behavior users rely on; `submarine update`), or behavior users rely on;
- **feature**: a new key, action, view or option, or a visible behavior; - **feature**: a new key, action, view or option, or a visible behavior;
- **fix / other**: bug fixes, docs, refactoring, tests, performance. - **fix / other**: bug fixes, docs, refactoring, tests, performance.
@@ -108,51 +109,64 @@ git ls-remote --tags origin vX.Y.Z # the tag is on the remote
If the push fails, report git's message. Do not retry with force. If the tag If the push fails, report git's message. Do not retry with force. If the tag
is wrong after it was pushed, ask before deleting it. is wrong after it was pushed, ask before deleting it.
## 7. Hand over: the developer runs `make release` ## 7. Write the release notes
Write them to `/tmp/submarine-vX.Y.Z-notes.md` (outside the repository:
`make release` refuses a dirty tree). They are for users of the tool, not a
commit dump: short, grouped under **Breaking changes** (only if any),
**New**, **Fixes** (leave out empty groups and pure refactoring/tests), each
item one line naming the key or behavior (`b` switches the branch of a
repository...). End with:
```
Install or update: `curl -fsSL https://raw.githubusercontent.com/simonfranken/submarine/main/install.sh | sh`, or `submarine update`.
Full changelog: https://github.com/simonfranken/submarine/compare/<last>...vX.Y.Z
```
Show the notes to the user; they can change them before the next step.
## 8. Hand over: the developer runs `make release`
HEAD is now the clean tag, which is what `make release` needs. Tell the HEAD is now the clean tag, which is what `make release` needs. Tell the
developer to run, in the repository: developer to run, in the repository:
```sh ```sh
make release make release NOTES=/tmp/submarine-vX.Y.Z-notes.md
``` ```
(it reads `GITEA_TOKEN` from `.env`, tests, builds, uploads, and points (it uses `gh`, tests, builds, creates the release as a draft with all
`submarine-latest` at the version last). **Stop here and wait** until they assets and publishes it last). **Stop here and wait** until they say it
say it finished. If it failed, help with the output; do not run it yourself. finished. If it failed, help with the output; do not run it yourself. A
leftover draft from a failed run must be deleted (ask first) before a retry.
## 8. Verify the upload, create the Gitea release ## 9. Verify the release
Once the developer reports success: Once the developer reports success:
```sh ```sh
curl -fsSL https://github.com/simonfranken/submarine/releases/latest/download/VERSION
```
must print `vX.Y.Z` (this is what `install.sh` and `submarine update`
read). Check with `mcp__github__get_release_by_tag` that it is not a draft
and has the assets `submarine_{linux,darwin}_{amd64,arm64}`,
`checksums.txt` and `VERSION`. If anything is missing, report it. Finish
with the link to the release and the version.
## 10. Bridge release (only while the Makefile has `release-gitea`)
The first GitHub release is also published to the old Gitea registry, so
binaries that still update from Gitea pick it up (D33). After step 9, and
after asking the user, push the tag to the `gitea` remote and hand over
again:
```sh
git push gitea main vX.Y.Z
make release-gitea # run by the developer, needs GITEA_TOKEN
curl -fsS https://git.simon-franken.de/api/packages/simonfranken/generic/submarine-latest/latest/VERSION curl -fsS https://git.simon-franken.de/api/packages/simonfranken/generic/submarine-latest/latest/VERSION
``` ```
must print `vX.Y.Z` (the registry is public; `install.sh` reads it the same The last command must print `vX.Y.Z`. Then create a Gitea release for the
way). If it doesn't, the upload did not complete: do not create the release, tag with `mcp__gitea__create_release`, its body saying that submarine moved
report it. to https://github.com/simonfranken/submarine.
Then create the release with `mcp__gitea__create_release` (load it with
ToolSearch first):
- `owner`: `simonfranken`, `repo`: `submarine`
- `tag_name`: `vX.Y.Z`
- `target`: the tag's commit, `git rev-parse vX.Y.Z^{commit}`
- `title`: `vX.Y.Z`
- `is_draft`: false, `is_pre_release`: false
- `body`: release notes, see below
Release notes are for users of the tool, not a commit dump: short, grouped
under **Breaking changes** (only if any), **New**, **Fixes** (leave out empty
groups and pure refactoring/tests), each item one line naming the key or
behavior (`b` switches the branch of a repository...). End with:
```
Install or update: `curl -fsSL https://git.simon-franken.de/simonfranken/submarine/raw/branch/main/install.sh | sh`, or `submarine update`.
Full changelog: https://git.simon-franken.de/simonfranken/submarine/compare/<last>...vX.Y.Z
```
The binaries live in the package registry, not on the release: attach
nothing. Finish with the link to the release and the version.
+9 -3
View File
@@ -1,8 +1,14 @@
# Copy to .env (gitignored); the Makefile loads it automatically. # Copy to .env (gitignored); the Makefile loads it automatically.
# Access token with write:package scope. Required for `make release`. # GitHub token for `make release` (gh): classic with the `repo` scope, or
GITEA_TOKEN= # fine-grained with Contents read/write on simonfranken/submarine.
GH_TOKEN=
# Optional overrides (defaults shown). # Optional override (default shown).
# GITHUB_REPO=simonfranken/submarine
# Bridge release only (`make release-gitea`, see docs/decisions.md D33):
# Gitea token with the write:package scope. Remove once the bridge is out.
GITEA_TOKEN=
# GITEA_URL=https://git.simon-franken.de # GITEA_URL=https://git.simon-franken.de
# GITEA_OWNER=simonfranken # GITEA_OWNER=simonfranken
+2 -2
View File
@@ -22,7 +22,7 @@ go run ./cmd/submarine [dir] # run on a repository (default: cwd)
go run ./cmd/submarine --mock # run on mock data go run ./cmd/submarine --mock # run on mock data
scripts/make-fixture.sh DIR # build a test superproject in DIR scripts/make-fixture.sh DIR # build a test superproject in DIR
make dist # cross-compile into dist/ make dist # cross-compile into dist/
GITEA_TOKEN=… make release # publish a tagged release (outward-facing; run by the developer) make release NOTES=FILE # publish a tagged release to GitHub (outward-facing; run by the developer)
go vet ./... go vet ./...
go test ./... go test ./...
gofmt -l . # must print nothing gofmt -l . # must print nothing
@@ -32,7 +32,7 @@ gofmt -l . # must print nothing
Use the `release` skill (`/release`, `.claude/skills/release/SKILL.md`): it Use the `release` skill (`/release`, `.claude/skills/release/SKILL.md`): it
picks the next semver, runs a check, tags and pushes, asks the developer to picks the next semver, runs a check, tags and pushes, asks the developer to
run `make release`, then creates the Gitea release. Never run `make release` run `make release`, then verifies the GitHub release. Never run `make release`
or push tags outside of it. or push tags outside of it.
## Rules ## Rules
+33 -9
View File
@@ -1,12 +1,16 @@
# Build and publish submarine. Releases are built locally and uploaded to the # Build and publish submarine. Releases are built locally and uploaded as
# Gitea generic package registry (see docs/architecture.md#distribution). # GitHub release assets (see docs/architecture.md#distribution).
# #
# make dist cross-compile into dist/ # make dist cross-compile into dist/
# GITEA_TOKEN=... make release test, build and publish the tagged HEAD # make release NOTES=FILE test, build and publish the tagged HEAD (gh)
# GITEA_TOKEN=... make release-gitea bridge only: the same version to the old Gitea registry
# Settings from .env (see .env.template); `make VAR=...` on the command line wins. # Settings from .env (see .env.template); `make VAR=...` on the command line wins.
-include .env -include .env
export GITEA_TOKEN export GITEA_TOKEN GH_TOKEN
GITHUB_REPO ?= simonfranken/submarine
RELEASES := https://github.com/$(GITHUB_REPO)/releases
GITEA_URL ?= https://git.simon-franken.de GITEA_URL ?= https://git.simon-franken.de
GITEA_OWNER ?= simonfranken GITEA_OWNER ?= simonfranken
@@ -17,7 +21,7 @@ LDFLAGS := -s -w -X main.version=$(VERSION)
PLATFORMS := linux_amd64 linux_arm64 darwin_amd64 darwin_arm64 PLATFORMS := linux_amd64 linux_arm64 darwin_amd64 darwin_arm64
BINARIES := $(addprefix dist/submarine_,$(PLATFORMS)) BINARIES := $(addprefix dist/submarine_,$(PLATFORMS))
.PHONY: build test vet dist release clean FORCE .PHONY: build test vet dist check-tag release release-gitea clean FORCE
build: build:
go build -ldflags '$(LDFLAGS)' -o submarine ./cmd/submarine go build -ldflags '$(LDFLAGS)' -o submarine ./cmd/submarine
@@ -41,11 +45,31 @@ dist/submarine_%: FORCE
dist/checksums.txt: $(BINARIES) dist/checksums.txt: $(BINARIES)
cd dist && sha256sum $(notdir $(BINARIES)) > checksums.txt cd dist && sha256sum $(notdir $(BINARIES)) > checksums.txt
release: check-tag:
@test -n "$$GITEA_TOKEN" || { echo "GITEA_TOKEN is not set (needs write:package)"; exit 1; }
@echo '$(VERSION)' | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+$$' || \ @echo '$(VERSION)' | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+$$' || \
{ echo "VERSION '$(VERSION)' is not a clean tag: tag HEAD as vX.Y.Z with a clean tree"; exit 1; } { echo "VERSION '$(VERSION)' is not a clean tag: tag HEAD as vX.Y.Z with a clean tree"; exit 1; }
@test -z "$$(git status --porcelain)" || { echo "working tree is not clean"; exit 1; } @test -z "$$(git status --porcelain)" || { echo "working tree is not clean"; exit 1; }
# A draft gets all assets first and is published last, so releases/latest
# never points at a release with missing files.
release: check-tag
@test -n "$(NOTES)" && test -f "$(NOTES)" || { echo "NOTES=FILE with the release notes is required"; exit 1; }
@command -v gh >/dev/null || { echo "gh (GitHub CLI) is required"; exit 1; }
@gh auth status >/dev/null 2>&1 || { echo "gh is not logged in: run gh auth login or set GH_TOKEN"; exit 1; }
$(MAKE) clean test vet dist VERSION=$(VERSION)
printf '%s\n' '$(VERSION)' > dist/VERSION
gh release create '$(VERSION)' --repo '$(GITHUB_REPO)' --verify-tag --draft \
--title '$(VERSION)' --notes-file '$(NOTES)' $(BINARIES) dist/checksums.txt dist/VERSION
gh release edit '$(VERSION)' --repo '$(GITHUB_REPO)' --draft=false --latest
@echo "released $(VERSION): $(RELEASES)/tag/$(VERSION)"
# Bridge release for binaries that still update from Gitea: same version,
# old registry layout. Refuses until GitHub serves this version, so a binary
# updated from Gitea finds its release on GitHub. Remove after the bridge.
release-gitea: check-tag
@test -n "$$GITEA_TOKEN" || { echo "GITEA_TOKEN is not set (needs write:package)"; exit 1; }
@test "$$(curl -fsSL '$(RELEASES)/latest/download/VERSION' | tr -d '[:space:]')" = '$(VERSION)' || \
{ echo "GitHub does not serve $(VERSION) as latest yet: run make release first"; exit 1; }
$(MAKE) clean test vet dist VERSION=$(VERSION) $(MAKE) clean test vet dist VERSION=$(VERSION)
@set -e; \ @set -e; \
for f in $(BINARIES) dist/checksums.txt; do \ for f in $(BINARIES) dist/checksums.txt; do \
@@ -59,7 +83,7 @@ release:
"$(GITEA_URL)/api/v1/packages/$(GITEA_OWNER)/generic/submarine-latest/latest" >/dev/null || true; \ "$(GITEA_URL)/api/v1/packages/$(GITEA_OWNER)/generic/submarine-latest/latest" >/dev/null || true; \
curl -fsS -X PUT -H "Authorization: token $$GITEA_TOKEN" \ curl -fsS -X PUT -H "Authorization: token $$GITEA_TOKEN" \
--upload-file dist/VERSION "$(REGISTRY)/submarine-latest/latest/VERSION" >/dev/null; \ --upload-file dist/VERSION "$(REGISTRY)/submarine-latest/latest/VERSION" >/dev/null; \
echo "released $(VERSION)" echo "released $(VERSION) to Gitea"
clean: clean:
rm -rf dist submarine rm -rf dist submarine
+9 -4
View File
@@ -38,7 +38,7 @@ the questions you actually have:
## Install ## Install
```sh ```sh
curl -fsSL https://git.simon-franken.de/simonfranken/submarine/raw/branch/main/install.sh | sh curl -fsSL https://raw.githubusercontent.com/simonfranken/submarine/main/install.sh | sh
``` ```
Installs `sub` and `submarine` (linux/macOS, amd64/arm64) to `~/.local/bin`. Installs `sub` and `submarine` (linux/macOS, amd64/arm64) to `~/.local/bin`.
@@ -117,6 +117,10 @@ something would be lost, you are asked first:
submodule with a staged pin, `x` first asks whether to restore to the staged submodule with a staged pin, `x` first asks whether to restore to the staged
pin (`s`) or the committed one (`c`, which unstages it). pin (`s`) or the committed one (`c`, which unstages it).
`X` restores to the committed pins without asking which one, and also
drops the staged pins of submodules below the selection, which `x` keeps
where it can. It asks if work or a staged pin would be lost.
### Switch a branch with `b` ### Switch a branch with `b`
Press `b` on a submodule (or the header for the superproject). A popup lists Press `b` on a submodule (or the header for the superproject). A popup lists
@@ -164,14 +168,15 @@ files.
| `H` `L` / `⇧←` `⇧→` | Collapse / expand all | | `H` `L` / `⇧←` `⇧→` | Collapse / expand all |
| `space` | Toggle the selected submodule | | `space` | Toggle the selected submodule |
| `home` `end` / `g` `G`, `pgup` `pgdn` | Jump, page | | `home` `end` / `g` `G`, `pgup` `pgdn` | Jump, page |
| `/` | Filter |
| `!` | Problems only | | `!` | Problems only |
| `/` | Filter |
| `c` | Copy path | | `c` | Copy path |
| `u` | Update: move a pin that is behind to the tip of its branch (staged, like `b`); on the header, fast-forward the superproject | | `u` | Update: move a pin that is behind to the tip of its branch (staged, like `b`); on the header, fast-forward the superproject |
| `b` | Switch branch: pick a local or remote branch; its tip is staged and the repository restored to it | | `b` | Switch branch: pick a local or remote branch; its tip is staged and the repository restored to it |
| `x` | Restore: make the worktree exactly what git records (asks if work would be lost) | | `x` | Restore to pin: make the worktree exactly what git records (asks if work would be lost) |
| `X` | Restore committed pins: like `x`, but dropping all staged pins below (asks first) |
| `f` / `r` | Fetch / reload | | `f` / `r` | Fetch / reload |
| `?` | Full help | | `?` | Full help: every key, then what the words and symbols mean (`esc` closes it) |
| `q` | Quit. If a newer release exists, the footer offers `q quit and update to vX` (highlighted) and plain quit moves to `Q` | | `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
+1 -1
View File
@@ -93,7 +93,7 @@ func main() {
} }
// latestRelease returns the version of a newer release, or "" if there is // latestRelease returns the version of a newer release, or "" if there is
// none or the registry can't be reached within a few seconds. // none or GitHub can't be reached within a few seconds.
func latestRelease(ctx context.Context) string { func latestRelease(ctx context.Context) string {
ctx, cancel := context.WithTimeout(ctx, 3*time.Second) ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel() defer cancel()
+8 -3
View File
@@ -20,12 +20,12 @@ bare commit hash.
## Install ## Install
```sh ```sh
curl -fsSL https://git.simon-franken.de/simonfranken/submarine/raw/branch/main/install.sh | sh curl -fsSL https://raw.githubusercontent.com/simonfranken/submarine/main/install.sh | sh
``` ```
Installs `submarine` and the alias `sub` (linux/macOS, amd64/arm64) to Installs `submarine` and the alias `sub` (linux/macOS, amd64/arm64) to
`~/.local/bin`. Update with `submarine update`. Maintainers publish with `~/.local/bin`. Update with `submarine update`. Maintainers publish with
`GITEA_TOKEN=… make release` (see [architecture](architecture.md#distribution)). `make release NOTES=…` (see [architecture](architecture.md#distribution)).
## Status ## Status
@@ -33,7 +33,8 @@ Installs `submarine` and the alias `sub` (linux/macOS, amd64/arm64) to
through a git provider (`internal/submodule/git`): `submarine [dir]`. It through a git provider (`internal/submodule/git`): `submarine [dir]`. It
fetches only when asked (`f`) and follows changes made in other shells. `submarine --mock` shows fetches only when asked (`f`) and follows changes made in other shells. `submarine --mock` shows
the built-in mock data (`internal/submodule/mock`). `!` shows only the built-in mock data (`internal/submodule/mock`). `!` shows only
submodules with problems. `x` restores the selection, `b` switches its submodules with problems. `x` restores the selection (`X` also drops
staged pins), `b` switches its
branch and `u` updates a pin that is behind ([actions.md](actions.md)). branch and `u` updates a pin that is behind ([actions.md](actions.md)).
Next steps, roughly in order: Next steps, roughly in order:
@@ -41,3 +42,7 @@ Next steps, roughly in order:
1. (done) Write actions: restore, switch branch, update pin, see 1. (done) Write actions: restore, switch branch, update pin, see
[actions.md](actions.md). Stage pin was dropped (D29). [actions.md](actions.md). Stage pin was dropped (D29).
2. (done) "Problems only" (`!`) view, reusing the tree's filter. 2. (done) "Problems only" (`!`) view, reusing the tree's filter.
3. Usability pass for users new to submodules, see
[notes/usability-plan.md](../notes/usability-plan.md). The low-effort
items are done (D31, D32); next are the issue hints and the palette
that fits the selection.
+39 -8
View File
@@ -1,6 +1,7 @@
# Actions (draft) # Actions (draft)
**Status:** [Restore](#restore) (key `x`, [D23](decisions.md)), **Status:** [Restore](#restore) (key `x`, [D23](decisions.md); hard restore
`X`, [D30](decisions.md)),
[Switch branch](#switch-branch) (key `b`, [D24](decisions.md)) and [Switch branch](#switch-branch) (key `b`, [D24](decisions.md)) and
[Update pin](#update-pin) (key `u`, [D29](decisions.md)) are implemented. [Update pin](#update-pin) (key `u`, [D29](decisions.md)) are implemented.
Stage pin was dropped ([D29](decisions.md)). Stage pin was dropped ([D29](decisions.md)).
@@ -13,7 +14,7 @@ a difference in one of two directions:
| Action | Direction | Key | | Action | Direction | Key |
|---|---|---| |---|---|---|
| [Restore](#restore) | The worktree follows the recorded state | `x` | | [Restore](#restore) | The worktree follows the recorded state | `x`, `X` (hard) |
| [Switch branch](#switch-branch) | Both: the branch tip is recorded, then restored to | `b` | | [Switch branch](#switch-branch) | Both: the branch tip is recorded, then restored to | `b` |
| [Update pin](#update-pin) | Both: a switch to the tip of the pin's ref | `u` | | [Update pin](#update-pin) | Both: a switch to the tip of the pin's ref | `u` |
@@ -66,6 +67,33 @@ Two exceptions, where a staged pin is not kept:
`.gitmodules` entry is reset with the other files. Its directory then `.gitmodules` entry is reset with the other files. Its directory then
counts as an untracked file. counts as an untracked file.
### Hard restore
`X` restores to the **committed** pins, at every depth: what the commits
record, without any staged pin.
- The selected submodule goes to the committed pin, without the `s` / `c`
question; a staged pin of it is unstaged (as with `c`). A submodule that
was added but not committed yet has no committed pin and goes to the one
in the index.
- Every restored repository's index is reset to its `HEAD`, the superproject
included: its staged pins are dropped, and the submodules below follow the
committed tree.
So `x` and `X` differ in the staged pins of repositories that the restore
does not move: `x` (`s` or `c`) keeps them, `X` drops them. This matters
for the superproject, for a selected submodule without a staged pin of its
own, and for nested repositories that are on their pin. A repository that
moves loses its staged pins either way (see above); then `x` → `c` and `X`
end the same, but `c` asks first.
The dropped staged pins are counted in the loss (`2 staged pins`), the
selected submodule's own staged pin included, and like any loss they make
restore ask (D31): `Restore libs/staged to the committed pins? Discards 1
staged pin.` The
commits of a dropped pin stay in the submodule; if HEAD leaves them and no
ref reaches them, they count as `commits on no branch`, as always.
### Postconditions ### Postconditions
After a successful restore of repository R with target T: After a successful restore of repository R with target T:
@@ -132,7 +160,7 @@ Restore discards work. The things it can lose:
| Untracked files | `changed` (untracked) | | Untracked files | `changed` (untracked) |
| Conflicts and in-progress operations | `conflict`; merge, rebase, cherry-pick, revert state | | Conflicts and in-progress operations | `conflict`; merge, rebase, cherry-pick, revert state |
| Commits | A detached HEAD off the pin whose commits are on no branch, tag or remote ref (only the reflog still has them) | | Commits | A detached HEAD off the pin whose commits are on no branch, tag or remote ref (only the reflog still has them) |
| Staged pins | Staged pins in a repository that restore moves to another commit (see [Target](#target)) | | Staged pins | Staged pins in a repository that restore moves to another commit (see [Target](#target)); with `X` all staged pins |
| Repositories | An untracked directory that is a repository with its **own** `.git` directory (a clone that was never added as a submodule). Its commits may exist nowhere else. A removed submodule whose git directory is absorbed into `.git/modules` loses only its worktree. Its objects stay | | Repositories | An untracked directory that is a repository with its **own** `.git` directory (a clone that was never added as a submodule). Its commits may exist nowhere else. A removed submodule whose git directory is absorbed into `.git/modules` loses only its worktree. Its objects stay |
Nothing else is lost. Branches, stashes, remote refs, ignored files and Nothing else is lost. Branches, stashes, remote refs, ignored files and
@@ -214,8 +242,10 @@ is resolved like `Status` does, and the first candidate (see
accepts wins. The branch checked out before the restore is passed to the 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. 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` and `X` the parent's index gets the committed pin first
--cacheinfo` in the parent). (`update-index --cacheinfo` in the parent). With `X` (`RestoreHard`) the
staged pins are not put back, and the loss check takes the children's
targets from `HEAD`'s tree instead of the index.
`RestoreLoss` (`lossOf`) follows the repositories on disk: per repository `RestoreLoss` (`lossOf`) follows the repositories on disk: per repository
`status` (without submodules), the in-progress state files, and `status` (without submodules), the in-progress state files, and
@@ -360,13 +390,14 @@ runs the switch flow with it (`SwitchLoss`, `Switch`).
All three are submodule keys (`keyMap.Submodule`), shown in the detail All three are submodule keys (`keyMap.Submodule`), shown in the detail
pane's palette, or in the footer when the pane can't show it. They are pane's palette, or in the footer when the pane can't show it. They are
always offered, the palette is static: restore is idempotent, and `u` says always offered, the palette is static: restore is idempotent, and `u` says
why it can't update. why it can't update. Only `u`'s label follows the selection: on the header
it reads `pull (fast-forward)`.
| Key | Action | Pressed when not possible (flash) | | Key | Action | Pressed when not possible (flash) |
|---|---|---| |---|---|---|
| `x` restore | Restore the selection | `this data source can't restore` (mock); `wait for the restore of … to finish` | | `x` restore to pin, `X` restore committed pins | Restore the selection; `X` see [Hard restore](#hard-restore) | `this data source can't restore` (mock); `wait for the restore of … to finish` |
| `b` switch branch | [Switch branch](#switch-branch) | `this data source can't switch branches`; `wait for the restore of … to finish`; `src/app is not initialized; restore it first` | | `b` switch branch | [Switch branch](#switch-branch) | `this data source can't switch branches`; `wait for the restore of … to finish`; `src/app is not initialized; restore it first` |
| `u` update pin | [Update pin](#update-pin) | `this data source can't update pins`; `wait for the restore of … to finish`; `the superproject has no upstream branch`; `src/app is still loading`; `src/app is not initialized; restore it first`; `the pin of src/app is not on a branch`; `the pin of src/app has diverged from origin/main; b switches the branch`; `the pin of src/app is ahead of origin/main`; `src/app is up to date with origin/main` (the superproject without `the pin of`); after the check `can't update src/app: main is a local branch; b switches to it` | | `u` update pin (`pull (fast-forward)` on the header) | [Update pin](#update-pin) | `this data source can't update pins`; `wait for the restore of … to finish`; `the superproject has no upstream branch`; `src/app is still loading`; `src/app is not initialized; restore it first`; `the pin of src/app is not on a branch`; `the pin of src/app has diverged from origin/main; b switches the branch`; `the pin of src/app is ahead of origin/main`; `src/app is up to date with origin/main` (the superproject without `the pin of`); after the check `can't update src/app: main is a local branch; b switches to it` |
`R` would sit next to `r` (reload), a dangerous mix-up for a destructive `R` would sit next to `r` (reload), a dangerous mix-up for a destructive
action, hence `x`. action, hence `x`.
+18 -11
View File
@@ -23,7 +23,7 @@ internal/submodule/git/ provider using the git CLI (reads, fetch, watch)
switch.go Branches, SwitchLoss, Switch (stage the tip, restore, attach or fast-forward the branch) switch.go Branches, SwitchLoss, Switch (stage the tip, restore, attach or fast-forward the branch)
gitdir.go resolves .git dirs and gitdir: files gitdir.go resolves .git dirs and gitdir: files
internal/submodule/mock/ fixture provider with artificial latency internal/submodule/mock/ fixture provider with artificial latency
internal/update/ self-update from the package registry; NO UI imports internal/update/ self-update from GitHub releases; NO UI imports
internal/tui/ Bubble Tea application internal/tui/ Bubble Tea application
app.go root model: layout, message routing, loading app.go root model: layout, message routing, loading
keys.go key bindings (also feed the help view) keys.go key bindings (also feed the help view)
@@ -37,7 +37,7 @@ internal/tui/ Bubble Tea application
detail/ detail pane; changes.go: change preview detail/ detail pane; changes.go: change preview
header/ header line header/ header line
branches/ branch picker popup (search line + list) branches/ branch picker popup (search line + list)
footer/ key bar (navigation left, global right) and flash messages footer/ key bar (navigation and tools left, global right), full help pages (keys, legend) and flash messages
``` ```
### Layering rules ### Layering rules
@@ -203,17 +203,24 @@ No CI runner: releases are built and published from a developer machine.
- `make dist` cross-compiles `CGO_ENABLED=0` binaries for linux/darwin × - `make dist` cross-compiles `CGO_ENABLED=0` binaries for linux/darwin ×
amd64/arm64 into `dist/` plus `checksums.txt`; the version comes from amd64/arm64 into `dist/` plus `checksums.txt`; the version comes from
`git describe` and is baked in with `-X main.version`. `git describe` and is baked in with `-X main.version`.
- `make release` with `GITEA_TOKEN` set, e.g. in `.env` (copy `.env.template`; token needs `write:package`; HEAD must be a - `make release NOTES=FILE` (needs `gh` logged in, or `GH_TOKEN` in `.env`,
clean `vX.Y.Z` tag) runs tests, builds and uploads to the Gitea generic see `.env.template`; HEAD must be a clean `vX.Y.Z` tag pushed to GitHub)
registry `https://git.simon-franken.de/api/packages/simonfranken/generic`: runs tests, builds and creates the GitHub release `vX.Y.Z` with the notes
- `submarine/<version>/submarine_<os>_<arch>` and `checksums.txt` and the assets `submarine_<os>_<arch>`, `checksums.txt` and `VERSION`. It
- `submarine-latest/latest/VERSION`, replaced **last**, so a failed upload is created as a **draft** and published last, so `releases/latest` never
never advertises a broken version. points at a release with missing assets. Clients read, without the API
(plain redirects, no rate limit), below
`https://github.com/simonfranken/submarine/releases`:
- `latest/download/VERSION`
- `download/<version>/submarine_<os>_<arch>` and `checksums.txt`
- Before the move to GitHub, releases lived in the Gitea generic registry
(`git.simon-franken.de/api/packages/simonfranken/generic`, see D33). It
stays online for old binaries. `make release-gitea` publishes the bridge
version there in the old layout and refuses until GitHub serves it.
- The `release` skill (`.claude/skills/release/SKILL.md`) drives a release: - The `release` skill (`.claude/skills/release/SKILL.md`) drives a release:
latest tag → next semver from the commits since → check (`vet`, `test`, latest tag → next semver from the commits since → check (`vet`, `test`,
`gofmt`, `make dist`) → tag and push → the developer runs `make release` → `gofmt`, `make dist`) → tag and push → the developer runs `make release` →
the skill verifies the registry's `VERSION` and creates the Gitea release the skill verifies that `latest/download/VERSION` serves the new version.
with MCP (notes only; the binaries stay in the registry).
- `install.sh` (`curl -fsSL …/raw/branch/main/install.sh | sh`) detects - `install.sh` (`curl -fsSL …/raw/branch/main/install.sh | sh`) detects
OS/arch, verifies the sha256, installs `submarine` and a `sub` symlink to OS/arch, verifies the sha256, installs `submarine` and a `sub` symlink to
`~/.local/bin` (`SUBMARINE_INSTALL_DIR`, `SUBMARINE_VERSION`, `~/.local/bin` (`SUBMARINE_INSTALL_DIR`, `SUBMARINE_VERSION`,
@@ -221,7 +228,7 @@ No CI runner: releases are built and published from a developer machine.
- `submarine update [--check] [--force]` (package `internal/update`) reads - `submarine update [--check] [--force]` (package `internal/update`) reads
`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 releases root.
- On every start the TUI looks for a newer release in the background (3 s - On every start the TUI looks for a newer release in the background (3 s
timeout, no cache, no blocking). `main` passes `tui.WithUpdateCheck` and timeout, no cache, no blocking). `main` passes `tui.WithUpdateCheck` and
the TUI gets the result as a message; the footer then offers `q quit and the TUI gets the result as a message; the footer then offers `q quit and
+96 -1
View File
@@ -201,7 +201,8 @@ package so versions stay clean.
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 background check at startup that can be disabled (it on `update` and a background check at startup that can be disabled (it
was once a day; see D27). was once a day; see D27). The registry was replaced by GitHub releases in
D33; local builds, `install.sh` and the pointer file stay.
## Copy path with `c` via OSC 52 ## Copy path with `c` via OSC 52
@@ -567,3 +568,97 @@ the branch.
its own rule. No new provider interface: `u` is `Branches`, `SwitchLoss` and its own rule. No new provider interface: `u` is `Branches`, `SwitchLoss` and
`Switch`. Since `Status.Tip.SHA` is abbreviated, the UI compares it as a `Switch`. Since `Status.Tip.SHA` is abbreviated, the UI compares it as a
prefix of the branch's full SHA. prefix of the branch's full SHA.
## D30 — Hard restore drops staged pins at every depth
**Context.** `x` keeps staged pins at every depth (D23), except in a
repository the restore moves. Its `c` answer unstages only the selected
submodule's pin. Staged pins of the superproject, or of nested repositories
that stay on their pin, could only be dropped one by one.
**Decision.** Amends D23. `X` is a hard restore: the selected submodule goes
to its committed pin without the `s` / `c` question, and every restored
repository's index is reset to `HEAD` (the superproject's too), so all
staged pins below are dropped and the submodules follow the committed
trees. Dropped staged pins are counted in the loss and listed if the
question appears, but alone they don't make it appear. `x` and its question
stay as they are.
**Rationale.** A separate key keeps the common `x` free of a further
question and makes the stronger action deliberate. A staged pin is only a
recorded SHA; its commit stays in the submodule, and if HEAD leaves a
commit no ref reaches, `commits on no branch` still asks.
**Alternatives.** A third answer in the `s` / `c` question: only reachable
for a submodule with a staged pin itself, not for the superproject or a
clean parent. Dropping the question from `x`: rejected, the choice between
staged and committed pin is still useful there.
**Consequences.** `RestoreTarget` gets `RestoreHard`, which also matters for
the superproject. `restoreRepo` and `lossOf` take whether to keep staged
pins; switch always keeps them. Without a committed pin (an added
submodule), `X` uses the index pin.
## D31 — Hard restore asks before dropping staged pins
**Context.** D30 let `X` drop staged pins without a question: pressing `X`
was the choice. In a usability walkthrough (see
[notes/usability-plan.md](../notes/usability-plan.md)) `X` on `libs/staged`
unstaged its pin silently. `X` is one Shift away from `x`, and users new to
submodules don't know where to find the dropped commit again.
**Decision.** Amends D30. Dropped staged pins are a loss like any other and
make `X` ask: `Restore libs/staged to the committed pins? Discards 1 staged
pin.` `RestoreLoss` with `RestoreHard` now also counts the selected
submodule's own staged pin (in its parent's index), which `lossOf` doesn't
see. The `c` answer of `x` stays silent: the user picked it in a question.
**Consequences.** `X` asks more often, but only where it changes what is
recorded. Without staged pins or other losses it still runs at once.
## D32 — The screen explains itself
**Context.** The target user is a developer who doesn't know submodules
well and doesn't read manuals. The walkthrough found labels that don't say
what a key does (`x restore`, `X hard restore`), important keys found only
in `?` (`!`, `/`, `f`), and status words explained nowhere.
**Decision.**
- Labels name the target: `x restore to pin`, `X restore committed pins`.
"Hard" suggested "discards changes", which both do.
- A fourth key group, Tools (`!`, `/`, `f`), in the footer after the
navigation keys, dropped before them.
- On the header, `u` reads `pull (fast-forward)`: the label follows the
selection, the key doesn't.
- The full help gets titled columns, and a second page, a legend of the
status words, symbols and spine roles in their colors. Issue levels move
to `IssueKind.Level()` so the legend can't drift from the tree. `esc`
closes either page: cycling back with `?` alone was not obvious.
- A start hint above the footer until the first key.
- `fetched <age> · f fetch` in the detail pane when the last fetch is older
than a day.
**Alternatives.** A first-run screen or tutorial: needs state, and is
skipped. Contextual palettes that grey out impossible keys: larger, kept for
later (item 10 of the usability plan).
**Consequences.** `footer.Keys` drops `help.KeyMap` for `Tools`,
`HelpGroups` and `LegendKeys`; the footer renders the full help itself.
## D33 — Releases move to GitHub, with one bridge release on Gitea
**Context.** The repository moves from `git.simon-franken.de` (Gitea) to
`github.com/simonfranken/submarine`. Installed binaries only know the Gitea
registry (D21), and check it on every start (D27).
**Decision.**
- Releases are GitHub releases with the binaries, `checksums.txt` and
`VERSION` as assets. GitHub Packages has no generic registry. Clients read
`releases/latest/download/VERSION` and `releases/download/<v>/<asset>`:
plain redirects, not the API, so the check on every start is not rate
limited and needs no token.
- `make release` creates a draft, uploads all assets, then publishes: the
draft takes the role of D21's "pointer last".
- One bridge version, the first that reads from GitHub, is also published to
Gitea in the old layout (`make release-gitea`). Old binaries update to it
from Gitea, and from then on update from GitHub. `release-gitea` refuses
until GitHub serves the version, so no bridge binary finds GitHub empty.
- The Gitea registry stays online with the bridge as its latest version, and
the Gitea repository is archived, not deleted: a binary started for the
first time in months still finds its way over.
**Alternatives.** Keep Gitea and mirror to GitHub: two places to publish
to. Have the updater try both hosts: permanent code for a one-time move.
**Consequences.** `SUBMARINE_UPDATE_URL` and `SUBMARINE_BASE_URL` now take
a releases root, not a registry root. Versions before the bridge exist only
on Gitea; `SUBMARINE_VERSION=<old>` with the new `install.sh` doesn't find
them. `release-gitea` and the Gitea settings go once the bridge is out.
+4
View File
@@ -148,6 +148,10 @@ commit hashes. It doesn't answer the questions users actually have:
staged or the committed pin (the latter unstages it). A restored submodule 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 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).
`X` is a hard restore: it goes to the committed pins at every depth,
without the pin question, and drops all staged pins below the selection
too. Dropped staged pins count as a loss, so it asks first. See
[actions.md](actions.md#hard-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
and the local and remote branches of the selection (a submodule, or the and the local and remote branches of the selection (a submodule, or the
+55 -17
View File
@@ -26,7 +26,7 @@
my_submodule_3 unpushed origin/main ↑1 │ ┊ 1 commit my_submodule_3 unpushed origin/main ↑1 │ ┊ 1 commit
libs/ │ tip ● 6f5e4d3 Release 2.1.0 libs/ │ tip ● 6f5e4d3 Release 2.1.0
logging origin/main ↓3 │ logging origin/main ↓3 │
↑↓/jk move • ←→/hl fold • ⇧←→/HL fold all • space toggle • ? help • q quit ↑↓/jk move • ←→/hl collapse/expand • ⇧←→/HL all • space toggle • ! problems only • / filter • f fetch ? help • q quit
``` ```
| Area | Height / width | | Area | Height / width |
@@ -34,14 +34,18 @@
| Header | 1 line | | Header | 1 line |
| Tree | Remaining width | | Tree | Remaining width |
| Detail pane | 40% of the width, at least 36 columns; hidden below 90 columns | | Detail pane | 40% of the width, at least 36 columns; hidden below 90 columns |
| Filter line | 1 line above the footer, only while filtering | | Line above the footer | 1 line, only while filtering, showing problems only, during a restore, after a failure, or until the first key (hint) |
| Footer | 1 line (more with full help) | | Footer | 1 line (more with full help) |
### Key bar and palette ### Key bar and palette
Keys come in three groups (`keyMap.Navigation`, `.Submodule`, `.Global`): Keys come in four groups (`keyMap.Navigation`, `.Tools`, `.Submodule`,
`.Global`):
- **Navigation** (move, fold, toggle): left in the footer. - **Navigation** (move, collapse/expand, toggle): left in the footer.
- **Tools** (`!` problems only, `/` filter, `f` fetch): in the footer after
the navigation keys, most useful first. They act on the whole list and
would otherwise be found only in the full help (D32).
- **Global** (`?`, `q`): right-aligned in the footer, always kept. If a newer - **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 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 item, on a highlighted background (`Theme.Highlight`: black on Primary), and
@@ -50,11 +54,36 @@ Keys come in three groups (`keyMap.Navigation`, `.Submodule`, `.Global`):
bottom of the detail pane, wrapped onto a second line if the pane is too bottom of the detail pane, wrapped onto a second line if the pane is too
narrow for all keys (none is cut off). It is left out if the pane is narrow for all keys (none is cut off). It is left out if the pane is
shorter than 12 lines. Whenever the palette isn't shown (pane hidden or too short), these shorter than 12 lines. Whenever the palette isn't shown (pane hidden or too short), these
keys move into the footer after the navigation keys. keys move into the footer after the tools. With the header selected, `u`
reads `u pull (fast-forward)`, which is what it does there (D29).
If the footer is too narrow, keys are dropped from the left group's end If the footer is too narrow, keys are dropped from the left group's end
(submodule keys first); the global keys stay. Full help (`?`) lists all keys (submodule keys first, then the tools); the global keys stay. Keys work
in columns, whatever the size. Keys work whether or not they are shown. whether or not they are shown.
### Full help
`?` steps through two pages, then back to the key bar; `esc` closes either
page at once (before it would close the filter):
1. **Keys**: every key in titled columns: `Move`, `Jump`, `Selected
submodule`, `All submodules`, `App`. The `App` column says `? what words
mean` and `esc close`.
2. **Legend**: what the words and symbols mean, in their colors: `Status`
(each issue word, `staged`, `in sync`), `Symbols` (`●`, `↑n ↓n`, `+n`,
`·k`, `[n]`), `Commits` (the spine's roles). Then `App` with `esc close`
(`?` closes it too).
The words come from `Theme.Legend()`; issue colors from
`IssueKind.Level()`, so they are the tree's.
Titles are muted and bold. Columns that don't fit are left out from the
right, marked with `…`; the `App` column is always kept.
### Start hint
Until the first key, the line above the footer reads muted `new here? ?
shows every key and what the words mean`. Every start, no state is kept.
Any other line above the footer (filter, restore, …) takes precedence.
### Tree row ### Tree row
@@ -85,7 +114,9 @@ For the superproject (header selected), the `pin` and `you` roles become
1. Directory (muted) and name (bold); `fetched <age>` of the submodule, 1. Directory (muted) and name (bold); `fetched <age>` of the submodule,
muted, right-aligned in the name's line (left out if the pane is too muted, right-aligned in the name's line (left out if the pane is too
narrow, or the submodule is missing) narrow, or the submodule is missing). If the last fetch is older than a
day, or there was none, it continues `· f fetch` (key bold), if there is
room
2. One line per issue: word (colored, 11 columns) + explanation; 2. One line per issue: word (colored, 11 columns) + explanation;
`in sync nothing to do` if there are none and no pin is staged; `in sync nothing to do` if there are none and no pin is staged;
`staged` and `detached HEAD on pin` as information `staged` and `detached HEAD on pin` as information
@@ -213,7 +244,7 @@ shows the superproject's own state word like a tree row (`in sync`,
`changed`, `unpushed +1`, spinner, `error`). The counts that follow are `changed`, `unpushed +1`, spinner, `error`). The counts that follow are
about submodules only. about submodules only.
`path branch ↑↓ state n error · <count> <issue>… · n pin staged · n loading · n submodules · <fetch>` `path branch ↑↓ state n error · <count> <issue>… · n staged · n loading · n submodules · <fetch>`
The summary and `<fetch>` form one group at the right edge; the path, The summary and `<fetch>` form one group at the right edge; the path,
branch and state stay at the left. If the line is too narrow it is cut with branch and state stay at the left. If the line is too narrow it is cut with
@@ -287,7 +318,8 @@ colors in components.
| `H` / `shift+←` / `ctrl+←` | Collapse all (resets remembered expansion); select the top-level ancestor | | `H` / `shift+←` / `ctrl+←` | Collapse all (resets remembered expansion); select the top-level ancestor |
| `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 | | `?` | Full help: keys, then the legend, then closed, see [Full help](#full-help) |
| `esc` | Close the full help; else close the filter |
| `q`, `ctrl+c` | Quit. With a newer release: `q` quits and updates, `Q` and `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) |
@@ -295,6 +327,7 @@ colors in components.
| `/` | Open the filter, see [Filter](#filter) | | `/` | Open the filter, see [Filter](#filter) |
| `!` | Toggle problems only, see [Problems only](#problems-only) | | `!` | Toggle problems only, see [Problems only](#problems-only) |
| `x` | Restore the selection, see [Restore](#restore) | | `x` | Restore the selection, see [Restore](#restore) |
| `X` | Restore the selection to the committed pins, staged pins dropped at every depth, see [Restore](#restore) |
"First child" always means the first child **as displayed** (children are "First child" always means the first child **as displayed** (children are
grouped by directory). grouped by directory).
@@ -361,7 +394,10 @@ the term*.
| failed | red `restore of src/app failed: <git's message>`, until the next key | | failed | red `restore of src/app failed: <git's message>`, until the next key |
`y` restores, any other key cancels; the keys are not passed on while a `y` restores, any other key cancels; the keys are not passed on while a
question is open. After `c` the name reads `src/app to the committed pin`. Without a loss there is no question. Success flashes question is open. After `c` the name reads `src/app to the committed pin`.
`X` (restore committed pins) never asks for the pin; its name reads
`src/app to the committed pins`. Staged pins it drops count as a loss
(`Discards 1 staged pin.`), so it asks (D31). Without a loss there is no question. Success flashes
`restored src/app` in the footer. For the header the name is `the `restored src/app` in the footer. For the header the name is `the
superproject`. This line takes precedence over the filter line and the superproject`. This line takes precedence over the filter line and the
problems-only notice. problems-only notice.
@@ -421,14 +457,16 @@ where the palette can't be shown, see [Key bar and palette](#key-bar-and-palette
| `home` / `g`, `end` / `G` | Header / last submodule | Navigation | Help | | `home` / `g`, `end` / `G` | Header / last submodule | Navigation | Help |
| `pgup`, `pgdn` | Move by one screen | Navigation | Help | | `pgup`, `pgdn` | Move by one screen | Navigation | Help |
| `c` | Copy path | Submodule | Palette, Help | | `c` | Copy path | Submodule | Palette, Help |
| `u` | Update pin to the tip of its ref (superproject: fast-forward to upstream) | Submodule | Palette, Help | | `u` | Update pin to the tip of its ref (superproject: fast-forward to upstream, label `pull (fast-forward)`) | Submodule | Palette, Help |
| `b` | Switch branch (popup) | Submodule | Palette, Help | | `b` | Switch branch (popup) | Submodule | Palette, Help |
| `x` | Restore | Submodule | Palette, Help | | `x` | Restore to pin | Submodule | Palette, Help |
| `f` | Fetch all repositories | Global | Help | | `X` | Restore committed pins | Submodule | Palette, Help |
| `!` | Problems only (toggle) | Tools | Bar, Help |
| `/` | Filter | Tools | Bar, Help |
| `f` | Fetch all repositories | Tools | Bar, Help |
| `r` | Reload everything | Global | Help | | `r` | Reload everything | Global | Help |
| `/` | Filter | Global | Help | | `?` | Full help: keys, legend, close | Global | Bar, Help |
| `!` | Problems only (toggle) | Global | Help | | `esc` | Close the full help (and the filter, see [Filter](#filter)) | Global | Help |
| `?` | Toggle full help | Global | Bar, Help |
| `q`, `ctrl+c` | Quit (`Q`, `ctrl+c` while an update is offered) | 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 | | `q` | Quit and update to the newer release (only if there is one) | Global | Bar (highlighted), Help |
+6 -6
View File
@@ -1,14 +1,14 @@
#!/bin/sh #!/bin/sh
# Install submarine (and the `sub` alias). # Install submarine (and the `sub` alias).
# curl -fsSL https://git.simon-franken.de/simonfranken/submarine/raw/branch/main/install.sh | sh # curl -fsSL https://raw.githubusercontent.com/simonfranken/submarine/main/install.sh | sh
# #
# Environment: # Environment:
# SUBMARINE_VERSION install this version (default: latest) # SUBMARINE_VERSION install this version (default: latest)
# SUBMARINE_INSTALL_DIR target directory (default: ~/.local/bin) # SUBMARINE_INSTALL_DIR target directory (default: ~/.local/bin)
# SUBMARINE_BASE_URL registry root (default: the Gitea generic registry) # SUBMARINE_BASE_URL releases root (default: the GitHub releases)
set -eu set -eu
base="${SUBMARINE_BASE_URL:-https://git.simon-franken.de/api/packages/simonfranken/generic}" base="${SUBMARINE_BASE_URL:-https://github.com/simonfranken/submarine/releases}"
dir="${SUBMARINE_INSTALL_DIR:-$HOME/.local/bin}" dir="${SUBMARINE_INSTALL_DIR:-$HOME/.local/bin}"
die() { echo "install: $*" >&2; exit 1; } die() { echo "install: $*" >&2; exit 1; }
@@ -35,7 +35,7 @@ fi
version="${SUBMARINE_VERSION:-}" version="${SUBMARINE_VERSION:-}"
if [ -z "$version" ]; then if [ -z "$version" ]; then
version="$(curl -fsSL "$base/submarine-latest/latest/VERSION")" || die "cannot determine the latest version" version="$(curl -fsSL "$base/latest/download/VERSION")" || die "cannot determine the latest version"
version="$(printf '%s' "$version" | tr -d '[:space:]')" version="$(printf '%s' "$version" | tr -d '[:space:]')"
fi fi
case "$version" in case "$version" in
@@ -48,8 +48,8 @@ tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT INT TERM trap 'rm -rf "$tmp"' EXIT INT TERM
echo "Installing submarine $version ($os/$arch) to $dir" echo "Installing submarine $version ($os/$arch) to $dir"
curl -fsSL -o "$tmp/$asset" "$base/submarine/$version/$asset" || die "download failed: $asset" curl -fsSL -o "$tmp/$asset" "$base/download/$version/$asset" || die "download failed: $asset"
curl -fsSL -o "$tmp/checksums.txt" "$base/submarine/$version/checksums.txt" || die "download failed: checksums.txt" curl -fsSL -o "$tmp/checksums.txt" "$base/download/$version/checksums.txt" || die "download failed: checksums.txt"
want="$(awk -v a="$asset" '$2 == a || $2 == "*" a { print $1 }' "$tmp/checksums.txt")" want="$(awk -v a="$asset" '$2 == a || $2 == "*" a { print $1 }' "$tmp/checksums.txt")"
[ -n "$want" ] || die "no checksum for $asset" [ -n "$want" ] || die "no checksum for $asset"
+54 -24
View File
@@ -35,19 +35,39 @@ func (p *Provider) RestoreLoss(ctx context.Context, path string, to submodule.Re
if err != nil { if err != nil {
return submodule.Loss{}, err return submodule.Loss{}, err
} }
if dir == "" { // not initialized: nothing on disk to lose var loss submodule.Loss
return submodule.Loss{}, nil if dir != "" { // not initialized: nothing on disk to lose
loss = p.lossOf(ctx, dir, target, to.KeepsStaged())
} }
return p.lossOf(ctx, dir, target), nil if to == submodule.RestoreHard && path != "" && p.pinStaged(ctx, path, target) {
// a hard restore unstages the submodule's own pin too
loss.StagedPins++
loss.Modules = max(loss.Modules, 1)
}
return loss, nil
}
// pinStaged reports whether the pin of path in its parent's index differs
// from committed, the pin a hard restore goes to.
func (p *Provider) pinStaged(ctx context.Context, path, committed string) bool {
p.mu.RLock()
in, ok := p.mods[path]
p.mu.RUnlock()
if !ok {
return false
}
staged, err := pinOf(ctx, in, submodule.RestoreStaged)
return err == nil && staged != committed
} }
// Restore makes path ("" is the superproject) and all submodules below it // Restore makes path ("" is the superproject) and all submodules below it
// exactly what git records, see docs/actions.md. Staged pins are kept. With // exactly what git records, see docs/actions.md. Staged pins are kept. With
// RestoreCommitted, a submodule's own staged pin is unstaged first. A missing // RestoreCommitted, a submodule's own staged pin is unstaged first; with
// submodule is cloned and missing commits are fetched; git never prompts. // RestoreHard, the staged pins below are dropped too. A missing 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", nil) return p.restoreRepo(ctx, p.root, "HEAD", nil, to.KeepsStaged())
} }
p.mu.RLock() p.mu.RLock()
in, ok := p.mods[path] in, ok := p.mods[path]
@@ -59,7 +79,7 @@ func (p *Provider) Restore(ctx context.Context, path string, to submodule.Restor
if err != nil { if err != nil {
return err return err
} }
if to == submodule.RestoreCommitted { if to.Committed() {
if _, err := p.exec(ctx, in.superDir, nil, "update-index", "--cacheinfo", "160000,"+pin+","+in.relPath); err != nil { if _, err := p.exec(ctx, in.superDir, nil, "update-index", "--cacheinfo", "160000,"+pin+","+in.relPath); err != nil {
return err return err
} }
@@ -69,7 +89,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, &in) return p.restoreRepo(ctx, in.dir, pin, &in, to.KeepsStaged())
} }
// restoreTarget returns the directory and the commit path is restored to: // restoreTarget returns the directory and the commit path is restored to:
@@ -96,9 +116,10 @@ func (p *Provider) restoreTarget(ctx context.Context, path string, to submodule.
} }
// pinOf returns the gitlink of a submodule in its parent's index (staged) // pinOf returns the gitlink of a submodule in its parent's index (staged)
// or HEAD (committed). // or HEAD (committed). A hard restore of a submodule that was added but not
// committed yet uses the index: there is no staged pin to drop.
func pinOf(ctx context.Context, in info, to submodule.RestoreTarget) (string, error) { func pinOf(ctx context.Context, in info, to submodule.RestoreTarget) (string, error) {
if to == submodule.RestoreCommitted { if to.Committed() {
out, _, err := try(ctx, in.superDir, "ls-tree", "HEAD", "--", in.relPath) out, _, err := try(ctx, in.superDir, "ls-tree", "HEAD", "--", in.relPath)
if err != nil { if err != nil {
return "", err return "", err
@@ -106,7 +127,9 @@ func pinOf(ctx context.Context, in info, to submodule.RestoreTarget) (string, er
if pin := parseGitlink(out); pin != "" { if pin := parseGitlink(out); pin != "" {
return pin, nil return pin, nil
} }
return "", errors.New("has no committed pin (added, but not committed yet)") if to != submodule.RestoreHard {
return "", errors.New("has no committed pin (added, but not committed yet)")
}
} }
out, err := run(ctx, in.superDir, "ls-files", "-s", "--", in.relPath) out, err := run(ctx, in.superDir, "ls-files", "-s", "--", in.relPath)
if err != nil { if err != nil {
@@ -124,10 +147,11 @@ func pinOf(ctx context.Context, in info, to submodule.RestoreTarget) (string, er
// restoreRepo restores the initialized repository at dir to target (a commit // restoreRepo restores the initialized repository at dir to target (a commit
// 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 and keep is set, its staged pins are kept and are the
// submodules' targets; else the submodules follow target's tree.
// For a submodule (in is not nil) a detached HEAD is then put on a branch at // 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. // 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 { func (p *Provider) restoreRepo(ctx context.Context, dir, target string, in *info, keep bool) 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...)...)
@@ -143,18 +167,20 @@ func (p *Provider) restoreRepo(ctx context.Context, dir, target string, in *info
p.clearOperations(ctx, dir, gitDir) p.clearOperations(ctx, dir, gitDir)
} }
prev, _, _ := try(ctx, dir, "symbolic-ref", "--short", "-q", "HEAD") // for the ref, see attachBranch prev, _, _ := try(ctx, dir, "symbolic-ref", "--short", "-q", "HEAD") // for the ref, see attachBranch
var keep []gitlink var kept []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 {
return err return err
} }
} else if keep, err = stagedPins(ctx, dir); err != nil { } else if keep {
return err if kept, err = stagedPins(ctx, dir); err != nil {
return err
}
} }
if _, err := g("reset", "--hard", "-q"); err != nil { if _, err := g("reset", "--hard", "-q"); err != nil {
return err return err
} }
for _, l := range keep { for _, l := range kept {
if _, err := g("update-index", "--cacheinfo", "160000,"+l.sha+","+l.path); err != nil { if _, err := g("update-index", "--cacheinfo", "160000,"+l.sha+","+l.path); err != nil {
return err return err
} }
@@ -206,7 +232,7 @@ func (p *Provider) restoreRepo(ctx context.Context, dir, target string, in *info
go func() { go func() {
defer wg.Done() defer wg.Done()
child := info{superDir: dir, dir: filepath.Join(dir, filepath.FromSlash(l.path)), relPath: l.path, branch: branches[l.path]} 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 { if err := p.restoreRepo(ctx, child.dir, l.sha, &child, keep); err != nil {
errs[i] = err errs[i] = err
} }
}() }()
@@ -482,8 +508,9 @@ func stagedPins(ctx context.Context, dir string) ([]gitlink, error) {
// lossOf adds up what a restore of the repository at dir to target // lossOf adds up what a restore of the repository at dir to target
// discards, including the submodules on disk below it. target is "" if it is // discards, including the submodules on disk below it. target is "" if it is
// not known; then commits are only judged by the refs that reach them. // not known; then commits are only judged by the refs that reach them. keep
func (p *Provider) lossOf(ctx context.Context, dir, target string) submodule.Loss { // is false for a hard restore, which drops all staged pins.
func (p *Provider) lossOf(ctx context.Context, dir, target string, keep bool) submodule.Loss {
var own submodule.Loss var own submodule.Loss
var children []gitlink var children []gitlink
var targets map[string]string var targets map[string]string
@@ -545,16 +572,19 @@ func (p *Provider) lossOf(ctx context.Context, dir, target string) submodule.Los
} }
// staged pins are kept, unless the checkout moves away from // staged pins are kept, unless the checkout moves away from
// the commit they were staged on; then the submodules follow // the commit they were staged on or the restore is hard; then
// the target's tree // the submodules follow the target's tree
staged, err := stagedPins(ctx, dir) staged, err := stagedPins(ctx, dir)
if err != nil { if err != nil {
unknown() unknown()
} }
var links []gitlink var links []gitlink
switch { switch {
case !moves: case !moves && keep:
links, err = indexGitlinks(ctx, dir) links, err = indexGitlinks(ctx, dir)
case !moves:
own.StagedPins = len(staged)
links, err = treeGitlinks(ctx, dir, "HEAD")
case target != "": case target != "":
own.StagedPins = len(staged) own.StagedPins = len(staged)
links, err = treeGitlinks(ctx, dir, target) links, err = treeGitlinks(ctx, dir, target)
@@ -589,7 +619,7 @@ func (p *Provider) lossOf(ctx context.Context, dir, target string) submodule.Los
wg.Add(1) wg.Add(1)
go func() { go func() {
defer wg.Done() defer wg.Done()
results[i] = p.lossOf(ctx, sub, targets[c.path]) results[i] = p.lossOf(ctx, sub, targets[c.path], keep)
}() }()
} }
wg.Wait() wg.Wait()
+77
View File
@@ -310,6 +310,83 @@ func TestRestoreCommittedUnstagesThePin(t *testing.T) {
} }
} }
func TestRestoreHardDropsStagedPinsAtEveryDepth(t *testing.T) {
p, root := ownFixture(t)
super := filepath.Join(root, "super")
log := filepath.Join(super, "libs", "log")
nested := filepath.Join(log, "modules", "nested")
committed := out(t, nested, "rev-parse", "HEAD")
base, err := p.RestoreLoss(context.Background(), "", submodule.RestoreHard)
if err != nil {
t.Fatal(err)
}
// stage a new pin of nested in libs/log, on a commit only nested's
// detached HEAD reaches
git(t, nested, "checkout", "-q", "--detach")
git(t, nested, "commit", "-q", "--allow-empty", "-m", "Nested work")
git(t, log, "add", "modules/nested")
l, err := p.RestoreLoss(context.Background(), "", submodule.RestoreHard)
if err != nil {
t.Fatal(err)
}
if base.StagedPins == 0 || l.StagedPins != base.StagedPins+1 || l.Commits != base.Commits+1 {
t.Errorf("loss %+v, want the fixture's %d staged pins, the nested one and its commit", l, base.StagedPins)
}
if err := p.Restore(context.Background(), "", submodule.RestoreHard); err != nil {
t.Fatal(err)
}
for _, dir := range []string{super, log} {
if got := out(t, dir, "diff", "--cached", "--name-only"); got != "" {
t.Errorf("%s still staged: %q", dir, got)
}
}
if got := out(t, nested, "rev-parse", "HEAD"); got != committed {
t.Errorf("nested HEAD = %s, want the committed pin %s", got, committed)
}
assertExact(t, super)
}
func TestRestoreHardOfASubmoduleUnstagesItsPin(t *testing.T) {
p, root := ownFixture(t)
super := filepath.Join(root, "super")
committed := strings.Fields(out(t, super, "ls-tree", "HEAD", "libs/staged"))[2]
if err := p.Restore(context.Background(), "libs/staged", submodule.RestoreHard); err != nil {
t.Fatal(err)
}
if got := out(t, super, "diff", "--cached", "--name-only"); strings.Contains(got, "libs/staged") {
t.Errorf("still staged: %q", got)
}
if got := out(t, filepath.Join(super, "libs", "staged"), "rev-parse", "HEAD"); got != committed {
t.Errorf("HEAD = %s, want the committed pin %s", got, committed)
}
}
func TestRestoreLossOfAHardRestoreCountsTheOwnStagedPin(t *testing.T) {
p, _ := ownFixture(t)
committed, err := p.RestoreLoss(context.Background(), "libs/staged", submodule.RestoreCommitted)
if err != nil {
t.Fatal(err)
}
hard, err := p.RestoreLoss(context.Background(), "libs/staged", submodule.RestoreHard)
if err != nil {
t.Fatal(err)
}
if hard.StagedPins != committed.StagedPins+1 || hard.Modules == 0 {
t.Errorf("hard loss %+v, want the own staged pin on top of %+v", hard, committed)
}
// without a staged pin, a hard restore unstages nothing of its own
clean, err := p.RestoreLoss(context.Background(), "src/ui", submodule.RestoreHard)
if err != nil {
t.Fatal(err)
}
if clean.StagedPins != 0 {
t.Errorf("loss of src/ui %+v, want no staged pin", clean)
}
}
func TestRestoreLossCountsStagedPinsOfAMovingRepository(t *testing.T) { func TestRestoreLossCountsStagedPinsOfAMovingRepository(t *testing.T) {
p, root := ownFixture(t) p, root := ownFixture(t)
super := filepath.Join(root, "super") super := filepath.Join(root, "super")
+2 -2
View File
@@ -85,7 +85,7 @@ func (p *Provider) SwitchLoss(ctx context.Context, path string, b submodule.Bran
if err != nil { if err != nil {
return submodule.Loss{}, err return submodule.Loss{}, err
} }
return p.lossOf(ctx, dir, b.SHA), nil return p.lossOf(ctx, dir, b.SHA, true), nil
} }
// Switch makes b's tip the staged pin of a submodule, restores the repository // Switch makes b's tip the staged pin of a submodule, restores the repository
@@ -114,7 +114,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, nil); err != nil { // HEAD goes on b below if err := p.restoreRepo(ctx, dir, b.SHA, nil, true); err != nil { // HEAD goes on b below
return "", err return "", err
} }
+11 -2
View File
@@ -72,15 +72,24 @@ type Switcher interface {
Switch(ctx context.Context, path string, b Branch) (string, error) Switch(ctx context.Context, path string, b Branch) (string, error)
} }
// RestoreTarget is the pin a submodule is restored to. It doesn't matter for // RestoreTarget is the pin a submodule is restored to, and whether staged
// the superproject, whose target is always HEAD. // pins below it are kept. The superproject's target is always HEAD; only
// RestoreHard matters for it.
type RestoreTarget int type RestoreTarget int
const ( const (
RestoreStaged RestoreTarget = iota // the pin in the parent's index: a staged pin is kept and used RestoreStaged RestoreTarget = iota // the pin in the parent's index: a staged pin is kept and used
RestoreCommitted // the pin in the parent's HEAD: a staged pin is unstaged RestoreCommitted // the pin in the parent's HEAD: a staged pin is unstaged
RestoreHard // the pin in the parent's HEAD, and staged pins below are dropped too
) )
// Committed reports whether a submodule goes to the pin in its parent's HEAD.
func (t RestoreTarget) Committed() bool { return t != RestoreStaged }
// KeepsStaged reports whether staged pins below the restored repository are
// kept.
func (t RestoreTarget) KeepsStaged() bool { return t != RestoreHard }
// Loss is what a restore discards. The zero Loss means nothing is lost. // Loss is what a restore discards. The zero Loss means nothing is lost.
type Loss struct { type Loss struct {
Files int // changed, conflicted and untracked files and directories Files int // changed, conflicted and untracked files and directories
+23 -8
View File
@@ -24,6 +24,21 @@ const (
IssueOffTarget // pin pushed, but not on the target branch IssueOffTarget // pin pushed, but not on the target branch
) )
// Kinds lists every issue kind, most severe first.
var Kinds = []IssueKind{IssueUnpushed, IssueConflict, IssueMissing, IssueOffPin, IssueChanged, IssueOffTarget}
// Level is how much attention an issue of kind k deserves.
func (k IssueKind) Level() Level {
switch k {
case IssueUnpushed, IssueConflict:
return LevelDanger
case IssueOffTarget:
return LevelInfo
default:
return LevelWarn
}
}
// Issue is one problem of a submodule. Detail distinguishes the states that // Issue is one problem of a submodule. Detail distinguishes the states that
// are summarized into one kind. // are summarized into one kind.
type Issue struct { type Issue struct {
@@ -40,9 +55,9 @@ func (s *Status) Issues() []Issue {
} }
switch s.Presence { switch s.Presence {
case NotInitialized: case NotInitialized:
return []Issue{{IssueMissing, LevelWarn, "not initialized"}} return []Issue{{IssueMissing, IssueMissing.Level(), "not initialized"}}
case DirMissing: case DirMissing:
return []Issue{{IssueMissing, LevelWarn, "directory missing"}} return []Issue{{IssueMissing, IssueMissing.Level(), "directory missing"}}
} }
var out []Issue var out []Issue
@@ -51,24 +66,24 @@ func (s *Status) Issues() []Issue {
if s.Root { if s.Root {
detail = "HEAD not pushed to any remote" detail = "HEAD not pushed to any remote"
} }
out = append(out, Issue{IssueUnpushed, LevelDanger, detail}) out = append(out, Issue{IssueUnpushed, IssueUnpushed.Level(), detail})
} }
if s.Worktree == WorktreeConflict { if s.Worktree == WorktreeConflict {
out = append(out, Issue{IssueConflict, LevelDanger, "merge conflict"}) out = append(out, Issue{IssueConflict, IssueConflict.Level(), "merge conflict"})
} }
if s.Checkout == CheckoutDiffers { if s.Checkout == CheckoutDiffers {
out = append(out, Issue{IssueOffPin, LevelWarn, "checkout differs from pin"}) out = append(out, Issue{IssueOffPin, IssueOffPin.Level(), "checkout differs from pin"})
} }
switch s.Worktree { switch s.Worktree {
case WorktreeModified: case WorktreeModified:
out = append(out, Issue{IssueChanged, LevelWarn, "uncommitted changes"}) out = append(out, Issue{IssueChanged, IssueChanged.Level(), "uncommitted changes"})
case WorktreeUntracked: case WorktreeUntracked:
out = append(out, Issue{IssueChanged, LevelWarn, s.untrackedText()}) out = append(out, Issue{IssueChanged, IssueChanged.Level(), s.untrackedText()})
} }
// a pin that is pushed, but not on the target (usually main); an // a pin that is pushed, but not on the target (usually main); an
// unpushed pin is not on it either, but has the worse issue // unpushed pin is not on it either, but has the worse issue
if !s.Root && s.Pin.Pushed && s.Pin.Target != "" && s.Pin.Ref != s.Pin.Target { if !s.Root && s.Pin.Pushed && s.Pin.Target != "" && s.Pin.Ref != s.Pin.Target {
out = append(out, Issue{IssueOffTarget, LevelInfo, s.offTargetText()}) out = append(out, Issue{IssueOffTarget, IssueOffTarget.Level(), s.offTargetText()})
} }
return out return out
} }
+27 -7
View File
@@ -60,6 +60,7 @@ type Model struct {
picker *branches.Model // the branch picker, nil if closed picker *branches.Model // the branch picker, nil if closed
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
hint bool // the hint for newcomers above the footer, until the first key
checkUpdate func(context.Context) string // looks for a newer release, nil if off checkUpdate func(context.Context) string // looks for a newer release, nil if off
update string // the newer release found, "" if none update string // the newer release found, "" if none
@@ -104,6 +105,7 @@ func New(ctx context.Context, p submodule.Provider, opts ...Option) Model {
footer: footer.New(t, k), footer: footer.New(t, k),
spinner: sp, spinner: sp,
filter: fi, filter: fi,
hint: true,
} }
m.fetcher, _ = p.(submodule.Fetcher) m.fetcher, _ = p.(submodule.Fetcher)
m.watcher, _ = p.(submodule.Watcher) m.watcher, _ = p.(submodule.Watcher)
@@ -385,14 +387,17 @@ func (m Model) handleKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
return m.answerRestore(msg) return m.answerRestore(msg)
} }
} }
if m.notice != "" { if m.notice != "" || m.hint {
m.notice = "" m.notice, m.hint = "", false
m.layout() m.layout()
} }
if m.filter.Focused() { if m.filter.Focused() {
return m.typeFilter(msg) return m.typeFilter(msg)
} }
switch { switch {
case m.footer.HelpOpen() && msg.Type == tea.KeyEsc: // before the filter's esc
m.footer.CloseHelp()
m.layout()
case m.filtering && msg.Type == tea.KeyEsc: case m.filtering && msg.Type == tea.KeyEsc:
m.closeFilter() m.closeFilter()
case key.Matches(msg, k.Quit): case key.Matches(msg, k.Quit):
@@ -401,7 +406,7 @@ func (m Model) handleKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
m.updateTo = m.update m.updateTo = m.update
return m, tea.Quit return m, tea.Quit
case key.Matches(msg, k.Help): case key.Matches(msg, k.Help):
m.footer.ToggleHelp() m.footer.CycleHelp()
m.layout() m.layout()
case key.Matches(msg, k.Up): case key.Matches(msg, k.Up):
m.tree.Up() m.tree.Up()
@@ -448,7 +453,9 @@ func (m Model) handleKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
m.layout() m.layout()
return m, m.filter.Focus() return m, m.filter.Focus()
case key.Matches(msg, k.Restore): case key.Matches(msg, k.Restore):
return m.startRestore() return m.startRestore(false)
case key.Matches(msg, k.HardRestore):
return m.startRestore(true)
case key.Matches(msg, k.Switch): case key.Matches(msg, k.Switch):
return m.startSwitch() return m.startSwitch()
case key.Matches(msg, k.Update): case key.Matches(msg, k.Update):
@@ -515,10 +522,16 @@ func (m Model) filterView() string {
} }
// extraLine reports whether a line above the footer is shown: a restore in // extraLine reports whether a line above the footer is shown: a restore in
// progress, a failure, the filter, or the notice that only problems are // progress, a failure, the filter, the notice that only problems are shown,
// shown. // or the hint for newcomers.
func (m Model) extraLine() bool { func (m Model) extraLine() bool {
return m.filtering || m.tree.ProblemsOnly() || m.restore != nil || m.notice != "" return m.filtering || m.tree.ProblemsOnly() || m.restore != nil || m.notice != "" || m.hint
}
// hintView is the line above the footer until the first key: where help is.
func (m Model) hintView() string {
muted := theme.Fg(m.theme.Muted)
return m.line(muted.Render("new here? ")+theme.Fg(m.theme.Text).Bold(true).Render("?")+muted.Render(" shows every key and what the words mean"), "")
} }
// problemsView is the line above the footer while only problems are shown, so // problemsView is the line above the footer while only problems are shown, so
@@ -579,6 +592,11 @@ func (m Model) View() string {
return theme.Fg(m.theme.Danger).Render("error: " + m.err.Error()) return theme.Fg(m.theme.Danger).Render("error: " + m.err.Error())
} }
// the keys as they read for the selection; m is a copy
k := m.keys.forSelection(m.tree.RootSelected())
m.footer.SetKeys(k)
m.detail.SetActions(k.Submodule())
body := m.tree.View() body := m.tree.View()
if m.showDetail { if m.showDetail {
pane := lipgloss.NewStyle(). pane := lipgloss.NewStyle().
@@ -599,6 +617,8 @@ func (m Model) View() string {
parts = append(parts, m.filterView()) parts = append(parts, m.filterView())
} else if m.tree.ProblemsOnly() { } else if m.tree.ProblemsOnly() {
parts = append(parts, m.problemsView()) parts = append(parts, m.problemsView())
} else if m.hint {
parts = append(parts, m.hintView())
} }
view := zone.Scan(lipgloss.JoinVertical(lipgloss.Left, append(parts, m.footer.View())...)) view := zone.Scan(lipgloss.JoinVertical(lipgloss.Left, append(parts, m.footer.View())...))
if m.picker != nil { // after zone.Scan, so no zone marker is cut if m.picker != nil { // after zone.Scan, so no zone marker is cut
+17 -3
View File
@@ -6,6 +6,7 @@ import (
"path" "path"
"slices" "slices"
"strings" "strings"
"time"
"github.com/charmbracelet/bubbles/help" "github.com/charmbracelet/bubbles/help"
"github.com/charmbracelet/bubbles/key" "github.com/charmbracelet/bubbles/key"
@@ -18,6 +19,9 @@ import (
const labelWidth = 11 const labelWidth = 11
// staleFetch is the age of the last fetch from which the pane suggests f.
const staleFetch = 24 * time.Hour
type Model struct { type Model struct {
theme theme.Theme theme theme.Theme
width int width int
@@ -38,6 +42,9 @@ func New(t theme.Theme, actions []key.Binding) Model {
// PaletteVisible reports whether the palette of submodule actions fits. // PaletteVisible reports whether the palette of submodule actions fits.
func (m Model) PaletteVisible() bool { return m.height >= paletteMinHeight } func (m Model) PaletteVisible() bool { return m.height >= paletteMinHeight }
// SetActions replaces the bindings of the palette.
func (m *Model) SetActions(actions []key.Binding) { m.actions = actions }
func (m *Model) SetSize(w, h int) { m.width, m.height = w, h } func (m *Model) SetSize(w, h int) { m.width, m.height = w, h }
func (m *Model) SetSpinner(frame string) { m.spinner = frame } func (m *Model) SetSpinner(frame string) { m.spinner = frame }
@@ -123,10 +130,17 @@ func (m Model) lines(s *submodule.Submodule, repo *submodule.Repo) []string {
st := s.Status st := s.Status
// the age of the last fetch is right-aligned in the name's line // the age of the last fetch is right-aligned in the name's line
// with a hint to fetch if the last fetch is old, and room for it
if st.Presence == submodule.PresenceOK { if st.Presence == submodule.PresenceOK {
fetched := "fetched " + theme.Ago(st.FetchedAt) fetched := muted.Render("fetched " + theme.Ago(st.FetchedAt))
if gap := m.width - ansi.StringWidth(s.Name) - len(fetched); gap >= 2 { if time.Since(st.FetchedAt) > staleFetch {
out[1] += strings.Repeat(" ", gap) + muted.Render(fetched) hinted := fetched + muted.Render(" · ") + text.Bold(true).Render("f") + muted.Render(" fetch")
if m.width-ansi.StringWidth(s.Name)-lipgloss.Width(hinted) >= 2 {
fetched = hinted
}
}
if gap := m.width - ansi.StringWidth(s.Name) - lipgloss.Width(fetched); gap >= 2 {
out[1] += strings.Repeat(" ", gap) + fetched
} }
} }
+43
View File
@@ -0,0 +1,43 @@
package detail
import (
"strings"
"testing"
"time"
"github.com/charmbracelet/x/ansi"
"submarine/internal/submodule"
"submarine/internal/tui/theme"
)
func TestFetchHintForOldFetches(t *testing.T) {
m := New(theme.Default(), nil)
m.SetSize(60, 20)
for _, c := range []struct {
fetched time.Time
hint bool
}{
{time.Time{}, true},
{time.Now().Add(-48 * time.Hour), true},
{time.Now().Add(-time.Hour), false},
} {
s := &submodule.Submodule{Path: "src/app", Name: "app", Status: &submodule.Status{
Presence: submodule.PresenceOK, FetchedAt: c.fetched, Pin: submodule.PinInfo{Pushed: true},
}}
got := ansi.Strip(m.View(s, nil))
if strings.Contains(got, "f fetch") != c.hint {
t.Errorf("fetched %s: hint %v, want %v:\n%s", theme.Ago(c.fetched), !c.hint, c.hint, got)
}
if !strings.Contains(got, "fetched "+theme.Ago(c.fetched)) {
t.Errorf("the age is missing:\n%s", got)
}
}
// too narrow for the hint: the age alone
m.SetSize(24, 20)
s := &submodule.Submodule{Path: "src/app", Name: "app", Status: &submodule.Status{Presence: submodule.PresenceOK}}
if got := ansi.Strip(m.View(s, nil)); strings.Contains(got, "f fetch") || !strings.Contains(got, "fetched never") {
t.Errorf("narrow pane:\n%s", got)
}
}
+2 -2
View File
@@ -15,7 +15,7 @@ func TestPaletteWrapsInsteadOfCuttingKeys(t *testing.T) {
key.NewBinding(key.WithKeys("c"), key.WithHelp("c", "copy path")), key.NewBinding(key.WithKeys("c"), key.WithHelp("c", "copy path")),
key.NewBinding(key.WithKeys("u"), key.WithHelp("u", "update pin")), key.NewBinding(key.WithKeys("u"), key.WithHelp("u", "update pin")),
key.NewBinding(key.WithKeys("b"), key.WithHelp("b", "switch branch")), key.NewBinding(key.WithKeys("b"), key.WithHelp("b", "switch branch")),
key.NewBinding(key.WithKeys("x"), key.WithHelp("x", "restore")), key.NewBinding(key.WithKeys("x"), key.WithHelp("x", "restore to pin")),
} }
m := New(theme.Default(), keys) m := New(theme.Default(), keys)
m.SetSize(36, 20) m.SetSize(36, 20)
@@ -24,7 +24,7 @@ func TestPaletteWrapsInsteadOfCuttingKeys(t *testing.T) {
t.Fatalf("want 2 lines, got %q", lines) t.Fatalf("want 2 lines, got %q", lines)
} }
all := strings.Join(lines, "\n") all := strings.Join(lines, "\n")
for _, want := range []string{"copy path", "update pin", "switch branch", "x restore"} { for _, want := range []string{"copy path", "update pin", "switch branch", "x restore to pin"} {
if !strings.Contains(all, want) { if !strings.Contains(all, want) {
t.Errorf("palette lacks %q: %q", want, lines) t.Errorf("palette lacks %q: %q", want, lines)
} }
+132 -11
View File
@@ -2,6 +2,7 @@
package footer package footer
import ( import (
"slices"
"strings" "strings"
"time" "time"
@@ -18,18 +19,39 @@ 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, Tools (and
// Submodule, if requested) on the left, Global and then Highlight (on a // Submodule, if requested) on the left, Global and then Highlight (on a
// highlighted background) on the right; full help // highlighted background) on the right. The full help has two pages: the
// shows FullHelp. // HelpGroups (the last one is always kept), then the theme's legend with
// LegendKeys next to it.
type Keys interface { type Keys interface {
help.KeyMap
Navigation() []key.Binding Navigation() []key.Binding
Tools() []key.Binding
Submodule() []key.Binding Submodule() []key.Binding
Global() []key.Binding Global() []key.Binding
Highlight() []key.Binding Highlight() []key.Binding
HelpGroups() []Group
LegendKeys() Group
} }
// Group is a titled column of the full help.
type Group struct {
Title string
Keys []key.Binding
}
// helpPage is what the footer shows besides a flash.
type helpPage int
const (
pageBar helpPage = iota // one line of key hints
pageKeys // every key, in titled columns
pageLegend // what the words and symbols mean
)
// columnGap separates the columns of the full help.
const columnGap = " "
type Model struct { type Model struct {
theme theme.Theme theme theme.Theme
help help.Model help help.Model
@@ -37,6 +59,7 @@ type Model struct {
width int width int
flash string flash string
flashID int flashID int
page helpPage
actions bool // show the submodule bindings in the short bar actions bool // show the submodule bindings in the short bar
} }
@@ -56,8 +79,18 @@ func (m *Model) SetWidth(w int) {
m.help.Width = w - 2 m.help.Width = w - 2
} }
// ToggleHelp switches between short and full key help. // CycleHelp shows the next help page: the short bar, every key, the legend,
func (m *Model) ToggleHelp() { m.help.ShowAll = !m.help.ShowAll } // then the short bar again.
func (m *Model) CycleHelp() { m.page = (m.page + 1) % 3 }
// HelpOpen reports whether a full help page is shown.
func (m Model) HelpOpen() bool { return m.page != pageBar }
// CloseHelp goes back to the short bar from any help page.
func (m *Model) CloseHelp() { m.page = pageBar }
// Legend reports whether the legend is shown.
func (m Model) Legend() bool { return m.page == pageLegend }
// Flash shows msg for a short time instead of the key hints. // Flash shows msg for a short time instead of the key hints.
func (m *Model) Flash(msg string) tea.Cmd { func (m *Model) Flash(msg string) tea.Cmd {
@@ -78,14 +111,102 @@ func (m Model) View() string {
if m.flash != "" { if m.flash != "" {
return style.Foreground(m.theme.Warn).Render(m.flash) return style.Foreground(m.theme.Warn).Render(m.flash)
} }
if m.help.ShowAll { switch m.page {
return style.Render(m.help.View(m.keys)) case pageKeys:
var cols []column
for _, g := range m.keys.HelpGroups() {
cols = append(cols, m.keyColumn(g))
}
return style.Render(m.columns(cols[:len(cols)-1], cols[len(cols)-1], m.width-2))
case pageLegend:
var cols []column
for _, g := range m.theme.Legend() {
c := column{title: g.Title}
for _, r := range g.Rows {
c.rows = append(c.rows, [2]string{r.Word, m.help.Styles.FullDesc.Render(r.Meaning)})
}
cols = append(cols, c)
}
return style.Render(m.columns(cols, m.keyColumn(m.keys.LegendKeys()), m.width-2))
} }
return style.Render(m.shortBar(m.width - 2)) return style.Render(m.shortBar(m.width - 2))
} }
// column is a titled column of the full help: rows of a rendered key (or
// word) and its description.
type column struct {
title string
rows [][2]string
}
func (m Model) keyColumn(g Group) column {
c := column{title: g.Title}
for _, b := range g.Keys {
if b.Enabled() {
c.rows = append(c.rows, [2]string{m.help.Styles.FullKey.Render(b.Help().Key), m.help.Styles.FullDesc.Render(b.Help().Desc)})
}
}
return c
}
// columns lays cols out side by side, each under its title, and last at the
// end. Like the global keys in the short bar, last is always kept: the
// columns before it that don't fit into w are left out from the right,
// marked with an ellipsis.
func (m Model) columns(cols []column, last column, w int) string {
tail := m.block(last)
avail := w - lipgloss.Width(tail) - len(columnGap)
var out []string
width := 0
for i, c := range cols {
b := m.block(c)
bw := lipgloss.Width(b) + len(columnGap)
if i == 0 {
bw -= len(columnGap)
}
if width+bw > avail {
for len(out) > 0 && width+2 > avail { // room for the ellipsis
width -= lipgloss.Width(out[len(out)-1]) + len(columnGap)
out = out[:len(out)-1]
}
if width+2 <= avail {
out = append(out, " "+m.help.Styles.Ellipsis.Render("…"))
}
break
}
out = append(out, b)
width += bw
}
var parts []string
for i, b := range out {
if i > 0 && !strings.HasPrefix(b, " ") {
parts = append(parts, columnGap)
}
parts = append(parts, b)
}
if len(parts) > 0 {
parts = append(parts, columnGap)
}
parts = append(parts, tail)
return lipgloss.NewStyle().MaxWidth(w).Render(lipgloss.JoinHorizontal(lipgloss.Top, parts...))
}
// block renders a column: its title, then its rows with the descriptions
// aligned.
func (m Model) block(c column) string {
left := 0
for _, r := range c.rows {
left = max(left, lipgloss.Width(r[0]))
}
lines := []string{theme.Fg(m.theme.Muted).Bold(true).Render(c.title)}
for _, r := range c.rows {
lines = append(lines, r[0]+strings.Repeat(" ", left-lipgloss.Width(r[0])+1)+r[1])
}
return strings.Join(lines, "\n")
}
// shortBar puts the global keys on the right and as many of the others on the // shortBar puts the global keys on the right and as many of the others on the
// left as fit; the submodule keys are dropped first. // left as fit; the submodule keys are dropped first, then the tools.
func (m Model) shortBar(w int) string { func (m Model) shortBar(w int) string {
h := m.help h := m.help
h.Width = 0 h.Width = 0
@@ -97,9 +218,9 @@ func (m Model) shortBar(w int) string {
} }
right += " " + m.theme.Highlight().Render(" "+strings.Join(parts, " ")+" ") right += " " + m.theme.Highlight().Render(" "+strings.Join(parts, " ")+" ")
} }
left := m.keys.Navigation() left := append(slices.Clip(m.keys.Navigation()), m.keys.Tools()...)
if m.actions { if m.actions {
left = append(left[:len(left):len(left)], m.keys.Submodule()...) left = append(left, m.keys.Submodule()...)
} }
for ; ; left = left[:len(left)-1] { for ; ; left = left[:len(left)-1] {
l := h.ShortHelpView(left) l := h.ShortHelpView(left)
+88 -3
View File
@@ -15,14 +15,25 @@ type testKeys struct{ highlight []key.Binding }
func bind(k, desc string) key.Binding { return key.NewBinding(key.WithKeys(k), key.WithHelp(k, desc)) } 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 { func (testKeys) Navigation() []key.Binding {
return []key.Binding{bind("j", "move"), bind("h", "fold")} return []key.Binding{bind("j", "move"), bind("h", "fold")}
} }
func (testKeys) Submodule() []key.Binding { return nil } func (testKeys) Tools() []key.Binding {
return []key.Binding{bind("!", "problems only"), bind("/", "filter"), bind("f", "fetch")}
}
func (testKeys) Submodule() []key.Binding { return []key.Binding{bind("x", "restore to pin")} }
func (testKeys) Global() []key.Binding { return []key.Binding{bind("?", "help"), bind("Q", "quit")} } func (testKeys) Global() []key.Binding { return []key.Binding{bind("?", "help"), bind("Q", "quit")} }
func (k testKeys) Highlight() []key.Binding { return k.highlight } func (k testKeys) Highlight() []key.Binding { return k.highlight }
func (testKeys) HelpGroups() []Group {
return []Group{
{Title: "Move", Keys: []key.Binding{bind("j", "down"), bind("k", "up")}},
{Title: "Selected submodule", Keys: []key.Binding{bind("x", "restore to pin")}},
{Title: "App", Keys: []key.Binding{bind("?", "what words mean"), bind("Q", "quit")}},
}
}
func (testKeys) LegendKeys() Group {
return Group{Title: "App", Keys: []key.Binding{bind("esc", "close")}}
}
func bar(w int, hl ...key.Binding) string { func bar(w int, hl ...key.Binding) string {
m := New(theme.Default(), testKeys{hl}) m := New(theme.Default(), testKeys{hl})
@@ -52,3 +63,77 @@ func TestNavigationGivesWayToUpdate(t *testing.T) {
t.Errorf("the right group must be kept:\n%q", got) t.Errorf("the right group must be kept:\n%q", got)
} }
} }
func TestToolsFollowNavigation(t *testing.T) {
got := bar(80)
if !strings.Contains(got, "h fold • ! problems only • / filter • f fetch") {
t.Errorf("tools must follow the navigation keys:\n%q", got)
}
}
func TestToolsGiveWayBeforeNavigation(t *testing.T) {
got := bar(40)
if strings.Contains(got, "f fetch") || !strings.Contains(got, "j move") {
t.Errorf("tools must go before navigation:\n%q", got)
}
}
func TestSubmoduleKeysGoFirst(t *testing.T) {
m := New(theme.Default(), testKeys{})
m.SetActions(true)
m.SetWidth(80)
got := ansi.Strip(m.View())
if strings.Contains(got, "restore to pin") || !strings.Contains(got, "f fetch") {
t.Errorf("submodule keys must go before the tools:\n%q", got)
}
m.SetWidth(120)
if got := ansi.Strip(m.View()); !strings.Contains(got, "f fetch • x restore to pin") {
t.Errorf("submodule keys follow the tools:\n%q", got)
}
}
func TestHelpPages(t *testing.T) {
m := New(theme.Default(), testKeys{})
m.SetWidth(120)
m.CycleHelp()
keys := ansi.Strip(m.View())
for _, want := range []string{"Move", "Selected submodule", "App", "x restore to pin", "? what words mean"} {
if !strings.Contains(keys, want) {
t.Errorf("key page lacks %q:\n%s", want, keys)
}
}
m.CycleHelp()
if !m.Legend() {
t.Fatal("second page must be the legend")
}
legend := ansi.Strip(m.View())
for _, want := range []string{"Status", "off pin", "Symbols", "Commits", "esc close"} {
if !strings.Contains(legend, want) {
t.Errorf("legend lacks %q:\n%s", want, legend)
}
}
for _, l := range strings.Split(m.View(), "\n") {
if w := lipgloss.Width(l); w > 120 {
t.Errorf("legend line is %d wide: %q", w, ansi.Strip(l))
}
}
m.CycleHelp()
if got := ansi.Strip(m.View()); !strings.Contains(got, "? help") {
t.Errorf("third ? must close the help:\n%q", got)
}
}
func TestHelpLeavesOutColumnsThatDontFit(t *testing.T) {
m := New(theme.Default(), testKeys{})
m.SetWidth(30)
m.CycleHelp()
got := ansi.Strip(m.View())
if !strings.Contains(got, "App") || strings.Contains(got, "Selected") || !strings.Contains(got, "…") {
t.Errorf("want App kept, the columns before it left out with an ellipsis:\n%s", got)
}
for _, l := range strings.Split(m.View(), "\n") {
if w := lipgloss.Width(l); w > 30 {
t.Errorf("line is %d wide: %q", w, ansi.Strip(l))
}
}
}
+2 -5
View File
@@ -72,16 +72,13 @@ func View(t theme.Theme, repo *submodule.Repo, fetch Fetch, spinner string, widt
if errored > 0 { if errored > 0 {
parts = append(parts, t.LevelStyle(submodule.LevelDanger, bar).Render(fmt.Sprintf("%d error", errored))) parts = append(parts, t.LevelStyle(submodule.LevelDanger, bar).Render(fmt.Sprintf("%d error", errored)))
} }
for _, k := range []submodule.IssueKind{ for _, k := range submodule.Kinds {
submodule.IssueUnpushed, submodule.IssueConflict, submodule.IssueMissing,
submodule.IssueOffPin, submodule.IssueChanged, submodule.IssueOffTarget,
} {
if n := perKind[k]; n > 0 { if n := perKind[k]; n > 0 {
parts = append(parts, t.LevelStyle(level[k], bar).Render(fmt.Sprintf("%d %s", n, theme.IssueWord(k)))) parts = append(parts, t.LevelStyle(level[k], bar).Render(fmt.Sprintf("%d %s", n, theme.IssueWord(k))))
} }
} }
if staged > 0 { if staged > 0 {
parts = append(parts, seg(t.Info, fmt.Sprintf("%d pin staged", staged))) parts = append(parts, seg(t.Info, fmt.Sprintf("%d %s", staged, theme.Staged)))
} }
if loading > 0 { if loading > 0 {
parts = append(parts, seg(t.Muted, fmt.Sprintf("%d loading", loading))) parts = append(parts, seg(t.Muted, fmt.Sprintf("%d loading", loading)))
+37 -14
View File
@@ -2,6 +2,8 @@ package tui
import ( import (
"github.com/charmbracelet/bubbles/key" "github.com/charmbracelet/bubbles/key"
"submarine/internal/tui/footer"
) )
type keyMap struct { type keyMap struct {
@@ -10,6 +12,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, Update key.Binding Copy, Restore, Switch, Update key.Binding
HardRestore key.Binding
Help, Quit, QuitUpdate key.Binding Help, Quit, QuitUpdate key.Binding
} }
@@ -30,7 +33,8 @@ func defaultKeys() keyMap {
Reload: key.NewBinding(key.WithKeys("r"), key.WithHelp("r", "reload")), Reload: key.NewBinding(key.WithKeys("r"), key.WithHelp("r", "reload")),
Filter: key.NewBinding(key.WithKeys("/"), key.WithHelp("/", "filter")), Filter: key.NewBinding(key.WithKeys("/"), key.WithHelp("/", "filter")),
Issues: key.NewBinding(key.WithKeys("!"), key.WithHelp("!", "problems only")), Issues: key.NewBinding(key.WithKeys("!"), key.WithHelp("!", "problems only")),
Restore: key.NewBinding(key.WithKeys("x"), key.WithHelp("x", "restore")), Restore: key.NewBinding(key.WithKeys("x"), key.WithHelp("x", "restore to pin")),
HardRestore: key.NewBinding(key.WithKeys("X"), key.WithHelp("X", "restore committed pins")),
Switch: key.NewBinding(key.WithKeys("b"), key.WithHelp("b", "switch branch")), Switch: key.NewBinding(key.WithKeys("b"), key.WithHelp("b", "switch branch")),
Update: key.NewBinding(key.WithKeys("u"), key.WithHelp("u", "update pin")), Update: key.NewBinding(key.WithKeys("u"), key.WithHelp("u", "update pin")),
Copy: key.NewBinding(key.WithKeys("c"), key.WithHelp("c", "copy path")), Copy: key.NewBinding(key.WithKeys("c"), key.WithHelp("c", "copy path")),
@@ -50,15 +54,20 @@ func (k *keyMap) SetUpdate(v string) {
// 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"))
fold := key.NewBinding(key.WithKeys("left"), key.WithHelp("←→/hl", "fold")) fold := key.NewBinding(key.WithKeys("left"), key.WithHelp("←→/hl", "collapse/expand"))
all := key.NewBinding(key.WithKeys("H"), key.WithHelp("⇧←→/HL", "fold all")) all := key.NewBinding(key.WithKeys("H"), key.WithHelp("⇧←→/HL", "all"))
return []key.Binding{move, fold, all, k.Toggle} return []key.Binding{move, fold, all, k.Toggle}
} }
// Tools returns the bindings that act on the whole list: problems only,
// filter and fetch, most useful first, since the footer drops them from the
// end. It shows them after the navigation keys.
func (k keyMap) Tools() []key.Binding { return []key.Binding{k.Issues, k.Filter, k.Fetch} }
// Submodule returns the bindings that act on the selected submodule. They // Submodule returns the bindings that act on the selected submodule. They
// are shown in the detail pane, or in the footer if the pane can't show them. // are shown in the detail pane, or in the footer if the pane can't show them.
func (k keyMap) Submodule() []key.Binding { func (k keyMap) Submodule() []key.Binding {
return []key.Binding{k.Copy, k.Update, k.Switch, k.Restore} return []key.Binding{k.Copy, k.Update, k.Switch, k.Restore, k.HardRestore}
} }
// Global returns the bindings that don't depend on the selection. // Global returns the bindings that don't depend on the selection.
@@ -81,17 +90,31 @@ func (k keyMap) Highlight() []key.Binding {
return []key.Binding{k.QuitUpdate} return []key.Binding{k.QuitUpdate}
} }
func (k keyMap) ShortHelp() []key.Binding { // forSelection returns the keys as they read for the selection: on the
return append(append(k.Navigation(), k.Submodule()...), k.Global()...) // superproject, u fast-forwards its branch (D29).
func (k keyMap) forSelection(root bool) keyMap {
if root {
k.Update.SetHelp("u", "pull (fast-forward)")
}
return k
} }
func (k keyMap) FullHelp() [][]key.Binding { // HelpGroups returns the columns of the full help, each with a title.
return [][]key.Binding{ func (k keyMap) HelpGroups() []footer.Group {
{k.Up, k.Down, k.Left, k.Right, k.Toggle}, help := key.NewBinding(key.WithKeys("?"), key.WithHelp("?", "what words mean"))
{k.CollapseAll, k.ExpandAll}, esc := key.NewBinding(key.WithKeys("esc"), key.WithHelp("esc", "close"))
{k.Home, k.End, k.PageUp, k.PageDown}, return []footer.Group{
{k.Copy, k.Update, k.Switch, k.Restore}, {Title: "Move", Keys: []key.Binding{k.Up, k.Down, k.Left, k.Right, k.Toggle, k.CollapseAll, k.ExpandAll}},
{k.Fetch, k.Reload, k.Filter, k.Issues}, {Title: "Jump", Keys: []key.Binding{k.Home, k.End, k.PageUp, k.PageDown}},
append([]key.Binding{k.Help, k.Quit}, k.fullUpdate()...), {Title: "Selected submodule", Keys: k.Submodule()},
{Title: "All submodules", Keys: []key.Binding{k.Fetch, k.Reload, k.Filter, k.Issues}},
{Title: "App", Keys: append([]key.Binding{help, esc, k.Quit}, k.fullUpdate()...)},
} }
} }
// LegendKeys returns the column next to the legend, the help's last page;
// ? closes it too, but esc is the key to tell.
func (k keyMap) LegendKeys() footer.Group {
esc := key.NewBinding(key.WithKeys("esc"), key.WithHelp("esc", "close"))
return footer.Group{Title: "App", Keys: append([]key.Binding{esc, k.Quit}, k.fullUpdate()...)}
}
+16
View File
@@ -0,0 +1,16 @@
package tui
import "testing"
func TestUpdateReadsPullOnTheSuperproject(t *testing.T) {
k := defaultKeys()
if got := k.forSelection(true).Update.Help().Desc; got != "pull (fast-forward)" {
t.Errorf("superproject: u reads %q", got)
}
if got := k.forSelection(false).Update.Help().Desc; got != "update pin" {
t.Errorf("submodule: u reads %q", got)
}
if got := k.Update.Help().Desc; got != "update pin" {
t.Errorf("forSelection changed the key map: u reads %q", got)
}
}
+15 -7
View File
@@ -47,8 +47,9 @@ type restoreDoneMsg struct {
// startRestore checks what restoring the selection would discard. If nothing // startRestore checks what restoring the selection would discard. If nothing
// would be lost it restores at once, else it asks first. A submodule with a // would be lost it restores at once, else it asks first. A submodule with a
// staged pin first asks which pin to restore to. // staged pin first asks which pin to restore to; a hard restore doesn't: it
func (m Model) startRestore() (tea.Model, tea.Cmd) { // goes to the committed pins, at every depth.
func (m Model) startRestore(hard bool) (tea.Model, tea.Cmd) {
s := m.tree.Selected() s := m.tree.Selected()
_, ok := m.provider.(submodule.Restorer) _, ok := m.provider.(submodule.Restorer)
var flash string var flash string
@@ -67,6 +68,10 @@ func (m Model) startRestore() (tea.Model, tea.Cmd) {
} }
m.restore = &restoreState{path: s.Path, name: restoreName(s)} m.restore = &restoreState{path: s.Path, name: restoreName(s)}
if hard {
m.restore.to = submodule.RestoreHard
return m.checkRestore()
}
if !s.IsRoot() && s.Status != nil && s.Status.PinStaged { if !s.IsRoot() && s.Status != nil && s.Status.PinStaged {
m.restore.phase = restoreChoosing m.restore.phase = restoreChoosing
m.layout() m.layout()
@@ -199,13 +204,16 @@ func (m Model) restoreDone(msg restoreDoneMsg) (tea.Model, tea.Cmd) {
return m, tea.Batch(cmds...) return m, tea.Batch(cmds...)
} }
// toText is " to origin/feat" for a switch, " to the committed pin" if that was chosen; the staged pin is the // toText is " to origin/feat" for a switch, " to the committed pin" if that
// usual target and needs no words. // was chosen, " to the committed pins" for a hard restore; the staged pin is
// the usual target and needs no words.
func (r *restoreState) toText() string { func (r *restoreState) toText() string {
if r.branch != nil { switch {
case r.branch != nil:
return " to " + r.branch.Name return " to " + r.branch.Name
} case r.to == submodule.RestoreHard:
if r.to == submodule.RestoreCommitted { return " to the committed pins"
case r.to == submodule.RestoreCommitted:
return " to the committed pin" return " to the committed pin"
} }
return "" return ""
+52
View File
@@ -3,6 +3,7 @@ package tui
import ( import (
"context" "context"
"os" "os"
"strings"
"testing" "testing"
tea "github.com/charmbracelet/bubbletea" tea "github.com/charmbracelet/bubbletea"
@@ -187,3 +188,54 @@ func TestRestoreOfAStagedPinAsksWhichPin(t *testing.T) {
t.Fatalf("restored %q to %v, want %s to the committed pin", f.restored, f.to, staged.Path) t.Fatalf("restored %q to %v, want %s to the committed pin", f.restored, f.to, staged.Path)
} }
} }
func TestHardRestoreAsksToDropStagedPins(t *testing.T) {
m, f := newRestoreModel(t, submodule.Loss{StagedPins: 2, Modules: 2})
mm := m.(Model)
var staged *submodule.Submodule
submodule.Walk(mm.repo.Submodules, func(s *submodule.Submodule) {
if staged == nil && s.Children == nil {
staged = s
}
})
staged.Status = &submodule.Status{PinStaged: true, Pin: submodule.PinInfo{Pushed: true}}
mm.tree.Select(staged.Path)
m = mm
// not which pin, but y/n: staged pins alone are a reason to ask
m, cmd := press(m, "X")
for _, msg := range run(cmd) {
if l, ok := msg.(lossMsg); ok {
m, _ = m.Update(l)
}
}
r := m.(Model).restore
if r == nil || r.phase != restoreAsking {
t.Fatalf("want a question, got %+v", r)
}
if got := lossText(r.loss); got != "2 staged pins" {
t.Errorf("question lists %q, want the staged pins", got)
}
m, cmd = press(m, "y")
feed(m, cmd)
if len(f.to) != 1 || f.to[0] != submodule.RestoreHard || f.restored[0] != staged.Path {
t.Fatalf("restored %q to %v, want %s hard", f.restored, f.to, staged.Path)
}
}
func TestHardRestoreAsksWhenWorkIsLost(t *testing.T) {
m, _ := newRestoreModel(t, submodule.Loss{Files: 1, StagedPins: 1, Modules: 1})
m, cmd := press(m, "X")
for _, msg := range run(cmd) {
if l, ok := msg.(lossMsg); ok {
m, _ = m.Update(l)
}
}
r := m.(Model).restore
if r == nil || r.phase != restoreAsking {
t.Fatalf("want a question, got %+v", r)
}
if got := lossText(r.loss); !strings.Contains(got, "1 staged pin") {
t.Errorf("question %q doesn't list the staged pin", got)
}
}
+62
View File
@@ -0,0 +1,62 @@
package theme
import "submarine/internal/submodule"
// LegendRow is one word or symbol of the UI, rendered as it appears, and
// what it means.
type LegendRow struct{ Word, Meaning string }
// LegendGroup is a titled column of the legend.
type LegendGroup struct {
Title string
Rows []LegendRow
}
// issueMeaning explains an issue word in a few plain words.
func issueMeaning(k submodule.IssueKind) string {
switch k {
case submodule.IssueUnpushed:
return "pin is on no remote"
case submodule.IssueConflict:
return "merge conflict"
case submodule.IssueMissing:
return "not checked out"
case submodule.IssueOffPin:
return "checkout is not the pin"
case submodule.IssueChanged:
return "uncommitted files"
default:
return "pin not on target branch"
}
}
// Legend explains the words and symbols of the tree and the detail pane, in
// their colors: what the full help's second page shows.
func (t Theme) Legend() []LegendGroup {
g := t.Glyphs
muted := Fg(t.Muted)
status := LegendGroup{Title: "Status"}
for _, k := range submodule.Kinds {
status.Rows = append(status.Rows, LegendRow{t.LevelStyle(k.Level(), Fg(t.Text)).Render(IssueWord(k)), issueMeaning(k)})
}
status.Rows = append(status.Rows,
LegendRow{Fg(t.Info).Render(Staged), "new pin, not committed"},
LegendRow{muted.Render(InSync), "nothing to do"},
)
symbols := LegendGroup{Title: "Symbols", Rows: []LegendRow{
{Fg(t.Info).Render(g.Staged), "pin staged in parent"},
{muted.Render(g.Ahead + "n " + g.Behind + "n"), "ahead / behind the ref"},
{muted.Render("+n"), "n more issues"},
{Fg(t.Warn).Render(g.Problems + "k"), "issues below, collapsed"},
{muted.Render("[n]"), "children, collapsed"},
}}
commits := LegendGroup{Title: "Commits", Rows: []LegendRow{
{muted.Render(RoleWord(submodule.RolePin, "")), "what the parent records"},
{Fg(t.Text).Bold(true).Render(RoleWord(submodule.RoleYou, "")), "the checkout"},
{muted.Render(RoleWord(submodule.RoleTip, "")), "newest on the ref"},
{muted.Render("main"), "tip of target branch"},
{muted.Render(RoleWord(submodule.RoleBase, "")), "where lines split"},
{muted.Render(RoleWord(submodule.RoleHead, "")), "superproject checkout"},
}}
return []LegendGroup{status, symbols, commits}
}
+42
View File
@@ -66,3 +66,45 @@ func TestQuitAndUpdate(t *testing.T) {
t.Errorf("ctrl+c must quit without updating, got update to %q", m2.(Model).UpdateTo()) t.Errorf("ctrl+c must quit without updating, got update to %q", m2.(Model).UpdateTo())
} }
} }
func TestHintUntilTheFirstKey(t *testing.T) {
m := newUpdateModel("")
if !m.(Model).extraLine() || !strings.Contains(m.View(), "new here?") {
t.Fatal("no hint on start")
}
m, _ = press(m, "j")
if m.(Model).extraLine() || strings.Contains(m.View(), "new here?") {
t.Error("the hint must go away with the first key")
}
}
func TestEscClosesTheHelp(t *testing.T) {
for _, presses := range []int{1, 2} { // the keys page, the legend
m := newUpdateModel("")
for range presses {
m, _ = press(m, "?")
}
if !m.(Model).footer.HelpOpen() {
t.Fatalf("%d × ?: no help", presses)
}
m, _ = pressKey(m, tea.KeyEsc)
if m.(Model).footer.HelpOpen() {
t.Errorf("%d × ?: esc must close the help", presses)
}
}
}
func TestEscClosesTheHelpBeforeTheFilter(t *testing.T) {
m := newUpdateModel("")
m, _ = press(m, "/")
m, _ = pressKey(m, tea.KeyEnter) // keys back to the tree, the filter stays
m, _ = press(m, "?")
m, _ = pressKey(m, tea.KeyEsc)
if mm := m.(Model); mm.footer.HelpOpen() || !mm.filtering {
t.Errorf("first esc: help open %v, filtering %v; want the help closed, the filter kept", mm.footer.HelpOpen(), mm.filtering)
}
m, _ = pressKey(m, tea.KeyEsc)
if m.(Model).filtering {
t.Error("second esc must close the filter")
}
}
+12 -10
View File
@@ -1,5 +1,5 @@
// Package update implements self-update from the Gitea generic package // Package update implements self-update from GitHub release assets. It has no
// registry. It has no UI imports; the network is only used on explicit calls. // UI imports; the network is only used on explicit calls.
package update package update
import ( import (
@@ -19,16 +19,18 @@ import (
"time" "time"
) )
// DefaultBaseURL is the registry root; see docs/architecture.md#distribution. // DefaultBaseURL is the releases root; see docs/architecture.md#distribution.
const DefaultBaseURL = "https://git.simon-franken.de/api/packages/simonfranken/generic" // Both paths below it are plain redirects to the assets, not API calls, so
// they are not rate limited.
const DefaultBaseURL = "https://github.com/simonfranken/submarine/releases"
// EnvBaseURL overrides the registry root (tests, manual verification). // EnvBaseURL overrides the releases root (tests, manual verification).
const EnvBaseURL = "SUBMARINE_UPDATE_URL" const EnvBaseURL = "SUBMARINE_UPDATE_URL"
// maxBinary bounds a download so a bad server cannot fill the disk. // maxBinary bounds a download so a bad server cannot fill the disk.
const maxBinary = 256 << 20 const maxBinary = 256 << 20
// Client talks to the registry. // Client talks to the releases.
type Client struct { type Client struct {
BaseURL string BaseURL string
HTTP *http.Client HTTP *http.Client
@@ -36,7 +38,7 @@ type Client struct {
GOARCH string GOARCH string
} }
// New returns a client for the default (or $SUBMARINE_UPDATE_URL) registry. // New returns a client for the default (or $SUBMARINE_UPDATE_URL) releases.
func New() *Client { func New() *Client {
base := os.Getenv(EnvBaseURL) base := os.Getenv(EnvBaseURL)
if base == "" { if base == "" {
@@ -52,13 +54,13 @@ func New() *Client {
// Latest returns the newest released version, e.g. "v0.2.0". // Latest returns the newest released version, e.g. "v0.2.0".
func (c *Client) Latest(ctx context.Context) (string, error) { func (c *Client) Latest(ctx context.Context) (string, error) {
b, err := c.get(ctx, c.BaseURL+"/submarine-latest/latest/VERSION", 1<<10) b, err := c.get(ctx, c.BaseURL+"/latest/download/VERSION", 1<<10)
if err != nil { if err != nil {
return "", err return "", err
} }
v := strings.TrimSpace(string(b)) v := strings.TrimSpace(string(b))
if _, ok := parse(v); !ok { if _, ok := parse(v); !ok {
return "", fmt.Errorf("registry returned an invalid version %q", v) return "", fmt.Errorf("releases returned an invalid version %q", v)
} }
return v, nil return v, nil
} }
@@ -120,7 +122,7 @@ func (c *Client) Install(ctx context.Context, version string) (string, error) {
// InstallTo is Install with an explicit target path. // InstallTo is Install with an explicit target path.
func (c *Client) InstallTo(ctx context.Context, version, target string) error { func (c *Client) InstallTo(ctx context.Context, version, target string) error {
asset := fmt.Sprintf("submarine_%s_%s", c.GOOS, c.GOARCH) asset := fmt.Sprintf("submarine_%s_%s", c.GOOS, c.GOARCH)
base := c.BaseURL + "/submarine/" + version + "/" base := c.BaseURL + "/download/" + version + "/"
sums, err := c.get(ctx, base+"checksums.txt", 1<<20) sums, err := c.get(ctx, base+"checksums.txt", 1<<20)
if err != nil { if err != nil {
+12 -3
View File
@@ -32,16 +32,25 @@ func TestNewer(t *testing.T) {
} }
} }
// registry mimics GitHub releases: every asset URL redirects to storage.
func registry(t *testing.T, bin, sum string) *Client { func registry(t *testing.T, bin, sum string) *Client {
t.Helper() t.Helper()
mux := http.NewServeMux() mux := http.NewServeMux()
mux.HandleFunc("/submarine-latest/latest/VERSION", func(w http.ResponseWriter, _ *http.Request) { redirect := func(from, to string) {
mux.HandleFunc(from, func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, to, http.StatusFound)
})
}
redirect("/latest/download/VERSION", "/assets/VERSION")
redirect("/download/v0.2.0/checksums.txt", "/assets/checksums.txt")
redirect("/download/v0.2.0/submarine_linux_arm64", "/assets/submarine_linux_arm64")
mux.HandleFunc("/assets/VERSION", func(w http.ResponseWriter, _ *http.Request) {
w.Write([]byte("v0.2.0\n")) w.Write([]byte("v0.2.0\n"))
}) })
mux.HandleFunc("/submarine/v0.2.0/checksums.txt", func(w http.ResponseWriter, _ *http.Request) { mux.HandleFunc("/assets/checksums.txt", func(w http.ResponseWriter, _ *http.Request) {
w.Write([]byte(sum + " submarine_linux_arm64\n")) w.Write([]byte(sum + " submarine_linux_arm64\n"))
}) })
mux.HandleFunc("/submarine/v0.2.0/submarine_linux_arm64", func(w http.ResponseWriter, _ *http.Request) { mux.HandleFunc("/assets/submarine_linux_arm64", func(w http.ResponseWriter, _ *http.Request) {
w.Write([]byte(bin)) w.Write([]byte(bin))
}) })
srv := httptest.NewServer(mux) srv := httptest.NewServer(mux)
+240
View File
@@ -0,0 +1,240 @@
# Usability plan (draft)
**Status:** items 1–8 and 11 are done ([D31](../docs/decisions.md),
[D32](../docs/decisions.md)); the rest is a proposal. Items that change
behavior need a decision in [decisions.md](../docs/decisions.md) and
updates to [ux-guide.md](../docs/ux-guide.md) /
[actions.md](../docs/actions.md) when they are taken up.
Done differently than proposed below: the labels are `x restore to pin` and
`X restore committed pins`; the tools read `! problems only • / filter • f
fetch` (most useful first, dropped from the end); `space toggle` stays, as
it now follows `←→/hl collapse/expand`.
## Goal
The target user is a developer who doesn't know git submodules well. They
should understand the screen and act safely **without reading a manual**.
At any moment the screen should answer three questions:
1. **What is wrong?** What does this state mean, in plain words?
2. **What can I do about it?** Which key fixes it?
3. **What will this key do?** What happens to my work, and can I undo it?
Today the tool answers (1) partly (the issue lines in the detail pane) and
(3) well *after* a key is pressed (loss question, flash). It hardly answers
(2), and it answers (3) only by trying. Most items below move the answers
from "after pressing" to "before pressing".
## Findings this is based on
From a walkthrough on the `make-fixture.sh` superproject (2026-10-24):
- `x restore` and `X hard restore` don't say the target ("to the pin"), the
scope (the submodule and everything below it) or how they differ. "Hard"
suggests "discards my changes", but both do that. The real difference,
staged pins, can't be guessed.
- `X` drops a staged pin without asking (`restored libs/staged to the
committed pins`), one Shift away from `x`.
- `f` fetch, `/` filter and `!` problems only appear only in `?`. The detail
pane says `fetched never` but gives no hint how to fetch. `!` is the most
useful view for many submodules, and nothing points to it.
- The words in the tree (`off pin`, `off target`, `staged`, `●`, `·1`, `↓2`)
and on the spine (`pin`, `tip`, `you`, `base`) are explained nowhere in
the UI.
- `u update pin` on the superproject actually fast-forwards the current
branch; the label stays the same.
- The palette is static: `u` is offered when it can't do anything, and the
user finds out from a flash.
- Mismatched words: the footer says "fold", the help "collapse/expand";
`space toggle` doesn't say what it toggles.
- Good, and worth keeping: questions only when something would be lost, the
loss listed exactly, flashes that say why and suggest another key.
## Overview
Effort: **S** = hours, mostly labels and docs; **M** = a day or two, new
logic in existing components; **L** = several days, new UI or new provider
calls.
Impact: how much it helps the target user's main flows (*understand state*,
*fix a submodule*, *find problems*, *stay safe*).
| # | Item | Effort | Impact | Flow |
|---|---|---|---|---|
| 1 ✓ | Clear names for restore and hard restore | S | High | fix, safe |
| 2 ✓ | Ask before `X` drops staged pins | S | High | safe |
| 3 ✓ | Show `/`, `!`, `f` in the footer | S | High | find |
| 4 ✓ | Status legend in `?` | S–M | High | understand |
| 5 ✓ | Groups with titles in the full help | S | Medium | understand |
| 6 ✓ | Plain-word fixes for wording | S | Low | understand |
| 7 ✓ | `u` label for the superproject | S | Medium | fix |
| 8 ✓ | Fetch hint at `fetched never` / old fetches | S | Medium | understand |
| 9 | Next step for each issue in the detail pane | M | **Highest** | understand, fix |
| 10 | Palette that fits the selection | M | High | fix |
| 11 ✓ | First-start hint | S | Medium | understand |
| 12 | Undo hint after a restore, switch or update | M | Medium | safe |
| 13 | Action menu on `enter` | M–L | High | fix, understand |
| 14 | "What would happen" preview | L | Medium | safe |
Quick view by quadrant:
| | **Low effort** | **Medium effort** | **High effort** |
|---|---|---|---|
| **High impact** | 1, 2, 3, 4 | 9, 10, 13 | |
| **Medium impact** | 5, 7, 8, 11 | 12 | 14 |
| **Low impact** | 6 | | |
## Items
### Low effort
**1. Clear names for restore and hard restore.** *S · High*
The labels should give target and difference without the docs.
Proposal: `x restore to pin`, `X restore, unstage pins`. In the full help,
longer: `x restore to pin (with everything below)`, `X restore to committed
pins, drop staged ones`. The question lines already use "to the committed
pins"; keep the same words everywhere.
Alternative: rename the action to "reset". Rejected for now: `git reset`
moves branches, which restore never does (D23).
Docs: ux-guide key reference, actions.md "Keys and palette", README.
**2. Ask before `X` drops staged pins.** *S · High*
Amends D30 ("alone they don't make it ask"). A staged pin is a decision
the user made, and `X` sits next to `x`. If `X` would drop at least one
staged pin, ask: `Restore src/app to the committed pins? Unstages 2 pins.
y restore · n cancel`. The loss is already counted, so only the trigger
changes. D30's argument (the commit stays in the submodule) holds for an
expert, not for someone who doesn't know where to find it again.
**3. Show `/`, `!`, `f` in the footer.** *S · High*
Proposal: `/ filter • ! problems • f fetch` after the navigation keys,
before the global keys. The existing rule drops keys from the left group's
end when the footer is too narrow, so narrow terminals lose them first and
nothing else changes. While problems only is on, the footer could read
`! all` (the action the key does now). `r reload` stays in `?`.
**4. Status legend in `?`.** *S–M · High*
The full help gets a second block, "What the words mean", with one line per
status word and symbol, using the same colors as the tree:
`off pin the checkout is not the commit the parent records`, `staged`,
`●`, `↑n ↓n`, `·k`, and the spine roles (`pin`, `tip`, `you`, `base`,
target). Wording comes from state-model.md; the explanations the detail
pane already uses are a good source. Layout: below the key columns if there
is room, otherwise `?` pages between keys and legend (`? more`).
**5. Groups with titles in the full help.** *S · Medium*
The help columns are already grouped, but without titles. Add short titles
on top: `Move`, `Selected submodule`, `All repositories`, `App`. Then it is
clear that `x` acts on the selection and `f` on everything.
**6. Plain-word fixes.** *S · Low*
- Footer `fold` → `collapse/expand`; `⇧←→/HL fold all` → `H/L all`.
- `space toggle` → `space open/close`.
- `c copy path` → say which path (`copy path` is fine if it is the
relative path; check).
- Header `pin staged` vs tree `staged`: one word.
**7. `u` label for the superproject.** *S · Medium*
With the header selected the palette says `u pull (fast-forward)`, since
that is what it does (D29). Labels that change with the selection need
item 10's mechanism, but this one is simple on its own: one check for the
header.
**8. Fetch hint.** *S · Medium*
`fetched never` (and an age above a threshold, e.g. a day) gets a muted
`· f fetches`. Users who don't know that the arrows (`↓2`) are only as fresh
as the last fetch otherwise trust old numbers.
**11. First-start hint.** *S · Medium*
On start, the footer's flash line shows `? explains keys and states` until
the first key. No config file, no state: it is shown every start, and it is
just a muted line. Makes item 4 discoverable.
### Medium effort
**9. Next step for each issue in the detail pane.** *M · Highest*
Each issue line ends with what to do about it, as keys:
```
off pin checkout is not the pin x back to pin · b record a branch
changed 3 files changed commit outside, or x discard
missing not initialized x restore
off target pin is not on origin/main b switch branch
```
A pin that is only behind (`↓2`, no issue) gets the same kind of hint on
its `Ref` line: `u update pin`.
This is the single biggest step for the target user: they no longer need to
know what to do, only to read. Layering: which action resolves which issue
is meaning, not looks, so it belongs in `internal/submodule` (e.g. a
`Remedies()` on the issue, returning action kinds) and the words in
`theme`. It must agree with what the actions really allow (e.g. `u` only
when behind and not ahead, D29), which item 10 needs anyway.
**10. Palette that fits the selection.** *M · High*
Amends actions.md ("the palette is static"). The palette keeps the same keys
in the same places (muscle memory), but:
- keys that can't do anything for the selection are drawn muted (`u` when
up to date, `b` on a missing submodule); pressing them still flashes why;
- the key that item 9 recommends for the most severe issue is highlighted.
The checks for `u` already exist as flash reasons; they are cheap and need
only the status, so this is a matter of calling them for the palette too.
Restore stays always active (it is idempotent).
**12. Undo hint after a restore, switch or update.** *M · Medium*
The success flash names the old commit when a repository moved:
`restored src/app (was 1a2b3c4)`. A flash only lasts a moment, so the detail
pane could keep `previous 1a2b3c4` until the next reload. For a user who
doesn't know `git reflog`, this is the difference between "lost" and
"recoverable". No new provider call if the SHA is taken before the action.
**13. Action menu on `enter`.** *M–L · High*
`enter` on a row opens a small popup (reusing the branch popup's frame)
listing the actions for this submodule, each with one line of explanation
and its key; the recommended one first and selected. `enter` runs it, `esc`
closes. Users who know the keys never need it; users who don't need no
memory at all. `enter` is unused in the tree today.
### High effort
**14. "What would happen" preview.** *L · Medium*
In the action menu (13), the selected entry shows the effect before
running it: `moves the pin e510d9b → 906f119 (2 commits)`, `discards 3
changed files`. The loss check exists, but it is async git work, so it runs
when the entry is selected, with a spinner. Valuable, but the loss question
already covers the dangerous cases, so this comes last.
## Order
1. **Labels and safety** (1, 2, 3, 5, 6, 7): only labels, docs and one
question trigger. Fixes the worst risk (`X`) and the hidden keys at once.
2. **Explain the screen** (4, 8, 11): the legend and the hints that point
to it.
3. **Guide to the fix** (9, 10): issue → key, and a palette that agrees.
Needs a decision on where remedies live (layering).
4. **Menus and previews** (12, 13, 14).
## How to check
Give someone who hasn't used submarine the fixture (`make-fixture.sh`) and
these tasks, without the docs:
- Find every submodule that needs attention.
- Get `ui` up to date with its branch.
- Put `core` back where the superproject wants it.
- Find out whether the arrows are current.
- Explain what `staged` on `libs/staged` means.
Note keys tried, wrong actions and questions asked. Run it before phase 1
and after each phase.
## Open questions
- Item 1: are "restore to pin" / "restore, unstage pins" the right words, or
should `X` move under a different key that is not one Shift away?
- Item 2: ask for every dropped staged pin, or only for the selection's own?
- Item 9: are external actions (`commit outside submarine`) good hints, or
only keys?
- Item 13: does `enter` stay free for something else (e.g. opening a shell
in the submodule)?