@muhkoo/cli 0.11.0-alpha.0 → 0.12.0-alpha.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@muhkoo/cli",
3
- "version": "0.11.0-alpha.0",
3
+ "version": "0.12.0-alpha.0",
4
4
  "description": "Command-line interface for the Muhkoo platform — provision backends, deploy apps, and manage agents, functions, databases, and domains.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -39,7 +39,7 @@
39
39
  "test": "vitest run"
40
40
  },
41
41
  "dependencies": {
42
- "@muhkoo/connect": "0.11.0-alpha.0",
42
+ "@muhkoo/connect": "0.12.0-alpha.0",
43
43
  "snarkjs": "^0.7.0"
44
44
  },
45
45
  "packageManager": "yarn@1.22.22+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e",
@@ -0,0 +1,229 @@
1
+ /**
2
+ * `muhkoo vcs` — version control over your Muhkoo filesystem.
3
+ *
4
+ * Drives `client.vcs` through the SDK, for the same reason `muhkoo vfs` does:
5
+ * commit hashes are computed from a canonical encoding, and a second
6
+ * implementation here would only have to agree byte-for-byte forever. The first
7
+ * one to drift would fork the history of a project silently.
8
+ *
9
+ * There is no `push` or `pull`. The repository already lives in your account
10
+ * rather than on your disk, so every machine you sign in from is looking at the
11
+ * same objects — there is nowhere to push it to.
12
+ */
13
+
14
+ import { openClient } from "../lib/vfs.js";
15
+ import { loadConfig, saveConfig } from "../lib/config.js";
16
+ import { table, json, ok, info, warn, die, c } from "../lib/ui.js";
17
+
18
+ export const help = `muhkoo vcs — version control for your projects
19
+
20
+ Usage:
21
+ muhkoo vcs status what has changed since the last commit
22
+ muhkoo vcs commit -m <message> record the current state
23
+ muhkoo vcs log [-n <count>] history, newest first
24
+ muhkoo vcs show <commit> what one commit changed
25
+ muhkoo vcs diff [<a>] [<b>] compare two commits (default: last vs now)
26
+ muhkoo vcs branch [<name>] list branches, or start one here
27
+ muhkoo vcs switch <name> move onto a branch
28
+ muhkoo vcs checkout <commit> inspect an old state (detaches HEAD)
29
+ muhkoo vcs merge <name> bring a branch into this one
30
+ muhkoo vcs restore <path> [<commit>] put one file back
31
+
32
+ Options:
33
+ --project <slug> which project (default: taken from your vfs working
34
+ directory, so \`vfs cd /apps/my-app\` then \`vcs log\`)
35
+ -m <message> the commit message
36
+ -n <count> how many entries to show
37
+ --discard throw away uncommitted changes instead of refusing to move
38
+ --json machine-readable output
39
+
40
+ There is no push or pull: the repository lives in your account, so every
41
+ machine you sign in from already has it.`;
42
+
43
+ export default async function vcs(args) {
44
+ const sub = args._[1];
45
+ if (sub === undefined) return die("Missing subcommand. See `muhkoo vcs --help`.");
46
+
47
+ // `-m "message"` and `-n 20`, pulled out of the positionals by hand.
48
+ //
49
+ // The shared parser only understands `--flags`, and teaching it single-dash
50
+ // options would break the commands that pass `-r` and friends as positionals.
51
+ // Committing without `-m` is muscle memory though, so it is worth the seam.
52
+ const message = pullFlag(args, "-m") ?? args.message ?? (args.m === true ? undefined : args.m);
53
+ const count = pullFlag(args, "-n") ?? args.n;
54
+
55
+ const client = await openClient(args);
56
+ const slug = await resolveProject(args);
57
+ const repo = client.vcs.open(slug);
58
+ const a = (n, dflt) => args._[n] ?? dflt;
59
+
60
+ switch (sub) {
61
+ case "status": {
62
+ const changes = await repo.status();
63
+ const branch = (await repo.currentBranch()) ?? `${c.dim("detached at")} ${short(await repo.current())}`;
64
+ const pending = await repo.pendingMerge();
65
+ if (args.json) return json({ project: slug, branch, changes, merging: pending?.name ?? null });
66
+
67
+ info(`${c.bold(slug)} on ${branch}`);
68
+ if (pending) warn(`Merging ${pending.name} — resolve the files below, then commit to finish it.`);
69
+ if (!changes.length) return info("Nothing has changed since the last commit.");
70
+ return table(["", "PATH"], changes.map((ch) => [mark(ch.kind), ch.path]));
71
+ }
72
+
73
+ case "commit": {
74
+ if (!message) return die("A commit needs a message: `muhkoo vcs commit -m \"what changed\"`");
75
+ const hash = await repo.commit(String(message));
76
+ return ok(`${short(hash)} ${message}`);
77
+ }
78
+
79
+ case "log": {
80
+ const entries = await repo.log(Number(count ?? 20));
81
+ if (args.json) return json(entries);
82
+ if (!entries.length) return info("No commits yet.");
83
+ return table(
84
+ ["COMMIT", "WHEN", "MESSAGE"],
85
+ entries.map((e) => [
86
+ short(e.hash) + (e.parents.length > 1 ? c.dim(" (merge)") : ""),
87
+ when(e.at),
88
+ e.message,
89
+ ]),
90
+ );
91
+ }
92
+
93
+ case "show": {
94
+ const hash = await repo.resolve(required(a(2), "show <commit>"));
95
+ // The first commit has no parent to compare against; everything in it is
96
+ // an addition, which is what `diff(null, …)` reports.
97
+ const parent = await parentOf(repo, hash);
98
+ const changes = await repo.diff(parent, hash);
99
+ if (args.json) return json(changes);
100
+ return table(["", "PATH"], changes.map((ch) => [mark(ch.kind), ch.path]));
101
+ }
102
+
103
+ case "diff": {
104
+ // No arguments means the question people actually ask: what have I
105
+ // changed that is not committed yet.
106
+ if (a(2) === undefined) {
107
+ const pending = await repo.status();
108
+ if (args.json) return json(pending);
109
+ if (!pending.length) return info("No differences.");
110
+ return table(["", "PATH"], pending.map((ch) => [mark(ch.kind), ch.path]));
111
+ }
112
+ const from = await repo.resolve(a(2));
113
+ const to = a(3) === undefined ? await repo.resolve("HEAD") : await repo.resolve(a(3));
114
+ const changes = await repo.diff(from, to);
115
+ if (args.json) return json(changes);
116
+ if (!changes.length) return info("No differences.");
117
+ return table(["", "PATH"], changes.map((ch) => [mark(ch.kind), ch.path]));
118
+ }
119
+
120
+ case "branch": {
121
+ const name = a(2);
122
+ if (name) {
123
+ await repo.branch(name);
124
+ return ok(`Branch ${name} starts here. \`muhkoo vcs switch ${name}\` to move onto it.`);
125
+ }
126
+ const branches = await repo.branches();
127
+ const current = await repo.currentBranch();
128
+ if (args.json) return json({ branches, current });
129
+ if (!branches.length) return info("No branches yet — commit something first.");
130
+ return table(["", "BRANCH"], branches.map((b) => [b === current ? "*" : " ", b]));
131
+ }
132
+
133
+ case "switch": {
134
+ const name = required(a(2), "switch <name>");
135
+ await repo.switchTo(name, { discardChanges: Boolean(args.discard) });
136
+ return ok(`On ${name}.`);
137
+ }
138
+
139
+ case "checkout": {
140
+ const hash = await repo.resolve(required(a(2), "checkout <commit>"));
141
+ await repo.checkout(hash, { discardChanges: Boolean(args.discard) });
142
+ // Say what happened, not just that it worked: a detached HEAD surprises
143
+ // people, and committing from one loses work if they did not expect it.
144
+ return ok(
145
+ `Your files are as they were at ${short(hash)}. HEAD is detached — ` +
146
+ `\`muhkoo vcs switch <branch>\` to go back to working normally.`,
147
+ );
148
+ }
149
+
150
+ case "merge": {
151
+ const name = required(a(2), "merge <name>");
152
+ const result = await repo.merge(name, { discardChanges: Boolean(args.discard) });
153
+ if (result.kind === "up-to-date") return info(`Already up to date with ${name}.`);
154
+ if (result.kind === "fast-forward") return ok(`Fast-forwarded to ${short(result.commit)}.`);
155
+ if (result.kind === "merged") return ok(`Merged ${name} — ${short(result.commit)}.`);
156
+
157
+ warn(`Merged ${name}, but ${result.conflicts.length} file(s) need you:`);
158
+ table(["", "PATH"], result.conflicts.map((cf) => [c.dim(cf.reason), cf.path]));
159
+ return info("Edit them, then `muhkoo vcs commit -m \"...\"` to finish the merge.");
160
+ }
161
+
162
+ case "restore": {
163
+ const path = required(a(2), "restore <path> [<commit>]");
164
+ await repo.restore(path, a(3));
165
+ return ok(`Restored ${path}.`);
166
+ }
167
+
168
+ default:
169
+ return die(`Unknown subcommand "${sub}". See \`muhkoo vcs --help\`.`);
170
+ }
171
+ }
172
+
173
+ /**
174
+ * Which project this command is about.
175
+ *
176
+ * Taken from the VFS working directory when it can be, so `vfs cd /apps/my-app`
177
+ * followed by `vcs log` does what you would expect rather than making you name
178
+ * the project twice.
179
+ */
180
+ async function resolveProject(args) {
181
+ if (args.project) return String(args.project);
182
+ const cfg = await loadConfig();
183
+ const cwd = cfg.vfsCwd ?? "/";
184
+ const match = cwd.match(/^\/apps\/([^/]+)/);
185
+ if (match) return match[1];
186
+ return die(
187
+ "Which project? Pass `--project <slug>`, or `muhkoo vfs cd /apps/<slug>` first.",
188
+ );
189
+ }
190
+
191
+ /**
192
+ * Take a `-x value` pair out of the positionals and return the value.
193
+ *
194
+ * Mutates `args._` so the positional indices the subcommands read still line up
195
+ * with what the user typed.
196
+ */
197
+ function pullFlag(args, flag) {
198
+ const i = args._.indexOf(flag);
199
+ if (i === -1) return undefined;
200
+ const [, value] = args._.splice(i, 2);
201
+ return value;
202
+ }
203
+
204
+ /** A commit's first parent, or null for the very first commit. */
205
+ async function parentOf(repo, hash) {
206
+ try {
207
+ return await repo.resolve(`${hash}^`);
208
+ } catch {
209
+ return null;
210
+ }
211
+ }
212
+
213
+ function required(value, usage) {
214
+ if (value === undefined) die(`Usage: muhkoo vcs ${usage}`);
215
+ return value;
216
+ }
217
+
218
+ /** Commit hashes are long; the first 8 characters identify one in practice. */
219
+ function short(hash) {
220
+ return hash ? String(hash).slice(0, 8) : "-";
221
+ }
222
+
223
+ function mark(kind) {
224
+ return kind === "added" ? c.dim("+") : kind === "removed" ? c.dim("-") : c.dim("~");
225
+ }
226
+
227
+ function when(at) {
228
+ return new Date(at).toISOString().replace("T", " ").slice(0, 16);
229
+ }
@@ -10,9 +10,10 @@
10
10
  import { readFile, writeFile } from "node:fs/promises";
