oh-my-space 0.4.0 → 0.6.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.
Files changed (3) hide show
  1. package/README.md +53 -36
  2. package/dist/oms.js +419 -436
  3. package/package.json +2 -2
package/dist/oms.js CHANGED
@@ -1,7 +1,7 @@
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
7
  import { cancel, isCancel, log, multiselect } from "@clack/prompts";
@@ -9,14 +9,14 @@ import { parse as parseYaml } from "yaml";
9
9
  const ALIAS_PATTERN = /^[a-z0-9][a-z0-9-]*$/;
10
10
  const ALLOWED_TOP_KEYS = new Set(["repos"]);
11
11
  const ALLOWED_ITEM_KEYS = new Set(["alias", "url", "branch"]);
12
- const FETCH_REFSPEC = "+refs/heads/*:refs/remotes/origin/*";
13
12
  const MANIFEST_FILENAME = "oms.yaml";
14
13
  const DATA_DIRNAME = "oms";
15
14
  const GITIGNORE_ENTRY = `${DATA_DIRNAME}/`;
15
+ const GITIGNORE_COMMENT = "# managed by oms";
16
16
  const LEGACY_MANIFEST = "sources.yaml";
17
17
  const LEGACY_DATA_DIRNAME = "sources";
18
- const LEGACY_MIGRATION_DOC = "docs/migrations/0.3.x-to-0.4.0.md";
19
- const SUBMODULE_MIGRATION_DOC = "docs/migrations/0.2.x-to-0.3.0.md";
18
+ const RENAME_MIGRATION_DOC = "docs/migrations/0.3.x-to-0.4.0.md";
19
+ const WORKTREE_MIGRATION_DOC = "docs/migrations/0.5.x-to-0.6.0.md";
20
20
  const MIN_GIT_MAJOR = 2;
21
21
  const MIN_GIT_MINOR = 40;
22
22
  const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
@@ -117,9 +117,9 @@ function runGit(cwd, args, inheritOutput = false) {
117
117
  stdout: inheritOutput ? "" : (result.stdout ?? ""),
118
118
  };
119
119
  }
