rex-worktrees 0.3.3 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -78,27 +78,28 @@ The form adds no extra spacing between its side borders and content; selection g
78
78
 
79
79
  ## Projects and checkout locations
80
80
 
81
- Configuration is optional and belongs on the **execution machine** at `${XDG_CONFIG_HOME:-~/.config}/rex-worktrees/config.json`:
81
+ Configuration is optional and belongs in the **execution machine's Rex `init.lua`**, in the managed registration installed by setup:
82
82
 
83
- ```json
84
- {
85
- "projects": [
83
+ ```lua
84
+ -- BEGIN rex-worktrees
85
+ require("rex-worktrees").setup({
86
+ projects = {
86
87
  "/absolute/path/to/project",
87
- {
88
- "path": "/absolute/path/to/another-project",
89
- "worktreeRoot": "/absolute/path/to/another-project-checkouts"
90
- }
91
- ],
92
- "roots": ["/absolute/path/to/projects"],
93
- "worktreeRoot": "/absolute/path/to/checkouts"
94
- }
88
+ { path = "/absolute/path/to/another-project", worktreeRoot = "/absolute/path/to/another-project-checkouts" },
89
+ },
90
+ roots = { "/absolute/path/to/projects" },
91
+ worktreeRoot = "/absolute/path/to/checkouts",
92
+ })
93
+ -- END rex-worktrees
95
94
  ```
96
95
 
97
96
  `projects` explicitly registers paths; optional `roots` scans two directory levels for projects. Without either, the originating Rex pane's directory (or the CLI caller's directory) can suggest its Git or JJ project, but no parent directory is scanned. A local directory suggestion is not sent to another machine: paths typed in the form are interpreted on the selected destination. For a known project missing there, the proposed clone directory uses that machine's first configured root, otherwise the parent of its last successful clone, otherwise the one common parent of discovered projects, otherwise its home directory. This default never scans the home directory and can be changed in **Clone to**. A successful clone remembers its destination parent; editing or reviewing one does not. Git and JJ, not configuration, determine their existing checkouts and branches/revisions. Existing valid directories continue through ordinary open.
98
97
 
98
+ Setup leaves user-owned `setup({...})` settings untouched on upgrades, whether inside or outside the `-- BEGIN rex-worktrees` markers; it never appends a second registration to an existing unmarked `require("rex-worktrees")` configuration. Its installed binary path lives in the managed module, so no `bin` setting is needed. An explicit `bin` option overrides that installed path. After editing `init.lua`, run `rex config reload` on that machine. A default setup invocation migrates the former `${XDG_CONFIG_HOME:-~/.config}/rex-worktrees/config.json` to native Lua settings, resolving relative paths against the old JSON directory. Only after native installation succeeds does it remove `config.json`, any old `config.json.backup`, and the old directory if empty; other files in that directory are untouched. If user-owned Lua registration conflicts with legacy JSON, setup stops before making changes: transfer the legacy values into your registration, back up and remove the JSON file yourself, then rerun. `setup --config` targets an explicit Rex init and never migrates or removes the current user's JSON file. Runtime association state remains separate at `${XDG_STATE_HOME:-~/.local/state}/rex-worktrees/associations`.
99
+
99
100
  For a popup launched from a Rex pane on this machine, the chooser checks that exact pane's reported directory (a local OSC 7 `file://` URI or absolute path). If that directory is absent or its URI is not trusted as local, it uses the same verified pane's foreground process `cwd` when available. A remote pane or foreign URI is never treated as a local path. Context can legitimately be absent if the pane has no usable local directory, or the directory is not inside a Git or JJ repository; select or enter a project in that case. `--no-context` explicitly disables origin discovery.
100
101
 
101
- New checkout location follows this order: a project's `worktreeRoot/<name>`, the global `worktreeRoot/<primary-project-name>/<name>`, or, by default, a sibling `<main-checkout>.worktrees/<name>`. `~` refers to the destination user's home; relative configuration paths resolve against the config file's directory. Checkout locations must be outside existing checkouts and version-control metadata. Collisions and escaping paths are rejected rather than renamed. JJ's own `git.colocate` setting governs whether its workspace also has Git metadata; the helper does not emulate colocation.
102
+ New checkout location follows this order: a project's `worktreeRoot/<name>`, the global `worktreeRoot/<primary-project-name>/<name>`, or, by default, a sibling `<main-checkout>.worktrees/<name>`. `~` refers to the destination user's home; relative paths resolve against that machine's Rex config directory (the directory containing `init.lua`). Checkout locations must be outside existing checkouts and version-control metadata. Collisions and escaping paths are rejected rather than renamed. JJ's own `git.colocate` setting governs whether its workspace also has Git metadata; the helper does not emulate colocation.
102
103
 
103
104
  ## CLI
104
105
 
@@ -120,6 +121,8 @@ rex-worktrees open --repo /absolute/path/jj-workspace \
120
121
  --session session:FULL-ID --name Task
