oh-my-space 0.5.0 → 0.7.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/dist/oms.js CHANGED
@@ -1,23 +1,26 @@
1
1
  #!/usr/bin/env node
2
2
  import { spawnSync } from "node:child_process";
3
- import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, rmdirSync, writeFileSync, } from "node:fs";
4
- import { dirname, join, relative, resolve } from "node:path";
3
+ import { existsSync, readFileSync, readdirSync, rmSync, rmdirSync, writeFileSync, } from "node:fs";
4
+ import { dirname, join, resolve } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { Command } from "commander";
7
- import { cancel, isCancel, log, multiselect } from "@clack/prompts";
7
+ import { cancel, isCancel, log, multiselect, select } from "@clack/prompts";
8
8
  import { parse as parseYaml } from "yaml";
9
9
  const ALIAS_PATTERN = /^[a-z0-9][a-z0-9-]*$/;
10
+ const REMOTE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._/-]*$/;
10
11
  const ALLOWED_TOP_KEYS = new Set(["repos"]);
11
- const ALLOWED_ITEM_KEYS = new Set(["alias", "url", "branch"]);
12
- const FETCH_REFSPEC = "+refs/heads/*:refs/remotes/origin/*";
12
+ const ALLOWED_ITEM_KEYS = new Set(["alias", "remotes", "branch"]);
13
13
  const MANIFEST_FILENAME = "oms.yaml";
14
14
  const DATA_DIRNAME = "oms";
15
15
  const GITIGNORE_ENTRY = `${DATA_DIRNAME}/`;
16
16
  const GITIGNORE_COMMENT = "# managed by oms";
17
17
  const LEGACY_MANIFEST = "sources.yaml";
18
18
  const LEGACY_DATA_DIRNAME = "sources";
19
- const LEGACY_MIGRATION_DOC = "docs/migrations/0.3.x-to-0.4.0.md";
20
- const SUBMODULE_MIGRATION_DOC = "docs/migrations/0.2.x-to-0.3.0.md";
19
+ const RENAME_MIGRATION_DOC = "docs/migrations/0.3.x-to-0.4.0.md";
20
+ const WORKTREE_MIGRATION_DOC = "docs/migrations/0.5.x-to-0.6.0.md";
21
+ const REMOTES_MIGRATION_DOC = "docs/migrations/0.6.x-to-0.7.0.md";
22
+ /** GitHub blob base for the clickable doc permalinks shown in CLI messages. */
23
+ const DOCS_REPO_BLOB_BASE = "https://github.com/divlook/oh-my-space/blob";
21
24
  const MIN_GIT_MAJOR = 2;
22
25
  const MIN_GIT_MINOR = 40;
23
26
  const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
@@ -48,6 +51,10 @@ function validateSources(data) {
48
51
  throw new Error(`${MANIFEST_FILENAME}: ${where} must be a mapping`);
49
52
  }
50
53
  const r = item;
54
+ // Friendlier than "unknown key url": the 0.7.0 manifest replaced url with a remotes mapping.
55
+ if ("url" in r && !("remotes" in r)) {
56
+ throw new Error(`${MANIFEST_FILENAME}: ${where}.url is no longer supported; use a "remotes" mapping with an "origin" entry. See ${docUrl(REMOTES_MIGRATION_DOC)}`);
57
+ }
51
58
  for (const key of Object.keys(r)) {
52
59
  if (!ALLOWED_ITEM_KEYS.has(key)) {
53
60
  throw new Error(`${MANIFEST_FILENAME}: ${where} has unknown key "${key}"`);
@@ -63,8 +70,25 @@ function validateSources(data) {
63
70
  throw new Error(`${MANIFEST_FILENAME}: duplicate alias "${r.alias}"`);
64
71
  }
65
72
  seen.add(r.alias);
66
- if (typeof r.url !== "string" || r.url.length === 0) {
67
- throw new Error(`${MANIFEST_FILENAME}: ${where} missing required "url"`);
73
+ if (!r.remotes || typeof r.remotes !== "object" || Array.isArray(r.remotes)) {
74
+ throw new Error(`${MANIFEST_FILENAME}: ${where} missing required "remotes" mapping`);
75
+ }
76
+ const remoteEntries = Object.entries(r.remotes);
77
+ if (remoteEntries.length === 0) {
78
+ throw new Error(`${MANIFEST_FILENAME}: ${where}.remotes must have at least one remote`);
79
+ }
80
+ const remotes = {};
81
+ for (const [name, url] of remoteEntries) {
82
+ if (!REMOTE_NAME_PATTERN.test(name)) {
83
+ throw new Error(`${MANIFEST_FILENAME}: ${where}.remotes name "${name}" must match ${REMOTE_NAME_PATTERN}`);
84
+ }
85
+ if (typeof url !== "string" || url.length === 0) {
86
+ throw new Error(`${MANIFEST_FILENAME}: ${where}.remotes.${name} must be a non-empty string URL`);
87
+ }
88
+ remotes[name] = url;
89
+ }
90
+ if (!remotes.origin) {
91
+ throw new Error(`${MANIFEST_FILENAME}: ${where}.remotes must include an "origin" entry`);
68
92
  }
69
93
  let branch;
70
94
  if (r.branch !== undefined) {
@@ -73,19 +97,27 @@ function validateSources(data) {
73
97
  }
74
98
  branch = r.branch;
75
99
  }
76
- validated.push({ alias: r.alias, url: r.url, branch });
100
+ validated.push({ alias: r.alias, remotes, branch });
77
101
  });
78
102
  return validated;
79
103
  }
80
104
  function pad(s, width) {
81
105
  return s + " ".repeat(Math.max(0, width - s.length));
82
106
  }
107
+ /** Names of a repo's non-origin remotes, in declared order (origin is shown via its URL column). */
108
+ function extraRemoteNames(repo) {
109
+ return Object.keys(repo.remotes).filter((name) => name !== "origin");
110
+ }
83
111
  function printList(repos) {
112
+ const extras = (r) => {
113
+ const names = extraRemoteNames(r);
114
+ return names.length > 0 ? ` (+${names.join(",")})` : "";
115
+ };
84
116
  const aliasW = Math.max("ALIAS".length, ...repos.map((r) => r.alias.length));
85
- const urlW = Math.max("URL".length, ...repos.map((r) => r.url.length));
86
- console.log(dim(`${pad("ALIAS", aliasW)} ${pad("URL", urlW)} BRANCH`));
117
+ const urlW = Math.max("ORIGIN".length, ...repos.map((r) => (r.remotes.origin + extras(r)).length));
118
+ console.log(dim(`${pad("ALIAS", aliasW)} ${pad("ORIGIN", urlW)} BRANCH`));
87
119
  for (const r of repos) {
88
- console.log(`${pad(r.alias, aliasW)} ${pad(r.url, urlW)} ${r.branch ?? ""}`);
120
+ console.log(`${pad(r.alias, aliasW)} ${pad(r.remotes.origin + extras(r), urlW)} ${r.branch ?? ""}`);
89
121
  }
90
122
  }
