@bakers-build/addon-workspace-git 0.9.1-next.9 → 0.10.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.
@@ -5,14 +5,22 @@ 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
- export declare const DEFAULT_WORKTREE_DIR = ".bakers-worktrees";
8
+ /** Default branch template: `<prefix><key>-<title-slug>` (readable). */
9
+ export declare const DEFAULT_BRANCH_TEMPLATE = "{branch_prefix}{key}-{title_slug}";
9
10
  /** Runs `git <args>` in a cwd; resolves with stdout when it has one. */
10
11
  export type GitRunner = (args: string[], cwd: string) => Promise<string | undefined>;
11
12
  export interface GitWorkspaceOptions {
12
13
  /** Main clone (a git repo): config source + worktree base. */
13
14
  root: string;
14
- /** Directory of new worktrees, relative to `root` or absolute. Default: {@link DEFAULT_WORKTREE_DIR}. */
15
- worktreeDir?: 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;
16
24
  /**
17
25
  * Default `false`: before creating a worktree, set `branch.autoSetupMerge=false`
18
26
  * in `root`, and give runs `push.default=current`. `true` leaves Git alone.
@@ -29,26 +37,26 @@ export interface GitWorkspaceOptions {
29
37
  export declare class GitWorkspace implements BbWorkspace {
30
38
  private readonly runGit;
31
39
  private readonly root;
32
- private readonly worktreeDir;
40
+ private readonly worktreesRoot;
41
+ private readonly branchPrefix;
42
+ private readonly branchTemplate;
33
43
  private readonly autoSetupMerge;
34
44
  private readonly logger;
35
45
  private readonly clone;
36
46
  private readonly shared;
37
47
  constructor(options: GitWorkspaceOptions);
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;
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>;
46
53
  /** Tear down the ticket worktree with git ({@link removeGitWorktree}). */
47
54
  remove(branch: string, worktreePath?: string): Promise<WorktreeTeardown>;
48
55
  }
49
56
  /** The addon entry's `with` value (see options.schema.json). */
50
57
  export interface GitWorkspaceAddonOptions {
51
- worktree_dir?: string;
58
+ branch_prefix?: string;
59
+ branch_template?: string;
52
60
  auto_setup_merge?: boolean;
53
61
  shared?: boolean;
54
62
  }
package/dist/src/index.js CHANGED
@@ -4,19 +4,28 @@
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 { resolve } from 'node:path';
8
- import { deriveCheckoutRoot, exec, } from '@bakers-build/core';
7
+ import { join, resolve } from 'node:path';
8
+ import { deriveCheckoutRoot, exec, slugify, } from '@bakers-build/core';
9
9
  import { runBranchGit } from './git-config.js';
10
10
  import { loadInstructions } from './instructions.js';
11
- import { removeGitWorktree, ticketWorktrees } from './remove-git-worktree.js';
11
+ import { removeGitWorktree } 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
- // shortcut: one default for all executors, upgrade when an executor needs another value.
19
- export const DEFAULT_WORKTREE_DIR = '.bakers-worktrees';
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
+ }
20
29
  const defaultGitRunner = (args, cwd) => exec('git', args, { cwd });