121
122
  ```
122
123
 
124
+ Standalone CLI invocations obtain settings from the execution machine's native `worktrees_config` Rex action; register `require("rex-worktrees").setup(...)` there and reload Rex first. An unregistered action is an error, not a fallback to the former JSON file. The popup and Rex action paths pass those settings directly to the destination helper.
125
+
123
126
  `popup` runs the chooser in the invoking terminal; `launch-popup` opens its floating UI in the source Rex window. For `launch-popup` from an external terminal, supply `--session`; inside Rex, the originating session is available automatically. The `worktrees_open` shortcut delegates to the originating Rex server when invoked from a remote tab, so its popup and helper run on that machine. `launch-popup --host` keeps the UI on the caller's server while selecting another execution host. `--host` accepts an existing Rex host label or registry ID; find exact destination session IDs with `rex -S HOST ls --json`. `open --session` still requires an existing exact ID; new-session naming is available in the popup. Remote `--repo` and `--worktree` paths must be absolute paths on the destination.
124
127
 
125
128
  `open` detects Git or JJ at `--repo`; no VCS switch is needed. Git accepts `--branch` or `--worktree`, with `--worktree-name` for a new branch checkout. JJ accepts `--worktree` for an existing workspace, or `--revision` plus `--worktree-name` for a new workspace. `--repo` is the actual invoking JJ workspace on the destination: relative revisions such as `@-` resolve there, and creating a new workspace may snapshot it. `--name` independently labels the tab or pane. By default, a matching live tab is reused; `--additional` opens another tab, and `--split` splits a matching task or falls back to a new tab. These two flags cannot be combined. `--client ID` selects an exact Rex app client when needed. See `rex-worktrees --help` for popup origin/context flags.
@@ -1,4 +1,4 @@
1
1
  [diffend] Oversized file quarantined before diffing.
2
2
  name: package/dist/rex-worktrees
3
3
  size: 64491792 bytes
4
- sha256: fa2f0d926edb47e2640c8a5b8bac530c9a025f0e297023a88a54a462759925ca
4
+ sha256: 64000e1b797b1ed3c24ee7f9adaaec560f28f4c2a34726498cf5598d843abc89
@@ -33524,13 +33524,14 @@ var ConfigSchema = exports_Schema.Struct({
33524
33524
  })]))),
33525
33525
  worktreeRoot: exports_Schema.optional(exports_Schema.String)
33526
33526
  });
33527
+ var NativeConfigSchema = exports_Schema.Struct({ config: ConfigSchema, directory: exports_Schema.String });
33527
33528
  var ResolvedConfigSchema = exports_Schema.Struct({
33528
33529
  roots: exports_Schema.Array(exports_Schema.String),
33529
33530
  projects: exports_Schema.Array(exports_Schema.String),
33530
33531
  worktreeRoot: exports_Schema.UndefinedOr(exports_Schema.String),
33531
33532
  projectRoots: exports_Schema.Array(exports_Schema.Struct({ path: exports_Schema.String, worktreeRoot: exports_Schema.String }))
33532
33533
  });
33533
- var InstallSchema = exports_Schema.Struct({ source: exports_Schema.String, home: exports_Schema.String, configPath: exports_Schema.String, lua: exports_Schema.String, rexBinDir: exports_Schema.String, managedBin: exports_Schema.optional(exports_Schema.String), pathEnv: exports_Schema.optional(exports_Schema.String), allowLinkedConfig: exports_Schema.optional(exports_Schema.Boolean) });
33534
+ var InstallSchema = exports_Schema.Struct({ source: exports_Schema.String, home: exports_Schema.String, configPath: exports_Schema.String, lua: exports_Schema.String, rexBinDir: exports_Schema.String, managedBin: exports_Schema.optional(exports_Schema.String), pathEnv: exports_Schema.optional(exports_Schema.String), allowLinkedConfig: exports_Schema.optional(exports_Schema.Boolean), legacyConfigPath: exports_Schema.optional(exports_Schema.String) });
33534
33535
  var AssociationSchema = exports_Schema.Struct({
33535
33536
  vcs: VcsSchema,
33536
33537
  hostId: ServerHostIdSchema,
@@ -33735,6 +33736,7 @@ var ResponseSchema = exports_Schema.Union([
33735
33736
  exports_Schema.Struct({ ...RequestIdentitySchema.fields, kind: exports_Schema.Literal("launch"), result: LaunchResultSchema })
33736
33737
  ]);
33737
33738
  var RexWorktreesResponseSchema = exports_Schema.fromJsonString(exports_Schema.fromJsonString(ResponseSchema));
33739
+ var RexNativeConfigResponseSchema = exports_Schema.fromJsonString(exports_Schema.fromJsonString(NativeConfigSchema));
33738
33740
  var PopupOriginSchema = exports_Schema.Struct({ sessionId: exports_Schema.optional(SessionIdSchema), blockId: exports_Schema.optional(BlockIdSchema), clientId: exports_Schema.optional(ClientIdSchema) });
33739
33741
  var PopupSizeSchema = exports_Schema.Struct({ columns: exports_Schema.Number, rows: exports_Schema.Number });
33740
33742
  var PopupBoundsSchema = exports_Schema.Tuple([exports_Schema.Number, exports_Schema.Number, exports_Schema.Number, exports_Schema.Number]);
@@ -34452,58 +34454,6 @@ var associations = exports_Effect.gen(function* () {
34452
34454
  return result4;
34453
34455
  });
34454
34456
 
34455
- // src/config.ts
34456
- var loadConfig = exports_Effect.gen(function* () {
34457
- const fs = yield* exports_FileSystem.FileSystem;
34458
- const path = yield* exports_Path.Path;
34459
- const home = process.env.HOME;
34460
- if (!home)
34461
- return yield* new AppError({ message: "HOME is required" });
34462
- const configHome = process.env.XDG_CONFIG_HOME || path.join(home, ".config");
34463
- if (!path.isAbsolute(configHome))
34464
- return yield* new AppError({ message: "Config home must be absolute" });
34465
- const filename = path.join(configHome, "rex-worktrees", "config.json");
34466
- const exists2 = yield* fs.exists(filename);
34467
- const values2 = exists2 ? yield* fs.readFileString(filename).pipe(exports_Effect.flatMap(exports_Schema.decodeUnknownEffect(exports_Schema.fromJsonString(ConfigSchema)))) : { roots: undefined, projects: undefined, worktreeRoot: undefined };
34468
- const expand = (value3) => {
34469
- const expanded = value3 === "~" ? home : value3.startsWith("~/") ? path.join(home, value3.slice(2)) : value3;
34470
- return path.resolve(path.dirname(filename), expanded);
34471
- };
34472
- const config = {
34473
- roots: (values2.roots ?? []).map(expand),
34474
- projects: (values2.projects ?? []).map((entry) => expand(typeof entry === "string" ? entry : entry.path)),
34475
- worktreeRoot: values2.worktreeRoot === undefined ? undefined : expand(values2.worktreeRoot),
34476
- projectRoots: (values2.projects ?? []).flatMap((entry) => typeof entry === "string" || entry.worktreeRoot === undefined ? [] : [{ path: expand(entry.path), worktreeRoot: expand(entry.worktreeRoot) }])
34477
- };
34478
- return config;
34479
- });
34480
- var resolveCloneRoot = exports_Effect.fnUntraced(function* (roots, projects, stateRoot) {
34481
- const path = yield* exports_Path.Path;
34482
- if (roots[0])
34483
- return roots[0];
34484
- const remembered = yield* rememberedCloneRoot(stateRoot);
34485
- if (remembered)
34486
- return remembered;
34487
- const parents = new Set(projects.map((project4) => path.dirname(project4.path)));
34488
- if (parents.size === 1)
34489
- return [...parents][0];
34490
- const home = process.env.HOME;
34491
- if (!home || !path.isAbsolute(home))
34492
- return yield* new AppError({ message: "Target HOME must be an absolute directory" });
34493
- return home;
34494
- });
34495
- var resolveWorktreeRoot = exports_Effect.fnUntraced(function* (repoPath) {
34496
- const config = yield* loadConfig;
34497
- const target = yield* project3(repoPath);
34498
- for (const entry of config.projectRoots) {
34499
- const candidate = yield* exports_Effect.catchIf(exports_Effect.catchIf(repository3(entry.path), (error2) => missing3(error2), () => exports_Effect.succeed(undefined)), (error2) => notRepository(error2), () => exports_Effect.succeed(undefined));
34500
- if (candidate?.vcs === target.vcs && candidate.commonDir === target.commonDir)
34501
- return entry.worktreeRoot;
34502
- }
34503
- const path = yield* exports_Path.Path;
34504
- return config.worktreeRoot === undefined ? undefined : path.join(config.worktreeRoot, target.name);
34505
- });
34506
-
34507
34457
  // src/rex.ts
34508
34458
  import { hostname } from "os";
34509
34459
  var localName = hostname().toLowerCase().replace(/\.$/, "").replace(/\.local$/, "");
@@ -34687,7 +34637,13 @@ var makePopupSizer = exports_Effect.gen(function* () {
34687
34637
  }))));
34688
34638
  return resize;
34689
34639
  });
34690
- var commandWithPath = (command) => process.env.PATH ? ["/usr/bin/env", `PATH=${process.env.PATH}`, ...command] : command;
34640
+ var commandWithPath = (command) => {
34641
+ const env = [
34642
+ ...process.env.PATH ? [`PATH=${process.env.PATH}`] : [],
34643
+ ...process.env.REX_WORKTREES_CONFIG !== undefined ? [`REX_WORKTREES_CONFIG=${process.env.REX_WORKTREES_CONFIG}`] : []
34644
+ ];
34645
+ return env.length ? ["/usr/bin/env", ...env, ...command] : command;
34646
+ };
34691
34647
  var createTab = exports_Effect.fnUntraced(function* (sessionId, name, cwd, command) {
34692
34648
  const result4 = yield* parse3(RexCreatedSchema, yield* rex(["window", "new", "-s", sessionId, name, "-c", cwd, "--shell=none", "--keep-open", "--json", "--", ...commandWithPath(command)]));
34693
34649
  const blockId = result4.block_ids[0];
@@ -34768,6 +34724,56 @@ var closeManagedPopup = exports_Effect.gen(function* () {
34768
34724
  yield* localRex(["block", "close", "-s", sessionId, blockId]);
34769
34725
  });
34770
34726
 
34727
+ // src/config.ts
34728
+ var loadConfig = exports_Effect.gen(function* () {
34729
+ const path = yield* exports_Path.Path;
34730
+ const raw = process.env.REX_WORKTREES_CONFIG;
34731
+ const { config: values2, directory } = raw === undefined ? yield* rex(["do", "worktrees_config", "--json"]).pipe(exports_Effect.mapError(() => new AppError({ message: "Native Rex worktrees_config is unavailable; register rex-worktrees.setup in this machine's Rex config and reload it" })), exports_Effect.flatMap((response) => exports_Schema.decodeUnknownEffect(RexNativeConfigResponseSchema)(response))) : yield* exports_Schema.decodeUnknownEffect(exports_Schema.fromJsonString(NativeConfigSchema))(raw);
34732
+ if (!path.isAbsolute(directory) || directory.includes("\x00")) {
34733
+ return yield* new AppError({ message: "Native Rex config directory must be an absolute path" });
34734
+ }
34735
+ const home = process.env.HOME;
34736
+ if (!home || !path.isAbsolute(home))
34737
+ return yield* new AppError({ message: "HOME must be an absolute directory" });
34738
+ const expand = (value3) => {
34739
+ const expanded = value3 === "~" ? home : value3.startsWith("~/") ? path.join(home, value3.slice(2)) : value3;
34740
+ return path.resolve(directory, expanded);
34741
+ };
34742
+ const config = {
34743
+ roots: (values2.roots ?? []).map(expand),
34744
+ projects: (values2.projects ?? []).map((entry) => expand(typeof entry === "string" ? entry : entry.path)),
34745
+ worktreeRoot: values2.worktreeRoot === undefined ? undefined : expand(values2.worktreeRoot),
34746
+ projectRoots: (values2.projects ?? []).flatMap((entry) => typeof entry === "string" || entry.worktreeRoot === undefined ? [] : [{ path: expand(entry.path), worktreeRoot: expand(entry.worktreeRoot) }])
34747
+ };
34748
+ return config;
34749
+ });
34750
+ var resolveCloneRoot = exports_Effect.fnUntraced(function* (roots, projects, stateRoot) {
34751
+ const path = yield* exports_Path.Path;
34752
+ if (roots[0])
34753
+ return roots[0];
34754
+ const remembered = yield* rememberedCloneRoot(stateRoot);
34755
+ if (remembered)
34756
+ return remembered;
34757
+ const parents = new Set(projects.map((project4) => path.dirname(project4.path)));
34758
+ if (parents.size === 1)
34759
+ return [...parents][0];
34760
+ const home = process.env.HOME;
34761
+ if (!home || !path.isAbsolute(home))
34762
+ return yield* new AppError({ message: "Target HOME must be an absolute directory" });
34763
+ return home;
34764
+ });
34765
+ var resolveWorktreeRoot = exports_Effect.fnUntraced(function* (repoPath) {
34766
+ const config = yield* loadConfig;
34767
+ const target = yield* project3(repoPath);
34768
+ for (const entry of config.projectRoots) {
34769
+ const candidate = yield* exports_Effect.catchIf(exports_Effect.catchIf(repository3(entry.path), (error2) => missing3(error2), () => exports_Effect.succeed(undefined)), (error2) => notRepository(error2), () => exports_Effect.succeed(undefined));
34770
+ if (candidate?.vcs === target.vcs && candidate.commonDir === target.commonDir)
34771
+ return entry.worktreeRoot;
34772
+ }
34773
+ const path = yield* exports_Path.Path;
34774
+ return config.worktreeRoot === undefined ? undefined : path.join(config.worktreeRoot, target.name);
34775
+ });
34776
+
34771
34777
  // src/worktrees.ts
34772
34778
  import { constants as constants2 } from "fs";
34773
34779
  import { access as access3 } from "fs/promises";
@@ -35572,12 +35578,15 @@ var submitClone = exports_Effect.fnUntraced(function* (host, command, input, rev
35572
35578
  });
35573
35579
 
35574
35580
  // src/setup.ts
35581
+ import { rmdir } from "fs/promises";
35575
35582
  import { randomUUID as randomUUID2 } from "crypto";
35576
35583
 
35577
35584
  // lua/rex-worktrees.lua
35578
35585
  var rex_worktrees_default = `-- rex-worktrees: managed module
