Rex

Worktrees: ask git

December 04, 2026

At the end, you pick kobun, then you pick a worktree from a list that git wrote, and its session opens. You type no dir= value.

Before you start

From memory

From lessons 5 and 6: write the fields of one entry in projects.lua and say what a pane is in that file. Then: what does rex.ui.pick return when you pick an item, and what does it return when you press Escape?

What the variable was for

Three of your smug files are for bare clones with worktrees: kobun.yml, watchtower.yml and bunko.yml. This is the top of kobun.yml:

session: ${dir}-kobun
root: ~/Work/kobun/${dir}/

You start it with smug start kobun dir=main. smug puts the value in place of ${dir} (smug README). So you must know the name of each worktree and type it each time. git has that list. This lesson asks git.

How to run a program from Lua

rex.exec(argv, opts) runs a program and waits for it (Rex Lua API).

PartWhat it is
argvA list: the program, then each argument. No shell reads it, so &&, | and ~ mean nothing.
opts.cwdThe directory in which the program runs.
opts.timeoutSeconds. After that, Rex stops the program.
ResultA table: ok, code, stdout, stderr. ok is true when the exit status is 0 and there was no timeout.
nil, errOnly when the program could not start at all.

There are two ways to fail, and you check both. If the program could not start, you get nil and a message. If it ran and exited with a status that is not 0, you get a result, and ok is false.

What git prints

Run this in the directory that holds your worktrees. On a bare clone with two worktrees, git prints this:

$ git worktree list --porcelain
worktree /Users/i4o/Work/kobun/.bare
bare
 
worktree /Users/i4o/Work/kobun/feat-x
HEAD bfdfc993bb326d9953401f0b22ce99bb7cb2a80c
branch refs/heads/feat-x
 
worktree /Users/i4o/Work/kobun/main
HEAD bfdfc993bb326d9953401f0b22ce99bb7cb2a80c
branch refs/heads/main

The format has one line for each attribute: a name, one space, a value. bare and detached are a name with no value. An empty line ends a worktree. The format stays the same across git versions (git-worktree manual). The paths above are an example. Yours can differ, and step 1 shows them.