91
123
  async function selectInteractive(repos, actionLabel) {
@@ -106,6 +138,56 @@ async function selectInteractive(repos, actionLabel) {
106
138
  .map((alias) => repos.find((r) => r.alias === alias))
107
139
  .filter((r) => r !== undefined);
108
140
  }
141
+ /**
142
+ * Decide which remote(s) a fetch/pull/push targets for one repo. Honors an explicit --remote list,
143
+ * otherwise prompts interactively on a TTY (origin preselected) and falls back to origin off-TTY.
144
+ * pull is restricted to a single remote since --ff-only can advance to at most one. Returns the
145
+ * resolved remote names, or null when the request is invalid or the prompt was cancelled.
146
+ */
147
+ async function resolveRemotes(repo, requested, command) {
148
+ const declared = Object.keys(repo.remotes);
149
+ if (requested && requested.length > 0) {
150
+ const unique = uniqueAliases(requested);
151
+ const unknown = unique.filter((name) => !declared.includes(name));
152
+ if (unknown.length > 0) {
153
+ log.error(`${repo.alias}: unknown remote(s): ${unknown.join(", ")}. Declared: ${declared.join(", ")}.`);
154
+ return null;
155
+ }
156
+ if (command === "pull" && unique.length > 1) {
157
+ log.error(`${repo.alias}: pull targets a single remote (git pull --ff-only can advance only one).`);
158
+ return null;
159
+ }
160
+ return unique;
161
+ }
162
+ // No explicit remote: a lone origin needs no prompt, and a non-interactive shell defaults to origin.
163
+ if (declared.length === 1)
164
+ return declared;
165
+ if (!process.stdin.isTTY)
166
+ return ["origin"];
167
+ if (command === "pull") {
168
+ const choice = await select({
169
+ message: `${repo.alias}: select a remote to ${command}`,
170
+ options: declared.map((name) => ({ value: name, label: name, hint: repo.remotes[name] })),
171
+ initialValue: "origin",
172
+ });
173
+ if (isCancel(choice)) {
174
+ cancel("Cancelled.");
175
+ return null;
176
+ }
177
+ return [choice];
178
+ }
179
+ const choice = await multiselect({
180
+ message: `${repo.alias}: select remote(s) to ${command} (space to toggle, enter to confirm)`,
181
+ options: declared.map((name) => ({ value: name, label: name, hint: repo.remotes[name] })),
182
+ initialValues: ["origin"],
183
+ required: true,
184
+ });
185
+ if (isCancel(choice)) {
186
+ cancel("Cancelled.");
187
+ return null;
188
+ }
189
+ return choice;
190
+ }
109
191
  function runGit(cwd, args, inheritOutput = false) {
110
192
  const result = spawnSync("git", args, {
111
193
  cwd,
@@ -118,9 +200,9 @@ function runGit(cwd, args, inheritOutput = false) {
118
200
  stdout: inheritOutput ? "" : (result.stdout ?? ""),
119
201
  };
120
202
  }
121
- /** Run git from oms/<alias>/ with safe.bareRepository=all, so the .git placeholder routes to .bare. */
122
- function runBareGit(repoRoot, alias, args, inheritOutput = false) {
123
- return runGit(aliasDir(repoRoot, alias), ["-c", "safe.bareRepository=all", ...args], inheritOutput);
203
+ /** Run git inside the submodule working tree at oms/<alias>/. */
204
+ function runSub(repoRoot, alias, args, inheritOutput = false) {
205
+ return runGit(aliasDir(repoRoot, alias), args, inheritOutput);
124
206
  }
125
207
  function parseGitVersion(s) {
126
208
  const m = s.match(/git version (\d+)\.(\d+)/);
@@ -149,15 +231,14 @@ function findWorkspaceRoot(options = {}) {
149
231
  function aliasDir(repoRoot, alias) {
150
232
  return join(repoRoot, DATA_DIRNAME, alias);
151
233
  }
152
- function bareDir(repoRoot, alias) {
153
- return join(aliasDir(repoRoot, alias), ".bare");
154
- }
155
- function gitPlaceholderPath(repoRoot, alias) {
156
- return join(aliasDir(repoRoot, alias), ".git");
234
+ /** Submodule name and path are identical under our convention: oms/<alias>. */
235
+ function submodulePath(alias) {
236
+ return `${DATA_DIRNAME}/${alias}`;
157
237
  }
158
- function worktreePath(repoRoot, alias, branch) {
159
- return join(aliasDir(repoRoot, alias), branch);
238
+ function isGitRepo(repoRoot) {
239
+ return runGit(repoRoot, ["rev-parse", "--is-inside-work-tree"]).stdout.trim() === "true";
160
240
  }
241
+ /** True when .gitmodules registers a submodule at the given path (sources/<alias> or oms/<alias>). */
161
242
  function isRegisteredSubmodule(repoRoot, sourcePath) {
162
243
  if (!existsSync(join(repoRoot, ".gitmodules")))
163
244
  return false;
@@ -174,27 +255,84 @@ function isRegisteredSubmodule(repoRoot, sourcePath) {
174
255
  .split("\n")
175
256
  .some((line) => line.trim().split(/\s+/)[1] === sourcePath);
176
257
  }
177
- /** Returns true when .gitmodules registers any sources/<alias> or oms/<alias> entry for the loaded repos. */
178
- function hasLegacySubmoduleLayout(repoRoot, repos) {
179
- if (!existsSync(join(repoRoot, ".gitmodules")))
180
- return false;
181
- return repos.some((repo) => isRegisteredSubmodule(repoRoot, `${LEGACY_DATA_DIRNAME}/${repo.alias}`)
182
- || isRegisteredSubmodule(repoRoot, `${DATA_DIRNAME}/${repo.alias}`));
258
+ /** A submodule is initialized when its working tree has a .git gitlink file/dir. */
259
+ function submoduleInitialized(repoRoot, alias) {
260
+ return existsSync(join(aliasDir(repoRoot, alias), ".git"));
183
261
  }
184
- function abortOnLegacy(repoRoot, repos) {
185
- if (!hasLegacySubmoduleLayout(repoRoot, repos))
186
- return false;
187
- log.error('detected legacy submodule layout (.gitmodules registers an alias path). oh-my-space 0.3.0+ uses bare clone + worktrees.\n' +
188
- ` See ${SUBMODULE_MIGRATION_DOC} for the manual steps. Aborting to avoid destructive change.`);
189
- return true;
262
+ /** Short branch name, or null when HEAD is detached. */
263
+ function currentBranch(dir) {
264
+ const r = runGit(dir, ["rev-parse", "--abbrev-ref", "HEAD"]);
265
+ if (!r.success)
266
+ return null;
267
+ const b = r.stdout.trim();
268
+ return b && b !== "HEAD" ? b : null;
190
269
  }
191
- /** Inspect a single directory for 0.3.x rename artifacts. */
192
- function detectLegacyRenameArtifactsAt(dir) {
193
- const manifest = existsSync(join(dir, LEGACY_MANIFEST));
194
- const data = existsSync(join(dir, LEGACY_DATA_DIRNAME));
195
- if (!manifest && !data)
270
+ function shortSha(dir) {
271
+ const r = runGit(dir, ["rev-parse", "--short", "HEAD"]);
272
+ return r.success ? r.stdout.trim() : "???????";
273
+ }
274
+ function localBranchExists(dir, branch) {
275
+ return runGit(dir, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]).success;
276
+ }
277
+ function remoteBranchExists(dir, branch) {
278
+ return runGit(dir, ["rev-parse", "--verify", "--quiet", `refs/remotes/origin/${branch}`]).success;
279
+ }
280
+ function isDirty(dir) {
281
+ const r = runGit(dir, ["status", "--porcelain"]);
282
+ return r.success && r.stdout.trim().length > 0;
283
+ }
284
+ /** The branch recorded in .gitmodules for the submodule, if any. */
285
+ function gitmodulesBranch(repoRoot, alias) {
286
+ const r = runGit(repoRoot, [
287
+ "config",
288
+ "--file",
289
+ ".gitmodules",
290
+ "--get",
291
+ `submodule.${submodulePath(alias)}.branch`,
292
+ ]);
293
+ if (!r.success)
196
294
  return null;
197
- return { manifest, data };
295
+ const b = r.stdout.trim();
296
+ return b.length > 0 ? b : null;
297
+ }
298
+ /**
299
+ * Keep the submodule on a branch instead of a detached HEAD. Only acts when HEAD is detached,
300
+ * so a branch the user is already working on is never disturbed. When no local branch exists
301
+ * yet, a branch is created at the current (pinned) commit — the checked-out commit is preserved,
302
+ * which keeps the parent's recorded pointer reproducible.
303
+ */
304
+ function attachBranch(repoRoot, alias, branch) {
305
+ if (currentBranch(aliasDir(repoRoot, alias)) !== null)
306
+ return;
307
+ if (localBranchExists(aliasDir(repoRoot, alias), branch)) {
308
+ runSub(repoRoot, alias, ["switch", branch]);
309
+ return;
310
+ }
311
+ // Create the branch at the current HEAD (the pinned commit) so the worktree stays put.
312
+ if (!runSub(repoRoot, alias, ["switch", "-c", branch]).success)
313
+ return;
314
+ if (remoteBranchExists(aliasDir(repoRoot, alias), branch)) {
315
+ runSub(repoRoot, alias, ["branch", "--set-upstream-to", `origin/${branch}`, branch]);
316
+ }
317
+ }
318
+ /**
319
+ * Reconcile the submodule's git remotes with the declared `remotes` map: add missing remotes and
320
+ * update URLs that drifted. Non-destructive — remotes no longer in oms.yaml are left untouched.
321
+ */
322
+ function ensureRemotes(repoRoot, alias, remotes) {
323
+ for (const [name, url] of Object.entries(remotes)) {
324
+ const existing = runSub(repoRoot, alias, ["remote", "get-url", name]);
325
+ if (!existing.success) {
326
+ runSub(repoRoot, alias, ["remote", "add", name, url]);
327
+ }
328
+ else if (existing.stdout.trim() !== url) {
329
+ runSub(repoRoot, alias, ["remote", "set-url", name, url]);
330
+ }
331
+ }
332
+ }
333
+ /** Stage the submodule gitlink in the parent so a moved pointer shows up and is ready to commit. */
334
+ function stagePointer(repoRoot, alias) {
335
+ runGit(repoRoot, ["add", "--", submodulePath(alias)]);
198
336
  }
199
337
  function emitLegacyRenameMessage(dir, found) {
200
338
  const artifacts = [
@@ -205,14 +343,15 @@ function emitLegacyRenameMessage(dir, found) {
205
343
  .join(" and ");
206
344
  log.error(`detected legacy ${artifacts} at ${dir}.\n` +
207
345
  ` oh-my-space 0.4.0 renamed the manifest to ${MANIFEST_FILENAME} and the data directory to ${DATA_DIRNAME}/.\n` +
208
- ` See ${LEGACY_MIGRATION_DOC} for the manual steps. Aborting to avoid destructive change.`);
346
+ ` See ${docUrl(RENAME_MIGRATION_DOC)} for the manual steps. Aborting to avoid destructive change.`);
209
347
  }
210
- /** Block when the active oms.yaml workspace still has legacy artifacts at its root. */
348
+ /** Block when the active oms.yaml workspace still has 0.3.x rename artifacts at its root. */
211
349
  function abortOnLegacyRenameAt(repoRoot) {
212
- const found = detectLegacyRenameArtifactsAt(repoRoot);
213
- if (!found)
350
+ const manifest = existsSync(join(repoRoot, LEGACY_MANIFEST));
351
+ const data = existsSync(join(repoRoot, LEGACY_DATA_DIRNAME));
352
+ if (!manifest && !data)
214
353
  return false;
215
- emitLegacyRenameMessage(repoRoot, found);
354
+ emitLegacyRenameMessage(repoRoot, { manifest, data });
216
355
  return true;
217
356
  }
218
357
  /**
@@ -236,331 +375,241 @@ function emitLegacyRenameHintWalkUp(options = {}) {
236
375
  current = parent;
237
376
  }
238
377
  }
239
- function ensureGitignore(repoRoot) {
240
- const path = join(repoRoot, ".gitignore");
241
- let content = "";
242
- if (existsSync(path)) {
243
- content = readFileSync(path, "utf8");
244
- const present = content
245
- .split("\n")
246
- .some((line) => line.trim() === GITIGNORE_ENTRY || line.trim() === `/${GITIGNORE_ENTRY}`);
247
- if (present)
248
- return;
249
- }
250
- const needsNewline = content.length > 0 && !content.endsWith("\n");
251
- const block = `${GITIGNORE_COMMENT}\n${GITIGNORE_ENTRY}\n`;
252
- writeFileSync(path, `${content}${needsNewline ? "\n" : ""}${block}`);
253
- log.info(`added ${GITIGNORE_ENTRY} to .gitignore`);
254
- }
255
- function setupBareRepo(repo, repoRoot) {
256
- const alias = repo.alias;
257
- const aliasPath = aliasDir(repoRoot, alias);
258
- const barePath = bareDir(repoRoot, alias);
259
- mkdirSync(aliasPath, { recursive: true });
260
- const relBare = relative(repoRoot, barePath);
261
- log.step(`git clone --bare ${repo.url} ${relBare}`);
262
- const clone = runGit(repoRoot, ["clone", "--bare", repo.url, relBare], true);
263
- if (!clone.success) {
264
- log.error(`${alias}: git clone --bare failed (exit ${clone.exitCode})`);
265
- if (existsSync(barePath))
266
- rmSync(barePath, { recursive: true, force: true });
378
+ /** Detect leftover 0.3.x–0.5.x bare clone + worktree artifacts (oms/<alias>/.bare). */
379
+ function abortOnLegacyWorktree(repoRoot, repos) {
380
+ const stale = repos.find((repo) => existsSync(join(aliasDir(repoRoot, repo.alias), ".bare")));
381
+ if (!stale)
267
382
  return false;
268
- }
269
- // Write the placeholder before any further runBareGit calls, otherwise git ascends
270
- // out of oms/<alias>/ looking for a repo and touches the wrong .git.
271
- writeFileSync(gitPlaceholderPath(repoRoot, alias), "gitdir: ./.bare\n");
272
- const config = runBareGit(repoRoot, alias, [
273
- "config",
274
- "remote.origin.fetch",
275
- FETCH_REFSPEC,
276
- ]);
277
- if (!config.success) {
278
- log.error(`${alias}: failed to set remote.origin.fetch (exit ${config.exitCode})`);
279
- return false;
280
- }
281
- log.step(`${alias}: git fetch origin`);
282
- const fetch = runBareGit(repoRoot, alias, ["fetch", "origin", "--prune"], true);
283
- if (!fetch.success) {
284
- log.error(`${alias}: initial fetch failed (exit ${fetch.exitCode})`);
285
- return false;
286
- }
383
+ log.error(`detected a legacy bare clone at ${DATA_DIRNAME}/${stale.alias}/.bare. oh-my-space 0.6.0 manages sources as git submodules.\n` +
384
+ ` See ${docUrl(WORKTREE_MIGRATION_DOC)} for the manual steps. Aborting to avoid destructive change.`);
287
385
  return true;
288
386
  }
289
- function detectDefaultBranch(repoRoot, alias) {
290
- const r = runBareGit(repoRoot, alias, ["symbolic-ref", "--short", "HEAD"]);
291
- if (r.success) {
292
- const out = r.stdout.trim();
293
- return out.length > 0 ? out : null;
294
- }
295
- return null;
296
- }
297
- function listExistingWorktrees(repoRoot, alias) {
298
- if (!existsSync(bareDir(repoRoot, alias)))
299
- return [];
300
- const result = runBareGit(repoRoot, alias, ["worktree", "list", "--porcelain"]);
301
- if (!result.success)
302
- return [];
303
- const aliasPath = aliasDir(repoRoot, alias);
304
- const entries = [];
305
- const blocks = result.stdout
306
- .split(/\n\n+/)
307
- .map((b) => b.trim())
308
- .filter((b) => b.length > 0);
309
- for (const block of blocks) {
310
- let path = "";
311
- let branch = "(detached)";
312
- let bare = false;
313
- for (const line of block.split("\n")) {
314
- if (line.startsWith("worktree "))
315
- path = line.slice("worktree ".length);
316
- else if (line.startsWith("branch ")) {
317
- branch = line.slice("branch ".length).replace(/^refs\/heads\//, "");
318
- }
319
- else if (line === "bare")
320
- bare = true;
321
- }
322
- if (!path || bare)
323
- continue;
324
- const rel = relative(aliasPath, path);
325
- // Skip worktrees outside oms/<alias>/ (shouldn't happen, but be safe)
326
- if (rel.startsWith(".."))
327
- continue;
328
- entries.push({ branch, path, relativePath: rel });
329
- }
330
- return entries;
331
- }
332
- function cleanupEmptyParents(repoRoot, alias, branch) {
333
- const parts = branch.split("/").filter((p) => p.length > 0);
334
- if (parts.length < 2)
387
+ /** Submodules live inside the parent's history, so oms/ must not be gitignored. Strip a managed entry. */
388
+ function ensureOmsNotIgnored(repoRoot) {
389
+ const path = join(repoRoot, ".gitignore");
390
+ if (!existsSync(path))
335
391
  return;
336
- for (let i = parts.length - 1; i >= 1; i--) {
337
- const dirPath = join(aliasDir(repoRoot, alias), ...parts.slice(0, i));
338
- try {
339
- const entries = readdirSync(dirPath);
340
- if (entries.length === 0) {
341
- rmdirSync(dirPath);
342
- }
343
- else {
344
- break;
345
- }
346
- }
347
- catch {
348
- break;
392
+ const lines = readFileSync(path, "utf8").split("\n");
393
+ const out = [];
394
+ let removed = false;
395
+ for (const line of lines) {
396
+ const trimmed = line.trim();
397
+ if (trimmed === GITIGNORE_ENTRY || trimmed === `/${GITIGNORE_ENTRY}`) {
398
+ if (out.length > 0 && out[out.length - 1].trim() === GITIGNORE_COMMENT)
399
+ out.pop();
400
+ removed = true;
401
+ continue;
349
402
  }
403
+ out.push(line);
350
404
  }
351
- }
352
- function addWorktree(repo, repoRoot, branch) {
353
- const wtPath = worktreePath(repoRoot, repo.alias, branch);
354
- if (existsSync(wtPath)) {
355
- log.warn(`${repo.alias}: ${DATA_DIRNAME}/${repo.alias}/${branch} already exists; skipping.`);
356
- return true;
357
- }
358
- log.step(`${repo.alias}: git worktree add --track -B ${branch} ${branch} origin/${branch}`);
359
- const result = runBareGit(repoRoot, repo.alias, ["worktree", "add", "--track", "-B", branch, branch, `origin/${branch}`], true);
360
- if (!result.success) {
361
- log.error(`${repo.alias}: worktree add for ${branch} failed (exit ${result.exitCode})`);
362
- cleanupEmptyParents(repoRoot, repo.alias, branch);
363
- return false;
405
+ if (removed) {
406
+ writeFileSync(path, out.join("\n"));
407
+ log.info(`removed ${GITIGNORE_ENTRY} from .gitignore (submodules are tracked, not ignored)`);
364
408
  }
365
- return true;
366
409
  }
367
- function removeWorktree(repo, repoRoot, branch, force) {
368
- const wtPath = worktreePath(repoRoot, repo.alias, branch);
369
- if (!existsSync(wtPath))
370
- return true;
371
- const args = ["worktree", "remove", ...(force ? ["--force"] : []), branch];
372
- log.step(`${repo.alias}: git worktree remove ${branch}${force ? " --force" : ""}`);
373
- const result = runBareGit(repoRoot, repo.alias, args, true);
374
- if (!result.success) {
375
- log.error(`${repo.alias}: worktree remove for ${branch} failed (exit ${result.exitCode})`);
376
- return false;
410
+ function gitignoreIgnoresOms(repoRoot) {
411
+ const gi = join(repoRoot, ".gitignore");
412
+ return (existsSync(gi)
413
+ && readFileSync(gi, "utf8")
414
+ .split("\n")
415
+ .some((l) => l.trim() === GITIGNORE_ENTRY || l.trim() === `/${GITIGNORE_ENTRY}`));
416
+ }
417
+ function cleanupFailedAdd(repoRoot, alias) {
418
+ const path = submodulePath(alias);
419
+ runGit(repoRoot, ["submodule", "deinit", "-f", "--", path]);
420
+ runGit(repoRoot, ["rm", "-f", "--cached", "--", path]);
421
+ runGit(repoRoot, ["config", "--file", ".gitmodules", "--remove-section", `submodule.${path}`]);
422
+ if (existsSync(join(repoRoot, ".gitmodules")))
423
+ runGit(repoRoot, ["add", ".gitmodules"]);
424
+ try {
425
+ rmSync(join(repoRoot, ".git", "modules", DATA_DIRNAME, alias), { recursive: true, force: true });
377
426
  }
378
- cleanupEmptyParents(repoRoot, repo.alias, branch);
379
- return true;
427
+ catch { }
428
+ try {
429
+ if (existsSync(aliasDir(repoRoot, alias)))
430
+ rmSync(aliasDir(repoRoot, alias), { recursive: true, force: true });
431
+ }
432
+ catch { }
380
433
  }
381
434
  function syncRepo(repo, repoRoot) {
382
435
  const alias = repo.alias;
383
- const aliasPath = aliasDir(repoRoot, alias);
384
- const barePath = bareDir(repoRoot, alias);
385
- const placeholderPath = gitPlaceholderPath(repoRoot, alias);
386
- const bareExists = existsSync(barePath);
387
- if (!bareExists) {
388
- if (existsSync(aliasPath)) {
389
- const stray = readdirSync(aliasPath).filter((e) => e !== ".git");
390
- if (stray.length > 0) {
391
- log.error(`${alias}: ${DATA_DIRNAME}/${alias}/ already exists but is not a bare clone. Move or remove it manually, then retry.`);
392
- return "failed";
393
- }
436
+ const path = submodulePath(alias);
437
+ const registered = isRegisteredSubmodule(repoRoot, path);
438
+ if (!registered) {
439
+ if (existsSync(aliasDir(repoRoot, alias)) && readdirSync(aliasDir(repoRoot, alias)).length > 0) {
440
+ log.error(`${alias}: ${path}/ already exists but is not a registered submodule. Move or remove it manually, then retry.`);
441
+ return "failed";
394
442
  }
395
443
  if (repo.branch) {
396
444
  const lsRemote = runGit(repoRoot, [
397
445
  "ls-remote",
398
446
  "--exit-code",
399
447
  "--heads",
400
- repo.url,
448
+ repo.remotes.origin,
401
449
  repo.branch,
402
450
  ]);
403
451
  if (lsRemote.exitCode === 2) {
404
- log.error(`${alias}: branch "${repo.branch}" not found on ${repo.url}. Push the branch upstream or fix the alias, then retry.`);
452
+ log.error(`${alias}: branch "${repo.branch}" not found on ${repo.remotes.origin}. Push the branch upstream or fix the alias, then retry.`);
405
453
  return "failed";
406
454
  }
407
455
  if (!lsRemote.success && lsRemote.exitCode !== 2) {
408
456
  log.warn(`${alias}: branch existence check failed (exit ${lsRemote.exitCode}); proceeding.`);
409
457
  }
410
458
  }
411
- if (!setupBareRepo(repo, repoRoot)) {
412
- if (existsSync(barePath))
413
- rmSync(barePath, { recursive: true, force: true });
414
- if (existsSync(placeholderPath))
415
- rmSync(placeholderPath);
416
- try {
417
- if (readdirSync(aliasPath).length === 0)
418
- rmdirSync(aliasPath);
419
- }
420
- catch { }
421
- return "failed";
459
+ // `git submodule add` refuses when .gitmodules is tracked in HEAD but missing from the
460
+ // working tree — the state left by an uncommitted unsync. Restore an empty one so it can append.
461
+ const gitmodules = join(repoRoot, ".gitmodules");
462
+ if (!existsSync(gitmodules) && runGit(repoRoot, ["cat-file", "-e", "HEAD:.gitmodules"]).success) {
463
+ writeFileSync(gitmodules, "");
422
464
  }
423
- const branch = repo.branch ?? detectDefaultBranch(repoRoot, alias);
424
- if (!branch) {
425
- log.error(`${alias}: could not determine default branch from bare clone. Set "branch:" in ${MANIFEST_FILENAME}.`);
465
+ log.step(`${alias}: git submodule add${repo.branch ? ` -b ${repo.branch}` : ""} ${repo.remotes.origin} ${path}`);
466
+ const args = ["submodule", "add", ...(repo.branch ? ["-b", repo.branch] : []), "--", repo.remotes.origin, path];
467
+ const add = runGit(repoRoot, args, true);
468
+ if (!add.success) {
469
+ log.error(`${alias}: git submodule add failed (exit ${add.exitCode})`);
470
+ cleanupFailedAdd(repoRoot, alias);
426
471
  return "failed";
427
472
  }
428
- if (!addWorktree(repo, repoRoot, branch))
429
- return "failed";
430
- log.success(`${alias}: added (branch=${branch})`);
473
+ ensureRemotes(repoRoot, alias, repo.remotes);
474
+ const branch = repo.branch ?? currentBranch(aliasDir(repoRoot, alias));
475
+ if (branch)
476
+ attachBranch(repoRoot, alias, branch);
477
+ log.success(`${alias}: added${branch ? ` (branch=${branch})` : ""}`);
431
478
  return "added";
432
479
  }
433
- if (!existsSync(placeholderPath)) {
434
- writeFileSync(placeholderPath, "gitdir: ./.bare\n");
480
+ if (!submoduleInitialized(repoRoot, alias)) {
481
+ log.step(`${alias}: git submodule update --init ${path}`);
482
+ const upd = runGit(repoRoot, ["submodule", "update", "--init", "--", path], true);
483
+ if (!upd.success) {
484
+ log.error(`${alias}: git submodule update --init failed (exit ${upd.exitCode})`);
485
+ return "failed";
486
+ }
487
+ ensureRemotes(repoRoot, alias, repo.remotes);
488
+ const branch = gitmodulesBranch(repoRoot, alias) ?? repo.branch;
489
+ if (branch)
490
+ attachBranch(repoRoot, alias, branch);
491
+ log.success(`${alias}: initialized${branch ? ` (branch=${branch})` : ""}`);
492
+ return "added";
435
493
  }
436
- log.step(`${alias}: git fetch origin`);
437
- const fetch = runBareGit(repoRoot, alias, ["fetch", "origin", "--prune"], true);
494
+ ensureRemotes(repoRoot, alias, repo.remotes);
495
+ log.step(`${alias}: git fetch origin --prune`);
496
+ const fetch = runSub(repoRoot, alias, ["fetch", "origin", "--prune"], true);
438
497
  if (!fetch.success) {
439
498
  log.error(`${alias}: fetch failed (exit ${fetch.exitCode})`);
440
499
  return "failed";
441
500
  }
442
- const branch = repo.branch ?? detectDefaultBranch(repoRoot, alias);
443
- if (branch && !existsSync(worktreePath(repoRoot, alias, branch))) {
444
- if (!addWorktree(repo, repoRoot, branch))
445
- return "failed";
446
- }
447
- runBareGit(repoRoot, alias, ["worktree", "prune"]);
501
+ const branch = gitmodulesBranch(repoRoot, alias) ?? repo.branch;
502
+ if (branch)
503
+ attachBranch(repoRoot, alias, branch);
448
504
  log.success(`${alias}: updated`);
449
505
  return "updated";
450
506
  }
451
507
  function unsyncRepo(repo, repoRoot, force) {
452
- const aliasPath = aliasDir(repoRoot, repo.alias);
453
- const barePath = bareDir(repoRoot, repo.alias);
454
- const placeholderPath = gitPlaceholderPath(repoRoot, repo.alias);
455
- const aliasExists = existsSync(aliasPath);
456
- const bareExists = existsSync(barePath);
457
- if (!aliasExists && !bareExists)
508
+ const alias = repo.alias;
509
+ const path = submodulePath(alias);
510
+ const registered = isRegisteredSubmodule(repoRoot, path);
511
+ const exists = existsSync(aliasDir(repoRoot, alias));
512
+ if (!registered && !exists)
458
513
  return "nothing-to-remove";
459
- const worktrees = bareExists ? listExistingWorktrees(repoRoot, repo.alias) : [];
460
- if (!force) {
461
- for (const wt of worktrees) {
462
- const status = runGit(wt.path, ["status", "--porcelain"]);
463
- if (status.success && status.stdout.trim().length > 0) {
464
- log.error(`${repo.alias}: worktree at ${DATA_DIRNAME}/${repo.alias}/${wt.relativePath} has uncommitted changes. Commit, stash, or pass --force.`);
465
- return "failed";
466
- }
467
- }
514
+ if (!force && submoduleInitialized(repoRoot, alias) && isDirty(aliasDir(repoRoot, alias))) {
515
+ log.error(`${alias}: ${path} has uncommitted changes. Commit, stash, or pass --force.`);
516
+ return "failed";
468
517
  }
469
- for (const wt of worktrees) {
470
- const target = wt.branch === "(detached)" ? wt.relativePath : wt.branch;
471
- if (!removeWorktree(repo, repoRoot, target, force)) {
472
- return "failed";
473
- }
518
+ runGit(repoRoot, ["submodule", "deinit", ...(force ? ["-f"] : []), "--", path]);
519
+ const rm = runGit(repoRoot, ["rm", "-f", "--", path], true);
520
+ if (!rm.success) {
521
+ // Fall back to manual unregistration (e.g. the submodule was never initialized).
522
+ runGit(repoRoot, ["rm", "-f", "--cached", "--", path]);
523
+ runGit(repoRoot, ["config", "--file", ".gitmodules", "--remove-section", `submodule.${path}`]);
524
+ if (existsSync(join(repoRoot, ".gitmodules")))
525
+ runGit(repoRoot, ["add", ".gitmodules"]);
474
526
  }
475
- if (existsSync(barePath))
476
- rmSync(barePath, { recursive: true, force: true });
477
- if (existsSync(placeholderPath))
478
- rmSync(placeholderPath);
479
527
  try {
480
- if (existsSync(aliasPath)) {
481
- const remaining = readdirSync(aliasPath);
482
- if (remaining.length === 0)
483
- rmdirSync(aliasPath);
484
- }
528
+ rmSync(join(repoRoot, ".git", "modules", DATA_DIRNAME, alias), { recursive: true, force: true });
485
529
  }
486
530
  catch { }
531
+ if (existsSync(aliasDir(repoRoot, alias))) {
532
+ rmSync(aliasDir(repoRoot, alias), { recursive: true, force: true });
533
+ }
534
+ // Drop the now-empty oms/ directory if nothing else lives there.
535
+ try {
536
+ const parent = join(repoRoot, DATA_DIRNAME);
537
+ if (existsSync(parent) && readdirSync(parent).length === 0)
538
+ rmdirSync(parent);
539
+ }
540
+ catch { }
541
+ // Drop a .gitmodules that no longer registers any submodule (git rm leaves it empty).
542
+ const gitmodules = join(repoRoot, ".gitmodules");
543
+ if (existsSync(gitmodules) && readFileSync(gitmodules, "utf8").trim().length === 0) {
544
+ if (!runGit(repoRoot, ["rm", "-f", "--", ".gitmodules"]).success) {
545
+ rmSync(gitmodules, { force: true });
546
+ }
547
+ }
487
548
  return "removed";
488
549
  }
489
- function fetchRepo(repo, repoRoot) {
490
- if (!existsSync(bareDir(repoRoot, repo.alias))) {
550
+ function fetchRepo(repo, repoRoot, remotes) {
551
+ if (!submoduleInitialized(repoRoot, repo.alias)) {
491
552
  log.error(`${repo.alias}: not synced. Run "oms sync ${repo.alias}" first.`);
492
553
  return "failed";
493
554
  }
494
- log.step(`${repo.alias}: git fetch origin --prune`);
495
- const r = runBareGit(repoRoot, repo.alias, ["fetch", "origin", "--prune"], true);
496
- if (r.success) {
497
- log.success(`${repo.alias}: fetched`);
498
- return "fetched";
499
- }
500
- log.error(`${repo.alias}: fetch failed (exit ${r.exitCode})`);
501
- return "failed";
502
- }
503
- function resolveTargetWorktree(repo, repoRoot) {
504
- const defaultBranch = repo.branch ?? detectDefaultBranch(repoRoot, repo.alias);
505
- if (defaultBranch) {
506
- const path = worktreePath(repoRoot, repo.alias, defaultBranch);
507
- if (existsSync(path))
508
- return { branch: defaultBranch, path };
509
- }
510
- const wts = listExistingWorktrees(repoRoot, repo.alias);
511
- if (wts.length === 1) {
512
- const only = wts[0];
513
- return { branch: only.branch === "(detached)" ? only.relativePath : only.branch, path: only.path };
555
+ for (const remote of remotes) {
556
+ log.step(`${repo.alias}: git fetch ${remote} --prune`);
557
+ const r = runSub(repoRoot, repo.alias, ["fetch", remote, "--prune"], true);
558
+ if (!r.success) {
559
+ log.error(`${repo.alias}: fetch ${remote} failed (exit ${r.exitCode})`);
560
+ return "failed";
561
+ }
514
562
  }
515
- return null;
563
+ log.success(`${repo.alias}: fetched (${remotes.join(", ")})`);
564
+ return "fetched";
516
565
  }
517
- function pullRepo(repo, repoRoot) {
518
- if (!existsSync(bareDir(repoRoot, repo.alias))) {
566
+ function pullRepo(repo, repoRoot, remote) {
567
+ if (!submoduleInitialized(repoRoot, repo.alias)) {
519
568
  log.error(`${repo.alias}: not synced. Run "oms sync ${repo.alias}" first.`);
520
569
  return "failed";
521
570
  }
522
- const target = resolveTargetWorktree(repo, repoRoot);
523
- if (!target) {
524
- log.error(`${repo.alias}: cannot determine which worktree to pull. Use "oms worktree list ${repo.alias}".`);
571
+ const branch = currentBranch(aliasDir(repoRoot, repo.alias));
572
+ if (!branch) {
573
+ log.error(`${repo.alias}: detached HEAD. Run "oms checkout ${repo.alias} <branch>" before pulling.`);
525
574
  return "failed";
526
575
  }
527
- log.step(`${repo.alias}/${target.branch}: git pull --ff-only`);
528
- const r = runGit(target.path, ["pull", "--ff-only"], true);
576
+ log.step(`${repo.alias}/${branch}: git pull --ff-only ${remote} ${branch}`);
577
+ const r = runSub(repoRoot, repo.alias, ["pull", "--ff-only", remote, branch], true);
529
578
  if (r.success) {
530
- log.success(`${repo.alias}/${target.branch}: pulled`);
579
+ stagePointer(repoRoot, repo.alias);
580
+ log.success(`${repo.alias}/${branch}: pulled from ${remote}`);
531
581
  return "pulled";
532
582
  }
533
- log.error(`${repo.alias}/${target.branch}: pull failed (exit ${r.exitCode})`);
583
+ log.error(`${repo.alias}/${branch}: pull from ${remote} failed (exit ${r.exitCode})`);
534
584
  return "failed";
535
585
  }
536
- function pushRepo(repo, repoRoot) {
537
- if (!existsSync(bareDir(repoRoot, repo.alias))) {
586
+ function pushRepo(repo, repoRoot, remotes, commit) {
587
+ if (!submoduleInitialized(repoRoot, repo.alias)) {
538
588
  log.error(`${repo.alias}: not synced. Run "oms sync ${repo.alias}" first.`);
539
589
  return "failed";
540
590
  }
541
- const target = resolveTargetWorktree(repo, repoRoot);
542
- if (!target) {
543
- log.error(`${repo.alias}: cannot determine which worktree to push. Use "oms worktree list ${repo.alias}".`);
591
+ const branch = currentBranch(aliasDir(repoRoot, repo.alias));
592
+ if (!branch) {
593
+ log.error(`${repo.alias}: detached HEAD. Run "oms checkout ${repo.alias} <branch>" before pushing.`);
544
594
  return "failed";
545
595
  }
546
- const upstream = runGit(target.path, [
547
- "rev-parse",
548
- "--abbrev-ref",
549
- "--symbolic-full-name",
550
- "@{u}",
551
- ]);
552
- if (!upstream.success) {
553
- log.error(`${repo.alias}/${target.branch}: git push requires an upstream. Set it manually before pushing.`);
554
- return "failed";
596
+ for (const remote of remotes) {
597
+ // Only origin sets upstream — repointing @{u} to a fork would skew "oms status" ahead/behind.
598
+ const args = remote === "origin" ? ["push", "-u", "origin", branch] : ["push", remote, branch];
599
+ log.step(`${repo.alias}/${branch}: git ${args.join(" ")}`);
600
+ const r = runSub(repoRoot, repo.alias, args, true);
601
+ if (!r.success) {
602
+ log.error(`${repo.alias}/${branch}: push to ${remote} failed (exit ${r.exitCode})`);
603
+ return "failed";
604
+ }
555
605
  }
556
- log.step(`${repo.alias}/${target.branch}: git push`);
557
- const r = runGit(target.path, ["-c", "push.autoSetupRemote=false", "push"], true);
558
- if (r.success) {
559
- log.success(`${repo.alias}/${target.branch}: pushed`);
560
- return "pushed";
606
+ stagePointer(repoRoot, repo.alias);
607
+ if (commit) {
608
+ const sha = shortSha(aliasDir(repoRoot, repo.alias));
609
+ runGit(repoRoot, ["commit", "-m", `oms: bump ${repo.alias} to ${sha}`, "--", submodulePath(repo.alias)]);
561
610
  }
562
- log.error(`${repo.alias}/${target.branch}: push failed (exit ${r.exitCode})`);
563
- return "failed";
611
+ log.success(`${repo.alias}/${branch}: pushed to ${remotes.join(", ")}${commit ? " and recorded pointer" : ""}`);
612
+ return "pushed";
564
613
  }
565
614
  function printSummary(results) {
566
615
  const counts = {
@@ -597,6 +646,24 @@ function loadRepos(options = {}) {
597
646
  return null;
598
647
  }
599
648
  }
649
+ /** Shared preamble: load manifest, emit legacy hints, and confirm the workspace is a git repo. */
650
+ function loadForSubmodules() {
651
+ const loaded = loadRepos();
652
+ if (!loaded) {
653
+ emitLegacyRenameHintWalkUp();
654
+ return null;
655
+ }
656
+ const { repoRoot, repos } = loaded;
657
+ if (abortOnLegacyRenameAt(repoRoot))
658
+ return null;
659
+ if (!isGitRepo(repoRoot)) {
660
+ log.error(`${repoRoot} is not a git repository. oh-my-space 0.6.0 manages sources as git submodules; run "git init" at the workspace root first.`);
661
+ return null;
662
+ }
663
+ if (abortOnLegacyWorktree(repoRoot, repos))
664
+ return null;
665
+ return loaded;
666
+ }
600
667
  function uniqueAliases(aliases) {
601
668
  const seen = new Set();
602
669
  return aliases.filter((alias) => {
@@ -633,48 +700,52 @@ async function runSync(aliases, options) {
633
700
  printList(repos);
634
701
  return 0;
635
702
  }
636
- if (abortOnLegacy(repoRoot, repos))
703
+ if (!isGitRepo(repoRoot)) {
704
+ log.error(`${repoRoot} is not a git repository. oh-my-space 0.6.0 manages sources as git submodules; run "git init" at the workspace root first.`);
705
+ return 1;
706
+ }
707
+ if (abortOnLegacyWorktree(repoRoot, repos))
637
708
  return 1;
638
709
  const picked = await selectRepos(repos, aliases, options, "sync");
639
710
  if (!picked || picked.length === 0)
640
711
  return 1;
641
- ensureGitignore(repoRoot);
712
+ ensureOmsNotIgnored(repoRoot);
642
713
  const results = picked.map((repo) => syncRepo(repo, repoRoot));
643
714
  if (results.length > 1 || options.all)
644
715
  printSummary(results);
645
716
  return exitFromResults(results);
646
717
  }
647
718
  async function runManage(command, aliases, options) {
648
- const loaded = loadRepos();
649
- if (!loaded) {
650
- emitLegacyRenameHintWalkUp();
719
+ const loaded = loadForSubmodules();
720
+ if (!loaded)
651
721
  return 1;
652
- }
653
722
  const { repos, repoRoot } = loaded;
654
- if (abortOnLegacyRenameAt(repoRoot))
655
- return 1;
656
- if (abortOnLegacy(repoRoot, repos))
657
- return 1;
658
723
  const picked = await selectRepos(repos, aliases, options, command);
659
724
  if (!picked || picked.length === 0)
660
725
  return 1;
661
- const fn = command === "fetch" ? fetchRepo : command === "pull" ? pullRepo : pushRepo;
662
- const results = picked.map((repo) => fn(repo, repoRoot));
726
+ const results = [];
727
+ for (const repo of picked) {
728
+ const remotes = await resolveRemotes(repo, options.remote, command);
729
+ if (!remotes || remotes.length === 0) {
730
+ results.push("failed");
731
+ continue;
732
+ }
733
+ if (command === "fetch")
734
+ results.push(fetchRepo(repo, repoRoot, remotes));
735
+ else if (command === "pull")
736
+ results.push(pullRepo(repo, repoRoot, remotes[0]));
737
+ else
738
+ results.push(pushRepo(repo, repoRoot, remotes, options.commit ?? false));
739
+ }
663
740
  if (results.length > 1 || options.all)
664
741
  printSummary(results);
665
742
  return exitFromResults(results);
666
743
  }
667
744
  async function runUnsync(aliases, options) {
668
- const loaded = loadRepos();
669
- if (!loaded) {
670
- emitLegacyRenameHintWalkUp();
745
+ const loaded = loadForSubmodules();
746
+ if (!loaded)
671
747
  return 1;
672
- }
673
748
  const { repos, repoRoot } = loaded;
674
- if (abortOnLegacyRenameAt(repoRoot))
675
- return 1;
676
- if (abortOnLegacy(repoRoot, repos))
677
- return 1;
678
749
  const picked = await selectRepos(repos, aliases, options, "unsync");
679
750
  if (!picked || picked.length === 0)
680
751
  return 1;
@@ -695,117 +766,120 @@ async function runUnsync(aliases, options) {
695
766
  printSummary(results);
696
767
  return exitFromResults(results);
697
768
  }
698
- async function runWorktreeAdd(alias, branch) {
699
- const loaded = loadRepos();
700
- if (!loaded) {
701
- emitLegacyRenameHintWalkUp();
769
+ async function runCheckout(alias, branch, options) {
770
+ const loaded = loadForSubmodules();
771
+ if (!loaded)
702
772
  return 1;
703
- }
704
773
  const { repos, repoRoot } = loaded;
705
- if (abortOnLegacyRenameAt(repoRoot))
706
- return 1;
707
- if (abortOnLegacy(repoRoot, repos))
708
- return 1;
709
774
  const repo = repos.find((r) => r.alias === alias);
710
775
  if (!repo) {
711
776
  log.error(`Unknown alias "${alias}". Use "oms sync --list" to see registered aliases.`);
712
777
  return 1;
713
778
  }
714
- if (!existsSync(bareDir(repoRoot, alias))) {
779
+ if (!submoduleInitialized(repoRoot, alias)) {
715
780
  log.error(`${alias}: not synced. Run "oms sync ${alias}" first.`);
716
781
  return 1;
717
782
  }
718
- if (existsSync(worktreePath(repoRoot, alias, branch))) {
719
- log.error(`${alias}: worktree for ${branch} already exists at ${DATA_DIRNAME}/${alias}/${branch}.`);
720
- return 1;
783
+ const dir = aliasDir(repoRoot, alias);
784
+ // Best-effort refresh so an existing remote branch is recognized; offline is fine.
785
+ runSub(repoRoot, alias, ["fetch", "origin", "--quiet"]);
786
+ if (localBranchExists(dir, branch)) {
787
+ log.step(`${alias}: git switch ${branch}`);
788
+ const r = runSub(repoRoot, alias, ["switch", branch], true);
789
+ if (!r.success)
790
+ return 2;
791
+ log.success(`${alias}: on ${branch}`);
792
+ return 0;
721
793
  }
722
- log.step(`${alias}: git fetch origin --prune (refresh before add)`);
723
- runBareGit(repoRoot, alias, ["fetch", "origin", "--prune"], true);
724
- if (!addWorktree(repo, repoRoot, branch))
794
+ if (remoteBranchExists(dir, branch)) {
795
+ log.step(`${alias}: git switch -c ${branch} origin/${branch}`);
796
+ const r = runSub(repoRoot, alias, ["switch", "-c", branch, `origin/${branch}`], true);
797
+ if (!r.success)
798
+ return 2;
799
+ log.success(`${alias}: on ${branch} (tracking origin/${branch})`);
800
+ return 0;
801
+ }
802
+ // Brand-new branch: created locally, no remote precondition. Push later with "oms push".
803
+ const args = ["switch", "-c", branch, ...(options.from ? [options.from] : [])];
804
+ log.step(`${alias}: git ${args.join(" ")}`);
805
+ const r = runSub(repoRoot, alias, args, true);
806
+ if (!r.success)
725
807
  return 2;
726
- log.success(`${alias}: added worktree for ${branch}`);
808
+ log.success(`${alias}: created new local branch ${branch}. Push it with "oms push ${alias}".`);
727
809
  return 0;
728
810
  }
729
- async function runWorktreeList(alias) {
730
- const loaded = loadRepos();
731
- if (!loaded) {
732
- emitLegacyRenameHintWalkUp();
811
+ /** Parse the leading status char from `git submodule status` (' ' ok, '+' moved, '-' uninit, 'U' conflict). */
812
+ function pinState(repoRoot, alias) {
813
+ const r = runGit(repoRoot, ["submodule", "status", "--", submodulePath(alias)]);
814
+ if (!r.success || r.stdout.length === 0)
815
+ return "?";
816
+ const c = r.stdout[0];
817
+ if (c === " ")
818
+ return "ok";
819
+ if (c === "+")
820
+ return "moved";
821
+ if (c === "-")
822
+ return "uninit";
823
+ if (c === "U")
824
+ return "conflict";
825
+ return "?";
826
+ }
827
+ function aheadBehind(dir) {
828
+ const r = runGit(dir, ["rev-list", "--left-right", "--count", "@{u}...HEAD"]);
829
+ if (!r.success)
830
+ return { ahead: "", behind: "" };
831
+ const [behind, ahead] = r.stdout.trim().split(/\s+/);
832
+ return { ahead: ahead && ahead !== "0" ? ahead : "", behind: behind && behind !== "0" ? behind : "" };
833
+ }
834
+ async function runStatus(aliases, options) {
835
+ const loaded = loadForSubmodules();
836
+ if (!loaded)
733
837
  return 1;
734
- }
735
838
  const { repos, repoRoot } = loaded;
736
- if (abortOnLegacyRenameAt(repoRoot))
737
- return 1;
738
- if (abortOnLegacy(repoRoot, repos))
839
+ const targets = aliases.length > 0 || options.all
840
+ ? await selectRepos(repos, options.all ? [] : aliases, options.all ? options : {}, "inspect")
841
+ : repos;
842
+ if (!targets)
739
843
  return 1;
740
- const targets = alias ? repos.filter((r) => r.alias === alias) : repos;
741
- if (alias && targets.length === 0) {
742
- log.error(`Unknown alias "${alias}".`);
743
- return 1;
744
- }
745
844
  const rows = [];
746
845
  for (const repo of targets) {
747
- if (!existsSync(bareDir(repoRoot, repo.alias))) {
748
- rows.push({ alias: repo.alias, branch: "(not synced)", path: "-" });
846
+ if (!isRegisteredSubmodule(repoRoot, submodulePath(repo.alias))) {
847
+ rows.push({ alias: repo.alias, branch: "(not registered)", pin: "-", dirty: "", ahead: "", behind: "" });
749
848
  continue;
750
849
  }
751
- const wts = listExistingWorktrees(repoRoot, repo.alias);
752
- if (wts.length === 0) {
753
- rows.push({ alias: repo.alias, branch: "(no worktrees)", path: "-" });
850
+ if (!submoduleInitialized(repoRoot, repo.alias)) {
851
+ rows.push({ alias: repo.alias, branch: "(not synced)", pin: "uninit", dirty: "", ahead: "", behind: "" });
754
852
  continue;
755
853
  }
756
- for (const wt of wts) {
757
- rows.push({
758
- alias: repo.alias,
759
- branch: wt.branch,
760
- path: `${DATA_DIRNAME}/${repo.alias}/${wt.relativePath}`,
761
- });
762
- }
763
- }
764
- const aliasW = Math.max("ALIAS".length, ...rows.map((r) => r.alias.length));
765
- const branchW = Math.max("BRANCH".length, ...rows.map((r) => r.branch.length));
766
- console.log(dim(`${pad("ALIAS", aliasW)} ${pad("BRANCH", branchW)} PATH`));
854
+ const dir = aliasDir(repoRoot, repo.alias);
855
+ const branch = currentBranch(dir) ?? `(detached ${shortSha(dir)})`;
856
+ const { ahead, behind } = aheadBehind(dir);
857
+ rows.push({
858
+ alias: repo.alias,
859
+ branch,
860
+ pin: pinState(repoRoot, repo.alias),
861
+ dirty: isDirty(dir) ? "yes" : "",
862
+ ahead,
863
+ behind,
864
+ });
865
+ }
866
+ const col = (key, header) => Math.max(header.length, ...rows.map((r) => r[key].length));
867
+ const aW = col("alias", "ALIAS");
868
+ const bW = col("branch", "BRANCH");
869
+ const pW = col("pin", "PIN");
870
+ const dW = Math.max("DIRTY".length, ...rows.map((r) => r.dirty.length));
871
+ console.log(dim(`${pad("ALIAS", aW)} ${pad("BRANCH", bW)} ${pad("PIN", pW)} ${pad("DIRTY", dW)} AHEAD BEHIND`));
767
872
  for (const r of rows) {
768
- console.log(`${pad(r.alias, aliasW)} ${pad(r.branch, branchW)} ${r.path}`);
769
- }
770
- return 0;
771
- }
772
- async function runWorktreeRemove(alias, branch, options) {
773
- const loaded = loadRepos();
774
- if (!loaded) {
775
- emitLegacyRenameHintWalkUp();
776
- return 1;
777
- }
778
- const { repos, repoRoot } = loaded;
779
- if (abortOnLegacyRenameAt(repoRoot))
780
- return 1;
781
- if (abortOnLegacy(repoRoot, repos))
782
- return 1;
783
- const repo = repos.find((r) => r.alias === alias);
784
- if (!repo) {
785
- log.error(`Unknown alias "${alias}".`);
786
- return 1;
787
- }
788
- const wtPath = worktreePath(repoRoot, alias, branch);
789
- if (!existsSync(wtPath)) {
790
- log.info(`${alias}: no worktree for ${branch}`);
791
- return 0;
873
+ console.log(`${pad(r.alias, aW)} ${pad(r.branch, bW)} ${pad(r.pin, pW)} ${pad(r.dirty, dW)} ${pad(r.ahead, 5)} ${r.behind}`);
792
874
  }
793
- if (!options.force) {
794
- const status = runGit(wtPath, ["status", "--porcelain"]);
795
- if (status.success && status.stdout.trim().length > 0) {
796
- log.error(`${alias}/${branch}: has uncommitted changes. Commit, stash, or pass --force.`);
797
- return 2;
798
- }
799
- }
800
- if (!removeWorktree(repo, repoRoot, branch, options.force ?? false))
801
- return 2;
802
- log.success(`${alias}: removed worktree for ${branch}`);
803
875
  return 0;
804
876
  }
805
877
  const INIT_TEMPLATE = `# yaml-language-server: $schema=https://raw.githubusercontent.com/divlook/oh-my-space/main/oms.schema.json
806
878
  repos:
807
879
  - alias: example
808
- url: git@github.com:example/repo.git
880
+ remotes:
881
+ origin: git@github.com:example/repo.git
882
+ # upstream: git@github.com:upstream/repo.git
809
883
  branch: main
810
884
  `;
811
885
  /** 현재 디렉터리에 기본 oms.yaml 템플릿을 생성합니다. */
@@ -817,8 +891,12 @@ async function runInit(options) {
817
891
  }
818
892
  writeFileSync(target, INIT_TEMPLATE);
819
893
  log.success(`created ${MANIFEST_FILENAME} at ${target}`);
820
- ensureGitignore(process.cwd());
821
- log.info(`edit alias/url/branch, then run "oms sync".`);
894
+ // Sources are tracked submodules, so make sure no stale oms version left oms/ ignored.
895
+ ensureOmsNotIgnored(process.cwd());
896
+ if (!isGitRepo(process.cwd())) {
897
+ log.info(`oms manages sources as git submodules; run "git init" here if this is not a git repo yet.`);
898
+ }
899
+ log.info(`edit alias/remotes/branch, then run "oms sync".`);
822
900
  return 0;
823
901
  }
824
902
  async function runDoctor() {
@@ -848,39 +926,40 @@ async function runDoctor() {
848
926
  warnings++;
849
927
  }
850
928
  else if (!isGitVersionSupported(parsed)) {
851
- log.warn(`git ${parsed.major}.${parsed.minor} is older than the recommended ${MIN_GIT_MAJOR}.${MIN_GIT_MINOR}. oms uses "git worktree add --track -B" which may fail on older releases — upgrade git.`);
929
+ log.warn(`git ${parsed.major}.${parsed.minor} is older than the recommended ${MIN_GIT_MAJOR}.${MIN_GIT_MINOR}. oms uses "git switch" and submodule commands which may behave differently on older releases — upgrade git.`);
852
930
  warnings++;
853
931
  }
854
- if (hasLegacySubmoduleLayout(repoRoot, repos)) {
855
- log.warn(`detected legacy submodule layout (.gitmodules registers an alias path). See ${SUBMODULE_MIGRATION_DOC}.`);
932
+ if (!isGitRepo(repoRoot)) {
933
+ log.warn(`workspace is not a git repository. oms manages sources as submodules; run "git init" at ${repoRoot}.`);
856
934
  warnings++;
857
935
  }
858
- const gi = join(repoRoot, ".gitignore");
859
- const giHasSources = existsSync(gi)
860
- && readFileSync(gi, "utf8")
861
- .split("\n")
862
- .some((l) => l.trim() === GITIGNORE_ENTRY || l.trim() === `/${GITIGNORE_ENTRY}`);
863
- if (!giHasSources) {
864
- log.warn(`.gitignore does not exclude ${GITIGNORE_ENTRY}. Run "oms sync" to add it automatically.`);
936
+ if (abortOnLegacyWorktree(repoRoot, repos))
937
+ return 1;
938
+ if (gitignoreIgnoresOms(repoRoot)) {
939
+ log.warn(`.gitignore excludes ${GITIGNORE_ENTRY}, but submodules must be tracked. Run "oms sync" to remove it.`);
865
940
  warnings++;
866
941
  }
867
942
  for (const repo of repos) {
868
- const bare = bareDir(repoRoot, repo.alias);
869
- if (!existsSync(bare)) {
943
+ if (!isRegisteredSubmodule(repoRoot, submodulePath(repo.alias))) {
870
944
  log.info(`${repo.alias}: not synced`);
871
945
  continue;
872
946
  }
873
- const refspec = runBareGit(repoRoot, repo.alias, ["config", "--get", "remote.origin.fetch"]);
874
- if (!refspec.success || refspec.stdout.trim().length === 0) {
875
- log.warn(`${repo.alias}: bare clone is missing remote.origin.fetch. Run: git -C ${DATA_DIRNAME}/${repo.alias}/.bare -c safe.bareRepository=all config remote.origin.fetch '${FETCH_REFSPEC}'`);
947
+ if (!submoduleInitialized(repoRoot, repo.alias)) {
948
+ log.warn(`${repo.alias}: registered but not initialized. Run "oms sync ${repo.alias}".`);
949
+ warnings++;
950
+ continue;
951
+ }
952
+ const dir = aliasDir(repoRoot, repo.alias);
953
+ const branch = currentBranch(dir);
954
+ if (!branch) {
955
+ log.warn(`${repo.alias}: detached HEAD. Run "oms checkout ${repo.alias} <branch>" to get on a branch.`);
876
956
  warnings++;
877
957
  }
878
958
  else {
879
- log.success(`${repo.alias}: bare clone OK (refspec: ${refspec.stdout.trim()})`);
959
+ log.success(`${repo.alias}: submodule OK (branch=${branch})`);
880
960
  }
881
- if (!existsSync(gitPlaceholderPath(repoRoot, repo.alias))) {
882
- log.warn(`${repo.alias}: missing .git placeholder at ${DATA_DIRNAME}/${repo.alias}/.git. Recreate with: echo 'gitdir: ./.bare' > ${DATA_DIRNAME}/${repo.alias}/.git`);
883
- warnings++;
961
+ if (pinState(repoRoot, repo.alias) === "moved") {
962
+ log.info(`${repo.alias}: working commit differs from the recorded pointer. Commit oms/${repo.alias} to record it.`);
884
963
  }
885
964
  }
886
965
  return warnings > 0 ? 2 : 0;
@@ -894,6 +973,16 @@ function readPackageVersion() {
894
973
  const pkg = readJson(join(packageRoot, "package.json"));
895
974
  return pkg?.version ?? "0.0.0";
896
975
  }
976
+ /** The commit baked in at build time, or null when unavailable (dev/no-git build). */
977
+ function readBuildCommit() {
978
+ const info = readJson(join(dirname(fileURLToPath(import.meta.url)), "build-info.json"));
979
+ return info?.commit ?? null;
980
+ }
981
+ /** Clickable GitHub permalink for a repo doc, pinned to the build commit; falls back to the version tag. */
982
+ function docUrl(relPath) {
983
+ const ref = readBuildCommit() ?? `v${readPackageVersion()}`;
984
+ return `${DOCS_REPO_BLOB_BASE}/${ref}/${relPath}`;
985
+ }
897
986
  async function exitWith(action) {
898
987
  try {
899
988
  process.exit(await action);
@@ -908,17 +997,18 @@ const commandNames = new Set([
908
997
  "init",
909
998
  "doctor",
910
999
  "sync",
1000
+ "status",
1001
+ "checkout",
911
1002
  "fetch",
912
1003
  "pull",
913
1004
  "push",
914
1005
  "unsync",
915
- "worktree",
916
1006
  "help",
917
1007
  ]);
918
1008
  const program = new Command();
919
1009
  program
920
1010
  .name("oms")
921
- .description(`Manage source repositories listed in ${MANIFEST_FILENAME} as bare clones + worktrees under ${DATA_DIRNAME}/<alias>/.`)
1011
+ .description(`Manage source repositories listed in ${MANIFEST_FILENAME} as git submodules under ${DATA_DIRNAME}/<alias>/.`)
922
1012
  .version(readPackageVersion())
923
1013
  .addHelpText("after", exitHelp);
924
1014
  program
@@ -931,14 +1021,14 @@ program
931
1021
  });
932
1022
  program
933
1023
  .command("doctor")
934
- .description(`Check ${MANIFEST_FILENAME}, git availability, bare-clone state, and .gitignore for each registered alias.`)
1024
+ .description(`Check ${MANIFEST_FILENAME}, git availability, and the submodule state of each registered alias.`)
935
1025
  .addHelpText("after", exitHelp)
936
1026
  .action(async () => {
937
1027
  await exitWith(runDoctor());
938
1028
  });
939
1029
  program
940
1030
  .command("sync")
941
- .description(`Bare-clone each registered repo into ${DATA_DIRNAME}/<alias>/.bare and create the baseline worktree at ${DATA_DIRNAME}/<alias>/<branch>/.`)
1031
+ .description(`Register each repo as a submodule at ${DATA_DIRNAME}/<alias>/ (or initialize and refresh an existing one), checked out on its baseline branch.`)
942
1032
  .argument("[aliases...]", "repo aliases to sync (omit for interactive multi-select)")
943
1033
  .option("--all", "sync every registered source repo")
944
1034
  .option("--list", "print registered repos")
@@ -946,73 +1036,66 @@ program
946
1036
  .action(async (aliases, options) => {
947
1037
  await exitWith(runSync(aliases, options));
948
1038
  });
1039
+ program
1040
+ .command("status")
1041
+ .description("Show each submodule's branch, pointer state, dirtiness, and ahead/behind counts.")
1042
+ .argument("[aliases...]", "repo aliases to inspect (omit for all)")
1043
+ .option("--all", "inspect every registered source repo")
1044
+ .addHelpText("after", exitHelp)
1045
+ .action(async (aliases, options) => {
1046
+ await exitWith(runStatus(aliases, options));
1047
+ });
1048
+ program
1049
+ .command("checkout")
1050
+ .description("Switch a submodule to <branch>, creating it locally if it does not exist yet (no remote required).")
1051
+ .argument("<alias>", "registered source alias")
1052
+ .argument("<branch>", "branch name (may include slashes)")
1053
+ .option("--from <ref>", "start point for a new branch (default: current HEAD)")
1054
+ .addHelpText("after", exitHelp)
1055
+ .action(async (alias, branch, options) => {
1056
+ await exitWith(runCheckout(alias, branch, options));
1057
+ });
1058
+ const collectRemote = (value, acc) => [...acc, value];
949
1059
  program
950
1060
  .command("fetch")
951
- .description("Run git fetch origin --prune in each bare clone.")
1061
+ .description("Run git fetch <remote> --prune in each submodule (defaults to origin).")
952
1062
  .argument("[aliases...]", "repo aliases to fetch (omit for interactive multi-select)")
953
1063
  .option("--all", "fetch every registered source repo")
1064
+ .option("--remote <name>", "remote to fetch (repeatable; omit to choose interactively)", collectRemote, [])
954
1065
  .addHelpText("after", exitHelp)
955
1066
  .action(async (aliases, options) => {
956
1067
  await exitWith(runManage("fetch", aliases, options));
957
1068
  });
958
1069
  program
959
1070
  .command("pull")
960
- .description("Run git pull --ff-only in the baseline worktree of each selected alias; requires upstream.")
1071
+ .description("Run git pull --ff-only <remote> on each submodule's current branch and stage the moved pointer (defaults to origin).")
961
1072
  .argument("[aliases...]", "repo aliases to pull (omit for interactive multi-select)")
962
1073
  .option("--all", "pull every registered source repo")
1074
+ .option("--remote <name>", "remote to pull from (single; omit to choose interactively)", collectRemote, [])
963
1075
  .addHelpText("after", exitHelp)
964
1076
  .action(async (aliases, options) => {
965
1077
  await exitWith(runManage("pull", aliases, options));
966
1078
  });
967
1079
  program
968
1080
  .command("push")
969
- .description("Run git push in the baseline worktree of each explicitly listed alias; no --all, force, or upstream setup.")
1081
+ .description("Run git push <remote> <branch> on each listed submodule (creating the remote branch on first push) and stage the moved pointer (defaults to origin).")
970
1082
  .argument("<aliases...>", "repo aliases to push")
1083
+ .option("--commit", "also commit the pointer update in the parent repo")
1084
+ .option("--remote <name>", "remote to push to (repeatable; omit to choose interactively)", collectRemote, [])
971
1085
  .addHelpText("after", exitHelp)
972
- .action(async (aliases) => {
973
- await exitWith(runManage("push", aliases, {}));
1086
+ .action(async (aliases, options) => {
1087
+ await exitWith(runManage("push", aliases, options));
974
1088
  });
975
1089
  program
976
1090
  .command("unsync")
977
- .description(`Remove all worktrees and the bare clone for each alias (keeps ${MANIFEST_FILENAME} entry).`)
1091
+ .description(`Deinitialize and remove the submodule for each alias (keeps ${MANIFEST_FILENAME} entry).`)
978
1092
  .argument("[aliases...]", "repo aliases to unsync (omit for interactive multi-select)")
979
1093
  .option("--all", "unsync every registered source repo")
980
- .option("--force", "discard uncommitted changes in worktrees")
1094
+ .option("--force", "discard uncommitted changes in the submodule")
981
1095
  .addHelpText("after", exitHelp)
982
1096
  .action(async (aliases, options) => {
983
1097
  await exitWith(runUnsync(aliases, options));
984
1098
  });
985
- const worktreeCmd = program
986
- .command("worktree")
987
- .description("Manage additional worktrees for a synced source repo.")
988
- .addHelpText("after", exitHelp);
989
- worktreeCmd
990
- .command("add")
991
- .description(`Create a worktree for <branch> at ${DATA_DIRNAME}/<alias>/<branch>/.`)
992
- .argument("<alias>", "registered source alias")
993
- .argument("<branch>", "branch name (may include slashes)")
994
- .addHelpText("after", exitHelp)
995
- .action(async (alias, branch) => {
996
- await exitWith(runWorktreeAdd(alias, branch));
997
- });
998
- worktreeCmd
999
- .command("list")
1000
- .description("List existing worktrees for the given alias (or all aliases).")
1001
- .argument("[alias]", "registered source alias")
1002
- .addHelpText("after", exitHelp)
1003
- .action(async (alias) => {
1004
- await exitWith(runWorktreeList(alias));
1005
- });
1006
- worktreeCmd
1007
- .command("remove")
1008
- .description(`Remove the worktree at ${DATA_DIRNAME}/<alias>/<branch>.`)
1009
- .argument("<alias>", "registered source alias")
1010
- .argument("<branch>", "branch name (may include slashes)")
1011
- .option("--force", "discard uncommitted changes")
1012
- .addHelpText("after", exitHelp)
1013
- .action(async (alias, branch, options) => {
1014
- await exitWith(runWorktreeRemove(alias, branch, options));
1015
- });
1016
1099
  const requestedCommand = process.argv[2];
1017
1100
  if (requestedCommand && !requestedCommand.startsWith("-") && !commandNames.has(requestedCommand)) {
1018
1101
  console.error(`error: unknown command '${requestedCommand}'`);