35579
35586
  local installed_rex_bin_dir = false
35580
35587
  local installed_path_env = false
35588
+ local installed_bin = false
35589
+ local installed_config_dir = false
35581
35590
  -- Opening is opt-in via opts.key.
35582
35591
  local M = {}
35583
35592
 
@@ -35588,13 +35597,25 @@ function M.setup(opts)
35588
35597
  error("rex-worktrees: rex_bin_dir must be an absolute directory", 0)
35589
35598
  end
35590
35599
  local home = os.getenv("HOME")
35591
- local bin = opts.bin or (home and home .. "/.local/bin/rex-worktrees")
35600
+ local bin = opts.bin or installed_bin or (home and home .. "/.local/bin/rex-worktrees")
35592
35601
  if type(bin) ~= "string" or bin:sub(1, 1) ~= "/" then
35593
35602
  error("rex-worktrees: set HOME or provide an absolute bin path", 0)
35594
35603
  end
35604
+ local rex_config = os.getenv("REX_CONFIG")
35605
+ local config_dir = installed_config_dir or (rex_config and (rex_config:match("^(.+)/[^/]+$") or (rex_config:match("^/[^/]+$") and "/") or rex_config))
35606
+ or (os.getenv("XDG_CONFIG_HOME") and os.getenv("XDG_CONFIG_HOME") .. "/rex")
35607
+ or (home and home .. "/.config/rex")
35608
+ if type(config_dir) ~= "string" or config_dir:sub(1, 1) ~= "/" then
35609
+ error("rex-worktrees: Rex config directory must be absolute", 0)
35610
+ end
35611
+ local config = { roots = opts.roots, projects = opts.projects, worktreeRoot = opts.worktreeRoot }
35612
+ if type(config.roots) == "table" and next(config.roots) == nil then config.roots = nil end
35613
+ if type(config.projects) == "table" and next(config.projects) == nil then config.projects = nil end
35614
+ local settings = rex.json.encode({ config = config, directory = config_dir })
35595
35615
 