11
11
  import { basename, resolve } from "node:path";
12
12
  import { openClient, explainWriteFailure } from "../lib/vfs.js";
13
- import { mount as mountDir } from "../lib/mount.js";
13
+ import { mount as mountDir, importOnce } from "../lib/mount.js";
14
+ import { draftIgnores } from "../lib/ignore.js";
14
15
  import { loadConfig, saveConfig } from "../lib/config.js";
15
- import { table, json, ok, info, die } from "../lib/ui.js";
16
+ import { table, json, ok, info, warn, die } from "../lib/ui.js";
16
17
 
17
18
  export const help = `muhkoo vfs — your encrypted filesystem
18
19
 
@@ -32,11 +33,18 @@ Usage:
32
33
  muhkoo vfs find <glob> e.g. '/apps/**/*.ts'
33
34
  muhkoo vfs history <path> prior versions, newest first
34
35
  muhkoo vfs restore <path> [index] restore a version (default 0)
36
+ muhkoo vfs ignore [dir] [--write] draft a .vcsignore from the Node
37
+ defaults + the project's .gitignore
38
+ muhkoo vfs import <dir…> [--path <p>] upload whole projects (once, then stop)
35
39
  muhkoo vfs mount <dir> [--path <p>] sync a subtree to disk and keep it live
40
+ (dot-files skipped; deletes need --allow-delete)
36
41
  muhkoo vfs sweep [--force] reclaim orphaned records
37
42
  muhkoo vfs use-app <domain> use an app, by the domain you use it at
38
43
  muhkoo vfs app show which app you are writing as
39
44
 
45
+ What gets synced is decided by .vcsignore, or .gitignore if there is none, or
46
+ built-in Node defaults if there is neither. \`muhkoo vfs ignore\` drafts one.
47
+
40
48
  Reading your files is free. WRITING stores bytes, which are metered to an
41
49
  app — so put, rm, cp, mv and restore need an app signed in first.
42
50
 
@@ -44,12 +52,23 @@ Options:
44
52
  --app <name> write as this app for one command
45
53
  --key <k> supply the app key yourself (apps that publish their public
46
54
  config at /.well-known/muhkoo.json need no key)
55
+ --allow-delete propagate local deletions. OFF by default: a delete removes
56
+ the file's history too, so unlike an overwrite it cannot be undone
57
+ --hidden also sync dot-files and dot-directories
58
+ --dry-run (import) list what would be uploaded, and the total size,
59
+ without writing anything
47
60
  --no-pair unlock for this command only; pair nothing to this machine`;
