@bakers-build/addon-workspace-git 0.9.1-next.6 → 0.9.1-next.8

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.
@@ -5,22 +5,14 @@ export { pushCurrentEnv, runBranchGit, setNoAutoSetupMerge, } from './git-config
5
5
  export { loadInstructions } from './instructions.js';
6
6
  export { removeGitWorktree, type WorktreeGitExec, } from './remove-git-worktree.js';
7
7
  export { ensureRunClone, removeRunCloneWorkspace, targetOf, } from './run-clone.js';
8
- /** Default branch template: `<prefix><key>-<title-slug>` (readable). */
9
- export declare const DEFAULT_BRANCH_TEMPLATE = "{branch_prefix}{key}-{title_slug}";
8
+ export declare const DEFAULT_WORKTREE_DIR = ".bakers-worktrees";
10
9
  /** Runs `git <args>` in a cwd; resolves with stdout when it has one. */
11
10
  export type GitRunner = (args: string[], cwd: string) => Promise<string | undefined>;
12
11
  export interface GitWorkspaceOptions {
13
12
  /** Main clone (a git repo): config source + worktree base. */
14
13
  root: string;
15
- /** Where per-ticket worktrees live. Default: `${root}-worktrees`. */
16
- worktreesRoot?: string;
17
- /** Branch name prefix per ticket. Default: 'bakers/'. */
18
- branchPrefix?: string;
19
- /**
20
- * Branch name template. Vars: {branch_prefix}, {key} (sanitized identifier),
21
- * {identifier}, {title_slug}. Default: `{branch_prefix}{key}-{title_slug}`.
22
- */
23
- branchTemplate?: string;
14
+ /** Directory of new worktrees, relative to `root` or absolute. Default: {@link DEFAULT_WORKTREE_DIR}. */
15
+ worktreeDir?: string;
24
16
  /**
25
17
  * Default `false`: before creating a worktree, set `branch.autoSetupMerge=false`
26
18
  * in `root`, and give runs `push.default=current`. `true` leaves Git alone.
@@ -37,26 +29,26 @@ export interface GitWorkspaceOptions {
37
29
  export declare class GitWorkspace implements BbWorkspace {
38
30
  private readonly runGit;
39
31
  private readonly root;
40
- private readonly worktreesRoot;
41
- private readonly branchPrefix;
42
- private readonly branchTemplate;
32
+ private readonly worktreeDir;
43
33
  private readonly autoSetupMerge;
44
34
  private readonly logger;
45
35
  private readonly clone;
46
36
  private readonly shared;
47
37
  constructor(options: GitWorkspaceOptions);
48
- /** Render the branch name for a ticket from the configured template. */
49
- branchFor(identifier: string, title?: string): string;
50
- keyFor(identifier: string): string;
51
- private pathFor;
52
- ensure(identifier: string, title?: string, baseRef?: string): Promise<EnsuredWorkspace>;
38
+ /**
39
+ * Check out the ticket `branch` at `<worktreeDir>/<branch>`. `_identifier`
40
+ * is unused: the conductor passes the ticket's `branch_name`, which push and
41
+ * PR use, so the workspace never renders a branch of its own.
42
+ */
43
+ ensure(_identifier: string, branch?: string, baseRef?: string): Promise<EnsuredWorkspace>;
44
+ /** Create `branch` at the root's HEAD unless it exists; an existing one stays put. */
45
+ private ensureBranch;
53
46
  /** Tear down the ticket worktree with git ({@link removeGitWorktree}). */
54
47
  remove(branch: string, worktreePath?: string): Promise<WorktreeTeardown>;
55
48
  }
56
49
  /** The addon entry's `with` value (see options.schema.json). */
57
50
  export interface GitWorkspaceAddonOptions {
58
- branch_prefix?: string;
59
- branch_template?: string;
51
+ worktree_dir?: string;
60
52
  auto_setup_merge?: boolean;
61
53
  shared?: boolean;
62
54
  }
package/dist/src/index.js CHANGED
@@ -4,28 +4,19 @@
4
4
  // loader that used to be a core util). `@bakers-build/addon-herdr` depends on this
5
5
  // package for it: the one addon→addon edge the layered acyclic rule permits.
6
6
  import { existsSync } from 'node:fs';
7
- import { join, resolve } from 'node:path';
8
- import { deriveCheckoutRoot, exec, slugify, } from '@bakers-build/core';
7
+ import { resolve } from 'node:path';
8
+ import { deriveCheckoutRoot, exec, } from '@bakers-build/core';
9
9
  import { runBranchGit } from './git-config.js';