35596
35616
  local function worktrees_request(request)
35597
35617
  local exec_opts = { stdin = request, timeout = 20, env = {} }
35618
+ exec_opts.env.REX_WORKTREES_CONFIG = settings
35598
35619
  if rex_bin_dir then exec_opts.env.REX_BIN_DIR = rex_bin_dir end
35599
35620
  if installed_path_env ~= false then exec_opts.env.PATH = installed_path_env end
35600
35621
  if os.getenv("REX_WORKTREES_LOCAL_ENDPOINT") then exec_opts.env.REX_WORKTREES_LOCAL_ENDPOINT = os.getenv("REX_WORKTREES_LOCAL_ENDPOINT") end
@@ -35619,6 +35640,13 @@ function M.setup(opts)
35619
35640
  end,
35620
35641
  }
35621
35642
 
35643
+ rex.action{
35644
+ name = "worktrees_config",
35645
+ title = "Read this machine's worktree settings",
35646
+ description = "Return destination-local settings to standalone rex-worktrees commands",
35647
+ run = function() return settings end,
35648
+ }
35649
+
35622
35650
  rex.action{
35623
35651
  name = "worktrees_open",
35624
35652
  title = "Open Worktree\u2026",
@@ -35646,6 +35674,7 @@ function M.setup(opts)
35646
35674
  table.insert(command, ctx.client_id)
35647
35675
  end
35648
35676
  local exec_opts = { timeout = 20, env = {} }
35677
+ exec_opts.env.REX_WORKTREES_CONFIG = settings
35649
35678
  if rex_bin_dir then exec_opts.env.REX_BIN_DIR = rex_bin_dir end
35650
35679
  if installed_path_env ~= false then exec_opts.env.PATH = installed_path_env end
35651
35680
  if os.getenv("REX_WORKTREES_LOCAL_ENDPOINT") then exec_opts.env.REX_WORKTREES_LOCAL_ENDPOINT = os.getenv("REX_WORKTREES_LOCAL_ENDPOINT") end
@@ -35684,30 +35713,28 @@ require("rex-worktrees").setup()
35684
35713
  var managedRegistration = /^-- BEGIN rex-worktrees\nrequire\("rex-worktrees"\)\.setup\(\{ bin = "(?:\\.|[^"\\])*" \}\)\n-- END rex-worktrees\n$/;
35685
35714
  var marker2 = `-- rex-worktrees: managed module
35686
35715
  `;
35687
- var rexBinPlaceholder = "local installed_rex_bin_dir = false";
35688
- var pathEnvPlaceholder = "local installed_path_env = false";
35716
+ var placeholders = [
35717
+ "local installed_rex_bin_dir = false",
35718
+ "local installed_path_env = false",
35719
+ "local installed_bin = false",
35720
+ "local installed_config_dir = false"
35721
+ ];
35689
35722
  var luaLiteral = (value3) => JSON.stringify(value3).replace(/\\u00([0-1][0-9a-f])/gi, (_, hex) => `\\${parseInt(hex, 16).toString().padStart(3, "0")}`);
35690
35723
  var fail21 = (message) => exports_Effect.fail(new AppError({ message }));
35691
- var installSetup = exports_Effect.fnUntraced(function* ({ source, home, configPath, lua: module, rexBinDir, managedBin, pathEnv, allowLinkedConfig = true }) {
35724
+ var installSetup = exports_Effect.fnUntraced(function* ({ source, home, configPath, lua: module, rexBinDir, managedBin, pathEnv, legacyConfigPath, allowLinkedConfig = true }) {
35692
35725
  const fs = yield* exports_FileSystem.FileSystem;
35693
35726
  const path = yield* exports_Path.Path;
35694
- if (!path.isAbsolute(configPath) || !path.isAbsolute(home) || !path.isAbsolute(source) || !path.isAbsolute(rexBinDir) || managedBin !== undefined && !path.isAbsolute(managedBin))
35727
+ if (!path.isAbsolute(configPath) || !path.isAbsolute(home) || !path.isAbsolute(source) || !path.isAbsolute(rexBinDir) || managedBin !== undefined && !path.isAbsolute(managedBin) || legacyConfigPath !== undefined && !path.isAbsolute(legacyConfigPath))
35695
35728
  return yield* new AppError({ message: "Setup requires absolute paths" });
35696
- if (!module.startsWith(marker2))
35697
- return yield* new AppError({ message: "Embedded Lua module is missing its install marker" });
35698
- if (!module.startsWith(`${marker2}${rexBinPlaceholder}
35699
- `) || module.split(rexBinPlaceholder).length !== 2)
35700
- return yield* new AppError({ message: "Embedded Lua module must contain exactly one Rex CLI directory placeholder after its marker" });
35701
- if (!module.startsWith(`${marker2}${rexBinPlaceholder}
35702
- ${pathEnvPlaceholder}
35703
- `) || module.split(pathEnvPlaceholder).length !== 2)
35704
- return yield* new AppError({ message: "Embedded Lua module must contain exactly one host PATH placeholder after its Rex CLI directory placeholder" });
35705
- const installedLua = module.replace(rexBinPlaceholder, `local installed_rex_bin_dir = ${luaLiteral(rexBinDir)}`).replace(pathEnvPlaceholder, `local installed_path_env = ${pathEnv === undefined ? "false" : luaLiteral(pathEnv)}`);
35706
- const bin = managedBin ?? path.join(home, ".local", "bin", "rex-worktrees");
35707
- const registration = managedBin === undefined ? manualRegistration : `-- BEGIN rex-worktrees
35708
- require("rex-worktrees").setup({ bin = ${JSON.stringify(managedBin)} })
35709
- -- END rex-worktrees
35729
+ const header = `${marker2}${placeholders.join(`
35730
+ `)}
35710
35731
  `;
35732
+ if (!module.startsWith(header) || placeholders.some((placeholder) => module.split(placeholder).length !== 2))
35733
+ return yield* new AppError({ message: "Embedded Lua module must contain exactly four install placeholders in order after its marker" });
35734
+ const bin = managedBin ?? path.join(home, ".local", "bin", "rex-worktrees");
35735
+ const values2 = [rexBinDir, pathEnv, bin, path.dirname(configPath)];
35736
+ const installedLua = placeholders.reduce((text, placeholder, index2) => text.replace(placeholder, placeholder.replace("false", values2[index2] === undefined ? "false" : luaLiteral(values2[index2]))), module);
35737
+ const registration = manualRegistration;
35711
35738
  const luaPath = path.join(path.dirname(configPath), "rex-worktrees.lua");
35712
35739
  const info2 = (filename) => exports_Effect.catchIf(fs.lstat(filename), (error2) => exports_PlatformError.isPlatformError(error2) && error2.reason._tag === "NotFound", () => exports_Effect.succeed(undefined));
35713
35740
  const binaryInfo = managedBin === undefined ? yield* info2(bin) : undefined;
@@ -35724,14 +35751,41 @@ require("rex-worktrees").setup({ bin = ${JSON.stringify(managedBin)} })
35724
35751
  if (initInfo?.type === "SymbolicLink" && !allowLinkedConfig)
35725
35752
  return yield* fail21(`Refusing linked Rex init: ${configPath}`);
35726
35753
  const current = initInfo ? yield* fs.readFileString(configPath) : "";
35727
- const begin = "-- BEGIN rex-worktrees";
35728
- const end3 = "-- END rex-worktrees";
35754
+ const begin = `-- BEGIN rex-worktrees
35755
+ `;
35756
+ const end3 = `-- END rex-worktrees
35757
+ `;
35729
35758
  const start = current.indexOf(begin);
35730
35759
  const finish = current.indexOf(end3);
35731
- if (start < 0 !== finish < 0 || start >= 0 && (current.indexOf(begin, start + begin.length) !== -1 || current.indexOf(end3, finish + end3.length) !== -1 || current.slice(start, finish + end3.length + 1) !== manualRegistration && !managedRegistration.test(current.slice(start, finish + end3.length + 1))))
35760
+ if (start < 0 !== finish < 0 || start >= 0 && (current.indexOf(begin, start + begin.length) !== -1 || current.indexOf(end3, finish + end3.length) !== -1 || finish <= start || start > 0 && current[start - 1] !== `
35761
+ `))
35732
35762
  return yield* fail21(`Malformed rex-worktrees registration in ${configPath}`);
35733
- if (start < 0 && /require\s*\(?\s*["']rex-worktrees["']/.test(current))
35734
- return yield* fail21(`Existing rex-worktrees registration in ${configPath}; remove it before setup`);
35763
+ const existing = start < 0 ? undefined : current.slice(start, finish + end3.length);
35764
+ if (existing !== undefined && !(existing === manualRegistration || managedRegistration.test(existing) || /require\s*\(?\s*["']rex-worktrees["']\s*\)?\.setup\s*\(/.test(existing)))
35765
+ return yield* fail21(`Malformed rex-worktrees registration in ${configPath}`);
35766
+ const unmarkedRegistration = start < 0 && /require\s*\(?\s*["']rex-worktrees["']/.test(current);
35767
+ const simple = !unmarkedRegistration && (existing === undefined || existing === manualRegistration || existing !== undefined && managedRegistration.test(existing));
35768
+ const legacyInfo = legacyConfigPath === undefined ? undefined : yield* info2(legacyConfigPath);
35769
+ if (legacyInfo && legacyInfo.type !== "File")
35770
+ return yield* fail21(`Refusing non-file legacy settings: ${legacyConfigPath}`);
35771
+ if (legacyInfo && !simple)
35772
+ return yield* fail21(`Cannot merge legacy settings ${legacyConfigPath} with custom Rex registration in ${configPath}. Move roots/projects/worktreeRoot into require("rex-worktrees").setup({...}) manually, back up and remove the legacy JSON file, then rerun setup.`);
35773
+ const legacyBytes = legacyInfo ? yield* fs.readFileString(legacyConfigPath) : undefined;
35774
+ const legacy = legacyBytes === undefined ? undefined : yield* exports_Schema.decodeUnknownEffect(exports_Schema.fromJsonString(ConfigSchema))(legacyBytes);
35775
+ const expand = (value3) => value3 === "~" ? home : value3.startsWith("~/") ? path.join(home, value3.slice(2)) : path.resolve(path.dirname(legacyConfigPath), value3);
35776
+ const legacyRegistration = legacy === undefined ? undefined : `-- BEGIN rex-worktrees
35777
+ require("rex-worktrees").setup({${[
35778
+ legacy.roots?.length ? `roots = { ${legacy.roots.map((root) => luaLiteral(expand(root))).join(", ")} }` : undefined,
35779
+ legacy.projects?.length ? `projects = { ${legacy.projects.map((project4) => typeof project4 === "string" ? luaLiteral(expand(project4)) : `{ path = ${luaLiteral(expand(project4.path))}${project4.worktreeRoot === undefined ? "" : `, worktreeRoot = ${luaLiteral(expand(project4.worktreeRoot))}`} }`).join(", ")} }` : undefined,
35780
+ legacy.worktreeRoot === undefined ? undefined : `worktreeRoot = ${luaLiteral(expand(legacy.worktreeRoot))}`
35781
+ ].filter((value3) => value3 !== undefined).join(", ")} })
35782
+ -- END rex-worktrees
35783
+ `;
35784
+ const nextRegistration = legacyRegistration ?? (simple ? registration : existing ?? "");
35785
+ const backup = legacyConfigPath === undefined ? undefined : `${legacyConfigPath}.backup`;
35786
+ const backupInfo = backup === undefined ? undefined : yield* info2(backup);
35787
+ if (backupInfo && backupInfo.type !== "File")
35788
+ return yield* fail21(`Refusing non-file legacy backup: ${backup}`);
35735
35789
  const sourceInfo = yield* fs.stat(source);
35736
35790
  if (sourceInfo.type !== "File")
35737
35791
  return yield* fail21(`Installer source is not a file: ${source}`);
@@ -35751,6 +35805,10 @@ require("rex-worktrees").setup({ bin = ${JSON.stringify(managedBin)} })
35751
35805
  const temporary = path.join(path.dirname(destination), `.rex-worktrees-${randomUUID2()}.tmp`);
35752
35806
  return yield* write2(temporary).pipe(exports_Effect.flatMap(() => fs.rename(temporary, destination)), exports_Effect.ensuring(fs.remove(temporary, { force: true }).pipe(exports_Effect.ignore)));
35753
35807
  });
35808
+ const legacyDir = legacyConfigPath === undefined ? undefined : path.dirname(legacyConfigPath);
35809
+ const legacyDirInfo = legacyDir === undefined ? undefined : yield* info2(legacyDir);
35810
+ if (legacyDirInfo && legacyDirInfo.type !== "Directory")
35811
+ return yield* fail21(`Refusing non-directory legacy settings path: ${legacyDir}`);
35754
35812
  if (managedBin === undefined) {
35755
35813
  if (source !== bin)
35756
35814
  yield* atomic(bin, (temporary) => fs.copyFile(source, temporary).pipe(exports_Effect.flatMap(() => fs.chmod(temporary, 493))));
@@ -35758,13 +35816,26 @@ require("rex-worktrees").setup({ bin = ${JSON.stringify(managedBin)} })
35758
35816
  yield* fs.chmod(bin, 493);
35759
35817
  }
35760
35818
  yield* atomic(luaPath, (temporary) => fs.writeFileString(temporary, installedLua, { flag: "wx", mode: 420 }));
35761
- if (start < 0)
35819
+ if (start < 0 && !unmarkedRegistration)
35762
35820
  yield* fs.writeFileString(configPath, `${current && !current.endsWith(`
35763
35821
  `) ? `
35764
- ` : ""}${registration}`, { flag: "a" });
35765
- else if (current.slice(start, finish + end3.length + 1) !== registration)
35766
- yield* fs.writeFileString(configPath, `${current.slice(0, start)}${registration}${current.slice(finish + end3.length + 1)}`);
35767
- return { bin, luaPath, configPath };
35822
+ ` : ""}${nextRegistration}`, { flag: "a" });
35823
+ else if (start >= 0 && existing !== nextRegistration)
35824
+ yield* fs.writeFileString(configPath, `${current.slice(0, start)}${nextRegistration}${current.slice(finish + end3.length)}`);
35825
+ if (backupInfo)
35826
+ yield* fs.remove(backup);
35827
+ if (legacyInfo)
35828
+ yield* fs.remove(legacyConfigPath);
35829
+ if (legacyDirInfo)
35830
+ yield* exports_Effect.tryPromise({
35831
+ try: () => rmdir(legacyDir).catch((error2) => {
35832
+ if (error2 instanceof Error && "code" in error2 && (error2.code === "ENOTEMPTY" || error2.code === "EEXIST"))
35833
+ return;
35834
+ throw error2;
35835
+ }),
35836
+ catch: (error2) => new AppError({ message: `Cannot remove legacy settings directory ${legacyDir}: ${String(error2)}` })
35837
+ });
35838
+ return { bin, luaPath, configPath, migrated: legacy !== undefined };
35768
35839
  });
35769
35840
  var setup = exports_Effect.fnUntraced(function* (managedBin, configPath) {
35770
35841
  const home = process.env.HOME;
@@ -35799,7 +35870,7 @@ var setup = exports_Effect.fnUntraced(function* (managedBin, configPath) {
35799
35870
  return yield* fail21("Rex config has diagnostics; fix it before setup");
35800
35871
  target = checked.path;
35801
35872
  }
35802
- return yield* installSetup({ source: process.execPath, home, configPath: target, lua: rex_worktrees_default, rexBinDir, managedBin, allowLinkedConfig: configPath === undefined, ...process.env.PATH !== undefined ? { pathEnv: process.env.PATH } : {} });
35873
+ return yield* installSetup({ source: process.execPath, home, configPath: target, lua: rex_worktrees_default, rexBinDir, managedBin, allowLinkedConfig: configPath === undefined, ...configPath === undefined ? { legacyConfigPath: path.join(process.env.XDG_CONFIG_HOME ?? path.join(home, ".config"), "rex-worktrees", "config.json") } : {}, ...process.env.PATH !== undefined ? { pathEnv: process.env.PATH } : {} });
35803
35874
  });
35804
35875
  // node_modules/effect/dist/cli/Prompt.js
35805
35876
  var exports_Prompt = {};
@@ -39445,10 +39516,11 @@ var main = exports_Effect.gen(function* () {
39445
39516
  if (!compiled)
39446
39517
  return yield* exports_Effect.fail(new AppError({ message: "Build first with bun run build, then run ./dist/rex-worktrees setup" }));
39447
39518
  const installed = yield* setup(flags["--bin"], flags["--config"]);
39448
- yield* exports_Console.log(`${flags["--bin"] ? "Registered binary" : "Installed binary"}: ${installed.bin}
39519
+ yield* exports_Console.log(`Default binary: ${installed.bin}
39449
39520
  Installed Lua module: ${installed.luaPath}
39450
- Updated Rex config: ${installed.configPath}${flags["--config"] ? `
39451
- Rex will load the registration when it next starts.` : `
39521
+ Rex config: ${installed.configPath}${installed.migrated ? `
39522
+ Migrated legacy JSON settings to Rex Lua; removed legacy files.` : ""}${flags["--config"] ? `
39523
+ Reload the targeted Rex config to activate, or start that instance if it is stopped.` : `
39452
39524
  Run rex config reload to activate.`}`);
39453
39525
  return;
39454
39526
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rex-worktrees",
3
- "version": "0.3.3",
3
+ "version": "0.4.0",
4
4
  "description": "Git worktrees and Jujutsu workspaces for Rex",
5
5
  "license": "MIT",
6
6
  "author": "Samuel Ho",