48
61
 
49
62
  export default async function vfs(args) {
50
63
  const sub = args._[1];
51
64
  if (sub === undefined) return die("Missing subcommand. See `muhkoo vfs --help`.");
52
65
 
66
+ // Purely local subcommands run BEFORE the client exists. Unlocking the vault
67
+ // to write a file on this disk is both pointless and expensive: each unlock
68
+ // is a vault read, and a loop over a dozen projects trips the auth rate
69
+ // limiter long before it finishes.
70
+ if (sub === "ignore") return writeIgnores(args);
71
+
53
72
  const client = await openClient(args);
54
73
  const fs = client.vfs;
55
74
  const a = (n, dflt) => args._[n] ?? dflt;
@@ -138,8 +157,12 @@ export default async function vfs(args) {
138
157
  return ok(`Created ${a(2)}`);
139
158
 
140
159
  case "rm": {
141
- const path = required(a(2), "rm <path>");
142
- await fs.delete(path, { recursive: Boolean(args.r || args.recursive) });
160
+ // `-r` arrives as a POSITIONAL: the shared parser only understands
161
+ // `--flags`. Filter it out before reading the path, so `rm -r <path>` and
162
+ // `rm <path> -r` both work and neither tries to delete a file named "-r".
163
+ const recursive = args._.includes("-r") || Boolean(args.r || args.recursive);
164
+ const path = required(args._.filter((t) => t !== "-r")[2], "rm <path> [-r]");
165
+ await fs.delete(path, { recursive });
143
166
  return ok(`Deleted ${path}`);
144
167
  }
145
168
 
@@ -201,6 +224,36 @@ export default async function vfs(args) {
201
224
  return info(`Writing as "${slug}".`);
202
225
  }
203
226
 
227
+ case "import":
228
+ case "push": {
229
+ const dirs = args._.slice(2);
230
+ if (!dirs.length) return die("Usage: muhkoo vfs import <dir…> [--path /apps/<slug>]");
231
+ // `--path` names ONE destination, so it cannot mean anything sensible for
232
+ // several directories at once.
233
+ if (dirs.length > 1 && args.path) {
234
+ return die("--path takes a single directory. Without it each one goes to /apps/<its name>.");
235
+ }
236
+
237
+ // Several directories in ONE process, on purpose: every invocation of the
238
+ // CLI unlocks the vault, and a shell loop over a dozen projects trips the
239
+ // auth rate limiter before it finishes.
240
+ const opts = {
241
+ hidden: Boolean(args.hidden),
242
+ allowDelete: Boolean(args["allow-delete"]),
243
+ dryRun: Boolean(args["dry-run"]),
244
+ };
245
+ for (const d of dirs) {
246
+ const root = normalizeRoot(args.path ?? `/apps/${await slugFor(resolve(d))}`);
247
+ try {
248
+ await importOnce({ client, dir: resolve(d), root, opts });
249
+ } catch (err) {
250
+ // One unreadable project must not abandon the other twelve.
251
+ warn(`${d}: ${err?.message ?? err}`);
252
+ }
253
+ }
254
+ return;
255
+ }
256
+
204
257
  case "mount": {
205
258
  const dir = required(a(2), "mount <dir> [--path /apps]");
206
259
  const root = normalizeRoot(args.path ?? "/");
@@ -210,7 +263,10 @@ export default async function vfs(args) {
210
263
  const stop = () => controller.abort();
211
264
  process.on("SIGINT", stop);
212
265
  process.on("SIGTERM", stop);
213
- await mountDir({ client, dir: resolve(dir), root, signal: controller.signal });
266
+ await mountDir({
267
+ client, dir: resolve(dir), root, signal: controller.signal,
268
+ opts: { allowDelete: Boolean(args["allow-delete"]), hidden: Boolean(args.hidden) },
269
+ });
214
270
  return ok("Unmounted.");
215
271
  }
216
272
 
@@ -228,6 +284,44 @@ export default async function vfs(args) {
228
284
  }
229
285
  }
230
286
 
287
+ /**
288
+ * Draft or write a `.vcsignore`. Local only — no session, no network.
289
+ */
290
+ async function writeIgnores(args) {
291
+ const dir = resolve(args._[2] ?? ".");
292
+ const target = `${dir}/.vcsignore`;
293
+ const existing = await readFile(target, "utf8").catch(() => null);
294
+ if (existing && !args.force) {
295
+ return die(`${target} already exists. Pass --force to replace it.`);
296
+ }
297
+ const draft = draftIgnores(await readFile(`${dir}/.gitignore`, "utf8").catch(() => ""));
298
+ if (!args.write) {
299
+ process.stdout.write(draft);
300
+ return info(`\n(nothing written — pass --write to save this to ${target})`);
301
+ }
302
+ await writeFile(target, draft);
303
+ return ok(`Wrote ${target}`);
304
+ }
305
+
306
+ /**
307
+ * Where a project belongs in the filesystem.
308
+ *
309
+ * The app's own slug when the directory declares one, because that is the name
310
+ * everything else addresses it by: the portal opens the IDE at `?app=<slug>`,
311
+ * and the IDE reads `/apps/<slug>`. A project imported under its DIRECTORY name
312
+ * is invisible to both whenever the two differ — which they do for half of these
313
+ * (`portfolio` is `mattgagliardo`, `theater` is `muhkoo-theater`).
314
+ *
315
+ * Falls back to the directory name, which is right for a project that is not
316
+ * deployed anywhere yet.
317
+ */
318
+ async function slugFor(dir) {
319
+ const declared = await readFile(`${dir}/.muhkoo-app.json`, "utf8")
320
+ .then((raw) => JSON.parse(raw).slug)
321
+ .catch(() => null);
322
+ return declared || basename(dir);
323
+ }
324
+
231
325
  function required(value, usage) {
232
326
  if (!value) die(`Missing argument. Usage: muhkoo vfs ${usage}`);
233
327
  return value;
package/src/index.js CHANGED
@@ -21,6 +21,7 @@ const COMMANDS = {
21
21
  deploy: () => import("./commands/deploy.js"),
22
22
  promote: () => import("./commands/promote.js"),
23
23
  vfs: () => import("./commands/vfs.js"),
24
+ vcs: () => import("./commands/vcs.js"),
24
25
  devices: () => import("./commands/devices.js"),
25
26
  hosting: () => import("./commands/hosting.js"),
26
27
  domains: () => import("./commands/domains.js"),
@@ -55,6 +56,7 @@ Backend
55
56
 
56
57
  Files
57
58
  vfs ls|cat|put|get|rm|cp|mv|find|history|restore
59
+ vcs status|commit|log|diff|branch|switch|merge
58
60
  your encrypted filesystem
59
61
 
60
62
  Hosting
@@ -0,0 +1,174 @@
1
+ /**
2
+ * `.vcsignore` — what not to sync.
3
+ *
4
+ * Same syntax as `.gitignore`, because that is the file everyone already knows
5
+ * how to write and every project already has one to crib from. A separate file
6
+ * rather than reading `.gitignore` directly: the two answer different questions.
7
+ * Git ignores build output because it is derivable; the filesystem also wants to
8
+ * skip things that ARE committed but are pointless to sync — lockfiles you never
9
+ * open, fixtures measured in megabytes.
10
+ *
11
+ * `.gitignore` is still used as a fallback when no `.vcsignore` exists, so a
12
+ * project that has not opted in gets sensible behaviour on day one.
13
+ */
14
+
15
+ /** What a Node project almost always wants ignored. */
16
+ export const NODE_DEFAULTS = `# Dependencies and build output — reinstallable, and large.
17
+ node_modules/
18
+ dist/
19
+ build/
20
+ out/
21
+ coverage/
22
+ .next/
23
+ .nuxt/
24
+ .svelte-kit/
25
+ .turbo/
26
+ .parcel-cache/
27
+ .vite/
28
+ *.tsbuildinfo
29
+
30
+ # Logs and local state
31
+ *.log
32
+ npm-debug.log*
33
+ yarn-debug.log*
34
+ yarn-error.log*
35
+ .DS_Store
36
+ .muhkoo/
37
+
38
+ # Secrets. These should never leave the machine by accident.
39
+ .env
40
+ .env.*
41
+ !.env.example
42
+ `;
43
+
44
+ /**
45
+ * Compile ignore rules into a matcher.
46
+ *
47
+ * Returns `(path, isDir) => boolean`, where `path` is slash-separated and
48
+ * relative to the directory the ignore file sits in, with no leading slash.
49
+ *
50
+ * Last match wins, which is what makes `!` negation work: `*.log` followed by
51
+ * `!keep.log` keeps that one file.
52
+ */
53
+ export function compileIgnores(text) {
54
+ const rules = [];
55
+ for (const raw of String(text ?? "").split(/\r?\n/)) {
56
+ const line = raw.trim();
57
+ if (!line || line.startsWith("#")) continue;
58
+
59
+ let pattern = line;
60
+ let negated = false;
61
+ if (pattern.startsWith("!")) {
62
+ negated = true;
63
+ pattern = pattern.slice(1);
64
+ }
65
+ // An escaped leading '#' or '!' is a literal.
66
+ if (pattern.startsWith("\\")) pattern = pattern.slice(1);
67
+
68
+ let dirOnly = false;
69
+ if (pattern.endsWith("/")) {
70
+ dirOnly = true;
71
+ pattern = pattern.slice(0, -1);
72
+ }
73
+ if (!pattern) continue;
74
+
75
+ // A pattern with a slash anywhere but the end is anchored to the root;
76
+ // a bare name matches at any depth. This is the rule that makes
77
+ // `node_modules/` catch nested copies while `/dist` catches only the
78
+ // top-level one.
79
+ const anchored = pattern.includes("/");
80
+ if (anchored && pattern.startsWith("/")) pattern = pattern.slice(1);
81
+
82
+ rules.push({ ...toRegExp(pattern, anchored), negated, dirOnly });
83
+ }
84
+
85
+ return (path, isDir = false) => {
86
+ let ignored = false;
87
+ for (const rule of rules) {
88
+ // A directory rule matches the directory itself only when the thing
89
+ // being tested IS one — but it always matches what lives beneath it.
90
+ // `node_modules/` has to catch `node_modules/react/index.js`, which
91
+ // is a file, or pruning would ignore the directory and sync its
92
+ // entire contents anyway.
93
+ const hit = rule.under.test(path) || ((isDir || !rule.dirOnly) && rule.self.test(path));
94
+ if (hit) ignored = !rule.negated;
95
+ }
96
+ return ignored;
97
+ };
98
+ }
99
+
100
+ /**
101
+ * Glob → RegExp, with gitignore's wildcard rules.
102
+ *
103
+ * `*` stops at a path separator, `**` crosses them, `?` is a single character
104
+ * that is not a separator. An unanchored pattern may start at any segment
105
+ * boundary, which is how `*.log` matches `src/deep/thing.log`.
106
+ */
107
+ function toRegExp(pattern, anchored) {
108
+ let out = "";
109
+ for (let i = 0; i < pattern.length; i++) {
110
+ const ch = pattern[i];
111
+ if (ch === "*") {
112
+ if (pattern[i + 1] === "*") {
113
+ // `**/` may match nothing at all, so `**/foo` also matches `foo`.
114
+ if (pattern[i + 2] === "/") { out += "(?:.*/)?"; i += 2; }
115
+ else { out += ".*"; i += 1; }
116
+ } else out += "[^/]*";
117
+ } else if (ch === "?") out += "[^/]";
118
+ else if (ch === "[") {
119
+ const close = pattern.indexOf("]", i + 1);
120
+ if (close === -1) out += "\\[";
121
+ else { out += pattern.slice(i, close + 1); i = close; }
122
+ } else out += ch.replace(/[.+^${}()|\\]/g, "\\$&");
123
+ }
124
+ // Two regexes, because "is this the thing" and "is this inside the thing"
125
+ // are answered differently for a directory-only rule.
126
+ const head = anchored ? "^" : "^(?:.*/)?";
127
+ return {
128
+ self: new RegExp(`${head}${out}$`),
129
+ under: new RegExp(`${head}${out}/.*$`),
130
+ };
131
+ }
132
+
133
+ /**
134
+ * The ignore matcher for a directory.
135
+ *
136
+ * `.vcsignore` wins outright when present — a project that wrote one meant it.
137
+ * Otherwise `.gitignore` stands in, and the Node defaults apply when there is
138
+ * neither.
139
+ */
140
+ export async function loadIgnores(dir, readFile) {
141
+ for (const name of [".vcsignore", ".gitignore"]) {
142
+ try {
143
+ const text = await readFile(`${dir}/${name}`, "utf8");
144
+ // Defaults come first so a project file can negate them with `!`.
145
+ return { match: compileIgnores(NODE_DEFAULTS + "\n" + text), source: name };
146
+ } catch {
147
+ // not there; try the next
148
+ }
149
+ }
150
+ return { match: compileIgnores(NODE_DEFAULTS), source: "defaults" };
151
+ }
152
+
153
+ /**
154
+ * Starter `.vcsignore` for a project.
155
+ *
156
+ * Seeded from the Node defaults, then from the project's own `.gitignore` when
157
+ * it has one — the patterns a project already maintains are the best statement
158
+ * of what is derivable in it, and re-typing them is how the two files drift.
159
+ */
160
+ export function draftIgnores(gitignore) {
161
+ const theirs = String(gitignore ?? "")
162
+ .split(/\r?\n/)
163
+ .map((line) => line.trim())
164
+ // Drop what the defaults already cover, so the file reads as "and also
165
+ // these" rather than a wall of duplicates.
166
+ .filter((line) => line && !line.startsWith("#") && !DEFAULT_LINES.has(line));
167
+
168
+ if (!theirs.length) return NODE_DEFAULTS;
169
+ return `${NODE_DEFAULTS}\n# Carried over from .gitignore.\n${[...new Set(theirs)].join("\n")}\n`;
170
+ }
171
+
172
+ const DEFAULT_LINES = new Set(
173
+ NODE_DEFAULTS.split(/\r?\n/).map((l) => l.trim()).filter((l) => l && !l.startsWith("#")),
174
+ );
package/src/lib/mount.js CHANGED
@@ -27,10 +27,33 @@ import { watch } from "node:fs";
27
27
  import { dirname, join, relative, sep } from "node:path";
28
28
 
29
29
  import { planSync } from "./syncPlan.js";
30
+ import { loadIgnores } from "./ignore.js";
30
31
  import { info, ok, warn } from "./ui.js";
31
32
 
32
- /** Never sync these. Build output and dependencies belong to the machine. */
33
- const IGNORE = new Set([".git", "node_modules", ".muhkoo", ".DS_Store", "dist", ".cache", ".next"]);
33
+ /**
34
+ * Last-resort deny-list, used only for the watcher's fast path.
35
+ *
36
+ * The real rules come from `.vcsignore` (see `./ignore.js`); this exists so a
37
+ * filesystem event under `node_modules` can be dropped without a scan.
38
+ */
39
+ const IGNORE = new Set(["node_modules", "dist", "build", "coverage", "target", "vendor", ".git"]);
40
+
41
+ /**
42
+ * Skip dot-entries by default.
43
+ *
44
+ * The first version listed known-bad names and synced everything else, which is
45
+ * backwards: the set of tool directories a machine accumulates is open-ended and
46
+ * grows without asking. It uploaded a session-tooling directory (`.remember`) to
47
+ * a user's project on first contact with a real repo — a name no deny-list would
48
+ * have contained, because it did not exist when the list was written.
49
+ *
50
+ * Dot-entries are machine state until proven otherwise. `--hidden` opts back in
51
+ * for a project that genuinely keeps source there.
52
+ */
53
+ const isHidden = (name) => name.startsWith(".");
54
+
55
+ /** Dot-files that describe the project rather than the machine. */
56
+ const KEEP_HIDDEN = new Set([".vcsignore", ".gitignore"]);
34
57
 
35
58
  /**
36
59
  * Skip anything enormous.
@@ -48,21 +71,34 @@ const sha = (bytes) => createHash("sha256").update(bytes).digest("hex");
48
71
  /** Where the last-synced view lives, inside the mount. */
49
72
  const statePath = (dir) => join(dir, ".muhkoo", "mount.json");
50
73
 
51
- async function loadState(dir) {
74
+ /**
75
+ * The last-synced view, but ONLY if it describes the same remote root.
76
+ *
77
+ * State scoped to the directory alone is actively dangerous. It records "these
78
+ * paths were in sync", and `planSync` reads a path that is present locally and
79
+ * in the state but missing remotely as "deleted on the other side" — so pointing
80
+ * the same directory at a DIFFERENT root makes every local file look deleted,
81
+ * and with `--allow-delete` they would be. Re-rooting has to start from scratch.
82
+ */
83
+ async function loadState(dir, root) {
52
84
  try {
53
- return JSON.parse(await readFile(statePath(dir), "utf8"));
85
+ const saved = JSON.parse(await readFile(statePath(dir), "utf8"));
86
+ // Pre-versioning files were a bare path→hash map with no root recorded.
87
+ // They cannot be shown to be about this root, so they are not trusted.
88
+ if (!saved || saved.v !== 1 || saved.root !== root) return {};
89
+ return saved.paths ?? {};
54
90
  } catch {
55
- return {}; // first mount, or someone cleared it — a full compare is safe
91
+ return {}; // first sync, or someone cleared it — a full compare is safe
56
92
  }
57
93
  }
58
94
 
59
- async function saveState(dir, state) {
95
+ async function saveState(dir, root, paths) {
60
96
  await mkdir(dirname(statePath(dir)), { recursive: true });
61
- await writeFile(statePath(dir), JSON.stringify(state, null, 2) + "\n");
97
+ await writeFile(statePath(dir), JSON.stringify({ v: 1, root, paths }, null, 2) + "\n");
62
98
  }
63
99
 
64
100
  /** Hash every syncable file under `dir`, keyed by VFS-style relative path. */
65
- async function scanLocal(dir) {
101
+ async function scanLocal(dir, includeHidden = false, ignore = () => false) {
66
102
  const out = {};
67
103
  const walk = async (abs) => {
68
104
  let entries;
@@ -72,8 +108,15 @@ async function scanLocal(dir) {
72
108
  return; // vanished mid-scan; the next pass will see it
73
109
  }
74
110
  for (const entry of entries) {
75
- if (IGNORE.has(entry.name)) continue;
76
111
  const child = join(abs, entry.name);
112
+ const rel = relative(dir, child).split(sep).join("/");
113
+ // Pruned at the directory, not per file: never descend into
114
+ // node_modules to decide, file by file, not to sync it.
115
+ if (ignore(rel, entry.isDirectory())) continue;
116
+ // `.vcsignore` and `.gitignore` describe the project and belong with
117
+ // it; every other dot-entry is machine state until asked for.
118
+ const keepDotfile = KEEP_HIDDEN.has(entry.name);
119
+ if (!includeHidden && !keepDotfile && isHidden(entry.name)) continue;
77
120
  if (entry.isDirectory()) {
78
121
  await walk(child);
79
122
  continue;
@@ -112,8 +155,14 @@ async function scanRemote(vfs, root) {
112
155
  * record each, and two concurrent writes to the same record would have one
113
156
  * silently lose ([[VfsNamespace]] consistency note).
114
157
  */
115
- async function reconcile({ vfs, dir, root, state }) {
116
- const [local, remote] = await Promise.all([scanLocal(dir), scanRemote(vfs, root)]);
158
+ async function reconcile({ vfs, dir, root, state, opts = {} }) {
159
+ // Re-read every pass: editing `.vcsignore` should take effect on the next
160
+ // sync, not require a restart.
161
+ const { match } = await loadIgnores(dir, readFile);
162
+ const [local, remote] = await Promise.all([
163
+ scanLocal(dir, opts.hidden, match),
164
+ scanRemote(vfs, root),
165
+ ]);
117
166
  const plan = planSync({ last: state, local, remote });
118
167
  if (!plan.length) return state;
119
168
 
@@ -139,6 +188,23 @@ async function reconcile({ vfs, dir, root, state }) {
139
188
  break;
140
189
  }
141
190
  case "delete-remote":
191
+ // Deletes do NOT propagate unless asked for.
192
+ //
193
+ // Everything else this tool does is recoverable: an
194
+ // overwrite leaves the old version in `vfs history`. A
195
+ // delete is not — removing a file drops its history record
196
+ // along with it, so the safety net that justifies
197
+ // last-writer-wins does not cover this case. Losing a file
198
+ // to a directory you happened to clean up locally is too
199
+ // high a price for the convenience.
200
+ if (!opts.allowDelete) {
201
+ warn(
202
+ `${path} is gone locally but still in your filesystem — not deleting it.\n` +
203
+ ` Pass --allow-delete to propagate deletions, or remove it with: muhkoo vfs rm ${remoteAbs}`,
204
+ );
205
+ delete next[path]; // stop re-reporting it every pass
206
+ break;
207
+ }
142
208
  await vfs.delete(remoteAbs).catch(() => {});
143
209
  delete next[path];
144
210
  info(`✕ ${path} (removed here)`);
@@ -170,20 +236,115 @@ async function reconcile({ vfs, dir, root, state }) {
170
236
  warn(`${path}: ${err?.message ?? err}`);
171
237
  }
172
238
  }
173
- await saveState(dir, next);
239
+ await saveState(dir, root, next);
174
240
  return next;
175
241
  }
176
242
 
243
+ /**
244
+ * Push a directory up once and stop — no watcher.
245
+ *
246
+ * The same scan, plan and reconcile `mount` uses, so the rules about what is
247
+ * skipped and what a delete means are defined in exactly one place. This is the
248
+ * command for "get this project into my filesystem"; `mount` is for "and keep it
249
+ * that way".
250
+ *
251
+ * One process means ONE vault unlock, which is the practical reason this exists
252
+ * rather than a shell loop over `vfs put`: unlocking per file trips the auth
253
+ * rate limiter well before a real project finishes uploading.
254
+ */
255
+ export async function importOnce({ client, dir, root, opts = {} }) {
256
+ const vfs = client.vfs;
257
+ const { match, source } = await loadIgnores(dir, readFile);
258
+ const [local, remote] = await Promise.all([
259
+ scanLocal(dir, opts.hidden, match),
260
+ scanRemote(vfs, root),
261
+ ]);
262
+ const state = await loadState(dir, root);
263
+ const plan = planSync({ last: state, local, remote });
264
+
265
+ // Say what will happen before spending metered bytes. A project directory
266
+ // is easy to point at the wrong place, and the bytes are billed either way.
267
+ //
268
+ // Sizes are stat'd here rather than carried out of `scanLocal`, which
269
+ // returns hashes — the scan is shared with `mount`, and widening its return
270
+ // shape to serve one caller's progress line is not worth the churn.
271
+ const pushes = plan.filter((p) => p.action === "push");
272
+ const bytes = (
273
+ await Promise.all(
274
+ pushes.map(async ({ path }) => {
275
+ try {
276
+ return (await stat(join(dir, path.slice(1).split("/").join(sep)))).size;
277
+ } catch {
278
+ return 0;
279
+ }
280
+ }),
281
+ )
282
+ ).reduce((n, size) => n + size, 0);
283
+
284
+ if (opts.dryRun) {
285
+ if (!plan.length) return ok(`${root} already matches ${dir}.`);
286
+ for (const { path, action } of plan) info(`${SIGN[action] ?? "?"} ${path}`);
287
+ info(`\n${plan.length} change(s); ${pushes.length} file(s) to upload, ${human(bytes)}.`);
288
+ return info(`Ignoring per ${describeSource(source)}.`);
289
+ }
290
+
291
+ if (!plan.length) return ok(`${root} already matches ${dir} — nothing to do.`);
292
+ info(`Importing ${dir} → ${root} (${pushes.length} file(s), ${human(bytes)}; ignoring per ${describeSource(source)})`);
293
+ await reconcile({ vfs, dir, root, state, opts });
294
+ ok(`Imported into ${root}.`);
295
+ await noteStateFile(dir);
296
+ }
297
+
298
+ /**
299
+ * Mention the state file, once, in a repository that is not ignoring it.
300
+ *
301
+ * `.muhkoo/mount.json` is what makes a later import or mount incremental, so it
302
+ * has to live in the directory — but appearing as an untracked directory with no
303
+ * explanation is the kind of thing people delete, or commit by accident. Saying
304
+ * it here beats editing someone's `.gitignore` for them.
305
+ */
306
+ async function noteStateFile(dir) {
307
+ try {
308
+ await stat(join(dir, ".git"));
309
+ } catch {
310
+ return; // not a repository; nothing to explain
311
+ }
312
+ try {
313
+ const ignores = await readFile(join(dir, ".gitignore"), "utf8");
314
+ if (/^\.muhkoo\/?$/m.test(ignores)) return;
315
+ } catch {
316
+ // no .gitignore: still worth mentioning
317
+ }
318
+ info(" Tracking state is in .muhkoo/ — add it to .gitignore.");
319
+ }
320
+
321
+ const SIGN = {
322
+ push: "\u2191", pull: "\u2193", conflict: "!",
323
+ "delete-remote": "\u2715", "delete-local": "\u2715", forget: "\u00b7",
324
+ };
325
+
326
+ function describeSource(source) {
327
+ if (source === "defaults") return "the built-in Node defaults (write a .vcsignore to change them)";
328
+ if (source === ".gitignore") return ".gitignore (add a .vcsignore to diverge from it)";
329
+ return source;
330
+ }
331
+
332
+ function human(bytes) {
333
+ if (bytes < 1024) return `${bytes} B`;
334
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
335
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
336
+ }
337
+
177
338
  /**
178
339
  * Mount `root` at `dir` and keep them in step until `signal` aborts.
179
340
  */
180
- export async function mount({ client, dir, root, signal }) {
341
+ export async function mount({ client, dir, root, signal, opts = {} }) {
181
342
  const vfs = client.vfs;
182
343
  await mkdir(dir, { recursive: true });
183
344
 
184
- let state = await loadState(dir);
345
+ let state = await loadState(dir, root);
185
346
  info(`Mounting ${root} → ${dir}`);
186
- state = await reconcile({ vfs, dir, root, state });
347
+ state = await reconcile({ vfs, dir, root, state, opts });
187
348
  ok("In sync. Watching for changes — press Ctrl-C to stop.");
188
349
 
189
350
  // One reconcile at a time, with a trailing pass if anything arrived while we
@@ -199,7 +360,7 @@ export async function mount({ client, dir, root, signal }) {
199
360
  }
200
361
  running = true;
201
362
  try {
202
- state = await reconcile({ vfs, dir, root, state });
363
+ state = await reconcile({ vfs, dir, root, state, opts });
203
364
  } catch (err) {
204
365
  warn(`sync failed: ${err?.message ?? err}`);
205
366
  } finally {