10
10
  import { loadInstructions } from './instructions.js';
11
- import { removeGitWorktree } from './remove-git-worktree.js';
11
+ import { removeGitWorktree, ticketWorktrees } from './remove-git-worktree.js';
12
12
  import { ensureRunClone, removeRunCloneWorkspace, targetOf, } from './run-clone.js';
13
13
  export { restoreWritable } from './fs.js';
14
14
  export { pushCurrentEnv, runBranchGit, setNoAutoSetupMerge, } from './git-config.js';
15
15
  export { loadInstructions } from './instructions.js';
16
16
  export { removeGitWorktree, } from './remove-git-worktree.js';
17
17
  export { ensureRunClone, removeRunCloneWorkspace, targetOf, } from './run-clone.js';
18
- /** Default branch template: `<prefix><key>-<title-slug>` (readable). */
19
- export const DEFAULT_BRANCH_TEMPLATE = '{branch_prefix}{key}-{title_slug}';
20
- function renderBranchTemplate(template, vars) {
21
- const rendered = template.replace(/\{(\w+)\}/g, (whole, key) => {
22
- const value = vars[key];
23
- return value === undefined ? whole : value;
24
- });
25
- // An empty title slug leaves a dangling separator (e.g. `bakers/GL-9-`) —
26
- // trim trailing branch separators so the branch stays a valid, tidy ref.
27
- return rendered.replace(/[-_./]+$/g, '');
28
- }
18
+ // shortcut: one default for all executors, upgrade when an executor needs another value.
19
+ export const DEFAULT_WORKTREE_DIR = '.bakers-worktrees';
29
20
  const defaultGitRunner = (args, cwd) => exec('git', args, { cwd });