21
30
  const noopLogger = {
22
31
  debug() { },
@@ -27,7 +36,9 @@ const noopLogger = {
27
36
  export class GitWorkspace {
28
37
  runGit;
29
38
  root;
30
- worktreeDir;
39
+ worktreesRoot;
40
+ branchPrefix;
41
+ branchTemplate;
31
42
  autoSetupMerge;
32
43
  logger;
33
44
  clone;
@@ -35,40 +46,60 @@ export class GitWorkspace {
35
46
  constructor(options) {
36
47
  this.runGit = options.runGit ?? defaultGitRunner;
37
48
  this.root = resolve(options.root);
38
- this.worktreeDir = resolve(this.root, options.worktreeDir ?? DEFAULT_WORKTREE_DIR);
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;
39
54
  this.autoSetupMerge = options.autoSetupMerge ?? false;
40
55
  this.logger = options.logger;
41
56
  this.clone = options.clone ?? false;
42
57
  this.shared = options.shared ?? false;
43
58
  }
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);
57
- }
58
- catch {
59
- checked = undefined;
60
- }
61
- if (checked?.trim() !== branch) {
62
- throw new Error(`invalid branch name: ${branch}`);
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}`);
63
80
  }
64
- const path = resolve(this.worktreeDir, branch);
81
+ const path = this.pathFor(key);
65
82
  const env = this.autoSetupMerge
66
83
  ? undefined
67
84
  : await runBranchGit(this.root, this.logger);
68
85
  const extra = env ? { env } : {};
69
86
  if (this.clone) {
70
87
  const created = !existsSync(path);
71
- await this.ensureBranch(branch);
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
+ }
72
103
  const target = targetOf(baseRef);
73
104
  if (target && baseRef?.startsWith('origin/')) {
74
105
  try {
@@ -93,22 +124,16 @@ export class GitWorkspace {
93
124
  ...extra,
94
125
  };
95
126
  }
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) {
127
+ if (existsSync(path)) {
101
128
  return {
102
- path: existing,
103
- instructions: loadInstructions(existing),
129
+ path,
130
+ instructions: loadInstructions(path),
104
131
  created: false,
105
132
  ...extra,
106
133
  };
107
134
  }
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);
135
+ const branch = this.branchFor(identifier, title);
136
+ await this.runGit(['-C', this.root, 'worktree', 'add', '--force', '-B', branch, path], this.root);
112
137
  // The `after_create` hook is run by the conductor, not here — the
113
138
  // workspace only reports that it created a fresh worktree.
114
139
  return {
@@ -118,22 +143,6 @@ export class GitWorkspace {
118
143
  ...extra,
119
144
  };
120
145
  }
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
- }
137
146
  /** Tear down the ticket worktree with git ({@link removeGitWorktree}). */
138
147
  async remove(branch, worktreePath) {
139
148
  const removed = removeRunCloneWorkspace(worktreePath);
@@ -153,12 +162,14 @@ export function gitWorkspace(opts = {}) {
153
162
  const root = await deriveCheckoutRoot(config.config_path);
154
163
  return new GitWorkspace({
155
164
  root,
156
- ...(opts.worktree_dir ? { worktreeDir: opts.worktree_dir } : {}),
165
+ ...(opts.branch_prefix ? { branchPrefix: opts.branch_prefix } : {}),
166
+ ...(opts.branch_template
167
+ ? { branchTemplate: opts.branch_template }
168
+ : {}),
157
169
  ...(opts.auto_setup_merge ? { autoSetupMerge: true } : {}),
158
170
  ...(deps?.logger ? { logger: deps.logger } : {}),
159
171
  clone: config.runtime?.isolates === true,
160
- // A runtime's `shared` wins; the workspace option is the deprecated fallback.
161
- shared: config.runtime?.shared ?? opts.shared ?? false,
172
+ ...(opts.shared ? { shared: true } : {}),
162
173
  });
163
174
  },
164
175
  };
@@ -2,15 +2,6 @@ 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
- }[];
14
5
  /**
15
6
  * Tear down one ticket worktree with git alone — the shared teardown of every
16
7
  * 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
- export function ticketWorktrees(output, root) {
11
+ 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,10 +4,15 @@
4
4
  "title": "@bakers-build/addon-workspace-git options",
5
5
  "type": "object",
6
6
  "properties": {
7
- "worktree_dir": {
7
+ "branch_prefix": {
8
8
  "type": "string",
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"
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}"
11
16
  },
12
17
  "auto_setup_merge": {
13
18
  "type": "boolean",
@@ -17,8 +22,7 @@
17
22
  "shared": {
18
23
  "type": "boolean",
19
24
  "default": false,
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
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."
22
26
  }
23
27
  },
24
28
  "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.9",
3
+ "version": "0.10.0",
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.9",
26
- "@bakers-build/core": "^0.9.1-next.9"
25
+ "@bakers-build/conductor": "^0.10.0",
26
+ "@bakers-build/core": "^0.10.0"
27
27
  },
28
28
  "bakersBuild": {
29
- "commit": "fa0565441ae1aee6535c9205b3a37f87e9b52054",
30
- "channel": "next"
29
+ "commit": "5857b00008bc0926fd52fdc8d9366d6d52444e35",
30
+ "channel": "latest"
31
31
  }
32
32
  }