From 620f9f63e2d3c00cd41a4f9e95a7943f13237f51 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Corn=C3=A9=20Dorrestijn?= Date: Wed, 18 Nov 2026 10:37:29 +0100 Subject: [PATCH 1/2] feat(vcs): work in jj repositories Read branches, checkouts, commits and time from jj where a repo has a .jj: bookmarks are branches, workspaces worktrees. Start work makes a jj workspace itself unless multiplexer.jj_workspaces says the multiplexer does (drover). jj runs no git hooks, so laneway hook check does commit-msg's work. --- .github/workflows/ci.yml | 5 + completion.go | 4 +- docs/guide/06-work-on-an-issue.md | 7 + docs/reference/cli.md | 9 + docs/reference/config.md | 25 +- hook.go | 69 +++- hook_test.go | 36 ++ internal/config/config.go | 4 + internal/herdr/herdr.go | 46 ++- internal/i18n/nl/go-rest.json | 12 +- internal/i18n/nl/ui-dev.json | 1 - internal/ui/agents.go | 8 +- internal/ui/branch.go | 13 +- internal/ui/jira_work.go | 46 ++- internal/ui/mr_agent.go | 16 +- internal/ui/options.go | 2 + internal/ui/prompt.go | 7 +- internal/ui/pull_request.go | 5 +- internal/ui/pull_request_test.go | 4 + internal/ui/worktree.go | 82 ++--- internal/vcs/vcs.go | 574 ++++++++++++++++++++++++++++++ internal/vcs/vcs_test.go | 178 +++++++++ internal/vcs/vcstest/vcstest.go | 55 +++ internal/web/api_agents.go | 11 +- internal/web/api_agents_test.go | 79 +++- internal/web/api_agents_work.go | 107 +++--- internal/work/work.go | 39 +- internal/work/work_test.go | 28 ++ 28 files changed, 1298 insertions(+), 174 deletions(-) create mode 100644 internal/vcs/vcs.go create mode 100644 internal/vcs/vcs_test.go create mode 100644 internal/vcs/vcstest/vcstest.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f9abfae1..13e5e591 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,6 +26,11 @@ jobs: - name: tmux, for e2e/tui if: runner.os == 'Linux' run: command -v tmux || (sudo apt-get update && sudo apt-get install -y tmux) + - name: jj, for the jj repository tests + if: runner.os == 'Linux' + run: | + curl -fsSL https://github.com/jj-vcs/jj/releases/download/v0.46.0/jj-v0.46.0-x86_64-unknown-linux-musl.tar.gz | sudo tar xz -C /usr/local/bin ./jj + jj --version - run: go build ./... - run: go vet ./... - run: go test -race ./... diff --git a/completion.go b/completion.go index 1dc4f44d..d5eef497 100644 --- a/completion.go +++ b/completion.go @@ -51,7 +51,7 @@ var commandFlags = map[string][]string{ "create": {"-config", "-site", "-format", "-project", "-type", "-summary", "-description"}, "move": {"-config", "-site"}, "prompt": {"-config", "-site", "-format"}, - "hook": {"-config", "-site", "-strict", "-force"}, + "hook": {"-config", "-site", "-strict", "-force", "-fix"}, "rules": {"-config", "-site", "-on", "-key", "-summary", "-type", "-status", "-from-status", "-assignee", "-priority", "-points", "-watch", "-by-me"}, "setup": {"-config", "-site"}, "login": {"-config", "-site", "-device"}, @@ -62,7 +62,7 @@ var commandFlags = map[string][]string{ } var commandArgs = map[string][]string{ - "hook": {"install"}, + "hook": {"install", "check"}, "index": {"clear"}, "rules": {"list", "test", "watch"}, "token": {"list", "create", "revoke", "revoke-all"}, diff --git a/docs/guide/06-work-on-an-issue.md b/docs/guide/06-work-on-an-issue.md index 8745e16d..88544a70 100644 --- a/docs/guide/06-work-on-an-issue.md +++ b/docs/guide/06-work-on-an-issue.md @@ -39,6 +39,9 @@ refuses the commit; merges, reverts and fixups pass. `-strict` also refuses keys Jira doesn't know. Checking out an issue's branch while it's still to do asks `move ABC-12 (To Do) to In Progress? [y/N]`. +jj runs no git hooks: there, `laneway hook check -fix` before you push puts +the bookmark's key in front of your branch's changes that name no issue. + ## Start work with an agent: `S` With [herdr](https://herdr.dev) running, `S` on an issue starts work: the @@ -127,6 +130,10 @@ search `pr:open` finds the ones with an open one. Once it's merged, *Remove its worktree* in the same actions removes the checkout. Uncommitted changes keep it; the branch stays. +In a [jj](https://jj-vcs.github.io/jj/) repository the worktree is a jj +workspace and the branch a bookmark; [jj in the config +reference](../reference/config.md#jj) has the details. + ## Review a merge request The merge requests waiting on you on every GitLab you're signed in to diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 43d0f36a..77f5b450 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -77,6 +77,7 @@ it names the server's own page, which can. | `laneway prompt [-format TEMPLATE]` | the git branch's issue, its status, the timer and the inbox count: `ABC-12 · In review · ⏱ 1h 20m · ✉ 3`. Reads the state file only, never Jira; a Go template over `.Key .Status .TimerKey .Timer .Inbox` | | `laneway completion bash\|zsh\|fish` | a completion script: commands, flags, site names and, for `view` and `move`, the keys on the boards last loaded | | `laneway hook install [-strict] [-force]` | git hooks in this repository, see below | +| `laneway hook check [-fix] [-strict]` | in a jj repository: the issue keys of your branch's changes, see below | | `laneway index [clear]` | what the local index holds; `clear` drops it | ```sh @@ -110,6 +111,14 @@ set -g status-right '#(laneway prompt -format "{{.Key}} {{.Timer}}")' A hook that isn't laneway's is kept unless `-force`; the hooks do nothing where laneway isn't installed. +[jj](https://jj-vcs.github.io/jj/) runs no git hooks, so in a jj repository +`install` says so and installs nothing. `laneway hook check` does +`commit-msg`'s work there, for the changes of your branch (trunk to `@`) at +once, before you push: it lists those whose description names no issue and +fails, `-fix` puts the bookmark's key in front of them (`jj describe`), and +`-strict` refuses keys Jira doesn't know. Changes without a description are +left alone; jj won't push them anyway. + ## Rules | Command | | diff --git a/docs/reference/config.md b/docs/reference/config.md index a85b3520..3b3b783a 100644 --- a/docs/reference/config.md +++ b/docs/reference/config.md @@ -209,7 +209,7 @@ ui: | `work_args` | | its arguments before the prompt; `{key}` is replaced | | `work_create` | | the command that makes a missing worktree (`{branch} {base} {key}`); unset: herdr | | `agent_view` | `fullscreen` | `panel` attaches an agent in the panel. Terminal | -| `multiplexer` | herdr | another multiplexer speaking herdr's socket API and CLI: `command` (its CLI), `socket` (its API socket), `inside_env` (the variable it sets in its panes) | +| `multiplexer` | herdr | another multiplexer speaking herdr's socket API and CLI: `command` (its CLI), `socket` (its API socket), `inside_env` (the variable it sets in its panes), `jj_workspaces: true` when its worktree calls make and remove jj workspaces itself ([drover](#jj)) | | `llm` | `claude -p` when on the PATH | the ask command: the question last, the issue on stdin (`llm`, `ollama run llama3`) | | `actions` | | your own commands on an issue, see [Actions](#actions) | @@ -219,6 +219,29 @@ ui: work_create: [wt, switch, --create, "{branch}", --base, "{base}", --no-cd] ``` +#### jj + +A repository with a `.jj` (colocated with git or not) is read through jj: +bookmarks are its branches, workspaces its worktrees, `trunk()`'s remote +bookmark (`main@origin`) the base. The branch you're on is the bookmark on +`@` or its nearest ancestor, trunk's not counting. Start work makes a jj +workspace beside the repository (`../repo.issue-ABC-1-fix`) with a +bookmark at the base when the branch is new, and opens it as a plain +workspace; herdr's own worktrees are git's. `work_create` is a git command +and isn't run there. A multiplexer that does jj workspaces itself takes over +with `jj_workspaces`: + +```yaml +ui: + multiplexer: {command: drover, jj_workspaces: true} +``` + +Removing a done issue's workspace keeps it while its working copy has +changes or any change in it isn't in the base, a commit past the bookmark +too. A pull request pushes the bookmark where it is +(`jj git push -b`): move it onto your work first. Time proposals take +jj's record of your edits per change instead of git's branch switches. + ### Planning, roadmap and charts | Option | Default | | diff --git a/hook.go b/hook.go index 922d763a..6d95dc41 100644 --- a/hook.go +++ b/hook.go @@ -18,6 +18,7 @@ import ( "github.com/cornedor/laneway/internal/i18n" "github.com/cornedor/laneway/internal/jira" "github.com/cornedor/laneway/internal/ui" + "github.com/cornedor/laneway/internal/vcs" ) var hookUsage = i18n.N(`usage: laneway hook install [-strict] [-force] @@ -29,7 +30,15 @@ Installs two git hooks in the repository you are in: keys Jira doesn't know. post-checkout checking out an issue's branch while the issue is still to do asks to move it in progress. -An existing hook that isn't laneway's is kept unless -force.`) +An existing hook that isn't laneway's is kept unless -force. + +jj runs no git hooks. In a jj repository install says so, and + + laneway hook check [-fix] [-strict] + +does commit-msg's work for the changes of your branch (trunk to @) at +once, before you push: it lists those whose description names no issue +key, and -fix puts the bookmark's key in front of them.`) // hookMark tells laneway's hooks from others. const hookMark = "# laneway hook" @@ -50,12 +59,19 @@ func hookCmd(args []string, out, errOut io.Writer) int { site := fs.String("site", "", i18n.T("Jira site from the config's sites:")) strict := fs.Bool("strict", false, i18n.T("commit-msg: refuse keys Jira doesn't know")) force := fs.Bool("force", false, i18n.T("install: replace hooks that aren't laneway's")) + fix := fs.Bool("fix", false, i18n.T("check: put the bookmark's key in front of the changes without one")) if err := fs.Parse(args[1:]); err != nil { return 2 } switch args[0] { case "install": + if vcs.IsJJ(".") { + fmt.Fprintln(errOut, "laneway hook install:", i18n.T("jj runs no git hooks: run laneway hook check (-fix) before you push")) + return 1 + } return hookInstall(*strict, *force, *cfgPath, *site, out, errOut) + case "check": + return hookCheck(*fix, *strict, *cfgPath, *site, out, errOut) case "commit-msg": if fs.NArg() != 1 { fmt.Fprintln(errOut, "laneway hook commit-msg:", i18n.T("the message file, as git passes it")) @@ -224,6 +240,57 @@ func siteClient(cfgPath, site string) (*jira.Client, error) { return jira.New(jira.Config{BaseURL: cfg.Jira.BaseURL, Email: cfg.Jira.Email, APIToken: cfg.Jira.APIToken, SignIn: cfg.Jira.Credentials(), Timeout: 10 * time.Second}), nil } +// hookCheck is commit-msg for a jj branch's changes: those without an +// issue key get the bookmark's with fix, else they are listed and it +// fails. strict also refuses keys Jira doesn't know. +func hookCheck(fix, strict bool, cfgPath, site string, out, errOut io.Writer) int { + if !vcs.IsJJ(".") { + fmt.Fprintln(errOut, "laneway hook check:", i18n.T("not in a jj repository: in git, laneway hook install checks every commit")) + return 1 + } + ctx := context.Background() + changes, err := vcs.BranchChanges(ctx, ".") + if err != nil { + fmt.Fprintln(errOut, "laneway hook check:", err) + return 1 + } + branchKey, code := ui.BranchIssue(), 0 + var keys []string + for _, c := range changes { + if strings.TrimSpace(c.Description) == "" { + continue // jj won't push it before you describe it + } + if fix { + msg, err := keyedMessage(c.Description, branchKey) + if err == nil && msg != c.Description { + if err = vcs.Describe(ctx, ".", c.ID, msg); err == nil { + fmt.Fprintln(out, i18n.Tf("%s: added %s", c.ID, branchKey)) + c.Description = msg + } + } + if err != nil { + fmt.Fprintln(errOut, "laneway:", c.ID+":", err) + code = 1 + continue + } + } + k := messageKeys(c.Description) + if len(k) == 0 { + first, _, _ := strings.Cut(c.Description, "\n") + fmt.Fprintln(errOut, i18n.Tf("%s has no issue key: %s", c.ID, first)) + code = 1 + } + keys = append(keys, k...) + } + if strict && len(keys) > 0 { + if err := checkKeys(cfgPath, site, slices.Compact(slices.Sorted(slices.Values(keys)))); err != nil { + fmt.Fprintln(errOut, "laneway:", err) + return 1 + } + } + return code +} + // hookPostCheckout offers to move the branch's issue in progress while it // is still to do. Without a terminal to ask on it says nothing; it never // fails the checkout. diff --git a/hook_test.go b/hook_test.go index 2436c696..5da44f34 100644 --- a/hook_test.go +++ b/hook_test.go @@ -13,6 +13,7 @@ import ( "testing" "github.com/cornedor/laneway/internal/jira" + "github.com/cornedor/laneway/internal/vcs/vcstest" ) func TestKeyedMessage(t *testing.T) { @@ -105,3 +106,38 @@ func TestOfferStart(t *testing.T) { t.Error("enter alone should leave it") } } + +// jj runs no hooks: install says so, and check does commit-msg's work for +// the branch's changes. +func TestHookCheckJJ(t *testing.T) { + repo, _, jj := vcstest.JJRepo(t) + t.Chdir(repo) + var out, errOut strings.Builder + if code := hookCmd([]string{"install"}, &out, &errOut); code != 1 || !strings.Contains(errOut.String(), "jj runs no git hooks") { + t.Errorf("install = %d %q", code, errOut.String()) + } + jj(repo, "new", "main", "-m", "fix the login") + if err := os.WriteFile("b", []byte("b"), 0o600); err != nil { + t.Fatal(err) + } + jj(repo, "bookmark", "create", "issue/ABC-1-login", "-r", "@") + jj(repo, "new", "-m", "ABC-2 also this") + if err := os.WriteFile("c", []byte("c"), 0o600); err != nil { + t.Fatal(err) + } + + errOut.Reset() + if code := hookCmd([]string{"check"}, &out, &errOut); code != 1 || !strings.Contains(errOut.String(), "has no issue key: fix the login") || strings.Contains(errOut.String(), "also this") { + t.Errorf("check = %d %q", code, errOut.String()) + } + errOut.Reset() + if code := hookCmd([]string{"check", "-fix"}, &out, &errOut); code != 0 || errOut.Len() > 0 { + t.Errorf("check -fix = %d %q", code, errOut.String()) + } + if got := jj(repo, "log", "--no-graph", "-r", "issue/ABC-1-login", "-T", "description"); got != "ABC-1 fix the login" { + t.Errorf("fixed description %q", got) + } + if code := hookCmd([]string{"check"}, &out, &errOut); code != 0 { + t.Errorf("check after fix = %d %q", code, errOut.String()) + } +} diff --git a/internal/config/config.go b/internal/config/config.go index 51c3d85e..2026ea46 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -195,6 +195,10 @@ type MultiplexerConfig struct { // InsideEnv is the environment variable it sets in its panes, telling // laneway it runs inside it ("HERDR_ENV"). InsideEnv string `yaml:"inside_env"` + // JJWorkspaces says it makes, finds and removes jj workspaces itself + // (drover does). Without it laneway makes them in a jj repo and opens + // them as plain workspaces. + JJWorkspaces bool `yaml:"jj_workspaces,omitempty"` } // UIConfig tunes the app; every field is optional and "" / 0 keeps the diff --git a/internal/herdr/herdr.go b/internal/herdr/herdr.go index 4afadf92..7a55d74a 100644 --- a/internal/herdr/herdr.go +++ b/internal/herdr/herdr.go @@ -72,7 +72,13 @@ func IsCode(err error, code string) bool { } // Client addresses one herdr server by its socket path. -type Client struct{ path string } +type Client struct { + path string + // JJWorkspaces: the multiplexer makes, finds and removes a jj repo's + // workspaces through its worktree calls itself (drover). herdr makes git + // worktrees there, so laneway makes jj's. + JJWorkspaces bool +} // Default finds the socket the herdr CLI would use: HERDR_SOCKET_PATH, then // HERDR_SESSION's, then the default session's. Nil when there is none. @@ -318,6 +324,44 @@ func (c *Client) CreateWorktree(ctx context.Context, repo, branch, base string) return res.worktree(), err } +// OpenDir opens dir as a workspace labelled label, or finds the one open +// with that label: for checkouts the multiplexer doesn't know, a jj +// workspace laneway made. An open one without an agent gets a new tab to +// start one in. +func (c *Client) OpenDir(ctx context.Context, label, dir string) (Worktree, error) { + wss, err := c.Workspaces(ctx) + if err != nil { + return Worktree{}, err + } + for _, ws := range wss { + if ws.Label != label { + continue + } + wt := Worktree{Path: dir, Workspace: ws.ID, AlreadyOpen: true} + agents, err := c.Agents(ctx) + if err != nil { + return wt, err + } + for _, a := range agents { + if a.WorkspaceID == ws.ID && a.Agent != "" { + return wt, nil + } + } + wt.Tab, wt.Pane, err = c.NewTab(ctx, ws.ID, label, dir, nil) + return wt, err + } + var res worktreeResult + err = c.call(ctx, "workspace.create", map[string]any{"label": label, "cwd": dir}, &res) + wt := res.worktree() + wt.Path = dir + return wt, err +} + +// CloseWorkspace closes the workspace and its tabs. +func (c *Client) CloseWorkspace(ctx context.Context, workspace string) error { + return c.call(ctx, "workspace.close", map[string]any{"workspace_id": workspace}, nil) +} + // RemoveWorktree runs git worktree remove on the linked checkout open as // workspace, closing it. The branch stays. func (c *Client) RemoveWorktree(ctx context.Context, workspace string) error { diff --git a/internal/i18n/nl/go-rest.json b/internal/i18n/nl/go-rest.json index fc1e2217..0c10ea47 100644 --- a/internal/i18n/nl/go-rest.json +++ b/internal/i18n/nl/go-rest.json @@ -163,7 +163,6 @@ "enter goes back to the board… ": "enter gaat terug naar het bord… ", "field is empty": "veld is leeg", "font too large (max 4 MB)": "lettertype te groot (max 4 MB)", - "git status: %s": "git status: %s", "goal: %s": "doel: %s", "herdr is not running": "herdr draait niet", "herdr is not running: start herdr (the agents run in it), then open this again": "herdr draait niet: start herdr (de agents draaien erin) en open dit opnieuw", @@ -293,7 +292,7 @@ "usage: laneway [-site NAME] index [clear]": "gebruik: laneway [-site NAAM] index [clear]", "usage: laneway completion bash|zsh|fish (e.g. source <(laneway completion bash))": "gebruik: laneway completion bash|zsh|fish (bijv. source <(laneway completion bash))", "usage: laneway create -project ABC [-type Task] -summary TEXT [-description MD]": "gebruik: laneway create -project ABC [-type Task] -summary TEKST [-description MD]", - "usage: laneway hook install [-strict] [-force]\n\nInstalls two git hooks in the repository you are in:\n commit-msg a message without an issue key gets the branch's\n (issue/ABC-12-fix: \"ABC-12 fix it\"); without one on the\n branch either the commit is refused. -strict also refuses\n keys Jira doesn't know.\n post-checkout checking out an issue's branch while the issue is still to\n do asks to move it in progress.\nAn existing hook that isn't laneway's is kept unless -force.": "gebruik: laneway hook install [-strict] [-force]\n\nInstalleert twee git-hooks in de repository waarin je zit:\n commit-msg een bericht zonder issuesleutel krijgt die van de branch\n (issue/ABC-12-fix: \"ABC-12 fix it\"); zonder sleutel op de\n branch wordt de commit geweigerd. -strict weigert ook\n sleutels die Jira niet kent.\n post-checkout bij het uitchecken van de branch van een issue dat nog\n te doen is, vraagt het om het in behandeling te zetten.\nEen bestaande hook die niet van laneway is, blijft staan tenzij -force.", + "usage: laneway hook install [-strict] [-force]\n\nInstalls two git hooks in the repository you are in:\n commit-msg a message without an issue key gets the branch's\n (issue/ABC-12-fix: \"ABC-12 fix it\"); without one on the\n branch either the commit is refused. -strict also refuses\n keys Jira doesn't know.\n post-checkout checking out an issue's branch while the issue is still to\n do asks to move it in progress.\nAn existing hook that isn't laneway's is kept unless -force.\n\njj runs no git hooks. In a jj repository install says so, and\n\n laneway hook check [-fix] [-strict]\n\ndoes commit-msg's work for the changes of your branch (trunk to @) at\nonce, before you push: it lists those whose description names no issue\nkey, and -fix puts the bookmark's key in front of them.": "gebruik: laneway hook install [-strict] [-force]\n\nInstalleert twee git-hooks in de repository waarin je zit:\n commit-msg een bericht zonder issuesleutel krijgt die van de branch\n (issue/ABC-12-fix: \"ABC-12 fix it\"); zonder sleutel op de\n branch wordt de commit geweigerd. -strict weigert ook\n sleutels die Jira niet kent.\n post-checkout bij het uitchecken van de branch van een issue dat nog\n te doen is, vraagt het om het in behandeling te zetten.\nEen bestaande hook die niet van laneway is, blijft staan tenzij -force.\n\njj voert geen git-hooks uit. In een jj-repository zegt install dat, en\n\n laneway hook check [-fix] [-strict]\n\ndoet het werk van commit-msg in één keer voor de changes van je branch\n(trunk tot @), voordat je pusht: het toont de changes waarvan de\nbeschrijving geen issuesleutel noemt, en -fix zet de sleutel van de\nbookmark ervoor.", "usage: laneway move KEY [STATUS]": "gebruik: laneway move SLEUTEL [STATUS]", "usage: laneway mr note [-config FILE] LINK [FILE:LINE] TEXT\n\nAdds TEXT to your pending review of the GitLab merge request at LINK, on\nLINE of FILE as it is on the merge request's head (FILE:-LINE: a removed\nline, numbered as it was), or on the merge request as a whole without one.\nOnly you see it until the review is submitted (S in its diff). An agent\nreviewing the merge request (C) leaves its findings this way.": "gebruik: laneway mr note [-config BESTAND] LINK [BESTAND:REGEL] TEKST\n\nVoegt TEKST toe aan je lopende review van de GitLab merge request op LINK, op\nREGEL van BESTAND zoals het in de kop van de merge request staat (BESTAND:-REGEL:\neen verwijderde regel, genummerd zoals die was), of op de merge request als geheel\nzonder. Alleen jij ziet het tot de review is ingediend (S in de diff). Een agent\ndie de merge request reviewt (C) laat zijn bevindingen zo achter.", "usage: laneway prompt [-format TEMPLATE]\n\nPrints the git branch's issue, its status, the timer and the inbox count\nfrom the state file, without asking Jira: \"ABC-12 · In review · ⏱ 1h 20m · ✉ 3\".\nNothing known prints nothing. -format is a Go template over .Key .Status\n.TimerKey .Timer .Inbox, e.g. '{{.Key}}{{if .Timer}} {{.Timer}}{{end}}'.": "gebruik: laneway prompt [-format TEMPLATE]\n\nPrint de issue van de git-branch, de status, de timer en het aantal inbox-items\nuit het statusbestand, zonder Jira te vragen: \"ABC-12 · In review · ⏱ 1h 20m · ✉ 3\".\nIs er niets bekend, dan print het niets. -format is een Go-template over .Key .Status\n.TimerKey .Timer .Inbox, bijv. '{{.Key}}{{if .Timer}} {{.Timer}}{{end}}'.", @@ -364,5 +363,12 @@ "Signed out of laneway": "Afgemeld bij laneway", "Sign in again": "Log opnieuw in", "Also sign out of laneway-server in this browser": "Ook afmelden bij laneway-server in deze browser", - "where, field and account are required": "where, field en account zijn verplicht" + "where, field and account are required": "where, field en account zijn verplicht", + "%s has no issue key: %s": "%s heeft geen issuesleutel: %s", + "%s: added %s": "%s: %s toegevoegd", + "check: put the bookmark's key in front of the changes without one": "check: zet de sleutel van de bookmark voor de changes zonder sleutel", + "its jj workspace": "de jj-workspace ervan", + "jj runs no git hooks: run laneway hook check (-fix) before you push": "jj voert geen git-hooks uit: draai laneway hook check (-fix) voordat je pusht", + "new jj workspace": "nieuwe jj-workspace", + "not in a jj repository: in git, laneway hook install checks every commit": "geen jj-repository: in git controleert laneway hook install elke commit" } diff --git a/internal/i18n/nl/ui-dev.json b/internal/i18n/nl/ui-dev.json index 717c8262..b6155b4c 100644 --- a/internal/i18n/nl/ui-dev.json +++ b/internal/i18n/nl/ui-dev.json @@ -190,7 +190,6 @@ "exited: %v": "afgesloten: %v", "expand failed: %s": "uitklappen mislukt: %s", "failed, allowed to": "mislukt, toegestaan", - "git status: %s": "git status: %s", "hides": "verbergt", "idle": "inactief", "in your review": "in je review", diff --git a/internal/ui/agents.go b/internal/ui/agents.go index cc35073d..e49b2041 100644 --- a/internal/ui/agents.go +++ b/internal/ui/agents.go @@ -158,10 +158,14 @@ var herdrBin = "herdr" // multiplexer is the API client for ui.multiplexer's socket, else herdr's; // nil when nothing runs. func multiplexer(o options) *herdr.Client { + c := herdr.Default() if o.muxSocket != "" { - return herdr.At(expandUserPath(o.muxSocket)) + c = herdr.At(expandUserPath(o.muxSocket)) } - return herdr.Default() + if c != nil { + c.JJWorkspaces = o.muxJJ + } + return c } // muxBin is the multiplexer CLI: ui.multiplexer.command, else herdr. diff --git a/internal/ui/branch.go b/internal/ui/branch.go index 5c6814e6..66b07a6a 100644 --- a/internal/ui/branch.go +++ b/internal/ui/branch.go @@ -1,24 +1,19 @@ package ui import ( - "os/exec" - "strings" - tea "charm.land/bubbletea/v2" + "github.com/cornedor/laneway/internal/vcs" "github.com/cornedor/laneway/internal/work" ) // The issue of the git branch laneway starts in: opened on start, a ⎇ chip // in the header and first in the palette. -// gitBranch is the working directory's git branch, "" outside a repo. +// gitBranch is the working directory's git branch (jj: its bookmark), "" +// outside a repo. var gitBranch = func() string { - out, err := exec.Command("git", "branch", "--show-current").Output() - if err != nil { - return "" - } - return strings.TrimSpace(string(out)) + return vcs.Branch(".") } // branchIssueMsg is the branch's issue found in Jira. diff --git a/internal/ui/jira_work.go b/internal/ui/jira_work.go index 04ea6168..9789ecfd 100644 --- a/internal/ui/jira_work.go +++ b/internal/ui/jira_work.go @@ -17,6 +17,7 @@ import ( "github.com/cornedor/laneway/internal/herdr" "github.com/cornedor/laneway/internal/i18n" "github.com/cornedor/laneway/internal/jira" + "github.com/cornedor/laneway/internal/vcs" ) // Start work (S in the Jira panel): open the issue's worktree as a herdr @@ -239,11 +240,17 @@ func jiraWork(c *herdr.Client, repo, tmpl, branch, agent, key, typ, summary stri // ({branch}, {base} and {key} replaced) and opening what it made. func worktreeIn(c *herdr.Client, repo, branch, base, key string, create []string) func(context.Context) (herdr.Worktree, error) { return func(ctx context.Context) (herdr.Worktree, error) { + if vcs.IsJJ(repo) && !c.JJWorkspaces { + wt, _, err := OpenJJWorkspace(ctx, c, repo, branch, base) + return wt, err + } wt, err := c.OpenWorktree(ctx, repo, branch) if !herdr.IsCode(err, "worktree_not_found") { return wt, err } - if len(create) == 0 { + if len(create) == 0 || vcs.IsJJ(repo) { + // A jj repo's workspace is the multiplexer's to make: create + // commands make git worktrees. return c.CreateWorktree(ctx, repo, branch, base) } r := strings.NewReplacer("{branch}", branch, "{base}", cmp.Or(base, "HEAD"), "{key}", key) @@ -260,6 +267,26 @@ func worktreeIn(c *herdr.Client, repo, branch, base, key string, create []string } } +// OpenJJWorkspace opens the jj workspace on branch, making it from base +// when there is none, for a multiplexer that doesn't do jj workspaces: as +// a plain workspace labelled branch. made reports laneway made it. +func OpenJJWorkspace(ctx context.Context, c *herdr.Client, repo, branch, base string) (wt herdr.Worktree, made bool, err error) { + path := "" + for p, b := range vcs.Checkouts(repo) { + if b == branch { + path = p + } + } + if path == "" { + if path, err = vcs.AddWorkspace(ctx, repo, branch, base); err != nil { + return wt, false, err + } + made = true + } + wt, err = c.OpenDir(ctx, branch, path) + return wt, made, err +} + // agentInWorktree opens a worktree with open, labels its tab and starts the // agent kind in it with args and prompt. pane is the agent's; running // reports one was already there. @@ -334,12 +361,8 @@ func jiraAgentName(key string, now time.Time) string { // summary or none ("issue/ABC-1-old-title", "issue/ABC-1"), "" when there // is none. func issueBranch(repo, tmpl, key, typ string) string { - out, err := exec.Command("git", "-C", repo, "for-each-ref", "--format=%(refname:short)", "refs/heads/").Output() - if err != nil { - return "" - } fits := branchPattern(tmpl, key, typ) - for _, b := range strings.Fields(string(out)) { + for _, b := range vcs.Branches(repo) { if fits.MatchString(b) { return b } @@ -375,14 +398,11 @@ func branchPattern(tmpl, key, typ string) *regexp.Regexp { return regexp.MustCompile("^" + re.String() + "$") } -// defaultBase is the remote's default branch (origin/main), so a new branch -// doesn't start from whatever the main checkout has out. +// defaultBase is the remote's default branch (origin/main, in jj +// main@origin), so a new branch doesn't start from whatever the main +// checkout has out. func defaultBase(repo string) string { - out, err := exec.Command("git", "-C", repo, "rev-parse", "--abbrev-ref", "origin/HEAD").Output() - if err != nil { - return "" - } - return strings.TrimSpace(string(out)) + return vcs.DefaultBase(repo) } // slugify makes a branch-name slug of a summary: lowercase ASCII words joined diff --git a/internal/ui/mr_agent.go b/internal/ui/mr_agent.go index 07b855ff..4f38074e 100644 --- a/internal/ui/mr_agent.go +++ b/internal/ui/mr_agent.go @@ -6,7 +6,6 @@ import ( "github.com/cornedor/laneway/internal/i18n" "maps" "os" - "os/exec" pathpkg "path" "slices" "strconv" @@ -17,6 +16,7 @@ import ( "github.com/cornedor/laneway/internal/forge" "github.com/cornedor/laneway/internal/herdr" + "github.com/cornedor/laneway/internal/vcs" "github.com/cornedor/laneway/internal/work" ) @@ -106,11 +106,15 @@ func StartMRReview(ctx context.Context, c *herdr.Client, repos map[string]string return "", "", false, errors.New("bad branch name " + strconv.Quote(b) + " from GitLab") } } - if out, err := exec.CommandContext(ctx, "git", "-C", repo, "fetch", "origin", mr.SourceBranch, mr.TargetBranch).CombinedOutput(); err != nil { - return "", "", false, errors.New("git fetch: " + strings.TrimSpace(string(out))) + if err := vcs.Fetch(ctx, repo, mr.SourceBranch, mr.TargetBranch); err != nil { + return "", "", false, err } name := "mr-" + strconv.Itoa(ref.Number) + "-" + strconv.FormatInt(time.Now().Unix(), 36) - wt := worktreeIn(c, repo, mr.SourceBranch, "origin/"+mr.SourceBranch, "", create) + base := "origin/" + mr.SourceBranch + if vcs.IsJJ(repo) { + base = mr.SourceBranch + "@origin" + } + wt := worktreeIn(c, repo, mr.SourceBranch, base, "", create) args, prompt := workArgs(extra, prompt, label) return agentInWorktree(ctx, c, wt, pathpkg.Base(ref.Repo)+"!"+strconv.Itoa(ref.Number), kind, name, args, prompt) } @@ -133,11 +137,11 @@ func (m Model) handleMRReview(msg mrReviewMsg) (tea.Model, tea.Cmd) { // (group/project), "" when none is. func checkoutOf(project string, dirs []string) string { for _, d := range dirs { - out, err := exec.Command("git", "-C", d, "remote", "get-url", "origin").Output() + url, err := vcs.RemoteURL(context.Background(), d) if err != nil { continue } - if remoteIsProject(strings.TrimSpace(string(out)), project) { + if remoteIsProject(url, project) { return d } } diff --git a/internal/ui/options.go b/internal/ui/options.go index a1162e1c..14c92cdb 100644 --- a/internal/ui/options.go +++ b/internal/ui/options.go @@ -58,6 +58,7 @@ type options struct { muxCommand string // multiplexer CLI; "" is herdrBin muxSocket string // multiplexer API socket; "" finds herdr's muxInsideEnv string // env var the multiplexer sets in its panes; "" is HERDR_ENV + muxJJ bool // the multiplexer makes and removes jj workspaces itself workArgs []string // its arguments before the start prompt workCreate []string // the command that makes a missing worktree, nil: herdr's kanbanDoneDays int // done work older than this leaves kanban boards @@ -179,6 +180,7 @@ func optionsFrom(c config.UIConfig) (options, []string) { o.muxCommand = strings.TrimSpace(c.Multiplexer.Command) o.muxSocket = strings.TrimSpace(c.Multiplexer.Socket) o.muxInsideEnv = strings.TrimSpace(c.Multiplexer.InsideEnv) + o.muxJJ = c.Multiplexer.JJWorkspaces switch v := strings.ToLower(strings.TrimSpace(c.CardColors)); v { case "": case "ribbon", "off": diff --git a/internal/ui/prompt.go b/internal/ui/prompt.go index a4f46fba..193f545f 100644 --- a/internal/ui/prompt.go +++ b/internal/ui/prompt.go @@ -12,6 +12,7 @@ import ( "github.com/cornedor/laneway/internal/jira" "github.com/cornedor/laneway/internal/store" + "github.com/cornedor/laneway/internal/vcs" "github.com/cornedor/laneway/internal/work" ) @@ -52,10 +53,14 @@ func BranchIssue() string { } // headBranch is the working directory's branch read from .git/HEAD, which -// is quicker than running git; "" outside a repo or detached. +// is quicker than running git; "" outside a repo or detached. jj keeps +// git's HEAD detached, so in a jj repo it asks jj for the bookmark. var headBranch = func() string { dir, err := os.Getwd() for err == nil { + if fi, err := os.Stat(filepath.Join(dir, ".jj")); err == nil && fi.IsDir() { + return vcs.Branch(dir) + } dotGit := filepath.Join(dir, ".git") if fi, err := os.Stat(dotGit); err == nil { if !fi.IsDir() { // a worktree: "gitdir: /repo/.git/worktrees/x" diff --git a/internal/ui/pull_request.go b/internal/ui/pull_request.go index 98ca20ce..3a4bcffe 100644 --- a/internal/ui/pull_request.go +++ b/internal/ui/pull_request.go @@ -11,6 +11,7 @@ import ( tea "charm.land/bubbletea/v2" "github.com/cornedor/laneway/internal/cli" + "github.com/cornedor/laneway/internal/vcs" ) // A → Open a pull request: in the issue's jira.repos checkout, pushes its @@ -57,11 +58,11 @@ func (m *Model) openPullRequest(key string) tea.Cmd { return func() tea.Msg { ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) defer cancel() - remote, err := runIn(ctx, repo, "git", "remote", "get-url", "origin") + remote, err := vcs.RemoteURL(ctx, repo) if err != nil { return pullRequestMsg{key: key, err: err} } - if _, err := runIn(ctx, repo, "git", "push", "-u", "origin", branch); err != nil { + if _, err := vcs.Push(ctx, repo, branch); err != nil { return pullRequestMsg{key: key, err: err} } var out string diff --git a/internal/ui/pull_request_test.go b/internal/ui/pull_request_test.go index b71f6131..9711e5c5 100644 --- a/internal/ui/pull_request_test.go +++ b/internal/ui/pull_request_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/cornedor/laneway/internal/jira" + "github.com/cornedor/laneway/internal/vcs" ) // TestOpenPullRequest: A's row pushes the issue's branch and opens a draft @@ -33,6 +34,9 @@ func TestOpenPullRequest(t *testing.T) { } return "", nil } + oldRun := vcs.Run + t.Cleanup(func() { vcs.Run = oldRun }) + vcs.Run = runIn m := jiraTabModel(t) m.jiraRepos = map[string]string{"ABC": repo} m.jiraIssue = &jira.Issue{Key: "ABC-1", Summary: "Fix login", Type: "Bug"} diff --git a/internal/ui/worktree.go b/internal/ui/worktree.go index 352632f5..a53eccb7 100644 --- a/internal/ui/worktree.go +++ b/internal/ui/worktree.go @@ -1,45 +1,25 @@ package ui import ( + "cmp" "context" "errors" - "github.com/cornedor/laneway/internal/i18n" - "os/exec" - "strings" tea "charm.land/bubbletea/v2" + + "github.com/cornedor/laneway/internal/herdr" + "github.com/cornedor/laneway/internal/i18n" + "github.com/cornedor/laneway/internal/vcs" ) // A → Remove its worktree, on a done issue: once its branch is merged, the // checkout goes (herdr's worktree.remove, the branch stays). Uncommitted // changes, or a branch not merged yet, keep it. -// linkedWorktrees are repo's linked worktrees (not its main checkout) that -// have a branch: path → branch. +// linkedWorktrees are repo's other checkouts on a branch (not its main +// one): git's linked worktrees, jj's workspaces. path → branch. func linkedWorktrees(repo string) map[string]string { - out, err := exec.Command("git", "-C", repo, "worktree", "list", "--porcelain").Output() - if err != nil { - return nil - } - wts := map[string]string{} - for i, block := range strings.Split(strings.TrimSpace(string(out)), "\n\n") { - if i == 0 { - continue // the main checkout - } - var p, b string - for _, l := range strings.Split(block, "\n") { - if v, ok := strings.CutPrefix(l, "worktree "); ok { - p = v - } - if v, ok := strings.CutPrefix(l, "branch refs/heads/"); ok { - b = v - } - } - if b != "" { - wts[p] = b - } - } - return wts + return vcs.Checkouts(repo) } // issueWorktree is the repo's linked worktree whose branch fits tmpl for @@ -57,20 +37,40 @@ func issueWorktree(repo, tmpl, key, typ string) (path, branch string) { // worktreeGone reports why the worktree at path on branch must stay, "" // when it can go: it has uncommitted changes, or branch isn't in base. func worktreeGone(repo, path, branch, base string) string { - out, err := exec.Command("git", "-C", path, "status", "--porcelain").Output() - if err != nil { - return i18n.Tf("git status: %s", err.Error()) - } - if len(strings.TrimSpace(string(out))) > 0 { + switch err := vcs.Kept(repo, path, branch, base); { + case err == nil: + return "" + case errors.Is(err, vcs.ErrUncommitted): return i18n.T("it has uncommitted changes") + case errors.Is(err, vcs.ErrUnmerged): + return i18n.Tf("%s is not merged into %s", branch, cmp.Or(base, vcs.DefaultMerged(repo))) + default: + return err.Error() } - if base == "" { - base = "HEAD" +} + +// DropWorktree removes the checkout at path on branch: through the +// multiplexer, or in a jj repo it doesn't do workspaces of, by forgetting +// the workspace and closing the one open on it. +func DropWorktree(ctx context.Context, c *herdr.Client, repo, path, branch string) error { + if !vcs.IsJJ(repo) || c.JJWorkspaces { + wt, err := c.OpenWorktree(ctx, repo, branch) + if err != nil { + return err + } + return c.RemoveWorktree(ctx, wt.Workspace) } - if exec.Command("git", "-C", repo, "merge-base", "--is-ancestor", branch, base).Run() != nil { - return i18n.Tf("%s is not merged into %s", branch, base) + if err := vcs.ForgetWorkspace(ctx, repo, path); err != nil { + return err } - return "" + if wss, err := c.Workspaces(ctx); err == nil { + for _, ws := range wss { + if ws.Label == branch { + return c.CloseWorkspace(ctx, ws.ID) + } + } + } + return nil } // removeWorktree removes the done issue's worktree when nothing keeps it. @@ -94,10 +94,6 @@ func (m *Model) removeWorktree(key string) tea.Cmd { if why := worktreeGone(repo, path, branch, defaultBase(repo)); why != "" { return errors.New(i18n.Tf("keeping %s: %s", homeShort(path), why)) } - wt, err := c.OpenWorktree(ctx, repo, branch) - if err != nil { - return err - } - return c.RemoveWorktree(ctx, wt.Workspace) + return DropWorktree(ctx, c, repo, path, branch) }) } diff --git a/internal/vcs/vcs.go b/internal/vcs/vcs.go new file mode 100644 index 00000000..a6956327 --- /dev/null +++ b/internal/vcs/vcs.go @@ -0,0 +1,574 @@ +// Package vcs answers laneway's questions about a checkout from git or, in +// a jj repository (colocated or not), from jj: the branch you're on, the +// repo's branches and checkouts, your commits, pushing and fetching. jj's +// bookmarks are the branches; its workspaces the worktrees. A command that +// fails reads as "nothing". +package vcs + +import ( + "cmp" + "context" + "encoding/json" + "errors" + "os" + "os/exec" + "path/filepath" + "slices" + "strconv" + "strings" + "time" +) + +// IsJJ reports whether dir is in a jj workspace: a .jj directory in it or +// above it, found before a .git one is. +func IsJJ(dir string) bool { + dir, err := filepath.Abs(dir) + for err == nil { + if fi, err := os.Stat(filepath.Join(dir, ".jj")); err == nil && fi.IsDir() { + return true + } + if _, err := os.Stat(filepath.Join(dir, ".git")); err == nil { + return false + } + parent := filepath.Dir(dir) + if parent == dir { + break + } + dir = parent + } + return false +} + +// jjRead runs a jj query in dir without snapshotting the working copy, so +// it stays quick and writes nothing. +func jjRead(ctx context.Context, dir string, args ...string) (string, error) { + return jjRun(ctx, dir, append([]string{"--ignore-working-copy"}, args...)...) +} + +// jjRun runs jj in dir, its output trimmed; an error carries jj's message. +func jjRun(ctx context.Context, dir string, args ...string) (string, error) { + cmd := exec.CommandContext(ctx, "jj", append([]string{"--no-pager", "--color=never", "-R", dir}, args...)...) + var stderr strings.Builder + cmd.Stderr = &stderr + out, err := cmd.Output() + if err != nil { + if msg := strings.TrimSpace(stderr.String()); msg != "" { + return "", errors.New("jj: " + msg) + } + return "", err + } + return strings.TrimSpace(string(out)), nil +} + +// Run runs name in dir for what reaches outside: the remote, pushing, +// fetching. Its output is trimmed; an error carries what the command said. +// Tests swap it. +var Run = func(ctx context.Context, dir, name string, args ...string) (string, error) { + cmd := exec.CommandContext(ctx, name, args...) + cmd.Dir = dir + out, err := cmd.CombinedOutput() + if err != nil { + return "", errors.New(name + ": " + strings.TrimSpace(string(out))) + } + return strings.TrimSpace(string(out)), nil +} + +func git(ctx context.Context, dir string, args ...string) (string, error) { + out, err := exec.CommandContext(ctx, "git", append([]string{"-C", dir}, args...)...).Output() + return strings.TrimSpace(string(out)), err +} + +func lines(s string) []string { + return slices.DeleteFunc(strings.Split(s, "\n"), func(l string) bool { return strings.TrimSpace(l) == "" }) +} + +// IsRepo reports whether dir is in a git or jj repository. +func IsRepo(dir string) bool { + if IsJJ(dir) { + return true + } + _, err := git(context.Background(), dir, "rev-parse", "--git-dir") + return err == nil +} + +// bookmarksTmpl prints a commit's local bookmarks, one a line. +const bookmarksTmpl = `local_bookmarks.map(|b| b.name() ++ "\n").join("")` + +// trunkNames are the names of trunk()'s remote bookmarks, the ones every +// change sits on: main, master. A new branch's bookmark on the same commit +// isn't one, nor its copy in a colocated repo's git refs (name@git). +func trunkNames(ctx context.Context, dir string) []string { + out, _ := jjRead(ctx, dir, "log", "--no-graph", "-r", "trunk()", "-T", `remote_bookmarks.map(|b| if(b.remote() != "git", b.name() ++ "\n")).join("")`) + return lines(out) +} + +// nearestBookmark is the bookmark on rev or its closest ancestor that isn't +// trunk's, "" when there is none. Bookmarks below where rev leaves trunk +// are history, branches merged long ago; one right there is a branch that +// started there and hasn't moved yet. +func nearestBookmark(ctx context.Context, dir, rev string, trunk []string) string { + fork := "heads(::(" + rev + ") & ::trunk())" + out, err := jjRead(ctx, dir, "log", "--no-graph", "-r", "heads((::("+rev+") & bookmarks()) ~ ::("+fork+")-)", "-T", bookmarksTmpl) + if err != nil { + return "" + } + for _, b := range lines(out) { + if !slices.Contains(trunk, b) { + return b + } + } + return "" +} + +// Branch is the branch dir is on: git's checked out branch, or in jj the +// bookmark on @ or its closest ancestor (not trunk's, main names no work). +// "" outside a repo, detached, or without one. +func Branch(dir string) string { + ctx := context.Background() + if IsJJ(dir) { + return nearestBookmark(ctx, dir, "@", trunkNames(ctx, dir)) + } + b, _ := git(ctx, dir, "branch", "--show-current") + return b +} + +// Branches are repo's local branches (jj: bookmarks). +func Branches(repo string) []string { + ctx := context.Background() + if IsJJ(repo) { + out, _ := jjRead(ctx, repo, "bookmark", "list", "-T", `if(remote, "", if(present, name ++ "\n"))`) + return lines(out) + } + out, _ := git(ctx, repo, "for-each-ref", "--format=%(refname:short)", "refs/heads/") + return strings.Fields(out) +} + +// HasBranch reports whether repo has the local branch (jj: bookmark). +func HasBranch(repo, branch string) bool { + if repo == "" || branch == "" { + return false + } + if IsJJ(repo) { + return slices.Contains(Branches(repo), branch) + } + _, err := git(context.Background(), repo, "show-ref", "--verify", "--quiet", "refs/heads/"+branch) + return err == nil +} + +// DefaultBase is what new work starts from: the remote's default branch +// (origin/main), in jj trunk()'s remote bookmark (main@origin). "" when +// there is none. +func DefaultBase(repo string) string { + ctx := context.Background() + if !IsJJ(repo) { + b, err := git(ctx, repo, "rev-parse", "--abbrev-ref", "origin/HEAD") + if err != nil { + return "" + } + return b + } + out, _ := jjRead(ctx, repo, "log", "--no-graph", "-r", "trunk()", "-T", + `remote_bookmarks.map(|b| if(b.remote() != "git", b.name() ++ "@" ++ b.remote() ++ "\n")).join("")`) + refs := lines(out) + for _, r := range refs { + if strings.HasSuffix(r, "@origin") { + return r + } + } + if len(refs) > 0 { + return refs[0] + } + return "" +} + +// root is the repo's top directory, cleaned. +func root(ctx context.Context, repo string) string { + if IsJJ(repo) { + r, _ := jjRead(ctx, repo, "root") + return filepath.Clean(r) + } + r, _ := git(ctx, repo, "rev-parse", "--show-toplevel") + return filepath.Clean(r) +} + +// Checkouts are repo's other checkouts on a branch, not the one at repo +// itself: git's linked worktrees, jj's workspaces on a bookmark of their +// own. path → branch. +func Checkouts(repo string) map[string]string { + if IsJJ(repo) { + return workspaces(context.Background(), repo) + } + out, err := git(context.Background(), repo, "worktree", "list", "--porcelain") + if err != nil { + return nil + } + wts := map[string]string{} + for i, block := range strings.Split(out, "\n\n") { + if i == 0 { + continue // the main checkout + } + var p, b string + for _, l := range strings.Split(block, "\n") { + if v, ok := strings.CutPrefix(l, "worktree "); ok { + p = v + } + if v, ok := strings.CutPrefix(l, "branch refs/heads/"); ok { + b = v + } + } + if b != "" { + wts[p] = b + } + } + return wts +} + +// workspace is one of a jj repo's workspaces. +type workspace struct { + name, path, commit string +} + +// workspaceList is repo's workspaces but the one at repo. +func workspaceList(ctx context.Context, repo string) []workspace { + out, err := jjRead(ctx, repo, "workspace", "list", "-T", `name ++ "\t" ++ root ++ "\t" ++ target.commit_id() ++ "\n"`) + if err != nil { + return nil + } + here := root(ctx, repo) + var wss []workspace + for _, l := range lines(out) { + f := strings.Split(l, "\t") + if len(f) != 3 { + continue + } + ws := workspace{name: f[0], path: f[1], commit: f[2]} + if ws.path == "" { // made before jj recorded roots + ws.path, _ = jjRead(ctx, repo, "workspace", "root", "--name", ws.name) + } + if ws.path == "" || filepath.Clean(ws.path) == here { + continue + } + wss = append(wss, ws) + } + return wss +} + +func workspaces(ctx context.Context, repo string) map[string]string { + trunk := trunkNames(ctx, repo) + wss := map[string]string{} + for _, ws := range workspaceList(ctx, repo) { + if b := nearestBookmark(ctx, repo, ws.commit, trunk); b != "" { + wss[ws.path] = b + } + } + return wss +} + +// DefaultMerged is what Kept checks a branch is merged into when given no +// base: HEAD in git, trunk() in jj. +func DefaultMerged(repo string) string { + if IsJJ(repo) { + return "trunk()" + } + return "HEAD" +} + +// ErrUncommitted and ErrUnmerged are why a checkout must stay. +var ( + ErrUncommitted = errors.New("it has uncommitted changes") + ErrUnmerged = errors.New("not merged") +) + +// Kept is why the checkout at path on branch must stay, nil when it can +// go: ErrUncommitted, ErrUnmerged (branch is not in base, "" for the +// default), or the command that couldn't tell. In jj, uncommitted is a +// working-copy commit with changes, and unmerged any change in the +// workspace's history that base lacks, also one past the bookmark. +func Kept(repo, path, branch, base string) error { + ctx := context.Background() + if IsJJ(path) { + // No --ignore-working-copy: the snapshot picks up edits made since + // jj last ran there. + dirty, err := jjRun(ctx, path, "log", "--no-graph", "-r", "@ & ~empty()", "-T", "change_id") + if err != nil { + return err + } + if dirty != "" { + return ErrUncommitted + } + out, err := jjRun(ctx, path, "log", "--no-graph", "-r", "(::@ ~ ::("+cmp.Or(base, DefaultMerged(path))+")) ~ empty()", "-T", `change_id ++ "\n"`) + if err != nil { + return err + } + if out != "" { + return ErrUnmerged + } + return nil + } + out, err := git(ctx, path, "status", "--porcelain") + if err != nil { + return errors.New("git status: " + err.Error()) + } + if out != "" { + return ErrUncommitted + } + if _, err := git(ctx, repo, "merge-base", "--is-ancestor", branch, cmp.Or(base, DefaultMerged(repo))); err != nil { + return ErrUnmerged + } + return nil +} + +// AddWorkspace makes a jj workspace for branch beside repo +// (../.), on the bookmark, or on a new one made at base +// (trunk() for ""). Its path. +func AddWorkspace(ctx context.Context, repo, branch, base string) (string, error) { + top := root(ctx, repo) + name := slug(branch) + path := filepath.Join(filepath.Dir(top), filepath.Base(top)+"."+name) + if !HasBranch(repo, branch) { + // At base, where git's new branch would point; it moves on when + // you set it before pushing. + if _, err := jjRun(ctx, repo, "bookmark", "create", branch, "-r", cmp.Or(base, "trunk()")); err != nil { + return "", err + } + } + // A colocated repo's workspace gets a git worktree as well. + if _, err := jjRun(ctx, repo, "workspace", "add", "--name", name, "-r", "bookmarks(exact:"+strconv.Quote(branch)+")", path); err != nil { + return "", err + } + return path, nil +} + +// slug makes a workspace name of a branch: issue/ABC-1-fix → issue-ABC-1-fix. +func slug(branch string) string { + return strings.Map(func(r rune) rune { + if r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' || r >= '0' && r <= '9' || r == '-' || r == '_' || r == '.' { + return r + } + return '-' + }, branch) +} + +// ForgetWorkspace drops the jj workspace at path and deletes its directory. +// Its changes stay in the repo: jj snapshots them first. +func ForgetWorkspace(ctx context.Context, repo, path string) error { + for _, ws := range workspaceList(ctx, repo) { + if filepath.Clean(ws.path) != filepath.Clean(path) { + continue + } + if _, err := jjRun(ctx, path, "workspace", "forget", ws.name); err != nil { + return err + } + if err := os.RemoveAll(path); err != nil { + return err + } + _, _ = git(ctx, repo, "worktree", "prune") // a colocated workspace's + return nil + } + return errors.New("no jj workspace at " + path) +} + +// RemoteURL is the origin remote's URL. +func RemoteURL(ctx context.Context, repo string) (string, error) { + if !IsJJ(repo) { + return Run(ctx, repo, "git", "remote", "get-url", "origin") + } + out, err := Run(ctx, repo, "jj", "--no-pager", "--color=never", "--ignore-working-copy", "git", "remote", "list") + if err != nil { + return "", err + } + for _, l := range lines(out) { + if url, ok := strings.CutPrefix(l, "origin "); ok { + return strings.TrimSpace(url), nil + } + } + return "", errors.New("no origin remote in " + repo) +} + +// Push pushes branch to origin and tracks it there. jj pushes the bookmark +// where it is: changes after it stay local until you move it. +func Push(ctx context.Context, repo, branch string) (string, error) { + if !IsJJ(repo) { + return Run(ctx, repo, "git", "push", "-u", "origin", branch) + } + if _, err := Run(ctx, repo, "jj", "--no-pager", "--color=never", "bookmark", "track", "exact:"+branch, "--remote", "origin"); err != nil && + !strings.Contains(err.Error(), "already tracked") { + return "", err + } + return Run(ctx, repo, "jj", "--no-pager", "--color=never", "git", "push", "--remote", "origin", "-b", "exact:"+branch) +} + +// Fetch fetches branches from origin. +func Fetch(ctx context.Context, repo string, branches ...string) error { + if !IsJJ(repo) { + _, err := Run(ctx, repo, "git", append([]string{"fetch", "origin"}, branches...)...) + return err + } + args := []string{"--no-pager", "--color=never", "git", "fetch", "--remote", "origin"} + for _, b := range branches { + args = append(args, "-b", "exact:"+b) + } + _, err := Run(ctx, repo, "jj", args...) + return err +} + +// Commit is one of your commits. +type Commit struct { + ID string + At time.Time + Subject string +} + +// Commits are your commits in repo since since, on every branch, without +// merges; ok is false when the repo can't be read. jj's are the visible +// changes with content, not the versions rewriting left behind. +func Commits(repo string, since time.Time) (commits []Commit, ok bool) { + ctx := context.Background() + var out string + if IsJJ(repo) { + var err error + out, err = jjRead(ctx, repo, "log", "--no-graph", "-r", + `mine() & ~empty() & ~merges() & author_date(after:"`+since.Format(time.RFC3339)+`")`, + "-T", `commit_id ++ "\t" ++ author.timestamp().format("%s") ++ "\t" ++ description.first_line() ++ "\n"`) + if err != nil { + return nil, false + } + } else { + email, err := git(ctx, repo, "config", "user.email") + if err != nil || email == "" { + return nil, false + } + out, err = git(ctx, repo, "log", "--all", "--no-merges", + "--since="+strconv.FormatInt(since.Unix(), 10), "--author="+email, "--format=%H%x09%at%x09%s") + if err != nil { + return nil, false + } + } + for _, l := range lines(out) { + f := strings.SplitN(l, "\t", 3) + if len(f) != 3 { + continue + } + sec, err := strconv.ParseInt(f[1], 10, 64) + if err != nil { + continue + } + commits = append(commits, Commit{ID: f[0], At: time.Unix(sec, 0), Subject: f[2]}) + } + return commits, true +} + +// Snapshot is a moment jj recorded your work on a change: a snapshot of +// your edits, a describe, a new change. Bookmark is its branch's: the +// change's, else the nearest one above it, else below it. +type Snapshot struct { + At time.Time + Subject string + Bookmark string +} + +// fetchOps are operations that rewrite changes for you, not by you. +var fetchOps = []string{"import git refs", "fetch from git remote", "push ", "export ", "update working copy"} + +// Snapshots are the moments since from, oldest first, that jj recorded +// work on your changes in repo; nil outside a jj repo. git keeps none: its +// reflog has the branch switches instead. +func Snapshots(repo string, from time.Time) []Snapshot { + ctx := context.Background() + if !IsJJ(repo) { + return nil + } + revs := `mine() & committer_date(after:"` + from.Format(time.RFC3339) + `")` + out, err := jjRead(ctx, repo, "evolog", "--no-graph", "-r", revs, "-T", + `if(operation, operation.time().start().format("%s") ++ "\t" ++ commit.change_id() ++ "\t" ++ operation.description() ++ "\t" ++ commit.description().first_line() ++ "\n")`) + if err != nil { + return nil + } + bookmarkOf := changeBookmarks(ctx, repo, revs) + var snaps []Snapshot + for _, l := range lines(out) { + f := strings.SplitN(l, "\t", 4) + if len(f) != 4 || slices.ContainsFunc(fetchOps, func(op string) bool { return strings.HasPrefix(f[2], op) }) { + continue + } + sec, err := strconv.ParseInt(f[0], 10, 64) + if err != nil || time.Unix(sec, 0).Before(from) { + continue + } + snaps = append(snaps, Snapshot{At: time.Unix(sec, 0), Subject: f[3], Bookmark: bookmarkOf[f[1]]}) + } + slices.SortStableFunc(snaps, func(a, b Snapshot) int { return a.At.Compare(b.At) }) + return snaps +} + +// changeBookmarks maps the changes in revs to their branch's bookmark: the +// one on the change, else the nearest above it, else below it, that isn't +// trunk's. +func changeBookmarks(ctx context.Context, repo, revs string) map[string]string { + trunk := trunkNames(ctx, repo) + out, err := jjRead(ctx, repo, "log", "--no-graph", "-r", "bookmarks() & (("+revs+")::) ~ ::trunk()", "-T", bookmarksTmpl) + if err != nil { + return nil + } + of := map[string]string{} + for _, b := range lines(out) { + if slices.Contains(trunk, b) { + continue + } + // The bookmark's own branch: its ancestors trunk lacks, nearest + // first, so a change below two bookmarks takes the closer one. + ids, err := jjRead(ctx, repo, "log", "--no-graph", "-r", "(("+revs+") & ::bookmarks(exact:"+strconv.Quote(b)+")) ~ ::trunk()", "-T", `change_id ++ "\n"`) + if err != nil { + continue + } + for _, id := range lines(ids) { + if _, ok := of[id]; !ok { + of[id] = b + } + } + } + // A change past every bookmark, as work is until you move the bookmark + // to push it: the branch it was started on. + ids, err := jjRead(ctx, repo, "log", "--no-graph", "-r", revs, "-T", `change_id ++ "\n"`) + if err != nil { + return of + } + for _, id := range lines(ids) { + if _, ok := of[id]; !ok { + of[id] = nearestBookmark(ctx, repo, "change_id("+id+")", trunk) + } + } + return of +} + +// Change is one of the changes on a jj branch. +type Change struct { + ID string // its short change id + Description string +} + +// BranchChanges are the changes of the branch dir is on in jj: the mutable +// ones from trunk to @ with content, nearest first. +func BranchChanges(ctx context.Context, dir string) ([]Change, error) { + out, err := jjRun(ctx, dir, "log", "--no-graph", "-r", "(trunk()..@) & mutable() & ~empty()", + "-T", `json(change_id.short()) ++ "\t" ++ json(description) ++ "\n"`) + if err != nil { + return nil, err + } + var changes []Change + for _, l := range lines(out) { + id, desc, _ := strings.Cut(l, "\t") + var c Change + if json.Unmarshal([]byte(id), &c.ID) != nil || json.Unmarshal([]byte(desc), &c.Description) != nil { + continue + } + changes = append(changes, c) + } + return changes, nil +} + +// Describe sets a change's description. +func Describe(ctx context.Context, dir, change, msg string) error { + _, err := jjRun(ctx, dir, "describe", "-r", "change_id("+change+")", "-m", msg) + return err +} diff --git a/internal/vcs/vcs_test.go b/internal/vcs/vcs_test.go new file mode 100644 index 00000000..90ed6b96 --- /dev/null +++ b/internal/vcs/vcs_test.go @@ -0,0 +1,178 @@ +package vcs_test + +import ( + "context" + "errors" + "os" + "os/exec" + "path/filepath" + "slices" + "testing" + "time" + + "github.com/cornedor/laneway/internal/vcs" + "github.com/cornedor/laneway/internal/vcs/vcstest" +) + +// A jj repo's branch is the nearest bookmark that isn't trunk's, its +// workspaces its checkouts, and laneway makes, checks and drops them. +func TestJJWorkspaces(t *testing.T) { + repo, origin, jj := vcstest.JJRepo(t) + ctx := context.Background() + if !vcs.IsJJ(repo) || !vcs.IsRepo(repo) { + t.Fatal("not a jj repo") + } + if got := vcs.DefaultBase(repo); got != "main@origin" { + t.Errorf("base = %q", got) + } + if got := vcs.Branch(repo); got != "" { + t.Errorf("on main, branch = %q, want none", got) + } + if url, err := vcs.RemoteURL(ctx, repo); err != nil || url != origin { + t.Errorf("remote = %q %v", url, err) + } + + branch := "issue/ABC-1-fix" + path, err := vcs.AddWorkspace(ctx, repo, branch, "") + if err != nil { + t.Fatal(err) + } + if filepath.Base(path) != "repo.issue-ABC-1-fix" || filepath.Dir(path) != filepath.Dir(repo) { + t.Errorf("workspace at %s", path) + } + if got := vcs.Checkouts(repo); len(got) != 1 || got[path] != branch { + t.Errorf("checkouts = %v", got) + } + if got := vcs.Branch(path); got != branch { + t.Errorf("workspace branch = %q", got) + } + if !vcs.HasBranch(repo, branch) || !slices.Contains(vcs.Branches(repo), branch) || vcs.HasBranch(repo, "nope") { + t.Errorf("branches = %v", vcs.Branches(repo)) + } + if err := vcs.Kept(repo, path, branch, ""); err != nil { + t.Errorf("fresh workspace kept: %v", err) + } + + if err := os.WriteFile(filepath.Join(path, "b"), []byte("b"), 0o600); err != nil { + t.Fatal(err) + } + if err := vcs.Kept(repo, path, branch, ""); !errors.Is(err, vcs.ErrUncommitted) { + t.Errorf("edited workspace: %v", err) + } + jj(path, "commit", "-m", "ABC-1 fix it") + if err := vcs.Kept(repo, path, branch, ""); !errors.Is(err, vcs.ErrUnmerged) { + t.Errorf("committed, not merged: %v", err) + } + + // Past the bookmark, the change is still the branch's. + from := time.Now().Add(-time.Hour) + commits, ok := vcs.Commits(repo, from) + if !ok || !slices.ContainsFunc(commits, func(c vcs.Commit) bool { return c.Subject == "ABC-1 fix it" }) { + t.Errorf("commits = %v %v", commits, ok) + } + snaps := vcs.Snapshots(repo, from) + if !slices.ContainsFunc(snaps, func(s vcs.Snapshot) bool { return s.Subject == "ABC-1 fix it" && s.Bookmark == branch }) { + t.Errorf("snapshots = %+v", snaps) + } + changes, err := vcs.BranchChanges(ctx, path) + if err != nil || len(changes) != 1 || changes[0].Description != "ABC-1 fix it\n" { + t.Fatalf("branch changes = %+v %v", changes, err) + } + if err := vcs.Describe(ctx, path, changes[0].ID, "ABC-1 fix it well"); err != nil { + t.Fatal(err) + } + + // Merged: main moves onto the change and is pushed. + jj(repo, "bookmark", "set", "main", "-r", "description(substring:\"fix it well\")") + if _, err := vcs.Push(ctx, repo, "main"); err != nil { + t.Fatal(err) + } + if err := vcs.Fetch(ctx, repo, "main"); err != nil { + t.Error("fetch:", err) + } + if err := vcs.Kept(repo, path, branch, ""); err != nil { + t.Errorf("merged: %v", err) + } + + if err := vcs.ForgetWorkspace(ctx, repo, path); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(path); !os.IsNotExist(err) { + t.Errorf("directory stays: %v", err) + } + if got := vcs.Checkouts(repo); len(got) != 0 { + t.Errorf("checkouts after forget = %v", got) + } +} + +// Outside jj, git answers as before. +func TestGitRepo(t *testing.T) { + repo := t.TempDir() + for _, args := range [][]string{{"init", "-q", "-b", "main"}, {"-c", "user.email=t@t", "-c", "user.name=t", "commit", "-q", "--allow-empty", "-m", "ABC-1 init"}, {"branch", "issue/ABC-2-x"}} { + if out, err := exec.Command("git", append([]string{"-C", repo}, args...)...).CombinedOutput(); err != nil { + t.Skip("git:", err, string(out)) + } + } + if vcs.IsJJ(repo) || !vcs.IsRepo(repo) { + t.Fatal("not a git repo") + } + if got := vcs.Branch(repo); got != "main" { + t.Errorf("branch = %q", got) + } + if got := vcs.Branches(repo); !slices.Equal(got, []string{"issue/ABC-2-x", "main"}) { + t.Errorf("branches = %v", got) + } + if got := vcs.DefaultBase(repo); got != "" { + t.Errorf("base without a remote = %q", got) + } + if vcs.Snapshots(repo, time.Time{}) != nil { + t.Error("git has no snapshots") + } +} + +// A merged branch's bookmark is history, not the branch you're on: work +// on trunk names none. A branch whose bookmark is still at the commit it +// left trunk from, while trunk moved on, is still its own. +func TestJJBranchPastMerged(t *testing.T) { + repo, _, jj := vcstest.JJRepo(t) + write := func(name string) { + t.Helper() + if err := os.WriteFile(filepath.Join(repo, name), []byte(name), 0o600); err != nil { + t.Fatal(err) + } + } + // issue/ABC-1-old merged into main. + jj(repo, "new", "main", "-m", "ABC-1 old") + write("old") + jj(repo, "bookmark", "create", "issue/ABC-1-old", "-r", "@") + jj(repo, "new", "-m", "merge") + write("merge") + jj(repo, "bookmark", "set", "main", "-r", "@") + if _, err := vcs.Push(context.Background(), repo, "main"); err != nil { + t.Fatal(err) + } + // A change on trunk without a bookmark of its own, the local main + // behind main@origin as when you don't pull it along. + jj(repo, "bookmark", "set", "main", "--allow-backwards", "-r", "description(exact:\"init\n\")") + jj(repo, "new", "main@origin", "-m", "ABC-2 new") + write("new") + if got := vcs.Branch(repo); got != "" { + t.Errorf("on trunk past a merged branch: %q", got) + } + // A branch started from main, its bookmark not moved; main moves on. + jj(repo, "bookmark", "set", "main", "-r", "main@origin") + jj(repo, "bookmark", "create", "issue/ABC-3-lag", "-r", "main") + jj(repo, "new", "main", "-m", "ABC-3 work") + write("lag") + branchTip := jj(repo, "log", "--no-graph", "-r", "@", "-T", "change_id") + jj(repo, "new", "main", "-m", "more on main") + write("more") + jj(repo, "bookmark", "set", "main", "-r", "@") + if _, err := vcs.Push(context.Background(), repo, "main"); err != nil { + t.Fatal(err) + } + jj(repo, "edit", branchTip) + if got := vcs.Branch(repo); got != "issue/ABC-3-lag" { + t.Errorf("lagging bookmark: %q", got) + } +} diff --git a/internal/vcs/vcstest/vcstest.go b/internal/vcs/vcstest/vcstest.go new file mode 100644 index 00000000..c10d68bf --- /dev/null +++ b/internal/vcs/vcstest/vcstest.go @@ -0,0 +1,55 @@ +// Package vcstest makes jj repositories for tests. +package vcstest + +import ( + "context" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/cornedor/laneway/internal/vcs" +) + +// JJRepo is a colocated jj repository with a bare origin, main pushed to +// it: trunk() is main@origin. jj runs a jj command in a directory of it. +// It skips without jj. +func JJRepo(t *testing.T) (repo, origin string, jj func(dir string, args ...string) string) { + t.Helper() + if _, err := exec.LookPath("jj"); err != nil { + t.Skip("no jj") + } + tmp := t.TempDir() + cfg := filepath.Join(tmp, "jj.toml") + if err := os.WriteFile(cfg, []byte("user.name = \"T\"\nuser.email = \"t@example.test\"\n"), 0o600); err != nil { + t.Fatal(err) + } + t.Setenv("JJ_CONFIG", cfg) + jj = func(dir string, args ...string) string { + t.Helper() + out, err := exec.Command("jj", append([]string{"--no-pager", "--color=never", "-R", dir}, args...)...).CombinedOutput() + if err != nil { + t.Fatalf("jj %v: %v\n%s", args, err, out) + } + return strings.TrimSpace(string(out)) + } + origin = filepath.Join(tmp, "origin.git") + if out, err := exec.Command("git", "init", "-q", "--bare", origin).CombinedOutput(); err != nil { + t.Skip("git:", err, string(out)) + } + repo = filepath.Join(tmp, "repo") + if out, err := exec.Command("jj", "git", "init", "--colocate", repo).CombinedOutput(); err != nil { + t.Fatalf("jj git init: %v\n%s", err, out) + } + jj(repo, "git", "remote", "add", "origin", origin) + if err := os.WriteFile(filepath.Join(repo, "a"), []byte("a"), 0o600); err != nil { + t.Fatal(err) + } + jj(repo, "commit", "-m", "init") + jj(repo, "bookmark", "create", "main", "-r", "@-") + if _, err := vcs.Push(context.Background(), repo, "main"); err != nil { + t.Fatal("push a new bookmark:", err) + } + return repo, origin, jj +} diff --git a/internal/web/api_agents.go b/internal/web/api_agents.go index 57a9d76a..c2ce123f 100644 --- a/internal/web/api_agents.go +++ b/internal/web/api_agents.go @@ -34,10 +34,15 @@ var herdrBin = "herdr" // muxClient is ui.multiplexer's API socket, else the running herdr server; // nil for none. func muxClient(s *Server) *herdr.Client { - if p := strings.TrimSpace(s.UIConfig().Multiplexer.Socket); p != "" { - return herdr.At(expandUserPath(p)) + mux := s.UIConfig().Multiplexer + c := herdrClient() + if p := strings.TrimSpace(mux.Socket); p != "" { + c = herdr.At(expandUserPath(p)) } - return herdrClient() + if c != nil { + c.JJWorkspaces = mux.JJWorkspaces + } + return c } // muxBin is ui.multiplexer's CLI, else herdr. diff --git a/internal/web/api_agents_test.go b/internal/web/api_agents_test.go index b46fcb1c..b3643499 100644 --- a/internal/web/api_agents_test.go +++ b/internal/web/api_agents_test.go @@ -11,6 +11,7 @@ import ( "os" "os/exec" "path/filepath" + "slices" "strings" "sync" "testing" @@ -21,6 +22,8 @@ import ( "github.com/cornedor/laneway/internal/herdr" "github.com/cornedor/laneway/internal/jira" "github.com/cornedor/laneway/internal/store" + "github.com/cornedor/laneway/internal/vcs" + "github.com/cornedor/laneway/internal/vcs/vcstest" "github.com/cornedor/laneway/internal/work" ) @@ -37,6 +40,8 @@ type fakeHerdr struct { // notReady: agent.prompt says agent_not_ready this many times first. notReady int createErr string // worktree.create fails with it + // workspaces are what workspace.list answers; workspace.create adds one. + workspaces []map[string]any } func newFakeHerdr(t *testing.T) (*fakeHerdr, *herdr.Client) { @@ -110,6 +115,14 @@ func (f *fakeHerdr) serve(conn net.Conn) { f.startFails-- errObj = map[string]any{"code": "pane_busy", "message": "the pane is busy"} } + case "workspace.list": + result = map[string]any{"workspaces": f.workspaces} + case "workspace.create": + ws := map[string]any{"workspace_id": "w9", "label": req.Params["label"]} + f.workspaces = append(f.workspaces, ws) + result = map[string]any{"workspace": ws, "tab": map[string]any{"tab_id": "t9"}, "root_pane": map[string]any{"pane_id": "p9", "tab_id": "t9"}} + case "workspace.close": + f.workspaces = slices.DeleteFunc(f.workspaces, func(ws map[string]any) bool { return ws["workspace_id"] == req.Params["workspace_id"] }) case "tab.create": result = map[string]any{"tab": map[string]any{"tab_id": "t3"}, "root_pane": map[string]any{"pane_id": "p3"}} case "agent.prompt": @@ -404,6 +417,9 @@ func TestBranchAndPullRequest(t *testing.T) { return "", nil } defer func() { runIn = old }() + oldRun := vcs.Run + vcs.Run = runIn + defer func() { vcs.Run = oldRun }() var pr map[string]string if code := workCall(t, "POST", ts.URL+"/api/issues/DEMO-5/pr", "", &pr); code != 200 || pr["URL"] != "https://gitlab.example.com/x/y/-/merge_requests/3" || pr["Branch"] != "issue/DEMO-5-old" { t.Errorf("pr = %d %v calls %v", code, pr, calls) @@ -497,10 +513,10 @@ func TestStartWorkErrorsSayHow(t *testing.T) { // The cwd's branch names the palette's first issue, only one that exists. func TestCwdBranchIssue(t *testing.T) { ts := agentsServer(t, t.TempDir()) - old := runIn - defer func() { runIn = old }() + old := cwdBranch + defer func() { cwdBranch = old }() for branch, want := range map[string]string{"issue/demo-5-fix": "DEMO-5", "fix/utf-8": "", "DEMO-9999-gone": "", "": ""} { - runIn = func(context.Context, string, string, ...string) (string, error) { return branch, nil } + cwdBranch = func() string { return branch } var b map[string]string if workCall(t, "GET", ts.URL+"/api/branch", "", &b) != 200 || b["Key"] != want || want != "" && b["Summary"] == "" { t.Errorf("%q: branch = %v, want %q", branch, b, want) @@ -571,3 +587,60 @@ func TestRemoveWorktree(t *testing.T) { t.Errorf("clean = %d %v", c, out) } } + +// In a jj repo laneway makes the workspace and opens it as a plain one +// under herdr, and forgets it on remove; a multiplexer that does jj +// workspaces itself (jj_workspaces) gets the worktree calls, and the git +// create command isn't run. +func TestStartWorkJJ(t *testing.T) { + repo, _, _ := vcstest.JJRepo(t) + f, c := newFakeHerdr(t) + old := herdrClient + herdrClient = func() *herdr.Client { return c } + defer func() { herdrClient = old }() + oldWait := startAgentWait + startAgentWait = time.Millisecond + defer func() { startAgentWait = oldWait }() + + ts := agentsServerUI(t, repo, config.UIConfig{WorkCreate: []string{"false"}}) + var res struct{ Path string } + if code := workCall(t, "POST", ts.URL+"/api/issues/DEMO-12/work", `{"Agent":"claude"}`, &res); code != 200 { + t.Fatalf("start = %d %+v", code, res) + } + f.mu.Lock() + order, create := strings.Join(f.calls, ","), f.params["workspace.create"] + f.mu.Unlock() + if !strings.HasPrefix(filepath.Base(res.Path), "repo.issue-DEMO-12-") || create["cwd"] != res.Path { + t.Errorf("path %q, workspace.create %v", res.Path, create) + } + if strings.Contains(order, "worktree.") || !strings.Contains(order, "workspace.create,tab.rename,agent.start") { + t.Errorf("calls = %s", order) + } + branch, _ := create["label"].(string) + if wts := vcs.Checkouts(repo); wts[res.Path] != branch { + t.Errorf("checkouts = %v, label %q", wts, branch) + } + + var out map[string]string + if code := workCall(t, "DELETE", ts.URL+"/api/issues/DEMO-12/worktree", "", &out); code != 200 || out["Branch"] != branch { + t.Fatalf("remove = %d %v", code, out) + } + if _, err := os.Stat(res.Path); !os.IsNotExist(err) || len(vcs.Checkouts(repo)) != 0 || !f.called("workspace.close") || f.called("worktree.remove") { + t.Errorf("after remove: %v %v", err, vcs.Checkouts(repo)) + } + + // drover: its worktree calls do jj. + f.mu.Lock() + f.calls, f.open = nil, false + f.mu.Unlock() + ts = agentsServerUI(t, repo, config.UIConfig{WorkCreate: []string{"false"}, Multiplexer: config.MultiplexerConfig{JJWorkspaces: true}}) + if code := workCall(t, "POST", ts.URL+"/api/issues/DEMO-5/work", `{"Agent":"claude"}`, &res); code != 200 { + t.Fatalf("start under drover = %d", code) + } + f.mu.Lock() + order = strings.Join(f.calls, ",") + f.mu.Unlock() + if !strings.Contains(order, "worktree.open,worktree.create") || f.called("workspace.create") || len(vcs.Checkouts(repo)) != 0 { + t.Errorf("drover calls = %s, checkouts %v", order, vcs.Checkouts(repo)) + } +} diff --git a/internal/web/api_agents_work.go b/internal/web/api_agents_work.go index c7662dd9..7a050eb1 100644 --- a/internal/web/api_agents_work.go +++ b/internal/web/api_agents_work.go @@ -22,6 +22,8 @@ import ( "github.com/cornedor/laneway/internal/herdr" "github.com/cornedor/laneway/internal/i18n" "github.com/cornedor/laneway/internal/jira" + "github.com/cornedor/laneway/internal/ui" + "github.com/cornedor/laneway/internal/vcs" "github.com/cornedor/laneway/internal/work" ) @@ -155,11 +157,7 @@ func removeWorktree(ctx context.Context, s *Server, r *http.Request) (any, error if why := worktreeKept(repo, path, branch, defaultBase(repo)); why != "" { return nil, badRequest(i18n.Tf("keeping %s: %s", path, why)) } - wt, err := c.OpenWorktree(ctx, repo, branch) - if err != nil { - return nil, err - } - if err := c.RemoveWorktree(ctx, wt.Workspace); err != nil { + if err := ui.DropWorktree(ctx, c, repo, path, branch); err != nil { return nil, err } forgetWorktrees() @@ -181,26 +179,26 @@ func issueWorktree(repo, tmpl, key, typ string) (path, branch string) { // worktreeKept is why the worktree at path on branch must stay, "" when it // can go: it has uncommitted changes, or branch is not in base. func worktreeKept(repo, path, branch, base string) string { - out, err := exec.Command("git", "-C", path, "status", "--porcelain").Output() - if err != nil { - return i18n.Tf("git status: %s", cli.Error(err)) - } - if len(strings.TrimSpace(string(out))) > 0 { + switch err := vcs.Kept(repo, path, branch, base); { + case err == nil: + return "" + case errors.Is(err, vcs.ErrUncommitted): return i18n.T("it has uncommitted changes") + case errors.Is(err, vcs.ErrUnmerged): + return i18n.Tf("%s is not merged into %s", branch, cmp.Or(base, vcs.DefaultMerged(repo))) + default: + return cli.Error(err) } - if base == "" { - base = "HEAD" - } - if exec.Command("git", "-C", repo, "merge-base", "--is-ancestor", branch, base).Run() != nil { - return i18n.Tf("%s is not merged into %s", branch, base) - } - return "" } +// cwdBranch is the branch laneway web started in (jj: its bookmark); tests +// swap it. +var cwdBranch = func() string { return vcs.Branch(".") } + // cwdBranchIssue is the issue of the git branch laneway web started in, as // the TUI's: first in the palette. It must exist: fix/utf-8 names none. func cwdBranchIssue(ctx context.Context, s *Server, r *http.Request) (any, error) { - branch, _ := runIn(ctx, "", "git", "branch", "--show-current") + branch := cwdBranch() key := work.BranchKey(branch) if key == "" { return map[string]string{}, nil @@ -292,21 +290,17 @@ func runningOn(ctx context.Context, c *herdr.Client, key string) []AgentOut { } func isRepo(repo string) bool { - return exec.Command("git", "-C", repo, "rev-parse", "--git-dir").Run() == nil + return vcs.IsRepo(repo) } func branchExists(repo, branch string) bool { - return repo != "" && branch != "" && exec.Command("git", "-C", repo, "show-ref", "--verify", "--quiet", "refs/heads/"+branch).Run() == nil + return vcs.HasBranch(repo, branch) } // keyBranches are repo's local branches that name key. func keyBranches(repo, key string) []string { out := []string{} - b, err := exec.Command("git", "-C", repo, "for-each-ref", "--format=%(refname:short)", "refs/heads/").Output() - if err != nil { - return out - } - for _, br := range strings.Fields(string(b)) { + for _, br := range vcs.Branches(repo) { if work.BranchKey(br) == key { out = append(out, br) } @@ -728,11 +722,11 @@ func openPullRequest(ctx context.Context, s *Server, r *http.Request) (any, erro } ctx, cancel := context.WithTimeout(ctx, 2*time.Minute) defer cancel() - remote, err := runIn(ctx, repo, "git", "remote", "get-url", "origin") + remote, err := vcs.RemoteURL(ctx, repo) if err != nil { return nil, err } - if _, err := runIn(ctx, repo, "git", "push", "-u", "origin", branch); err != nil { + if _, err := vcs.Push(ctx, repo, branch); err != nil { return nil, err } title, body := key+" "+iss.Summary, "Jira: "+s.Client().BrowseURL(key) @@ -780,6 +774,18 @@ var safeArg = regexp.MustCompile(`^[A-Za-z0-9_][A-Za-z0-9._/+@-]*$`) // says which, in words. func worktreeIn(c *herdr.Client, repo, branch, base, key string, create []string) func(context.Context) (wt herdr.Worktree, how string, err error) { return func(ctx context.Context) (herdr.Worktree, string, error) { + if vcs.IsJJ(repo) && !c.JJWorkspaces { + wt, made, err := ui.OpenJJWorkspace(ctx, c, repo, branch, base) + switch { + case err != nil: + return wt, "", err + case made: + return wt, i18n.T("new jj workspace"), nil + case wt.AlreadyOpen: + return wt, i18n.T("already open in herdr"), nil + } + return wt, i18n.T("its jj workspace"), nil + } wt, err := c.OpenWorktree(ctx, repo, branch) switch { case err == nil && wt.AlreadyOpen: @@ -793,7 +799,9 @@ func worktreeIn(c *herdr.Client, repo, branch, base, key string, create []string if !branchExists(repo, branch) { how = i18n.Tf("new worktree, branch from %s", cmp.Or(base, i18n.T("herdr's default"))) } - if len(create) == 0 { + if len(create) == 0 || vcs.IsJJ(repo) { + // A jj repo's workspace is the multiplexer's to make: create + // commands make git worktrees. wt, err := c.CreateWorktree(ctx, repo, branch, base) return wt, how, err } @@ -876,43 +884,17 @@ func expandUserPath(p string) string { return filepath.Join(home, p[2:]) } -// linkedWorktrees are repo's linked worktrees (not its main checkout) that -// have a branch: path → branch. +// linkedWorktrees are repo's other checkouts on a branch (not its main +// one): git's linked worktrees, jj's workspaces. path → branch. func linkedWorktrees(repo string) map[string]string { - out, err := exec.Command("git", "-C", repo, "worktree", "list", "--porcelain").Output() - if err != nil { - return nil - } - wts := map[string]string{} - for i, block := range strings.Split(strings.TrimSpace(string(out)), "\n\n") { - if i == 0 { - continue - } - var p, b string - for _, l := range strings.Split(block, "\n") { - if v, ok := strings.CutPrefix(l, "worktree "); ok { - p = v - } - if v, ok := strings.CutPrefix(l, "branch refs/heads/"); ok { - b = v - } - } - if b != "" { - wts[p] = b - } - } - return wts + return vcs.Checkouts(repo) } // issueBranch is the repo's local branch that fits tmpl for the issue, any // summary or none, "" when there is none. func issueBranch(repo, tmpl, key, typ string) string { - out, err := exec.Command("git", "-C", repo, "for-each-ref", "--format=%(refname:short)", "refs/heads/").Output() - if err != nil { - return "" - } fits := branchPattern(tmpl, key, typ) - for _, b := range strings.Fields(string(out)) { + for _, b := range vcs.Branches(repo) { if fits.MatchString(b) { return b } @@ -944,13 +926,10 @@ func branchPattern(tmpl, key, typ string) *regexp.Regexp { return regexp.MustCompile("^" + re.String() + "$") } -// defaultBase is the remote's default branch (origin/main). +// defaultBase is the remote's default branch (origin/main, in jj +// main@origin). func defaultBase(repo string) string { - out, err := exec.Command("git", "-C", repo, "rev-parse", "--abbrev-ref", "origin/HEAD").Output() - if err != nil { - return "" - } - return strings.TrimSpace(string(out)) + return vcs.DefaultBase(repo) } func branchName(tmpl, issueKey, typ, summary string) string { diff --git a/internal/work/work.go b/internal/work/work.go index 808bc4c8..f25f04c0 100644 --- a/internal/work/work.go +++ b/internal/work/work.go @@ -22,6 +22,7 @@ import ( "github.com/cornedor/laneway/internal/jira" "github.com/cornedor/laneway/internal/timesheet" + "github.com/cornedor/laneway/internal/vcs" ) // NoTicket names the keyless commits' group. @@ -80,30 +81,19 @@ func Repos(paths map[string]string) []string { // Commits are your commits in repos since since, on every branch and // without merges, as standup entries; a commit in two repos (a fork) once. -// A repo git can't read is left out. +// A repo that can't be read is left out. A jj repo's are its visible +// changes, not the versions rewriting them left behind. func Commits(repos []string, since time.Time) []jira.InboxEntry { seen := map[string]bool{} var out []jira.InboxEntry for _, repo := range repos { - email, err := exec.Command("git", "-C", repo, "config", "user.email").Output() - if err != nil || strings.TrimSpace(string(email)) == "" { - continue - } - log, err := exec.Command("git", "-C", repo, "log", "--all", "--no-merges", - "--since="+strconv.FormatInt(since.Unix(), 10), "--author="+strings.TrimSpace(string(email)), - "--format=%H%x09%at%x09%s").Output() - if err != nil { - continue - } - for _, line := range strings.Split(strings.TrimSpace(string(log)), "\n") { - hash, rest, ok := strings.Cut(line, "\t") - at, subject, ok2 := strings.Cut(rest, "\t") - sec, err := strconv.ParseInt(at, 10, 64) - if !ok || !ok2 || err != nil || seen[hash] { + commits, _ := vcs.Commits(repo, since) + for _, c := range commits { + if seen[c.ID] { continue } - seen[hash] = true - out = append(out, jira.InboxEntry{Key: KeyRe.FindString(subject), When: time.Unix(sec, 0), What: "commit: " + subject}) + seen[c.ID] = true + out = append(out, jira.InboxEntry{Key: KeyRe.FindString(c.Subject), When: c.At, What: "commit: " + c.Subject}) } } return out @@ -216,7 +206,10 @@ func (p Proposal) SourcesText() string { } // Git is the events in repos between from and to: your commits (the key -// their subject names) and HEAD's reflog (the key the branch then names). +// their subject names) and HEAD's reflog (the key the branch then names); +// in a jj repo, which has no reflog to speak of, the moments jj recorded +// your work on a change (the key its description names, else its +// bookmark). func Git(repos []string, from, to time.Time) []Event { var out []Event for _, c := range Commits(repos, from) { @@ -225,6 +218,14 @@ func Git(repos []string, from, to time.Time) []Event { } } for _, repo := range repos { + if vcs.IsJJ(repo) { + for _, s := range vcs.Snapshots(repo, from) { + if s.At.Before(to) { + out = append(out, Event{At: s.At, Key: cmp.Or(KeyRe.FindString(s.Subject), BranchKey(s.Bookmark)), Source: "jj"}) + } + } + continue + } log, err := exec.Command("git", "-C", repo, "log", "-g", "--reverse", "--format=%at%x09%gs", "--since="+strconv.FormatInt(from.Unix(), 10), "HEAD").Output() if err != nil { diff --git a/internal/work/work_test.go b/internal/work/work_test.go index 6839562e..61de6d5a 100644 --- a/internal/work/work_test.go +++ b/internal/work/work_test.go @@ -5,6 +5,8 @@ import ( "strings" "testing" "time" + + "github.com/cornedor/laneway/internal/vcs/vcstest" ) func TestValidBranch(t *testing.T) { @@ -83,3 +85,29 @@ func TestCommits(t *testing.T) { t.Errorf("commits:\n%s", strings.Join(rows, "\n")) } } + +// In jj the moments it recorded work on a change count, for the key its +// description names or else its branch's bookmark; commits are the +// visible changes, once. +func TestGitJJ(t *testing.T) { + repo, _, jj := vcstest.JJRepo(t) + from := time.Now().Add(-time.Hour) + jj(repo, "new", "main", "-m", "wip") + jj(repo, "bookmark", "create", "issue/ABC-7-wip", "-r", "@") + jj(repo, "describe", "-m", "wip again") + jj(repo, "new", "-m", "ABC-8 other") + keys := map[string]int{} + for _, e := range Git([]string{repo}, from, time.Now().Add(time.Minute)) { + keys[e.Source+" "+e.Key]++ + } + if keys["jj ABC-7"] < 2 || keys["jj ABC-8"] < 1 { + t.Errorf("events = %v", keys) + } + var subjects []string + for _, c := range Commits([]string{repo, repo}, from) { + subjects = append(subjects, c.What) + } + if strings.Join(subjects, ",") != "commit: init" { + t.Errorf("commits = %v", subjects) + } +} From d7875d5806856e3b8f56527ddefa8360681f91a3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Corn=C3=A9=20Dorrestijn?= Date: Wed, 18 Nov 2026 11:52:54 +0100 Subject: [PATCH 2/2] fix(vcs): look a branch up without passing its name to git --- internal/vcs/vcs.go | 6 ++++-- internal/vcs/vcs_test.go | 3 +++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/internal/vcs/vcs.go b/internal/vcs/vcs.go index a6956327..57cc4b18 100644 --- a/internal/vcs/vcs.go +++ b/internal/vcs/vcs.go @@ -151,8 +151,10 @@ func HasBranch(repo, branch string) bool { if IsJJ(repo) { return slices.Contains(Branches(repo), branch) } - _, err := git(context.Background(), repo, "show-ref", "--verify", "--quiet", "refs/heads/"+branch) - return err == nil + // Listed and compared rather than asked for by name: the branch can + // come from a request, and so never reaches git's command line. + out, _ := git(context.Background(), repo, "for-each-ref", "--format=%(refname)", "refs/heads/") + return slices.Contains(strings.Fields(out), "refs/heads/"+branch) } // DefaultBase is what new work starts from: the remote's default branch diff --git a/internal/vcs/vcs_test.go b/internal/vcs/vcs_test.go index 90ed6b96..fda67c17 100644 --- a/internal/vcs/vcs_test.go +++ b/internal/vcs/vcs_test.go @@ -122,6 +122,9 @@ func TestGitRepo(t *testing.T) { if got := vcs.Branches(repo); !slices.Equal(got, []string{"issue/ABC-2-x", "main"}) { t.Errorf("branches = %v", got) } + if !vcs.HasBranch(repo, "issue/ABC-2-x") || vcs.HasBranch(repo, "issue/ABC-2") || vcs.HasBranch(repo, "nope") { + t.Error("has branch") + } if got := vcs.DefaultBase(repo); got != "" { t.Errorf("base without a remote = %q", got) }