30
21
  const noopLogger = {
31
22
  debug() { },
@@ -36,9 +27,7 @@ const noopLogger = {
36
27
  export class GitWorkspace {
37
28
  runGit;
38
29
  root;
39
- worktreesRoot;
40
- branchPrefix;
41
- branchTemplate;
30
+ worktreeDir;
42
31
  autoSetupMerge;
43
32
  logger;
44
33
  clone;
@@ -46,60 +35,40 @@ export class GitWorkspace {
46
35
  constructor(options) {
47
36
  this.runGit = options.runGit ?? defaultGitRunner;
48
37
  this.root = resolve(options.root);
49
- this.worktreesRoot = options.worktreesRoot
50
- ? resolve(options.worktreesRoot)
51
- : `${this.root}-worktrees`;
52
- this.branchPrefix = options.branchPrefix ?? 'bakers/';
53
- this.branchTemplate = options.branchTemplate ?? DEFAULT_BRANCH_TEMPLATE;
38
+ this.worktreeDir = resolve(this.root, options.worktreeDir ?? DEFAULT_WORKTREE_DIR);
54
39
  this.autoSetupMerge = options.autoSetupMerge ?? false;
55
40
  this.logger = options.logger;
56
41
  this.clone = options.clone ?? false;
57
42
  this.shared = options.shared ?? false;
58
43
  }
59
- /** Render the branch name for a ticket from the configured template. */
60
- branchFor(identifier, title) {
61
- return renderBranchTemplate(this.branchTemplate, {
62
- branch_prefix: this.branchPrefix,
63
- key: this.keyFor(identifier),
64
- identifier,
65
- title_slug: slugify(title ?? ''),
66
- });
67
- }
68
- keyFor(identifier) {
69
- return identifier.replace(/[^A-Za-z0-9._-]/g, '_');
70
- }
71
- pathFor(key) {
72
- return resolve(join(this.worktreesRoot, key));
73
- }
74
- async ensure(identifier, title, baseRef) {
75
- const key = this.keyFor(identifier);
76
- // Reject empty and dot-leading keys: a dot-leading key would produce an
77
- // invalid git ref (e.g. `bakers/.hidden`) and covers '.'/'..' too.
78
- if (key === '' || key.startsWith('.')) {
79
- throw new Error(`invalid workspace identifier: ${identifier}`);
44
+ /**
45
+ * Check out the ticket `branch` at `<worktreeDir>/<branch>`. `_identifier`
46
+ * is unused: the conductor passes the ticket's `branch_name`, which push and
47
+ * PR use, so the workspace never renders a branch of its own.
48
+ */
49
+ async ensure(_identifier, branch, baseRef) {
50
+ if (!branch)
51
+ throw new Error('git workspace requires a branch name');
52
+ // A ref git accepts has no `..`, leading `/`, `-` or `.`, so the path
53
+ // below cannot leave worktreeDir; `@{-1}` expands, hence the comparison.
54
+ let checked;
55
+ try {
56
+ checked = await this.runGit(['check-ref-format', '--branch', branch], this.root);
80
57
  }
81
- const path = this.pathFor(key);
58
+ catch {
59
+ checked = undefined;
60
+ }
61
+ if (checked?.trim() !== branch) {
62
+ throw new Error(`invalid branch name: ${branch}`);
63
+ }
64
+ const path = resolve(this.worktreeDir, branch);
82
65
  const env = this.autoSetupMerge
83
66
  ? undefined
84
67
  : await runBranchGit(this.root, this.logger);
85
68
  const extra = env ? { env } : {};
86
69
  if (this.clone) {
87
70
  const created = !existsSync(path);
88
- const branch = this.branchFor(identifier, title);
89
- // Like `worktree add -B` on first use, but an existing branch stays put.
90
- try {
91
- await this.runGit([
92
- '-C',
93
- this.root,
94
- 'rev-parse',
95
- '--verify',
96
- '--quiet',
97
- `refs/heads/${branch}`,
98
- ], this.root);
99
- }
100
- catch {
101
- await this.runGit(['-C', this.root, 'branch', branch], this.root);
102
- }
71
+ await this.ensureBranch(branch);
103
72
  const target = targetOf(baseRef);
104
73
  if (target && baseRef?.startsWith('origin/')) {
105
74
  try {
@@ -124,16 +93,22 @@ export class GitWorkspace {
124
93
  ...extra,
125
94
  };
126
95
  }
127
- if (existsSync(path)) {
96
+ // Reuse the branch's worktree wherever it lives: old `<root>-worktrees/`
97
+ // checkouts keep working and are never moved.
98
+ const listed = await this.runGit(['-C', this.root, 'worktree', 'list', '--porcelain'], this.root);
99
+ const existing = ticketWorktrees(listed ?? '', this.root).find((w) => w.branch === branch && existsSync(w.path))?.path ?? (existsSync(path) ? path : undefined);
100
+ if (existing) {
128
101
  return {
129
- path,
130
- instructions: loadInstructions(path),
102
+ path: existing,
103
+ instructions: loadInstructions(existing),
131
104
  created: false,
132
105
  ...extra,
133
106
  };
134
107
  }
135
- const branch = this.branchFor(identifier, title);
136
- await this.runGit(['-C', this.root, 'worktree', 'add', '--force', '-B', branch, path], this.root);
108
+ await this.ensureBranch(branch);
109
+ // No `-B`: an existing ticket branch is checked out, never reset;
110
+ // `--force` takes over a registration whose directory is gone.
111
+ await this.runGit(['-C', this.root, 'worktree', 'add', '--force', path, branch], this.root);
137
112
  // The `after_create` hook is run by the conductor, not here — the
138
113
  // workspace only reports that it created a fresh worktree.
139
114
  return {
@@ -143,6 +118,22 @@ export class GitWorkspace {
143
118
  ...extra,
144
119
  };
145
120
  }
121
+ /** Create `branch` at the root's HEAD unless it exists; an existing one stays put. */
122
+ async ensureBranch(branch) {
123
+ try {
124
+ await this.runGit([
125
+ '-C',
126
+ this.root,
127
+ 'rev-parse',
128
+ '--verify',
129
+ '--quiet',
130
+ `refs/heads/${branch}`,
131
+ ], this.root);
132
+ }
133
+ catch {
134
+ await this.runGit(['-C', this.root, 'branch', branch], this.root);
135
+ }
136
+ }
146
137
  /** Tear down the ticket worktree with git ({@link removeGitWorktree}). */
147
138
  async remove(branch, worktreePath) {
148
139
  const removed = removeRunCloneWorkspace(worktreePath);
@@ -162,14 +153,12 @@ export function gitWorkspace(opts = {}) {
162
153
  const root = await deriveCheckoutRoot(config.config_path);
163
154
  return new GitWorkspace({
164
155
  root,
165
- ...(opts.branch_prefix ? { branchPrefix: opts.branch_prefix } : {}),
166
- ...(opts.branch_template
167
- ? { branchTemplate: opts.branch_template }
168
- : {}),
156
+ ...(opts.worktree_dir ? { worktreeDir: opts.worktree_dir } : {}),
169
157
  ...(opts.auto_setup_merge ? { autoSetupMerge: true } : {}),
170
158
  ...(deps?.logger ? { logger: deps.logger } : {}),
171
159
  clone: config.runtime?.isolates === true,
172
- ...(opts.shared ? { shared: true } : {}),
160
+ // A runtime's `shared` wins; the workspace option is the deprecated fallback.
161
+ shared: config.runtime?.shared ?? opts.shared ?? false,
173
162
  });
174
163
  },
175
164
  };
@@ -2,6 +2,15 @@ import type { WorktreeTeardown } from '@bakers-build/conductor/contract';
2
2
  import type { ConductorLogger } from '@bakers-build/core';
3
3
  /** Runs `git <args>` in `cwd`; resolves with stdout, rejects on non-zero exit. */
4
4
  export type WorktreeGitExec = (args: string[], cwd: string) => Promise<string>;
5
+ /**
6
+ * The ticket worktrees of `git worktree list --porcelain` (record 0, the main
7
+ * checkout, and `root` are never one). A `prunable` entry still carries its
8
+ * `worktree <path>` line, so it parses too.
9
+ */
10
+ export declare function ticketWorktrees(output: string, root: string | undefined): {
11
+ path: string;
12
+ branch: string | null;
13
+ }[];
5
14
  /**
6
15
  * Tear down one ticket worktree with git alone — the shared teardown of every
7
16
  * workspace, and the fallback of a tool workspace whose tool lost track of it.
@@ -8,7 +8,7 @@ function normPath(path) {
8
8
  * checkout, and `root` are never one). A `prunable` entry still carries its
9
9
  * `worktree <path>` line, so it parses too.
10
10
  */
11
- function ticketWorktrees(output, root) {
11
+ export function ticketWorktrees(output, root) {
12
12
  const entries = [];
13
13
  for (const record of output.split(/\n\s*\n/)) {
14
14
  const path = record.match(/^worktree (.+)$/m)?.[1]?.trim();
@@ -4,15 +4,10 @@
4
4
  "title": "@bakers-build/addon-workspace-git options",
5
5
  "type": "object",
6
6
  "properties": {
7
- "branch_prefix": {
7
+ "worktree_dir": {
8
8
  "type": "string",
9
- "description": "Prefix of every ticket branch.",
10
- "default": "bakers/"
11
- },
12
- "branch_template": {
13
- "type": "string",
14
- "description": "Branch name template. Placeholders: {branch_prefix}, {key}, {identifier}, {title_slug}.",
15
- "default": "{branch_prefix}{key}-{title_slug}"
9
+ "description": "Directory of new worktrees, relative to the repository root or absolute; a ticket checks out at `<worktree_dir>/<branch_name>`.",
10
+ "default": ".bakers-worktrees"
16
11
  },
17
12
  "auto_setup_merge": {
18
13
  "type": "boolean",
@@ -22,7 +17,8 @@
22
17
  "shared": {
23
18
  "type": "boolean",
24
19
  "default": false,
25
- "description": "Isolating runtimes only: run clones borrow the parent repository's objects (git clone --shared) instead of copying them. Faster and smaller, but never prune or repack the parent with -d while a run is open."
20
+ "description": "Deprecated: set shared on the isolating runtime (runtime-bwrap, runtime-docker) instead; a value set there wins. Run clones borrow the parent repository's objects (git clone --shared) instead of copying them.",
21
+ "deprecated": true
26
22
  }
27
23
  },
28
24
  "additionalProperties": false
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bakers-build/addon-workspace-git",
3
- "version": "0.9.1-next.6",
3
+ "version": "0.9.1-next.8",
4
4
  "description": "bakers.build conductor workspace addon: plain git-worktree workspace + the WORKFLOW.md instruction loader.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -22,11 +22,11 @@
22
22
  "directory": "bakers-cli/addons/workspace-git"
23
23
  },
24
24
  "peerDependencies": {
25
- "@bakers-build/conductor": "^0.9.1-next.6",
26
- "@bakers-build/core": "^0.9.1-next.6"
25
+ "@bakers-build/conductor": "^0.9.1-next.8",
26
+ "@bakers-build/core": "^0.9.1-next.8"
27
27
  },
28
28
  "bakersBuild": {
29
- "commit": "e7d9921d51d5c045f29ca7e35d1e6a348e6ddf08",
29
+ "commit": "41eb5631e4ddf107b0b7a5ce2ffe2ed2a6052b5e",
30
30
  "channel": "next"
31
31
  }
32
32
  }