Do it

  1. Look at your real list

    cd ~/Work/kobun
    git worktree list --porcelain

    If git says that this is not a repository, the directory that holds your worktrees is not part of the repository. Tell Claude how the directory is laid out, because the root of the entry must then point to a different place.

  2. Write worktrees.lua

    Make ~/.config/rex/worktrees.lua:

    -- ~/.config/rex/worktrees.lua
    -- Asks git for the worktrees of a repository.
     
    local M = {}
     
    -- Runs git in `root` and returns what it printed. Raises an error if git fails.
    local function git(root, args)
      local argv = { "git" }
      for _, arg in ipairs(args) do
        argv[#argv + 1] = arg
      end
      local result, err = rex.exec(argv, { cwd = root, timeout = 20 })
      if result == nil then
        error(err, 0)
      end
      if not result.ok then
        error("git " .. table.concat(args, " ") .. ": " .. result.stderr, 0)
      end
      return result.stdout
    end
     
    -- Parses the text of `git worktree list --porcelain`.
    -- Each worktree is a group of lines. An empty line ends a group.
    function M.parse(text)
      local list = {}
      local current = nil
      for line in (text .. "\n"):gmatch("(.-)\n") do
        if line == "" then
          if current ~= nil then
            list[#list + 1] = current
            current = nil
          end
        else
          current = current or {}
          local name, value = line:match("^(%S+) ?(.*)$")
          if name == "worktree" then
            current.path = value
          elseif name == "branch" then
            current.branch = (value:gsub("^refs/heads/", ""))
          elseif name == "bare" then
            current.bare = true
          elseif name == "detached" then
            current.detached = true
          end
        end
      end
      if current ~= nil then
        list[#list + 1] = current
      end
      return list
    end
     
    -- Returns the worktrees you can work in: { path, dir, branch }.
    -- The bare repository is in git's list, but it has no files to edit, so it is left out.
    function M.list(root)
      local usable = {}
      local text = git(root, { "worktree", "list", "--porcelain" })
      for _, worktree in ipairs(M.parse(text)) do
        if not worktree.bare then
          worktree.dir = worktree.path:match("([^/]+)/?$")
          usable[#usable + 1] = worktree
        end
      end
      return usable
    end
     
    return M

    git checks the two ways to fail. parse reads the text line by line and starts a new table at each group.

    The new Lua is patterns. They are Lua's small form of regular expressions. %S+ is one or more characters that are not spaces. (.*) captures the rest. [^/]+ is one or more characters that are not /. text:gmatch(pattern) gives each match in a loop, and line:match(pattern) gives the captures of one match. gsub replaces text and returns two values: the new string and a count. The brackets round (value:gsub(...)) keep only the first.

  3. Test it alone

    Make ~/.config/rex/scripts/try-worktrees.lua:

    package.path = os.getenv("HOME") .. "/.config/rex/?.lua;" .. package.path
    return require("worktrees").list(os.getenv("HOME") .. "/Work/kobun")
    rex do ~/.config/rex/scripts/try-worktrees.lua --json

    You must see one item for each worktree, with path, dir and branch, and no item for the bare repository. Compare with step 1.

  4. Add kobun to the data

    In projects.lua, add an entry. Two things are new: worktrees = true, and a label with %s in it.

      -- Worktree projects. smug used ${dir} for these.
      kobun = {
        label = "%s-kobun",
        root = home .. "/Work/kobun",
        worktrees = true,
        windows = {
          { name = "code", panes = { "gitty https://github.com/aureliushq/kobun", "vp i\nvp run dev" } },
          { name = "agents", panes = { "claude" } },
        },
      },

    root is now the directory that holds the worktrees. string.format("%s-kobun", "main") gives main-kobun, which is the label that your YAML made.

  5. Teach the action to ask a second question

    In actions.lua, add one require at the top:

    local worktrees = require("worktrees")

    Add this function after pick_project:

    -- Returns the path of the worktree that the person picked.
    local function pick_worktree(project)
      local items = {}
      for _, worktree in ipairs(worktrees.list(project.root)) do
        items[#items + 1] = {
          id = worktree.path,
          title = worktree.dir,
          subtitle = worktree.branch or "detached",
          icon = "branch",
        }
      end
      return answered(rex.ui.pick{ title = "Worktree", items = items })
    end

    Then replace the args line and the run function of the action:

      args = { project = "string?", worktree = "string?" },
      run = function(ctx, args)
        local name = args.project or pick_project()
        if name == nil then
          return
        end
        local project = projects[name]
        if project == nil then
          error("no project named " .. name, 0)
        end
     
        if not project.worktrees then
          return launcher.open(project)
        end
     
        local path
        local dir = args.worktree
        if dir ~= nil then
          path = project.root .. "/" .. dir
        else
          path = pick_worktree(project)
          if path == nil then
            return
          end
          dir = path:match("([^/]+)/?$")
        end
     
        return launcher.open(project, {
          root = path,
          label = string.format(project.label, dir),
        })
      end,

    The launcher does not change. In lesson 5 you gave open a second parameter, opts, with a root and a label that replace the values of the entry. The action now uses it.

  6. Check, reload, open

    rex config check
    rex config reload

    Press Ctrl+A, then O. Pick kobun. A second list shows your worktrees with their branches. Pick one. Press Cmd+K: a session with a label such as main-kobun is there, and its panes are in that worktree.

    With no picker:

    rex do open_project project=kobun worktree=main --json
  7. Your turn: watchtower and bunko

    Port watchtower.yml and bunko.yml. Their labels differ: %s-watchtower and bunko-%s. Both have a before_start line that starts two containers. Leave that out today and start the containers by hand. Lesson 8 adds it.

Check yourself

Check yourself

Answer from memory. Do not scroll up first.

  1. rex.exec runs git, and git exits with status 128. What does your code get?

  2. In the porcelain format, what ends the lines of one worktree?

  3. What does string.format("%s-kobun", "main") return?

  4. One argument of rex.exec is the text a && b. How does Rex treat it?

  5. From lesson 6: where can a prompt such as rex.ui.pick run?

0 of 5 answered

Primary source

git-worktree manual

Read the part on list and the section "Porcelain Format". Then read the first paragraphs on add. Lesson 8 uses them. For rex.exec, the section "Running Commands" of the Rex Lua API reference has each option and each field of the result.

Stuck, or curious?

Ask Claude. Paste the output or the error and say what you expected. A follow-up question is part of the lesson, and it tells Claude what to teach next.

Next: lesson 8, a new worktree, set up and running.