120
- /** Run git from oms/<alias>/ with safe.bareRepository=all, so the .git placeholder routes to .bare. */
121
- function runBareGit(repoRoot, alias, args, inheritOutput = false) {
122
- return runGit(aliasDir(repoRoot, alias), ["-c", "safe.bareRepository=all", ...args], inheritOutput);
120
+ /** Run git inside the submodule working tree at oms/<alias>/. */
121
+ function runSub(repoRoot, alias, args, inheritOutput = false) {
122
+ return runGit(aliasDir(repoRoot, alias), args, inheritOutput);
123
123
  }
124
124
  function parseGitVersion(s) {
125
125
  const m = s.match(/git version (\d+)\.(\d+)/);
@@ -148,15 +148,14 @@ function findWorkspaceRoot(options = {}) {
148
148
  function aliasDir(repoRoot, alias) {
149
149
  return join(repoRoot, DATA_DIRNAME, alias);
150
150
  }
151
- function bareDir(repoRoot, alias) {
152
- return join(aliasDir(repoRoot, alias), ".bare");
151
+ /** Submodule name and path are identical under our convention: oms/<alias>. */
152
+ function submodulePath(alias) {
153
+ return `${DATA_DIRNAME}/${alias}`;
153
154
  }
154
- function gitPlaceholderPath(repoRoot, alias) {
155
- return join(aliasDir(repoRoot, alias), ".git");
156
- }
157
- function worktreePath(repoRoot, alias, branch) {
158
- return join(aliasDir(repoRoot, alias), branch);
155
+ function isGitRepo(repoRoot) {
156
+ return runGit(repoRoot, ["rev-parse", "--is-inside-work-tree"]).stdout.trim() === "true";
159
157
  }
158
+ /** True when .gitmodules registers a submodule at the given path (sources/<alias> or oms/<alias>). */
160
159
  function isRegisteredSubmodule(repoRoot, sourcePath) {
161
160
  if (!existsSync(join(repoRoot, ".gitmodules")))
162
161
  return false;
@@ -173,27 +172,69 @@ function isRegisteredSubmodule(repoRoot, sourcePath) {
173
172
  .split("\n")
174
173
  .some((line) => line.trim().split(/\s+/)[1] === sourcePath);
175
174
  }
176
- /** Returns true when .gitmodules registers any sources/<alias> or oms/<alias> entry for the loaded repos. */
177
- function hasLegacySubmoduleLayout(repoRoot, repos) {
178
- if (!existsSync(join(repoRoot, ".gitmodules")))
179
- return false;
180
- return repos.some((repo) => isRegisteredSubmodule(repoRoot, `${LEGACY_DATA_DIRNAME}/${repo.alias}`)
181
- || isRegisteredSubmodule(repoRoot, `${DATA_DIRNAME}/${repo.alias}`));
175
+ /** A submodule is initialized when its working tree has a .git gitlink file/dir. */
176
+ function submoduleInitialized(repoRoot, alias) {
177
+ return existsSync(join(aliasDir(repoRoot, alias), ".git"));
182
178
  }
183
- function abortOnLegacy(repoRoot, repos) {
184
- if (!hasLegacySubmoduleLayout(repoRoot, repos))
185
- return false;
186
- log.error('detected legacy submodule layout (.gitmodules registers an alias path). oh-my-space 0.3.0+ uses bare clone + worktrees.\n' +
187
- ` See ${SUBMODULE_MIGRATION_DOC} for the manual steps. Aborting to avoid destructive change.`);
188
- return true;
179
+ /** Short branch name, or null when HEAD is detached. */
180
+ function currentBranch(dir) {
181
+ const r = runGit(dir, ["rev-parse", "--abbrev-ref", "HEAD"]);
182
+ if (!r.success)
183
+ return null;
184
+ const b = r.stdout.trim();
185
+ return b && b !== "HEAD" ? b : null;
189
186
  }
190
- /** Inspect a single directory for 0.3.x rename artifacts. */
191
- function detectLegacyRenameArtifactsAt(dir) {
192
- const manifest = existsSync(join(dir, LEGACY_MANIFEST));
193
- const data = existsSync(join(dir, LEGACY_DATA_DIRNAME));
194
- if (!manifest && !data)
187
+ function shortSha(dir) {
188
+ const r = runGit(dir, ["rev-parse", "--short", "HEAD"]);
189
+ return r.success ? r.stdout.trim() : "???????";
190
+ }
191
+ function localBranchExists(dir, branch) {
192
+ return runGit(dir, ["rev-parse", "--verify", "--quiet", `refs/heads/${branch}`]).success;
193
+ }
194
+ function remoteBranchExists(dir, branch) {
195
+ return runGit(dir, ["rev-parse", "--verify", "--quiet", `refs/remotes/origin/${branch}`]).success;
196
+ }
197
+ function isDirty(dir) {
198
+ const r = runGit(dir, ["status", "--porcelain"]);
199
+ return r.success && r.stdout.trim().length > 0;
200
+ }
201
+ /** The branch recorded in .gitmodules for the submodule, if any. */
202
+ function gitmodulesBranch(repoRoot, alias) {
203
+ const r = runGit(repoRoot, [
204
+ "config",
205
+ "--file",
206
+ ".gitmodules",
207
+ "--get",
208
+ `submodule.${submodulePath(alias)}.branch`,
209
+ ]);
210
+ if (!r.success)
195
211
  return null;
196
- return { manifest, data };
212
+ const b = r.stdout.trim();
213
+ return b.length > 0 ? b : null;
214
+ }
215
+ /**
216
+ * Keep the submodule on a branch instead of a detached HEAD. Only acts when HEAD is detached,
217
+ * so a branch the user is already working on is never disturbed. When no local branch exists
218
+ * yet, a branch is created at the current (pinned) commit — the checked-out commit is preserved,
219
+ * which keeps the parent's recorded pointer reproducible.
220
+ */
221
+ function attachBranch(repoRoot, alias, branch) {
222
+ if (currentBranch(aliasDir(repoRoot, alias)) !== null)
223
+ return;
224
+ if (localBranchExists(aliasDir(repoRoot, alias), branch)) {
225
+ runSub(repoRoot, alias, ["switch", branch]);
226
+ return;
227
+ }
228
+ // Create the branch at the current HEAD (the pinned commit) so the worktree stays put.
229
+ if (!runSub(repoRoot, alias, ["switch", "-c", branch]).success)
230
+ return;
231
+ if (remoteBranchExists(aliasDir(repoRoot, alias), branch)) {
232
+ runSub(repoRoot, alias, ["branch", "--set-upstream-to", `origin/${branch}`, branch]);
233
+ }
234
+ }
235
+ /** Stage the submodule gitlink in the parent so a moved pointer shows up and is ready to commit. */
236
+ function stagePointer(repoRoot, alias) {
237
+ runGit(repoRoot, ["add", "--", submodulePath(alias)]);
197
238
  }
198
239
  function emitLegacyRenameMessage(dir, found) {
199
240
  const artifacts = [
@@ -204,14 +245,15 @@ function emitLegacyRenameMessage(dir, found) {
204
245
  .join(" and ");
205
246
  log.error(`detected legacy ${artifacts} at ${dir}.\n` +
206
247
  ` oh-my-space 0.4.0 renamed the manifest to ${MANIFEST_FILENAME} and the data directory to ${DATA_DIRNAME}/.\n` +
207
- ` See ${LEGACY_MIGRATION_DOC} for the manual steps. Aborting to avoid destructive change.`);
248
+ ` See ${RENAME_MIGRATION_DOC} for the manual steps. Aborting to avoid destructive change.`);
208
249
  }
209
- /** Block when the active oms.yaml workspace still has legacy artifacts at its root. */
250
+ /** Block when the active oms.yaml workspace still has 0.3.x rename artifacts at its root. */
210
251
  function abortOnLegacyRenameAt(repoRoot) {
211
- const found = detectLegacyRenameArtifactsAt(repoRoot);
212
- if (!found)
252
+ const manifest = existsSync(join(repoRoot, LEGACY_MANIFEST));
253
+ const data = existsSync(join(repoRoot, LEGACY_DATA_DIRNAME));
254
+ if (!manifest && !data)
213
255
  return false;
214
- emitLegacyRenameMessage(repoRoot, found);
256
+ emitLegacyRenameMessage(repoRoot, { manifest, data });
215
257
  return true;
216
258
  }
217
259
  /**
@@ -235,160 +277,70 @@ function emitLegacyRenameHintWalkUp(options = {}) {
235
277
  current = parent;
236
278
  }
237
279
  }
238
- function ensureGitignore(repoRoot) {
239
- const path = join(repoRoot, ".gitignore");
240
- let content = "";
241
- if (existsSync(path)) {
242
- content = readFileSync(path, "utf8");
243
- const present = content
244
- .split("\n")
245
- .some((line) => line.trim() === GITIGNORE_ENTRY || line.trim() === `/${GITIGNORE_ENTRY}`);
246
- if (present)
247
- return;
248
- }
249
- const needsNewline = content.length > 0 && !content.endsWith("\n");
250
- writeFileSync(path, `${content}${needsNewline ? "\n" : ""}${GITIGNORE_ENTRY}\n`);
251
- log.info(`added ${GITIGNORE_ENTRY} to .gitignore`);
252
- }
253
- function setupBareRepo(repo, repoRoot) {
254
- const alias = repo.alias;
255
- const aliasPath = aliasDir(repoRoot, alias);
256
- const barePath = bareDir(repoRoot, alias);
257
- mkdirSync(aliasPath, { recursive: true });
258
- const relBare = relative(repoRoot, barePath);
259
- log.step(`git clone --bare ${repo.url} ${relBare}`);
260
- const clone = runGit(repoRoot, ["clone", "--bare", repo.url, relBare], true);
261
- if (!clone.success) {
262
- log.error(`${alias}: git clone --bare failed (exit ${clone.exitCode})`);
263
- if (existsSync(barePath))
264
- rmSync(barePath, { recursive: true, force: true });
280
+ /** Detect leftover 0.3.x–0.5.x bare clone + worktree artifacts (oms/<alias>/.bare). */
281
+ function abortOnLegacyWorktree(repoRoot, repos) {
282
+ const stale = repos.find((repo) => existsSync(join(aliasDir(repoRoot, repo.alias), ".bare")));
283
+ if (!stale)
265
284
  return false;
266
- }
267
- // Write the placeholder before any further runBareGit calls, otherwise git ascends
268
- // out of oms/<alias>/ looking for a repo and touches the wrong .git.
269
- writeFileSync(gitPlaceholderPath(repoRoot, alias), "gitdir: ./.bare\n");
270
- const config = runBareGit(repoRoot, alias, [
271
- "config",
272
- "remote.origin.fetch",
273
- FETCH_REFSPEC,
274
- ]);
275
- if (!config.success) {
276
- log.error(`${alias}: failed to set remote.origin.fetch (exit ${config.exitCode})`);
277
- return false;
278
- }
279
- log.step(`${alias}: git fetch origin`);
280
- const fetch = runBareGit(repoRoot, alias, ["fetch", "origin", "--prune"], true);
281
- if (!fetch.success) {
282
- log.error(`${alias}: initial fetch failed (exit ${fetch.exitCode})`);
283
- return false;
284
- }
285
+ 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` +
286
+ ` See ${WORKTREE_MIGRATION_DOC} for the manual steps. Aborting to avoid destructive change.`);
285
287
  return true;
286
288
  }
287
- function detectDefaultBranch(repoRoot, alias) {
288
- const r = runBareGit(repoRoot, alias, ["symbolic-ref", "--short", "HEAD"]);
289
- if (r.success) {
290
- const out = r.stdout.trim();
291
- return out.length > 0 ? out : null;
292
- }
293
- return null;
294
- }
295
- function listExistingWorktrees(repoRoot, alias) {
296
- if (!existsSync(bareDir(repoRoot, alias)))
297
- return [];
298
- const result = runBareGit(repoRoot, alias, ["worktree", "list", "--porcelain"]);
299
- if (!result.success)
300
- return [];
301
- const aliasPath = aliasDir(repoRoot, alias);
302
- const entries = [];
303
- const blocks = result.stdout
304
- .split(/\n\n+/)
305
- .map((b) => b.trim())
306
- .filter((b) => b.length > 0);
307
- for (const block of blocks) {
308
- let path = "";
309
- let branch = "(detached)";
310
- let bare = false;
311
- for (const line of block.split("\n")) {
312
- if (line.startsWith("worktree "))
313
- path = line.slice("worktree ".length);
314
- else if (line.startsWith("branch ")) {
315
- branch = line.slice("branch ".length).replace(/^refs\/heads\//, "");
316
- }
317
- else if (line === "bare")
318
- bare = true;
319
- }
320
- if (!path || bare)
321
- continue;
322
- const rel = relative(aliasPath, path);
323
- // Skip worktrees outside oms/<alias>/ (shouldn't happen, but be safe)
324
- if (rel.startsWith(".."))
325
- continue;
326
- entries.push({ branch, path, relativePath: rel });
327
- }
328
- return entries;
329
- }
330
- function cleanupEmptyParents(repoRoot, alias, branch) {
331
- const parts = branch.split("/").filter((p) => p.length > 0);
332
- if (parts.length < 2)
289
+ /** Submodules live inside the parent's history, so oms/ must not be gitignored. Strip a managed entry. */
290
+ function ensureOmsNotIgnored(repoRoot) {
291
+ const path = join(repoRoot, ".gitignore");
292
+ if (!existsSync(path))
333
293
  return;
334
- for (let i = parts.length - 1; i >= 1; i--) {
335
- const dirPath = join(aliasDir(repoRoot, alias), ...parts.slice(0, i));
336
- try {
337
- const entries = readdirSync(dirPath);
338
- if (entries.length === 0) {
339
- rmdirSync(dirPath);
340
- }
341
- else {
342
- break;
343
- }
344
- }
345
- catch {
346
- break;
294
+ const lines = readFileSync(path, "utf8").split("\n");
295
+ const out = [];
296
+ let removed = false;
297
+ for (const line of lines) {
298
+ const trimmed = line.trim();
299
+ if (trimmed === GITIGNORE_ENTRY || trimmed === `/${GITIGNORE_ENTRY}`) {
300
+ if (out.length > 0 && out[out.length - 1].trim() === GITIGNORE_COMMENT)
301
+ out.pop();
302
+ removed = true;
303
+ continue;
347
304
  }
305
+ out.push(line);
348
306
  }
349
- }
350
- function addWorktree(repo, repoRoot, branch) {
351
- const wtPath = worktreePath(repoRoot, repo.alias, branch);
352
- if (existsSync(wtPath)) {
353
- log.warn(`${repo.alias}: ${DATA_DIRNAME}/${repo.alias}/${branch} already exists; skipping.`);
354
- return true;
307
+ if (removed) {
308
+ writeFileSync(path, out.join("\n"));
309
+ log.info(`removed ${GITIGNORE_ENTRY} from .gitignore (submodules are tracked, not ignored)`);
355
310
  }
356
- log.step(`${repo.alias}: git worktree add --track -B ${branch} ${branch} origin/${branch}`);
357
- const result = runBareGit(repoRoot, repo.alias, ["worktree", "add", "--track", "-B", branch, branch, `origin/${branch}`], true);
358
- if (!result.success) {
359
- log.error(`${repo.alias}: worktree add for ${branch} failed (exit ${result.exitCode})`);
360
- cleanupEmptyParents(repoRoot, repo.alias, branch);
361
- return false;
362
- }
363
- return true;
364
311
  }
365
- function removeWorktree(repo, repoRoot, branch, force) {
366
- const wtPath = worktreePath(repoRoot, repo.alias, branch);
367
- if (!existsSync(wtPath))
368
- return true;
369
- const args = ["worktree", "remove", ...(force ? ["--force"] : []), branch];
370
- log.step(`${repo.alias}: git worktree remove ${branch}${force ? " --force" : ""}`);
371
- const result = runBareGit(repoRoot, repo.alias, args, true);
372
- if (!result.success) {
373
- log.error(`${repo.alias}: worktree remove for ${branch} failed (exit ${result.exitCode})`);
374
- return false;
312
+ function gitignoreIgnoresOms(repoRoot) {
313
+ const gi = join(repoRoot, ".gitignore");
314
+ return (existsSync(gi)
315
+ && readFileSync(gi, "utf8")
316
+ .split("\n")
317
+ .some((l) => l.trim() === GITIGNORE_ENTRY || l.trim() === `/${GITIGNORE_ENTRY}`));
318
+ }
319
+ function cleanupFailedAdd(repoRoot, alias) {
320
+ const path = submodulePath(alias);
321
+ runGit(repoRoot, ["submodule", "deinit", "-f", "--", path]);
322
+ runGit(repoRoot, ["rm", "-f", "--cached", "--", path]);
323
+ runGit(repoRoot, ["config", "--file", ".gitmodules", "--remove-section", `submodule.${path}`]);
324
+ if (existsSync(join(repoRoot, ".gitmodules")))
325
+ runGit(repoRoot, ["add", ".gitmodules"]);
326
+ try {
327
+ rmSync(join(repoRoot, ".git", "modules", DATA_DIRNAME, alias), { recursive: true, force: true });
375
328
  }
376
- cleanupEmptyParents(repoRoot, repo.alias, branch);
377
- return true;
329
+ catch { }
330
+ try {
331
+ if (existsSync(aliasDir(repoRoot, alias)))
332
+ rmSync(aliasDir(repoRoot, alias), { recursive: true, force: true });
333
+ }
334
+ catch { }
378
335
  }
379
336
  function syncRepo(repo, repoRoot) {
380
337
  const alias = repo.alias;
381
- const aliasPath = aliasDir(repoRoot, alias);
382
- const barePath = bareDir(repoRoot, alias);
383
- const placeholderPath = gitPlaceholderPath(repoRoot, alias);
384
- const bareExists = existsSync(barePath);
385
- if (!bareExists) {
386
- if (existsSync(aliasPath)) {
387
- const stray = readdirSync(aliasPath).filter((e) => e !== ".git");
388
- if (stray.length > 0) {
389
- log.error(`${alias}: ${DATA_DIRNAME}/${alias}/ already exists but is not a bare clone. Move or remove it manually, then retry.`);
390
- return "failed";
391
- }
338
+ const path = submodulePath(alias);
339
+ const registered = isRegisteredSubmodule(repoRoot, path);
340
+ if (!registered) {
341
+ if (existsSync(aliasDir(repoRoot, alias)) && readdirSync(aliasDir(repoRoot, alias)).length > 0) {
342
+ log.error(`${alias}: ${path}/ already exists but is not a registered submodule. Move or remove it manually, then retry.`);
343
+ return "failed";
392
344
  }
393
345
  if (repo.branch) {
394
346
  const lsRemote = runGit(repoRoot, [
@@ -406,91 +358,101 @@ function syncRepo(repo, repoRoot) {
406
358
  log.warn(`${alias}: branch existence check failed (exit ${lsRemote.exitCode}); proceeding.`);
407
359
  }
408
360
  }
409
- if (!setupBareRepo(repo, repoRoot)) {
410
- if (existsSync(barePath))
411
- rmSync(barePath, { recursive: true, force: true });
412
- if (existsSync(placeholderPath))
413
- rmSync(placeholderPath);
414
- try {
415
- if (readdirSync(aliasPath).length === 0)
416
- rmdirSync(aliasPath);
417
- }
418
- catch { }
419
- return "failed";
361
+ // `git submodule add` refuses when .gitmodules is tracked in HEAD but missing from the
362
+ // working tree — the state left by an uncommitted unsync. Restore an empty one so it can append.
363
+ const gitmodules = join(repoRoot, ".gitmodules");
364
+ if (!existsSync(gitmodules) && runGit(repoRoot, ["cat-file", "-e", "HEAD:.gitmodules"]).success) {
365
+ writeFileSync(gitmodules, "");
420
366
  }
421
- const branch = repo.branch ?? detectDefaultBranch(repoRoot, alias);
422
- if (!branch) {
423
- log.error(`${alias}: could not determine default branch from bare clone. Set "branch:" in ${MANIFEST_FILENAME}.`);
367
+ log.step(`${alias}: git submodule add${repo.branch ? ` -b ${repo.branch}` : ""} ${repo.url} ${path}`);
368
+ const args = ["submodule", "add", ...(repo.branch ? ["-b", repo.branch] : []), "--", repo.url, path];
369
+ const add = runGit(repoRoot, args, true);
370
+ if (!add.success) {
371
+ log.error(`${alias}: git submodule add failed (exit ${add.exitCode})`);
372
+ cleanupFailedAdd(repoRoot, alias);
424
373
  return "failed";
425
374
  }
426
- if (!addWorktree(repo, repoRoot, branch))
427
- return "failed";
428
- log.success(`${alias}: added (branch=${branch})`);
375
+ const branch = repo.branch ?? currentBranch(aliasDir(repoRoot, alias));
376
+ if (branch)
377
+ attachBranch(repoRoot, alias, branch);
378
+ log.success(`${alias}: added${branch ? ` (branch=${branch})` : ""}`);
429
379
  return "added";
430
380
  }
431
- if (!existsSync(placeholderPath)) {
432
- writeFileSync(placeholderPath, "gitdir: ./.bare\n");
381
+ if (!submoduleInitialized(repoRoot, alias)) {
382
+ log.step(`${alias}: git submodule update --init ${path}`);
383
+ const upd = runGit(repoRoot, ["submodule", "update", "--init", "--", path], true);
384
+ if (!upd.success) {
385
+ log.error(`${alias}: git submodule update --init failed (exit ${upd.exitCode})`);
386
+ return "failed";
387
+ }
388
+ const branch = gitmodulesBranch(repoRoot, alias) ?? repo.branch;
389
+ if (branch)
390
+ attachBranch(repoRoot, alias, branch);
391
+ log.success(`${alias}: initialized${branch ? ` (branch=${branch})` : ""}`);
392
+ return "added";
433
393
  }
434
- log.step(`${alias}: git fetch origin`);
435
- const fetch = runBareGit(repoRoot, alias, ["fetch", "origin", "--prune"], true);
394
+ log.step(`${alias}: git fetch origin --prune`);
395
+ const fetch = runSub(repoRoot, alias, ["fetch", "origin", "--prune"], true);
436
396
  if (!fetch.success) {
437
397
  log.error(`${alias}: fetch failed (exit ${fetch.exitCode})`);
438
398
  return "failed";
439
399
  }
440
- const branch = repo.branch ?? detectDefaultBranch(repoRoot, alias);
441
- if (branch && !existsSync(worktreePath(repoRoot, alias, branch))) {
442
- if (!addWorktree(repo, repoRoot, branch))
443
- return "failed";
444
- }
445
- runBareGit(repoRoot, alias, ["worktree", "prune"]);
400
+ const branch = gitmodulesBranch(repoRoot, alias) ?? repo.branch;
401
+ if (branch)
402
+ attachBranch(repoRoot, alias, branch);
446
403
  log.success(`${alias}: updated`);
447
404
  return "updated";
448
405
  }
449
406
  function unsyncRepo(repo, repoRoot, force) {
450
- const aliasPath = aliasDir(repoRoot, repo.alias);
451
- const barePath = bareDir(repoRoot, repo.alias);
452
- const placeholderPath = gitPlaceholderPath(repoRoot, repo.alias);
453
- const aliasExists = existsSync(aliasPath);
454
- const bareExists = existsSync(barePath);
455
- if (!aliasExists && !bareExists)
407
+ const alias = repo.alias;
408
+ const path = submodulePath(alias);
409
+ const registered = isRegisteredSubmodule(repoRoot, path);
410
+ const exists = existsSync(aliasDir(repoRoot, alias));
411
+ if (!registered && !exists)
456
412
  return "nothing-to-remove";
457
- const worktrees = bareExists ? listExistingWorktrees(repoRoot, repo.alias) : [];
458
- if (!force) {
459
- for (const wt of worktrees) {
460
- const status = runGit(wt.path, ["status", "--porcelain"]);
461
- if (status.success && status.stdout.trim().length > 0) {
462
- log.error(`${repo.alias}: worktree at ${DATA_DIRNAME}/${repo.alias}/${wt.relativePath} has uncommitted changes. Commit, stash, or pass --force.`);
463
- return "failed";
464
- }
465
- }
413
+ if (!force && submoduleInitialized(repoRoot, alias) && isDirty(aliasDir(repoRoot, alias))) {
414
+ log.error(`${alias}: ${path} has uncommitted changes. Commit, stash, or pass --force.`);
415
+ return "failed";
466
416
  }
467
- for (const wt of worktrees) {
468
- const target = wt.branch === "(detached)" ? wt.relativePath : wt.branch;
469
- if (!removeWorktree(repo, repoRoot, target, force)) {
470
- return "failed";
471
- }
417
+ runGit(repoRoot, ["submodule", "deinit", ...(force ? ["-f"] : []), "--", path]);
418
+ const rm = runGit(repoRoot, ["rm", "-f", "--", path], true);
419
+ if (!rm.success) {
420
+ // Fall back to manual unregistration (e.g. the submodule was never initialized).
421
+ runGit(repoRoot, ["rm", "-f", "--cached", "--", path]);
422
+ runGit(repoRoot, ["config", "--file", ".gitmodules", "--remove-section", `submodule.${path}`]);
423
+ if (existsSync(join(repoRoot, ".gitmodules")))
424
+ runGit(repoRoot, ["add", ".gitmodules"]);
472
425
  }
473
- if (existsSync(barePath))
474
- rmSync(barePath, { recursive: true, force: true });
475
- if (existsSync(placeholderPath))
476
- rmSync(placeholderPath);
477
426
  try {
478
- if (existsSync(aliasPath)) {
479
- const remaining = readdirSync(aliasPath);
480
- if (remaining.length === 0)
481
- rmdirSync(aliasPath);
482
- }
427
+ rmSync(join(repoRoot, ".git", "modules", DATA_DIRNAME, alias), { recursive: true, force: true });
483
428
  }
484
429
  catch { }
430
+ if (existsSync(aliasDir(repoRoot, alias))) {
431
+ rmSync(aliasDir(repoRoot, alias), { recursive: true, force: true });
432
+ }
433
+ // Drop the now-empty oms/ directory if nothing else lives there.
434
+ try {
435
+ const parent = join(repoRoot, DATA_DIRNAME);
436
+ if (existsSync(parent) && readdirSync(parent).length === 0)
437
+ rmdirSync(parent);
438
+ }
439
+ catch { }
440
+ // Drop a .gitmodules that no longer registers any submodule (git rm leaves it empty).
441
+ const gitmodules = join(repoRoot, ".gitmodules");
442
+ if (existsSync(gitmodules) && readFileSync(gitmodules, "utf8").trim().length === 0) {
443
+ if (!runGit(repoRoot, ["rm", "-f", "--", ".gitmodules"]).success) {
444
+ rmSync(gitmodules, { force: true });
445
+ }
446
+ }
485
447
  return "removed";
486
448
  }
487
449
  function fetchRepo(repo, repoRoot) {
488
- if (!existsSync(bareDir(repoRoot, repo.alias))) {
450
+ if (!submoduleInitialized(repoRoot, repo.alias)) {
489
451
  log.error(`${repo.alias}: not synced. Run "oms sync ${repo.alias}" first.`);
490
452
  return "failed";
491
453
  }
492
454
  log.step(`${repo.alias}: git fetch origin --prune`);
493
- const r = runBareGit(repoRoot, repo.alias, ["fetch", "origin", "--prune"], true);
455
+ const r = runSub(repoRoot, repo.alias, ["fetch", "origin", "--prune"], true);
494
456
  if (r.success) {
495
457
  log.success(`${repo.alias}: fetched`);
496
458
  return "fetched";
@@ -498,67 +460,49 @@ function fetchRepo(repo, repoRoot) {
498
460
  log.error(`${repo.alias}: fetch failed (exit ${r.exitCode})`);
499
461
  return "failed";
500
462
  }
501
- function resolveTargetWorktree(repo, repoRoot) {
502
- const defaultBranch = repo.branch ?? detectDefaultBranch(repoRoot, repo.alias);
503
- if (defaultBranch) {
504
- const path = worktreePath(repoRoot, repo.alias, defaultBranch);
505
- if (existsSync(path))
506
- return { branch: defaultBranch, path };
507
- }
508
- const wts = listExistingWorktrees(repoRoot, repo.alias);
509
- if (wts.length === 1) {
510
- const only = wts[0];
511
- return { branch: only.branch === "(detached)" ? only.relativePath : only.branch, path: only.path };
512
- }
513
- return null;
514
- }
515
463
  function pullRepo(repo, repoRoot) {
516
- if (!existsSync(bareDir(repoRoot, repo.alias))) {
464
+ if (!submoduleInitialized(repoRoot, repo.alias)) {
517
465
  log.error(`${repo.alias}: not synced. Run "oms sync ${repo.alias}" first.`);
518
466
  return "failed";
519
467
  }
520
- const target = resolveTargetWorktree(repo, repoRoot);
521
- if (!target) {
522
- log.error(`${repo.alias}: cannot determine which worktree to pull. Use "oms worktree list ${repo.alias}".`);
468
+ const branch = currentBranch(aliasDir(repoRoot, repo.alias));
469
+ if (!branch) {
470
+ log.error(`${repo.alias}: detached HEAD. Run "oms checkout ${repo.alias} <branch>" before pulling.`);
523
471
  return "failed";
524
472
  }
525
- log.step(`${repo.alias}/${target.branch}: git pull --ff-only`);
526
- const r = runGit(target.path, ["pull", "--ff-only"], true);
473
+ log.step(`${repo.alias}/${branch}: git pull --ff-only`);
474
+ const r = runSub(repoRoot, repo.alias, ["pull", "--ff-only"], true);
527
475
  if (r.success) {
528
- log.success(`${repo.alias}/${target.branch}: pulled`);
476
+ stagePointer(repoRoot, repo.alias);
477
+ log.success(`${repo.alias}/${branch}: pulled`);
529
478
  return "pulled";
530
479
  }
531
- log.error(`${repo.alias}/${target.branch}: pull failed (exit ${r.exitCode})`);
480
+ log.error(`${repo.alias}/${branch}: pull failed (exit ${r.exitCode})`);
532
481
  return "failed";
533
482
  }
534
- function pushRepo(repo, repoRoot) {
535
- if (!existsSync(bareDir(repoRoot, repo.alias))) {
483
+ function pushRepo(repo, repoRoot, commit) {
484
+ if (!submoduleInitialized(repoRoot, repo.alias)) {
536
485
  log.error(`${repo.alias}: not synced. Run "oms sync ${repo.alias}" first.`);
537
486
  return "failed";
538
487
  }
539
- const target = resolveTargetWorktree(repo, repoRoot);
540
- if (!target) {
541
- log.error(`${repo.alias}: cannot determine which worktree to push. Use "oms worktree list ${repo.alias}".`);
488
+ const branch = currentBranch(aliasDir(repoRoot, repo.alias));
489
+ if (!branch) {
490
+ log.error(`${repo.alias}: detached HEAD. Run "oms checkout ${repo.alias} <branch>" before pushing.`);
542
491
  return "failed";
543
492
  }
544
- const upstream = runGit(target.path, [
545
- "rev-parse",
546
- "--abbrev-ref",
547
- "--symbolic-full-name",
548
- "@{u}",
549
- ]);
550
- if (!upstream.success) {
551
- log.error(`${repo.alias}/${target.branch}: git push requires an upstream. Set it manually before pushing.`);
493
+ log.step(`${repo.alias}/${branch}: git push -u origin ${branch}`);
494
+ const r = runSub(repoRoot, repo.alias, ["push", "-u", "origin", branch], true);
495
+ if (!r.success) {
496
+ log.error(`${repo.alias}/${branch}: push failed (exit ${r.exitCode})`);
552
497
  return "failed";
553
498
  }
554
- log.step(`${repo.alias}/${target.branch}: git push`);
555
- const r = runGit(target.path, ["-c", "push.autoSetupRemote=false", "push"], true);
556
- if (r.success) {
557
- log.success(`${repo.alias}/${target.branch}: pushed`);
558
- return "pushed";
499
+ stagePointer(repoRoot, repo.alias);
500
+ if (commit) {
501
+ const sha = shortSha(aliasDir(repoRoot, repo.alias));
502
+ runGit(repoRoot, ["commit", "-m", `oms: bump ${repo.alias} to ${sha}`, "--", submodulePath(repo.alias)]);
559
503
  }
560
- log.error(`${repo.alias}/${target.branch}: push failed (exit ${r.exitCode})`);
561
- return "failed";
504
+ log.success(`${repo.alias}/${branch}: pushed${commit ? " and recorded pointer" : ""}`);
505
+ return "pushed";
562
506
  }
563
507
  function printSummary(results) {
564
508
  const counts = {
@@ -595,6 +539,24 @@ function loadRepos(options = {}) {
595
539
  return null;
596
540
  }
597
541
  }
542
+ /** Shared preamble: load manifest, emit legacy hints, and confirm the workspace is a git repo. */
543
+ function loadForSubmodules() {
544
+ const loaded = loadRepos();
545
+ if (!loaded) {
546
+ emitLegacyRenameHintWalkUp();
547
+ return null;
548
+ }
549
+ const { repoRoot, repos } = loaded;
550
+ if (abortOnLegacyRenameAt(repoRoot))
551
+ return null;
552
+ if (!isGitRepo(repoRoot)) {
553
+ 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.`);
554
+ return null;
555
+ }
556
+ if (abortOnLegacyWorktree(repoRoot, repos))
557
+ return null;
558
+ return loaded;
559
+ }
598
560
  function uniqueAliases(aliases) {
599
561
  const seen = new Set();
600
562
  return aliases.filter((alias) => {
@@ -631,48 +593,45 @@ async function runSync(aliases, options) {
631
593
  printList(repos);
632
594
  return 0;
633
595
  }
634
- if (abortOnLegacy(repoRoot, repos))
596
+ if (!isGitRepo(repoRoot)) {
597
+ 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.`);
598
+ return 1;
599
+ }
600
+ if (abortOnLegacyWorktree(repoRoot, repos))
635
601
  return 1;
636
602
  const picked = await selectRepos(repos, aliases, options, "sync");
637
603
  if (!picked || picked.length === 0)
638
604
  return 1;
639
- ensureGitignore(repoRoot);
605
+ ensureOmsNotIgnored(repoRoot);
640
606
  const results = picked.map((repo) => syncRepo(repo, repoRoot));
641
607
  if (results.length > 1 || options.all)
642
608
  printSummary(results);
643
609
  return exitFromResults(results);
644
610
  }
645
611
  async function runManage(command, aliases, options) {
646
- const loaded = loadRepos();
647
- if (!loaded) {
648
- emitLegacyRenameHintWalkUp();
612
+ const loaded = loadForSubmodules();
613
+ if (!loaded)
649
614
  return 1;
650
- }
651
615
  const { repos, repoRoot } = loaded;
652
- if (abortOnLegacyRenameAt(repoRoot))
653
- return 1;
654
- if (abortOnLegacy(repoRoot, repos))
655
- return 1;
656
616
  const picked = await selectRepos(repos, aliases, options, command);
657
617
  if (!picked || picked.length === 0)
658
618
  return 1;
659
- const fn = command === "fetch" ? fetchRepo : command === "pull" ? pullRepo : pushRepo;
660
- const results = picked.map((repo) => fn(repo, repoRoot));
619
+ const results = picked.map((repo) => {
620
+ if (command === "fetch")
621
+ return fetchRepo(repo, repoRoot);
622
+ if (command === "pull")
623
+ return pullRepo(repo, repoRoot);
624
+ return pushRepo(repo, repoRoot, options.commit ?? false);
625
+ });
661
626
  if (results.length > 1 || options.all)
662
627
  printSummary(results);
663
628
  return exitFromResults(results);
664
629
  }
665
630
  async function runUnsync(aliases, options) {
666
- const loaded = loadRepos();
667
- if (!loaded) {
668
- emitLegacyRenameHintWalkUp();
631
+ const loaded = loadForSubmodules();
632
+ if (!loaded)
669
633
  return 1;
670
- }
671
634
  const { repos, repoRoot } = loaded;
672
- if (abortOnLegacyRenameAt(repoRoot))
673
- return 1;
674
- if (abortOnLegacy(repoRoot, repos))
675
- return 1;
676
635
  const picked = await selectRepos(repos, aliases, options, "unsync");
677
636
  if (!picked || picked.length === 0)
678
637
  return 1;
@@ -693,111 +652,135 @@ async function runUnsync(aliases, options) {
693
652
  printSummary(results);
694
653
  return exitFromResults(results);
695
654
  }
696
- async function runWorktreeAdd(alias, branch) {
697
- const loaded = loadRepos();
698
- if (!loaded) {
699
- emitLegacyRenameHintWalkUp();
655
+ async function runCheckout(alias, branch, options) {
656
+ const loaded = loadForSubmodules();
657
+ if (!loaded)
700
658
  return 1;
701
- }
702
659
  const { repos, repoRoot } = loaded;
703
- if (abortOnLegacyRenameAt(repoRoot))
704
- return 1;
705
- if (abortOnLegacy(repoRoot, repos))
706
- return 1;
707
660
  const repo = repos.find((r) => r.alias === alias);
708
661
  if (!repo) {
709
662
  log.error(`Unknown alias "${alias}". Use "oms sync --list" to see registered aliases.`);
710
663
  return 1;
711
664
  }
712
- if (!existsSync(bareDir(repoRoot, alias))) {
665
+ if (!submoduleInitialized(repoRoot, alias)) {
713
666
  log.error(`${alias}: not synced. Run "oms sync ${alias}" first.`);
714
667
  return 1;
715
668
  }
716
- if (existsSync(worktreePath(repoRoot, alias, branch))) {
717
- log.error(`${alias}: worktree for ${branch} already exists at ${DATA_DIRNAME}/${alias}/${branch}.`);
718
- return 1;
669
+ const dir = aliasDir(repoRoot, alias);
670
+ // Best-effort refresh so an existing remote branch is recognized; offline is fine.
671
+ runSub(repoRoot, alias, ["fetch", "origin", "--quiet"]);
672
+ if (localBranchExists(dir, branch)) {
673
+ log.step(`${alias}: git switch ${branch}`);
674
+ const r = runSub(repoRoot, alias, ["switch", branch], true);
675
+ if (!r.success)
676
+ return 2;
677
+ log.success(`${alias}: on ${branch}`);
678
+ return 0;
679
+ }
680
+ if (remoteBranchExists(dir, branch)) {
681
+ log.step(`${alias}: git switch -c ${branch} origin/${branch}`);
682
+ const r = runSub(repoRoot, alias, ["switch", "-c", branch, `origin/${branch}`], true);
683
+ if (!r.success)
684
+ return 2;
685
+ log.success(`${alias}: on ${branch} (tracking origin/${branch})`);
686
+ return 0;
719
687
  }
720
- log.step(`${alias}: git fetch origin --prune (refresh before add)`);
721
- runBareGit(repoRoot, alias, ["fetch", "origin", "--prune"], true);
722
- if (!addWorktree(repo, repoRoot, branch))
688
+ // Brand-new branch: created locally, no remote precondition. Push later with "oms push".
689
+ const args = ["switch", "-c", branch, ...(options.from ? [options.from] : [])];
690
+ log.step(`${alias}: git ${args.join(" ")}`);
691
+ const r = runSub(repoRoot, alias, args, true);
692
+ if (!r.success)
723
693
  return 2;
724
- log.success(`${alias}: added worktree for ${branch}`);
694
+ log.success(`${alias}: created new local branch ${branch}. Push it with "oms push ${alias}".`);
725
695
  return 0;
726
696
  }
727
- async function runWorktreeList(alias) {
728
- const loaded = loadRepos();
729
- if (!loaded) {
730
- emitLegacyRenameHintWalkUp();
697
+ /** Parse the leading status char from `git submodule status` (' ' ok, '+' moved, '-' uninit, 'U' conflict). */
698
+ function pinState(repoRoot, alias) {
699
+ const r = runGit(repoRoot, ["submodule", "status", "--", submodulePath(alias)]);
700
+ if (!r.success || r.stdout.length === 0)
701
+ return "?";
702
+ const c = r.stdout[0];
703
+ if (c === " ")
704
+ return "ok";
705
+ if (c === "+")
706
+ return "moved";
707
+ if (c === "-")
708
+ return "uninit";
709
+ if (c === "U")
710
+ return "conflict";
711
+ return "?";
712
+ }
713
+ function aheadBehind(dir) {
714
+ const r = runGit(dir, ["rev-list", "--left-right", "--count", "@{u}...HEAD"]);
715
+ if (!r.success)
716
+ return { ahead: "", behind: "" };
717
+ const [behind, ahead] = r.stdout.trim().split(/\s+/);
718
+ return { ahead: ahead && ahead !== "0" ? ahead : "", behind: behind && behind !== "0" ? behind : "" };
719
+ }
720
+ async function runStatus(aliases, options) {
721
+ const loaded = loadForSubmodules();
722
+ if (!loaded)
731
723
  return 1;
732
- }
733
724
  const { repos, repoRoot } = loaded;
734
- if (abortOnLegacyRenameAt(repoRoot))
725
+ const targets = aliases.length > 0 || options.all
726
+ ? await selectRepos(repos, options.all ? [] : aliases, options.all ? options : {}, "inspect")
727
+ : repos;
728
+ if (!targets)
735
729
  return 1;
736
- if (abortOnLegacy(repoRoot, repos))
737
- return 1;
738
- const targets = alias ? repos.filter((r) => r.alias === alias) : repos;
739
- if (alias && targets.length === 0) {
740
- log.error(`Unknown alias "${alias}".`);
741
- return 1;
742
- }
743
730
  const rows = [];
744
731
  for (const repo of targets) {
745
- if (!existsSync(bareDir(repoRoot, repo.alias))) {
746
- rows.push({ alias: repo.alias, branch: "(not synced)", path: "-" });
732
+ if (!isRegisteredSubmodule(repoRoot, submodulePath(repo.alias))) {
733
+ rows.push({ alias: repo.alias, branch: "(not registered)", pin: "-", dirty: "", ahead: "", behind: "" });
747
734
  continue;
748
735
  }
749
- const wts = listExistingWorktrees(repoRoot, repo.alias);
750
- if (wts.length === 0) {
751
- rows.push({ alias: repo.alias, branch: "(no worktrees)", path: "-" });
736
+ if (!submoduleInitialized(repoRoot, repo.alias)) {
737
+ rows.push({ alias: repo.alias, branch: "(not synced)", pin: "uninit", dirty: "", ahead: "", behind: "" });
752
738
  continue;
753
739
  }
754
- for (const wt of wts) {
755
- rows.push({
756
- alias: repo.alias,
757
- branch: wt.branch,
758
- path: `${DATA_DIRNAME}/${repo.alias}/${wt.relativePath}`,
759
- });
760
- }
761
- }
762
- const aliasW = Math.max("ALIAS".length, ...rows.map((r) => r.alias.length));
763
- const branchW = Math.max("BRANCH".length, ...rows.map((r) => r.branch.length));
764
- console.log(dim(`${pad("ALIAS", aliasW)} ${pad("BRANCH", branchW)} PATH`));
740
+ const dir = aliasDir(repoRoot, repo.alias);
741
+ const branch = currentBranch(dir) ?? `(detached ${shortSha(dir)})`;
742
+ const { ahead, behind } = aheadBehind(dir);
743
+ rows.push({
744
+ alias: repo.alias,
745
+ branch,
746
+ pin: pinState(repoRoot, repo.alias),
747
+ dirty: isDirty(dir) ? "yes" : "",
748
+ ahead,
749
+ behind,
750
+ });
751
+ }
752
+ const col = (key, header) => Math.max(header.length, ...rows.map((r) => r[key].length));
753
+ const aW = col("alias", "ALIAS");
754
+ const bW = col("branch", "BRANCH");
755
+ const pW = col("pin", "PIN");
756
+ const dW = Math.max("DIRTY".length, ...rows.map((r) => r.dirty.length));
757
+ console.log(dim(`${pad("ALIAS", aW)} ${pad("BRANCH", bW)} ${pad("PIN", pW)} ${pad("DIRTY", dW)} AHEAD BEHIND`));
765
758
  for (const r of rows) {
766
- console.log(`${pad(r.alias, aliasW)} ${pad(r.branch, branchW)} ${r.path}`);
759
+ console.log(`${pad(r.alias, aW)} ${pad(r.branch, bW)} ${pad(r.pin, pW)} ${pad(r.dirty, dW)} ${pad(r.ahead, 5)} ${r.behind}`);
767
760
  }
768
761
  return 0;
769
762
  }
770
- async function runWorktreeRemove(alias, branch, options) {
771
- const loaded = loadRepos();
772
- if (!loaded) {
773
- emitLegacyRenameHintWalkUp();
774
- return 1;
775
- }
776
- const { repos, repoRoot } = loaded;
777
- if (abortOnLegacyRenameAt(repoRoot))
763
+ const INIT_TEMPLATE = `# yaml-language-server: $schema=https://raw.githubusercontent.com/divlook/oh-my-space/main/oms.schema.json
764
+ repos:
765
+ - alias: example
766
+ url: git@github.com:example/repo.git
767
+ branch: main
768
+ `;
769
+ /** 현재 디렉터리에 기본 oms.yaml 템플릿을 생성합니다. */
770
+ async function runInit(options) {
771
+ const target = join(process.cwd(), MANIFEST_FILENAME);
772
+ if (existsSync(target) && !options.force) {
773
+ log.error(`${MANIFEST_FILENAME} already exists at ${target}. Use --force to overwrite.`);
778
774
  return 1;
779
- if (abortOnLegacy(repoRoot, repos))
780
- return 1;
781
- const repo = repos.find((r) => r.alias === alias);
782
- if (!repo) {
783
- log.error(`Unknown alias "${alias}".`);
784
- return 1;
785
- }
786
- const wtPath = worktreePath(repoRoot, alias, branch);
787
- if (!existsSync(wtPath)) {
788
- log.info(`${alias}: no worktree for ${branch}`);
789
- return 0;
790
775
  }
791
- if (!options.force) {
792
- const status = runGit(wtPath, ["status", "--porcelain"]);
793
- if (status.success && status.stdout.trim().length > 0) {
794
- log.error(`${alias}/${branch}: has uncommitted changes. Commit, stash, or pass --force.`);
795
- return 2;
796
- }
776
+ writeFileSync(target, INIT_TEMPLATE);
777
+ log.success(`created ${MANIFEST_FILENAME} at ${target}`);
778
+ // Sources are tracked submodules, so make sure no stale oms version left oms/ ignored.
779
+ ensureOmsNotIgnored(process.cwd());
780
+ if (!isGitRepo(process.cwd())) {
781
+ log.info(`oms manages sources as git submodules; run "git init" here if this is not a git repo yet.`);
797
782
  }
798
- if (!removeWorktree(repo, repoRoot, branch, options.force ?? false))
799
- return 2;
800
- log.success(`${alias}: removed worktree for ${branch}`);
783
+ log.info(`edit alias/url/branch, then run "oms sync".`);
801
784
  return 0;
802
785
  }
803
786
  async function runDoctor() {
@@ -827,39 +810,40 @@ async function runDoctor() {
827
810
  warnings++;
828
811
  }
829
812
  else if (!isGitVersionSupported(parsed)) {
830
- 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.`);
813
+ 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.`);
831
814
  warnings++;
832
815
  }
833
- if (hasLegacySubmoduleLayout(repoRoot, repos)) {
834
- log.warn(`detected legacy submodule layout (.gitmodules registers an alias path). See ${SUBMODULE_MIGRATION_DOC}.`);
816
+ if (!isGitRepo(repoRoot)) {
817
+ log.warn(`workspace is not a git repository. oms manages sources as submodules; run "git init" at ${repoRoot}.`);
835
818
  warnings++;
836
819
  }
837
- const gi = join(repoRoot, ".gitignore");
838
- const giHasSources = existsSync(gi)
839
- && readFileSync(gi, "utf8")
840
- .split("\n")
841
- .some((l) => l.trim() === GITIGNORE_ENTRY || l.trim() === `/${GITIGNORE_ENTRY}`);
842
- if (!giHasSources) {
843
- log.warn(`.gitignore does not exclude ${GITIGNORE_ENTRY}. Run "oms sync" to add it automatically.`);
820
+ if (abortOnLegacyWorktree(repoRoot, repos))
821
+ return 1;
822
+ if (gitignoreIgnoresOms(repoRoot)) {
823
+ log.warn(`.gitignore excludes ${GITIGNORE_ENTRY}, but submodules must be tracked. Run "oms sync" to remove it.`);
844
824
  warnings++;
845
825
  }
846
826
  for (const repo of repos) {
847
- const bare = bareDir(repoRoot, repo.alias);
848
- if (!existsSync(bare)) {
827
+ if (!isRegisteredSubmodule(repoRoot, submodulePath(repo.alias))) {
849
828
  log.info(`${repo.alias}: not synced`);
850
829
  continue;
851
830
  }
852
- const refspec = runBareGit(repoRoot, repo.alias, ["config", "--get", "remote.origin.fetch"]);
853
- if (!refspec.success || refspec.stdout.trim().length === 0) {
854
- 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}'`);
831
+ if (!submoduleInitialized(repoRoot, repo.alias)) {
832
+ log.warn(`${repo.alias}: registered but not initialized. Run "oms sync ${repo.alias}".`);
833
+ warnings++;
834
+ continue;
835
+ }
836
+ const dir = aliasDir(repoRoot, repo.alias);
837
+ const branch = currentBranch(dir);
838
+ if (!branch) {
839
+ log.warn(`${repo.alias}: detached HEAD. Run "oms checkout ${repo.alias} <branch>" to get on a branch.`);
855
840
  warnings++;
856
841
  }
857
842
  else {
858
- log.success(`${repo.alias}: bare clone OK (refspec: ${refspec.stdout.trim()})`);
843
+ log.success(`${repo.alias}: submodule OK (branch=${branch})`);
859
844
  }
860
- if (!existsSync(gitPlaceholderPath(repoRoot, repo.alias))) {
861
- log.warn(`${repo.alias}: missing .git placeholder at ${DATA_DIRNAME}/${repo.alias}/.git. Recreate with: echo 'gitdir: ./.bare' > ${DATA_DIRNAME}/${repo.alias}/.git`);
862
- warnings++;
845
+ if (pinState(repoRoot, repo.alias) === "moved") {
846
+ log.info(`${repo.alias}: working commit differs from the recorded pointer. Commit oms/${repo.alias} to record it.`);
863
847
  }
864
848
  }
865
849
  return warnings > 0 ? 2 : 0;
@@ -884,31 +868,41 @@ async function exitWith(action) {
884
868
  }
885
869
  const exitHelp = "\nExit codes: 0 ok | 1 usage/config error | 2 one or more git operations failed.";
886
870
  const commandNames = new Set([
871
+ "init",
887
872
  "doctor",
888
873
  "sync",
874
+ "status",
875
+ "checkout",
889
876
  "fetch",
890
877
  "pull",
891
878
  "push",
892
879
  "unsync",
893
- "worktree",
894
880
  "help",
895
881
  ]);
896
882
  const program = new Command();
897
883
  program
898
884
  .name("oms")
899
- .description(`Manage source repositories listed in ${MANIFEST_FILENAME} as bare clones + worktrees under ${DATA_DIRNAME}/<alias>/.`)
885
+ .description(`Manage source repositories listed in ${MANIFEST_FILENAME} as git submodules under ${DATA_DIRNAME}/<alias>/.`)
900
886
  .version(readPackageVersion())
901
887
  .addHelpText("after", exitHelp);
888
+ program
889
+ .command("init")
890
+ .description(`Create a starter ${MANIFEST_FILENAME} in the current directory.`)
891
+ .option("--force", `overwrite an existing ${MANIFEST_FILENAME}`)
892
+ .addHelpText("after", exitHelp)
893
+ .action(async (options) => {
894
+ await exitWith(runInit(options));
895
+ });
902
896
  program
903
897
  .command("doctor")
904
- .description(`Check ${MANIFEST_FILENAME}, git availability, bare-clone state, and .gitignore for each registered alias.`)
898
+ .description(`Check ${MANIFEST_FILENAME}, git availability, and the submodule state of each registered alias.`)
905
899
  .addHelpText("after", exitHelp)
906
900
  .action(async () => {
907
901
  await exitWith(runDoctor());
908
902
  });
909
903
  program
910
904
  .command("sync")
911
- .description(`Bare-clone each registered repo into ${DATA_DIRNAME}/<alias>/.bare and create the baseline worktree at ${DATA_DIRNAME}/<alias>/<branch>/.`)
905
+ .description(`Register each repo as a submodule at ${DATA_DIRNAME}/<alias>/ (or initialize and refresh an existing one), checked out on its baseline branch.`)
912
906
  .argument("[aliases...]", "repo aliases to sync (omit for interactive multi-select)")
913
907
  .option("--all", "sync every registered source repo")
914
908
  .option("--list", "print registered repos")
@@ -916,9 +910,28 @@ program
916
910
  .action(async (aliases, options) => {
917
911
  await exitWith(runSync(aliases, options));
918
912
  });
913
+ program
914
+ .command("status")
915
+ .description("Show each submodule's branch, pointer state, dirtiness, and ahead/behind counts.")
916
+ .argument("[aliases...]", "repo aliases to inspect (omit for all)")
917
+ .option("--all", "inspect every registered source repo")
918
+ .addHelpText("after", exitHelp)
919
+ .action(async (aliases, options) => {
920
+ await exitWith(runStatus(aliases, options));
921
+ });
922
+ program
923
+ .command("checkout")
924
+ .description("Switch a submodule to <branch>, creating it locally if it does not exist yet (no remote required).")
925
+ .argument("<alias>", "registered source alias")
926
+ .argument("<branch>", "branch name (may include slashes)")
927
+ .option("--from <ref>", "start point for a new branch (default: current HEAD)")
928
+ .addHelpText("after", exitHelp)
929
+ .action(async (alias, branch, options) => {
930
+ await exitWith(runCheckout(alias, branch, options));
931
+ });
919
932
  program
920
933
  .command("fetch")
921
- .description("Run git fetch origin --prune in each bare clone.")
934
+ .description("Run git fetch origin --prune in each submodule.")
922
935
  .argument("[aliases...]", "repo aliases to fetch (omit for interactive multi-select)")
923
936
  .option("--all", "fetch every registered source repo")
924
937
  .addHelpText("after", exitHelp)
@@ -927,7 +940,7 @@ program
927
940
  });
928
941
  program
929
942
  .command("pull")
930
- .description("Run git pull --ff-only in the baseline worktree of each selected alias; requires upstream.")
943
+ .description("Run git pull --ff-only on each submodule's current branch and stage the moved pointer.")
931
944
  .argument("[aliases...]", "repo aliases to pull (omit for interactive multi-select)")
932
945
  .option("--all", "pull every registered source repo")
933
946
  .addHelpText("after", exitHelp)
@@ -936,53 +949,23 @@ program
936
949
  });
937
950
  program
938
951
  .command("push")
939
- .description("Run git push in the baseline worktree of each explicitly listed alias; no --all, force, or upstream setup.")
952
+ .description("Run git push -u origin <branch> on each listed submodule (creating the remote branch on first push) and stage the moved pointer.")
940
953
  .argument("<aliases...>", "repo aliases to push")
954
+ .option("--commit", "also commit the pointer update in the parent repo")
941
955
  .addHelpText("after", exitHelp)
942
- .action(async (aliases) => {
943
- await exitWith(runManage("push", aliases, {}));
956
+ .action(async (aliases, options) => {
957
+ await exitWith(runManage("push", aliases, options));
944
958
  });
945
959
  program
946
960
  .command("unsync")
947
- .description(`Remove all worktrees and the bare clone for each alias (keeps ${MANIFEST_FILENAME} entry).`)
961
+ .description(`Deinitialize and remove the submodule for each alias (keeps ${MANIFEST_FILENAME} entry).`)
948
962
  .argument("[aliases...]", "repo aliases to unsync (omit for interactive multi-select)")
949
963
  .option("--all", "unsync every registered source repo")
950
- .option("--force", "discard uncommitted changes in worktrees")
964
+ .option("--force", "discard uncommitted changes in the submodule")
951
965
  .addHelpText("after", exitHelp)
952
966
  .action(async (aliases, options) => {
953
967
  await exitWith(runUnsync(aliases, options));
954
968
  });
955
- const worktreeCmd = program
956
- .command("worktree")
957
- .description("Manage additional worktrees for a synced source repo.")
958
- .addHelpText("after", exitHelp);
959
- worktreeCmd
960
- .command("add")
961
- .description(`Create a worktree for <branch> at ${DATA_DIRNAME}/<alias>/<branch>/.`)
962
- .argument("<alias>", "registered source alias")
963
- .argument("<branch>", "branch name (may include slashes)")
964
- .addHelpText("after", exitHelp)
965
- .action(async (alias, branch) => {
966
- await exitWith(runWorktreeAdd(alias, branch));
967
- });
968
- worktreeCmd
969
- .command("list")
970
- .description("List existing worktrees for the given alias (or all aliases).")
971
- .argument("[alias]", "registered source alias")
972
- .addHelpText("after", exitHelp)
973
- .action(async (alias) => {
974
- await exitWith(runWorktreeList(alias));
975
- });
976
- worktreeCmd
977
- .command("remove")
978
- .description(`Remove the worktree at ${DATA_DIRNAME}/<alias>/<branch>.`)
979
- .argument("<alias>", "registered source alias")
980
- .argument("<branch>", "branch name (may include slashes)")
981
- .option("--force", "discard uncommitted changes")
982
- .addHelpText("after", exitHelp)
983
- .action(async (alias, branch, options) => {
984
- await exitWith(runWorktreeRemove(alias, branch, options));
985
- });
986
969
  const requestedCommand = process.argv[2];
987
970
  if (requestedCommand && !requestedCommand.startsWith("-") && !commandNames.has(requestedCommand)) {
988
971
  console.error(`error: unknown command '${requestedCommand}'`);