@vite-hub/workspace 0.1.0 → 0.3.1
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/README.md +164 -107
- package/dist/abort-BCwpdrN0.js +32 -0
- package/dist/blob-database.d.ts +70 -117
- package/dist/blob-database.js +48 -41
- package/dist/checkout.d.ts +128 -0
- package/dist/checkout.js +849 -0
- package/dist/cloudflare.d.ts +2 -2
- package/dist/cloudflare.js +1 -1
- package/dist/config-B-863EgC.js +15 -0
- package/dist/{config-B7dmzDX3.js → config-BAgL2dtB.js} +48 -84
- package/dist/{config-DLKdaFWN.d.ts → config-BQKcPawI.d.ts} +1 -1
- package/dist/discard-CNNtCozM.js +8 -0
- package/dist/durability.d.ts +22 -0
- package/dist/durability.js +70 -0
- package/dist/error-diagnostics-CtKjGtGb.js +188 -0
- package/dist/error-diagnostics-DSkCJC_L.js +266 -0
- package/dist/file-2pFYNtsU.js +22 -0
- package/dist/{files-C7Px8uaC.js → files-BOo4SbwE.js} +2 -2
- package/dist/files.d.ts +38 -0
- package/dist/files.js +6 -0
- package/dist/{github-CPxHtFB7.js → github-CrYp4v8k.js} +32 -5
- package/dist/{glob--XcLlcml.js → glob-B8YGvTrZ.js} +4 -5
- package/dist/{glob--kNYDbfU.js → glob-Cjxms1t7.js} +1 -1
- package/dist/{host-CFnrTXTK.js → host-BFBpXn0N.js} +58 -47
- package/dist/{hosted-acMA5XyL.js → hosted-KcUR_jPv.js} +216 -93
- package/dist/hosted-vercel-blob-B3-wRdUm.js +410 -0
- package/dist/hosted-vercel-blob.d.ts +2 -2
- package/dist/hosted-vercel-blob.js +1 -1
- package/dist/hosted.d.ts +5 -3
- package/dist/hosted.js +2 -2
- package/dist/index.d.ts +9 -51
- package/dist/index.js +21 -91
- package/dist/{lifecycle-BwZ7c9hb.js → lifecycle-B-enk_4A.js} +8 -8
- package/dist/lineage.d.ts +26 -0
- package/dist/lineage.js +76 -0
- package/dist/loader.d.ts +1 -1
- package/dist/loader.js +2 -2
- package/dist/{mcp-resources-BREFCmtn.js → mcp-resources-DF0F5rcL.js} +2 -2
- package/dist/{memory-BbwOqDXl.js → memory-BOexthyW.js} +3 -4
- package/dist/{metadata-target-DZEZQGHA.js → metadata-target-CWz6KHKq.js} +17 -16
- package/dist/object-Da1zyPCR.js +11 -0
- package/dist/operation-definition-8gOe-ubD.d.ts +234 -0
- package/dist/operations-C6FpR8Rr.js +389 -0
- package/dist/operations-CE2drFih.js +1234 -0
- package/dist/operations.d.ts +41 -4
- package/dist/operations.js +3 -2
- package/dist/{path-CNAwN7pw.js → path--wrT_Azm.js} +2 -3
- package/dist/path-AxMho1wo.d.ts +7 -0
- package/dist/{plugins-DqQ8b4T5.d.ts → plugins-C8C0auoW.d.ts} +1 -1
- package/dist/{provider-kXjfli9u.js → provider-9s4Ufkm5.js} +104 -82
- package/dist/providers/github/store.d.ts +1 -1
- package/dist/providers/github/store.js +1 -1
- package/dist/registry-B3BBm4Ts.d.ts +19 -0
- package/dist/{registry-Bp-8UUfG.js → registry-CNphafBx.js} +55 -20
- package/dist/registry-CYNN623b.d.ts +9 -0
- package/dist/request-scope-Dw5n8bMC.js +83 -0
- package/dist/results-DgkZUmTL.js +8 -0
- package/dist/{rolldown-runtime-B4iAMlE-.js → rolldown-runtime-rQ84J-ij.js} +2 -3
- package/dist/runtime/assets.d.ts +1 -1
- package/dist/runtime/assets.js +3 -3
- package/dist/runtime/empty-assets-registry.d.ts +1 -1
- package/dist/runtime/empty-registry.d.ts +2 -1
- package/dist/runtime/registry.d.ts +2 -0
- package/dist/runtime/registry.js +23 -0
- package/dist/runtime/request.d.ts +4 -0
- package/dist/runtime/request.js +8 -0
- package/dist/runtime/state.d.ts +5 -4
- package/dist/runtime/state.js +8 -18
- package/dist/runtime/workspace.d.ts +1 -1
- package/dist/runtime/workspace.js +1 -1
- package/dist/runtime.d.ts +9 -8
- package/dist/runtime.js +23 -26
- package/dist/{search-CrTmXj5h.js → search-C_RfoM2j.js} +2 -2
- package/dist/{server-BNQ-Nbjj.js → server-8tGltlGz.js} +53 -40
- package/dist/server.d.ts +17 -8
- package/dist/server.js +1 -1
- package/dist/shared-B3_EUk89.js +848 -0
- package/dist/source-metadata.d.ts +6 -2
- package/dist/source-metadata.js +8 -8
- package/dist/state-BISnUf1s.d.ts +35 -0
- package/dist/{ai-BZyLwULx.js → state-DbrW-njQ.js} +96 -54
- package/dist/{store-CXgmu-uw.js → store-ybhyD38Z.js} +250 -106
- package/dist/{sync-CN6ec-5M.js → sync-CCD_VYC8.js} +4 -4
- package/dist/target-jWhTdIuF.js +89 -0
- package/dist/test.d.ts +1 -1
- package/dist/test.js +1 -1
- package/dist/{types-DeK9GIxy.d.ts → types-BbtwmBZ5.d.ts} +68 -14
- package/dist/use-C6lV3-wC.d.ts +321 -0
- package/dist/{use-BQj7nSz6.js → use-CSpT5W87.js} +75 -82
- package/dist/{utils-Blrh4N2n.js → utils-CgMZCHsX.js} +112 -41
- package/dist/vite.d.ts +585 -2
- package/dist/vite.js +21368 -1
- package/dist/{workspace-BWJQBK1u.d.ts → workspace-CYB2xZ1T.d.ts} +1 -1
- package/dist/{workspace-6pxkOuxr.js → workspace-sPWn2Jxj.js} +125 -40
- package/package.json +46 -55
- package/dist/ai-BW2ZhizI.d.ts +0 -177
- package/dist/ai.d.ts +0 -3
- package/dist/ai.js +0 -2
- package/dist/association-Cm0dUTDU-CDDhJnIh-Cv3bWnVb.js +0 -19
- package/dist/error-diagnostics-A_8Kp-48.js +0 -116
- package/dist/error-diagnostics-DY5GP47p.js +0 -96
- package/dist/events-7EBoeIPd-A2RUkJi5-BxrICQ17.js +0 -354
- package/dist/events-CRaLy7U3-3PNNp5WZ-Gv9nd0cH.js +0 -214
- package/dist/events-CeChclTf-CX-gD8oy-4aL2j6V-.js +0 -527
- package/dist/feed-DsC7Vws1-M_de2nSK-tKc0Pwo8.js +0 -248
- package/dist/feed-Dyf730Ys-D0HgBba6-BUnCa5gS.js +0 -179
- package/dist/file-C0_aPWSS.js +0 -26
- package/dist/file-metadata-CxDy-E2H.js +0 -58
- package/dist/forgejo-BN8ItCfl-Bbn4vhDd.js +0 -2278
- package/dist/github-DtncTfmv-Du2S8lGF.js +0 -4159
- package/dist/gitlab-BoDm8-BC-xzZsW9eW.js +0 -2530
- package/dist/graphql-DG5aJBT3-DceyFYdM-C4saqX37.js +0 -489
- package/dist/hosted-vercel-blob-DKntsHaf.js +0 -12603
- package/dist/inspect-BoObD2cJ.js +0 -167
- package/dist/mountx.d.ts +0 -8
- package/dist/mountx.js +0 -145
- package/dist/nitro.d.ts +0 -2
- package/dist/nitro.js +0 -2
- package/dist/nuxt.d.ts +0 -27
- package/dist/nuxt.js +0 -38
- package/dist/operations-BcpWr41m.js +0 -159
- package/dist/operations-CGqY1XeG.js +0 -965
- package/dist/operations-DnOwKsJT.d.ts +0 -136
- package/dist/registry-Cg1TJVVZ.d.ts +0 -10
- package/dist/request-execution-Dk9rY-Yh.js +0 -84
- package/dist/shared-DalXdP0i.js +0 -2158
- package/dist/state-B8zbLi5t.d.ts +0 -26
- package/dist/target-D4Bqb1eH.js +0 -11
- package/dist/templates-Bn8a-pd2-D9DhJEVD-CBfXNRzz.js +0 -125
- package/dist/token-CO62GglH.js +0 -61
- package/dist/use-DhwhbAVV.d.ts +0 -108
- package/dist/vite-BEvgU2GY.js +0 -20909
- package/dist/vite-CcZmMQ7S.d.ts +0 -476
- package/dist/webhooks-DgHwxxYz-D1V2LOr1-azofFOiP.js +0 -1565
package/dist/checkout.js
ADDED
|
@@ -0,0 +1,849 @@
|
|
|
1
|
+
import { t as workspaceErrorDiagnostics } from "./error-diagnostics-CtKjGtGb.js";
|
|
2
|
+
import { staleDerivedFiles } from "./lineage.js";
|
|
3
|
+
import { t as workspaceCommitRequestBytes } from "./results-DgkZUmTL.js";
|
|
4
|
+
import { isRuntimeDiagnostic } from "@vite-hub/runtime";
|
|
5
|
+
import { basename, dirname, join, relative, resolve, sep } from "node:path";
|
|
6
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
7
|
+
import { Diagnostic } from "nostics";
|
|
8
|
+
import { constants } from "node:fs";
|
|
9
|
+
import { lstat, mkdir, open, readFile, readdir, rename, rm, writeFile } from "node:fs/promises";
|
|
10
|
+
//#region src/checkout.ts
|
|
11
|
+
/** The lock file at the project root. Commit it: it records the remote revision that each checkout folder matches. */
|
|
12
|
+
const workspaceLockFile = "vitehub.lock";
|
|
13
|
+
/** A failed remote operation, with the code, message, and fix of the app's diagnostic. */
|
|
14
|
+
function remoteFailure(result) {
|
|
15
|
+
if (!result.code) return workspaceErrorDiagnostics.WORKSPACE_CHECKOUT_FAILED({ message: result.message });
|
|
16
|
+
return new Diagnostic({
|
|
17
|
+
code: result.code,
|
|
18
|
+
why: result.message,
|
|
19
|
+
...result.fix ? { fix: result.fix } : {}
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
/** The code, message, and fix that the checkout commands print for a failure. */
|
|
23
|
+
function checkoutFailure(error) {
|
|
24
|
+
const failure = isRuntimeDiagnostic(error) ? error : workspaceErrorDiagnostics.WORKSPACE_CHECKOUT_FAILED({ message: error instanceof Error ? error.message : String(error) });
|
|
25
|
+
return {
|
|
26
|
+
code: failure.code,
|
|
27
|
+
message: failure.message,
|
|
28
|
+
...failure.fix ? { fix: failure.fix } : {}
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
const ignored = /* @__PURE__ */ new Set([
|
|
32
|
+
".git",
|
|
33
|
+
".vitehub",
|
|
34
|
+
"node_modules",
|
|
35
|
+
".ds_store"
|
|
36
|
+
]);
|
|
37
|
+
/** Line patterns shared by working-tree scans and Git index searches. */
|
|
38
|
+
const conflictMarkerPatterns = ["^<{7}( |\r?$)", "^>{7}( |\r?$)"];
|
|
39
|
+
const conflictMarkers = conflictMarkerPatterns.map((pattern) => new RegExp(pattern, "m"));
|
|
40
|
+
/** The suffix of the temporary file of an atomic write. A command that stopped before the rename leaves one behind. */
|
|
41
|
+
const temporarySuffix = ".vitehub-tmp";
|
|
42
|
+
function portableKey(name) {
|
|
43
|
+
return name.normalize("NFC").toUpperCase().toLowerCase().normalize("NFC");
|
|
44
|
+
}
|
|
45
|
+
/** True for a file or folder name that a checkout skips, such as `node_modules`, `.GIT`, or a leftover temporary file. */
|
|
46
|
+
function ignoredName(name) {
|
|
47
|
+
const normalized = portableKey(name).replace(/[. ]+$/, "");
|
|
48
|
+
return ignored.has(normalized) || normalized.endsWith(temporarySuffix);
|
|
49
|
+
}
|
|
50
|
+
function ignoredPath(path) {
|
|
51
|
+
return path.split("/").some(ignoredName);
|
|
52
|
+
}
|
|
53
|
+
/** A folder path to compare. Windows and macOS file systems ignore case, so `content` and `CONTENT` are one folder. */
|
|
54
|
+
function folderKey(folder) {
|
|
55
|
+
return process.platform === "win32" || process.platform === "darwin" ? portableKey(folder) : folder;
|
|
56
|
+
}
|
|
57
|
+
/** Lock keys are Workspace names and file paths, including names such as `__proto__`. */
|
|
58
|
+
function ownRecord(record) {
|
|
59
|
+
Object.setPrototypeOf(record, null);
|
|
60
|
+
return record;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Use one portable spelling for every file and directory component, on every platform. Check the whole tree before
|
|
64
|
+
* writing: checking only changed files misses aliases of unchanged files, local files, and shared parent folders.
|
|
65
|
+
*/
|
|
66
|
+
function validateCheckoutPaths(paths, directories = []) {
|
|
67
|
+
const nodes = /* @__PURE__ */ new Map();
|
|
68
|
+
const add = (path, directory) => {
|
|
69
|
+
if (!directory && [
|
|
70
|
+
"__proto__",
|
|
71
|
+
"constructor",
|
|
72
|
+
"prototype"
|
|
73
|
+
].includes(path)) throw workspaceErrorDiagnostics.WORKSPACE_CHECKOUT_PATH({
|
|
74
|
+
path,
|
|
75
|
+
problem: "reserved"
|
|
76
|
+
});
|
|
77
|
+
let key = "";
|
|
78
|
+
let spelling = "";
|
|
79
|
+
const parts = path.split("/");
|
|
80
|
+
parts.forEach((part, index) => {
|
|
81
|
+
const component = portableKey(part);
|
|
82
|
+
if (!part || part === "." || part === ".." || /[. ]$|[<>:"|?*\\]/.test(part) || [...part].some((character) => character.charCodeAt(0) < 32) || /^(?:con|prn|aux|nul|conin\$|conout\$|com[1-9¹²³]|lpt[1-9¹²³])(?:[ .]|$)/.test(component)) throw workspaceErrorDiagnostics.WORKSPACE_CHECKOUT_PATH({
|
|
83
|
+
path,
|
|
84
|
+
problem: "not-portable"
|
|
85
|
+
});
|
|
86
|
+
key += `/${component}`;
|
|
87
|
+
spelling += `${spelling ? "/" : ""}${part}`;
|
|
88
|
+
const isDirectory = directory || index < parts.length - 1;
|
|
89
|
+
const existing = nodes.get(key);
|
|
90
|
+
if (existing && (existing.path !== spelling || existing.directory !== isDirectory)) throw workspaceErrorDiagnostics.WORKSPACE_CHECKOUT_PATH({
|
|
91
|
+
other: existing.path,
|
|
92
|
+
path: spelling,
|
|
93
|
+
problem: "spelling"
|
|
94
|
+
});
|
|
95
|
+
nodes.set(key, {
|
|
96
|
+
path: spelling,
|
|
97
|
+
directory: isDirectory
|
|
98
|
+
});
|
|
99
|
+
});
|
|
100
|
+
};
|
|
101
|
+
for (const path of paths) add(path, false);
|
|
102
|
+
for (const path of directories) add(path, true);
|
|
103
|
+
}
|
|
104
|
+
function digestOf(bytes) {
|
|
105
|
+
return `sha256-${createHash("sha256").update(bytes).digest("hex")}`;
|
|
106
|
+
}
|
|
107
|
+
function decode(file) {
|
|
108
|
+
return file.encoding === "utf8" ? new TextEncoder().encode(file.content) : Uint8Array.from(Buffer.from(file.content, "base64"));
|
|
109
|
+
}
|
|
110
|
+
function text(bytes) {
|
|
111
|
+
try {
|
|
112
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
113
|
+
} catch {
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
function encode(bytes) {
|
|
118
|
+
const value = text(bytes);
|
|
119
|
+
return value === void 0 ? {
|
|
120
|
+
content: Buffer.from(bytes).toString("base64"),
|
|
121
|
+
encoding: "base64"
|
|
122
|
+
} : {
|
|
123
|
+
content: value,
|
|
124
|
+
encoding: "utf8"
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
/** True when a text file still has Git conflict markers. */
|
|
128
|
+
function hasConflictMarkers(content) {
|
|
129
|
+
return conflictMarkers.every((pattern) => pattern.test(content));
|
|
130
|
+
}
|
|
131
|
+
function lines(value) {
|
|
132
|
+
return value.match(/[^\n]*\n|[^\n]+$/g) ?? [];
|
|
133
|
+
}
|
|
134
|
+
const maximumMatchCells = 4e6;
|
|
135
|
+
/**
|
|
136
|
+
* For each line of `base`, the index of the same line in `side` on a longest common subsequence, or -1. The common
|
|
137
|
+
* first and last lines match directly, so the table covers only the changed middle.
|
|
138
|
+
*/
|
|
139
|
+
function matches(base, side) {
|
|
140
|
+
const result = Array.from({ length: base.length }, () => -1);
|
|
141
|
+
let start = 0;
|
|
142
|
+
while (start < base.length && start < side.length && base[start] === side[start]) {
|
|
143
|
+
result[start] = start;
|
|
144
|
+
start++;
|
|
145
|
+
}
|
|
146
|
+
let baseEnd = base.length;
|
|
147
|
+
let sideEnd = side.length;
|
|
148
|
+
while (baseEnd > start && sideEnd > start && base[baseEnd - 1] === side[sideEnd - 1]) {
|
|
149
|
+
baseEnd--;
|
|
150
|
+
sideEnd--;
|
|
151
|
+
result[baseEnd] = sideEnd;
|
|
152
|
+
}
|
|
153
|
+
const rows = baseEnd - start;
|
|
154
|
+
const columns = sideEnd - start + 1;
|
|
155
|
+
if (rows * columns > maximumMatchCells) return result;
|
|
156
|
+
const table = new Uint32Array((rows + 1) * columns);
|
|
157
|
+
for (let i = rows - 1; i >= 0; i--) for (let j = columns - 2; j >= 0; j--) table[i * columns + j] = base[start + i] === side[start + j] ? table[(i + 1) * columns + j + 1] + 1 : Math.max(table[(i + 1) * columns + j], table[i * columns + j + 1]);
|
|
158
|
+
let i = 0;
|
|
159
|
+
let j = 0;
|
|
160
|
+
while (i < rows && j < columns - 1) if (base[start + i] === side[start + j]) {
|
|
161
|
+
result[start + i] = start + j;
|
|
162
|
+
i++;
|
|
163
|
+
j++;
|
|
164
|
+
} else if (table[(i + 1) * columns + j] >= table[i * columns + j + 1]) i++;
|
|
165
|
+
else j++;
|
|
166
|
+
return result;
|
|
167
|
+
}
|
|
168
|
+
function same(left, right) {
|
|
169
|
+
return left.length === right.length && left.every((line, index) => line === right[index]);
|
|
170
|
+
}
|
|
171
|
+
/**
|
|
172
|
+
* A three-way merge by line, as `git merge-file` does. A region that only one side changed takes that side. In a region
|
|
173
|
+
* that both sides changed, lines that each side replaced one for one merge line by line. Other lines that both sides
|
|
174
|
+
* changed in different ways get Git conflict markers, with the local lines first.
|
|
175
|
+
*/
|
|
176
|
+
function mergeText(base, local, remote, labels = {
|
|
177
|
+
local: "local",
|
|
178
|
+
remote: "remote"
|
|
179
|
+
}) {
|
|
180
|
+
const o = lines(base);
|
|
181
|
+
const a = lines(local);
|
|
182
|
+
const b = lines(remote);
|
|
183
|
+
const ma = matches(o, a);
|
|
184
|
+
const mb = matches(o, b);
|
|
185
|
+
const out = [];
|
|
186
|
+
let conflicts = 0;
|
|
187
|
+
const conflict = (localLines, remoteLines) => {
|
|
188
|
+
conflicts++;
|
|
189
|
+
const close = (part) => part.length && !part.at(-1).endsWith("\n") ? [...part.slice(0, -1), `${part.at(-1)}\n`] : part;
|
|
190
|
+
out.push(`<<<<<<< ${labels.local}\n`, ...close(localLines), "=======\n", ...close(remoteLines), `>>>>>>> ${labels.remote}\n`);
|
|
191
|
+
};
|
|
192
|
+
const chunk = (baseLines, localLines, remoteLines) => {
|
|
193
|
+
if (same(localLines, baseLines)) out.push(...remoteLines);
|
|
194
|
+
else if (same(remoteLines, baseLines) || same(localLines, remoteLines)) out.push(...localLines);
|
|
195
|
+
else if (baseLines.length === localLines.length && baseLines.length === remoteLines.length) {
|
|
196
|
+
let localRun = [];
|
|
197
|
+
let remoteRun = [];
|
|
198
|
+
const flush = () => {
|
|
199
|
+
if (localRun.length) conflict(localRun, remoteRun);
|
|
200
|
+
localRun = [];
|
|
201
|
+
remoteRun = [];
|
|
202
|
+
};
|
|
203
|
+
baseLines.forEach((line, index) => {
|
|
204
|
+
const localLine = localLines[index];
|
|
205
|
+
const remoteLine = remoteLines[index];
|
|
206
|
+
if (localLine === line || remoteLine === line || localLine === remoteLine) {
|
|
207
|
+
flush();
|
|
208
|
+
out.push(localLine === line ? remoteLine : localLine);
|
|
209
|
+
} else {
|
|
210
|
+
localRun.push(localLine);
|
|
211
|
+
remoteRun.push(remoteLine);
|
|
212
|
+
}
|
|
213
|
+
});
|
|
214
|
+
flush();
|
|
215
|
+
} else conflict(localLines, remoteLines);
|
|
216
|
+
};
|
|
217
|
+
let io = 0;
|
|
218
|
+
let ia = 0;
|
|
219
|
+
let ib = 0;
|
|
220
|
+
for (;;) {
|
|
221
|
+
let k = io;
|
|
222
|
+
while (k < o.length && !(ma[k] >= ia && mb[k] >= ib)) k++;
|
|
223
|
+
if (k >= o.length) {
|
|
224
|
+
chunk(o.slice(io), a.slice(ia), b.slice(ib));
|
|
225
|
+
break;
|
|
226
|
+
}
|
|
227
|
+
if (k === io && ma[k] === ia && mb[k] === ib) {
|
|
228
|
+
out.push(o[k]);
|
|
229
|
+
io++;
|
|
230
|
+
ia++;
|
|
231
|
+
ib++;
|
|
232
|
+
continue;
|
|
233
|
+
}
|
|
234
|
+
chunk(o.slice(io, k), a.slice(ia, ma[k]), b.slice(ib, mb[k]));
|
|
235
|
+
io = k;
|
|
236
|
+
ia = ma[k];
|
|
237
|
+
ib = mb[k];
|
|
238
|
+
}
|
|
239
|
+
return {
|
|
240
|
+
conflicts,
|
|
241
|
+
text: out.join("")
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
/**
|
|
245
|
+
* Writes a file as a new file in the same folder, then renames it over `target`. A hard link to the old file keeps
|
|
246
|
+
* its content, a link at `target` is replaced and not followed, and a failed write leaves the old file.
|
|
247
|
+
*/
|
|
248
|
+
async function writeAtomic(target, bytes) {
|
|
249
|
+
const mode = await lstat(target).then((stat) => stat.isFile() ? stat.mode & 511 : 438, () => 438);
|
|
250
|
+
const temporary = join(dirname(target), `.${basename(target)}.${randomBytes(6).toString("hex")}${temporarySuffix}`);
|
|
251
|
+
await writeFile(temporary, bytes, {
|
|
252
|
+
flag: constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,
|
|
253
|
+
mode
|
|
254
|
+
});
|
|
255
|
+
try {
|
|
256
|
+
await rename(temporary, target);
|
|
257
|
+
} catch (error) {
|
|
258
|
+
await rm(temporary, { force: true });
|
|
259
|
+
throw error;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
function lockSymlinkError() {
|
|
263
|
+
return workspaceErrorDiagnostics.WORKSPACE_CHECKOUT_SYMLINK({ path: workspaceLockFile });
|
|
264
|
+
}
|
|
265
|
+
async function readWorkspaceLock(rootDir) {
|
|
266
|
+
let source;
|
|
267
|
+
try {
|
|
268
|
+
if ((await lstat(join(rootDir, "vitehub.lock"))).isSymbolicLink()) throw lockSymlinkError();
|
|
269
|
+
const handle = await open(join(rootDir, workspaceLockFile), constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
270
|
+
try {
|
|
271
|
+
source = await handle.readFile("utf8");
|
|
272
|
+
} finally {
|
|
273
|
+
await handle.close();
|
|
274
|
+
}
|
|
275
|
+
} catch (error) {
|
|
276
|
+
if (error.code === "ENOENT") return {
|
|
277
|
+
version: 1,
|
|
278
|
+
workspaces: ownRecord({})
|
|
279
|
+
};
|
|
280
|
+
if (error.code === "ELOOP") throw lockSymlinkError();
|
|
281
|
+
throw error;
|
|
282
|
+
}
|
|
283
|
+
let parsed;
|
|
284
|
+
try {
|
|
285
|
+
parsed = JSON.parse(source);
|
|
286
|
+
} catch {
|
|
287
|
+
throw workspaceErrorDiagnostics.WORKSPACE_LOCK_INVALID({ problem: "json" });
|
|
288
|
+
}
|
|
289
|
+
const workspaces = Object(parsed) === parsed ? Reflect.get(Object(parsed), "workspaces") : void 0;
|
|
290
|
+
if (Reflect.get(Object(parsed), "version") !== 1 || Object(workspaces) !== workspaces) throw workspaceErrorDiagnostics.WORKSPACE_LOCK_INVALID({ problem: "shape" });
|
|
291
|
+
const lock = parsed;
|
|
292
|
+
ownRecord(lock.workspaces);
|
|
293
|
+
validateCheckoutFolders(rootDir, lock);
|
|
294
|
+
for (const entry of Object.values(lock.workspaces)) {
|
|
295
|
+
ownRecord(entry.files);
|
|
296
|
+
for (const path of Object.keys(entry.files)) if (ignoredPath(path)) delete entry.files[path];
|
|
297
|
+
validateCheckoutPaths(Object.keys(entry.files));
|
|
298
|
+
const conflicts = entry.conflicts?.filter((path) => !ignoredPath(path));
|
|
299
|
+
if (conflicts?.length) entry.conflicts = conflicts;
|
|
300
|
+
else delete entry.conflicts;
|
|
301
|
+
}
|
|
302
|
+
return lock;
|
|
303
|
+
}
|
|
304
|
+
async function writeWorkspaceLock(rootDir, lock) {
|
|
305
|
+
const sorted = {
|
|
306
|
+
version: 1,
|
|
307
|
+
workspaces: ownRecord({})
|
|
308
|
+
};
|
|
309
|
+
for (const name of Object.keys(lock.workspaces).sort()) {
|
|
310
|
+
const entry = lock.workspaces[name];
|
|
311
|
+
sorted.workspaces[name] = {
|
|
312
|
+
dir: entry.dir,
|
|
313
|
+
ref: entry.ref,
|
|
314
|
+
...entry.remote ? { remote: entry.remote } : {},
|
|
315
|
+
head: entry.head,
|
|
316
|
+
files: Object.fromEntries(Object.entries(entry.files).sort(([left], [right]) => left < right ? -1 : 1)),
|
|
317
|
+
...entry.conflicts?.length ? { conflicts: [...entry.conflicts].sort() } : {}
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
await writeAtomic(join(rootDir, workspaceLockFile), `${JSON.stringify(sorted, null, 2)}\n`);
|
|
321
|
+
}
|
|
322
|
+
const lockMutexFile = `${workspaceLockFile}.lock`;
|
|
323
|
+
const lockWaitMs = 1e4;
|
|
324
|
+
async function withLockMutex(rootDir, work) {
|
|
325
|
+
const path = join(rootDir, lockMutexFile);
|
|
326
|
+
const token = `${process.pid}:${randomBytes(16).toString("hex")}\n`;
|
|
327
|
+
const started = Date.now();
|
|
328
|
+
for (;;) try {
|
|
329
|
+
await writeFile(path, token, { flag: "wx" });
|
|
330
|
+
break;
|
|
331
|
+
} catch (error) {
|
|
332
|
+
if (error.code !== "EEXIST") throw error;
|
|
333
|
+
if (Date.now() - started > lockWaitMs) throw workspaceErrorDiagnostics.WORKSPACE_LOCK_BUSY();
|
|
334
|
+
await new Promise((resolve) => setTimeout(resolve, 20));
|
|
335
|
+
}
|
|
336
|
+
try {
|
|
337
|
+
return await work();
|
|
338
|
+
} finally {
|
|
339
|
+
if (await readFile(path, "utf8").catch(() => void 0) === token) await rm(path, { force: true });
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* Writes the entries of `names` from `lock` into the lock file as it is now, and keeps the other entries. Another
|
|
344
|
+
* command can have changed them since this command read the lock, such as a concurrent pull of another Workspace.
|
|
345
|
+
* A name without an entry in `lock` is removed.
|
|
346
|
+
*/
|
|
347
|
+
async function saveWorkspaceLock(rootDir, lock, names) {
|
|
348
|
+
await withLockMutex(rootDir, async () => {
|
|
349
|
+
const current = await readWorkspaceLock(rootDir);
|
|
350
|
+
for (const name of names) {
|
|
351
|
+
const entry = lock.workspaces[name];
|
|
352
|
+
if (entry) current.workspaces[name] = entry;
|
|
353
|
+
else delete current.workspaces[name];
|
|
354
|
+
}
|
|
355
|
+
validateCheckoutFolders(rootDir, current);
|
|
356
|
+
if (Object.keys(current.workspaces).length || await lstat(join(rootDir, "vitehub.lock")).then(() => true, () => false)) await writeWorkspaceLock(rootDir, current);
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
/** The absolute checkout folder of a lock `dir`. Fails unless it is a folder inside the project. */
|
|
360
|
+
function folderOf(rootDir, dir) {
|
|
361
|
+
const folder = resolve(rootDir, dir);
|
|
362
|
+
const inside = relative(rootDir, folder);
|
|
363
|
+
if (!inside || inside.startsWith("..") || inside.split(sep).includes("..")) throw workspaceErrorDiagnostics.WORKSPACE_CHECKOUT_DIR({ dir });
|
|
364
|
+
validateCheckoutPaths([], [inside.split(sep).join("/")]);
|
|
365
|
+
return folder;
|
|
366
|
+
}
|
|
367
|
+
function validateCheckoutFolders(rootDir, lock) {
|
|
368
|
+
const folders = /* @__PURE__ */ new Map();
|
|
369
|
+
for (const [workspace, entry] of Object.entries(lock.workspaces)) {
|
|
370
|
+
const folder = folderKey(folderOf(rootDir, entry.dir));
|
|
371
|
+
for (const [other, existing] of folders) if (folder === existing || folder.startsWith(`${existing}${sep}`) || existing.startsWith(`${folder}${sep}`)) throw workspaceErrorDiagnostics.WORKSPACE_CHECKOUT_OVERLAP({
|
|
372
|
+
dir: entry.dir,
|
|
373
|
+
other,
|
|
374
|
+
otherDir: lock.workspaces[other].dir,
|
|
375
|
+
workspace
|
|
376
|
+
});
|
|
377
|
+
folders.set(workspace, folder);
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
/** Every file of the checkout folder by Workspace path, with its bytes. Fails on a link in it or its ancestors. */
|
|
381
|
+
async function scan(rootDir, folder, directories = []) {
|
|
382
|
+
await assertNoSymlinks(rootDir, folder);
|
|
383
|
+
const files = /* @__PURE__ */ new Map();
|
|
384
|
+
const walk = async (dir) => {
|
|
385
|
+
let entries;
|
|
386
|
+
try {
|
|
387
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
388
|
+
} catch (error) {
|
|
389
|
+
if (error.code === "ENOENT") return;
|
|
390
|
+
throw error;
|
|
391
|
+
}
|
|
392
|
+
for (const entry of entries) {
|
|
393
|
+
if (ignoredName(entry.name)) continue;
|
|
394
|
+
const path = join(dir, entry.name);
|
|
395
|
+
if (entry.isSymbolicLink()) throw workspaceErrorDiagnostics.WORKSPACE_CHECKOUT_SYMLINK({ path: relative(folder, path) });
|
|
396
|
+
if (entry.isDirectory()) {
|
|
397
|
+
directories.push(relative(folder, path).split(sep).join("/"));
|
|
398
|
+
await walk(path);
|
|
399
|
+
} else if (entry.isFile()) files.set(relative(folder, path).split(sep).join("/"), new Uint8Array(await readFile(path)));
|
|
400
|
+
}
|
|
401
|
+
};
|
|
402
|
+
await walk(folder);
|
|
403
|
+
validateCheckoutPaths(files.keys(), directories);
|
|
404
|
+
return files;
|
|
405
|
+
}
|
|
406
|
+
/** Checks every existing path component inside the project before a checkout reads or writes it. */
|
|
407
|
+
async function assertNoSymlinks(rootDir, target) {
|
|
408
|
+
let current = rootDir;
|
|
409
|
+
for (const segment of relative(rootDir, target).split(sep)) {
|
|
410
|
+
current = join(current, segment);
|
|
411
|
+
let stat;
|
|
412
|
+
try {
|
|
413
|
+
stat = await lstat(current);
|
|
414
|
+
} catch (error) {
|
|
415
|
+
if (error.code === "ENOENT") break;
|
|
416
|
+
throw error;
|
|
417
|
+
}
|
|
418
|
+
if (stat.isSymbolicLink()) throw workspaceErrorDiagnostics.WORKSPACE_CHECKOUT_SYMLINK({ path: relative(rootDir, current) });
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
/** The local file of a relative Workspace path, checked for existing symbolic links. */
|
|
422
|
+
async function localPath(rootDir, folder, path) {
|
|
423
|
+
validateCheckoutPaths([path]);
|
|
424
|
+
const segments = path.split("/");
|
|
425
|
+
if (segments.some((segment) => !segment || segment === "." || segment === ".." || segment.includes("\\"))) throw workspaceErrorDiagnostics.WORKSPACE_CHECKOUT_PATH({
|
|
426
|
+
path,
|
|
427
|
+
problem: "not-relative"
|
|
428
|
+
});
|
|
429
|
+
const target = join(folder, ...segments);
|
|
430
|
+
await assertNoSymlinks(rootDir, target);
|
|
431
|
+
return target;
|
|
432
|
+
}
|
|
433
|
+
async function put(rootDir, folder, path, bytes) {
|
|
434
|
+
const target = await localPath(rootDir, folder, path);
|
|
435
|
+
await mkdir(dirname(target), { recursive: true });
|
|
436
|
+
await writeAtomic(target, bytes);
|
|
437
|
+
}
|
|
438
|
+
async function remove(rootDir, folder, path) {
|
|
439
|
+
await rm(await localPath(rootDir, folder, path), { force: true });
|
|
440
|
+
}
|
|
441
|
+
function localChanges(entry, files) {
|
|
442
|
+
const result = {
|
|
443
|
+
added: [],
|
|
444
|
+
modified: [],
|
|
445
|
+
deleted: [],
|
|
446
|
+
conflicted: [...entry.conflicts ?? []]
|
|
447
|
+
};
|
|
448
|
+
for (const [path, bytes] of files) {
|
|
449
|
+
const known = entry.files[path];
|
|
450
|
+
if (known === void 0) result.added.push(path);
|
|
451
|
+
else if (known !== digestOf(bytes)) result.modified.push(path);
|
|
452
|
+
const value = text(bytes);
|
|
453
|
+
if (value !== void 0 && hasConflictMarkers(value) && !result.conflicted.includes(path)) result.conflicted.push(path);
|
|
454
|
+
}
|
|
455
|
+
for (const path of Object.keys(entry.files)) if (!files.has(path)) result.deleted.push(path);
|
|
456
|
+
for (const list of Object.values(result)) list.sort();
|
|
457
|
+
return result;
|
|
458
|
+
}
|
|
459
|
+
async function callOrThrow(context, remote, operation, input) {
|
|
460
|
+
const result = await context.call(operation, input, remote);
|
|
461
|
+
if (!result.ok) throw remoteFailure(result);
|
|
462
|
+
return result.value;
|
|
463
|
+
}
|
|
464
|
+
/** Creates the lock entry of a Workspace on its first pull, or checks the options of a later pull against it. */
|
|
465
|
+
function checkoutEntry(rootDir, lock, workspace, options) {
|
|
466
|
+
const existing = lock.workspaces[workspace];
|
|
467
|
+
if (existing) {
|
|
468
|
+
for (const key of [
|
|
469
|
+
"dir",
|
|
470
|
+
"ref",
|
|
471
|
+
"remote"
|
|
472
|
+
]) if (options[key] !== void 0 && options[key] !== existing[key]) throw workspaceErrorDiagnostics.WORKSPACE_CHECKOUT_OPTIONS({
|
|
473
|
+
actual: String(options[key]),
|
|
474
|
+
expected: String(existing[key]),
|
|
475
|
+
key,
|
|
476
|
+
workspace
|
|
477
|
+
});
|
|
478
|
+
return existing;
|
|
479
|
+
}
|
|
480
|
+
if (!options.dir) throw workspaceErrorDiagnostics.WORKSPACE_CHECKOUT_DIR({ workspace });
|
|
481
|
+
const entry = {
|
|
482
|
+
dir: options.dir,
|
|
483
|
+
ref: options.ref ?? "main",
|
|
484
|
+
...options.remote ? { remote: options.remote } : {},
|
|
485
|
+
head: null,
|
|
486
|
+
files: ownRecord({})
|
|
487
|
+
};
|
|
488
|
+
lock.workspaces[workspace] = entry;
|
|
489
|
+
validateCheckoutFolders(rootDir, lock);
|
|
490
|
+
return entry;
|
|
491
|
+
}
|
|
492
|
+
async function pullEntry(context, workspace, entry) {
|
|
493
|
+
const folder = folderOf(context.rootDir, entry.dir);
|
|
494
|
+
await assertNoSymlinks(context.rootDir, folder);
|
|
495
|
+
const changes = await callOrThrow(context, entry.remote, "workspace.changes", {
|
|
496
|
+
workspace,
|
|
497
|
+
ref: entry.ref,
|
|
498
|
+
since: entry.head
|
|
499
|
+
});
|
|
500
|
+
const result = {
|
|
501
|
+
workspace,
|
|
502
|
+
ref: entry.ref,
|
|
503
|
+
from: entry.head,
|
|
504
|
+
head: changes.head?.id ?? null,
|
|
505
|
+
files: []
|
|
506
|
+
};
|
|
507
|
+
if (result.head === entry.head) return result;
|
|
508
|
+
const directories = [];
|
|
509
|
+
const local = await scan(context.rootDir, folder, directories);
|
|
510
|
+
const incoming = changes.files.filter((file) => !ignoredPath(file.path));
|
|
511
|
+
validateCheckoutPaths([
|
|
512
|
+
...Object.keys(entry.files),
|
|
513
|
+
...local.keys(),
|
|
514
|
+
...incoming.map((file) => file.path)
|
|
515
|
+
], directories);
|
|
516
|
+
const conflicts = new Set(entry.conflicts ?? []);
|
|
517
|
+
const labels = {
|
|
518
|
+
local: "local",
|
|
519
|
+
remote: `${entry.ref} ${result.head ?? ""}`.trim()
|
|
520
|
+
};
|
|
521
|
+
for (const file of incoming) result.files.push(await applyRemote(context.rootDir, folder, entry, file, local.get(file.path), conflicts, labels));
|
|
522
|
+
entry.head = result.head;
|
|
523
|
+
if (conflicts.size) entry.conflicts = [...conflicts];
|
|
524
|
+
else delete entry.conflicts;
|
|
525
|
+
return result;
|
|
526
|
+
}
|
|
527
|
+
async function applyRemote(rootDir, folder, entry, file, localBytes, conflicts, labels) {
|
|
528
|
+
const { path } = file;
|
|
529
|
+
const remoteBytes = file.head ? decode(file.head) : void 0;
|
|
530
|
+
const known = entry.files[path];
|
|
531
|
+
if (remoteBytes) entry.files[path] = digestOf(remoteBytes);
|
|
532
|
+
else delete entry.files[path];
|
|
533
|
+
const localDigest = localBytes ? digestOf(localBytes) : void 0;
|
|
534
|
+
const remoteDigest = remoteBytes ? digestOf(remoteBytes) : void 0;
|
|
535
|
+
if (localDigest === known) {
|
|
536
|
+
if (remoteBytes) {
|
|
537
|
+
await put(rootDir, folder, path, remoteBytes);
|
|
538
|
+
return {
|
|
539
|
+
path,
|
|
540
|
+
action: localBytes ? "updated" : "added"
|
|
541
|
+
};
|
|
542
|
+
}
|
|
543
|
+
if (localBytes) await remove(rootDir, folder, path);
|
|
544
|
+
return {
|
|
545
|
+
path,
|
|
546
|
+
action: "deleted"
|
|
547
|
+
};
|
|
548
|
+
}
|
|
549
|
+
if (localDigest === remoteDigest) return {
|
|
550
|
+
path,
|
|
551
|
+
action: remoteBytes ? "updated" : "deleted"
|
|
552
|
+
};
|
|
553
|
+
if (!remoteBytes) return {
|
|
554
|
+
path,
|
|
555
|
+
action: "kept",
|
|
556
|
+
note: "The remote deleted this file and you changed it. Your file stays; push it to restore it on the remote, or delete it."
|
|
557
|
+
};
|
|
558
|
+
if (!localBytes) {
|
|
559
|
+
await put(rootDir, folder, path, remoteBytes);
|
|
560
|
+
return {
|
|
561
|
+
path,
|
|
562
|
+
action: "updated",
|
|
563
|
+
note: "You deleted this file and the remote changed it. The remote version is back; delete it again to remove it."
|
|
564
|
+
};
|
|
565
|
+
}
|
|
566
|
+
const baseText = file.base ? text(decode(file.base)) : "";
|
|
567
|
+
const localText = text(localBytes);
|
|
568
|
+
const remoteText = text(remoteBytes);
|
|
569
|
+
if (baseText === void 0 || localText === void 0 || remoteText === void 0) {
|
|
570
|
+
conflicts.add(path);
|
|
571
|
+
return {
|
|
572
|
+
path,
|
|
573
|
+
action: "conflict",
|
|
574
|
+
note: "Both sides changed this binary file. Your file stays. Run `vitehub resolve` to keep it, or `vitehub pull --theirs` to take the remote file."
|
|
575
|
+
};
|
|
576
|
+
}
|
|
577
|
+
const merged = mergeText(baseText, localText, remoteText, labels);
|
|
578
|
+
await put(rootDir, folder, path, new TextEncoder().encode(merged.text));
|
|
579
|
+
if (merged.conflicts) return {
|
|
580
|
+
path,
|
|
581
|
+
action: "conflict",
|
|
582
|
+
note: `${merged.conflicts} conflicting ${merged.conflicts === 1 ? "region" : "regions"}. Edit the file, remove the markers, then push.`
|
|
583
|
+
};
|
|
584
|
+
return {
|
|
585
|
+
path,
|
|
586
|
+
action: "merged"
|
|
587
|
+
};
|
|
588
|
+
}
|
|
589
|
+
function selected(lock, workspace) {
|
|
590
|
+
if (workspace) {
|
|
591
|
+
if (!lock.workspaces[workspace]) throw workspaceErrorDiagnostics.WORKSPACE_CHECKOUT_MISSING({ workspace });
|
|
592
|
+
return [workspace];
|
|
593
|
+
}
|
|
594
|
+
const names = Object.keys(lock.workspaces).sort();
|
|
595
|
+
if (!names.length) throw workspaceErrorDiagnostics.WORKSPACE_CHECKOUT_MISSING({});
|
|
596
|
+
return names;
|
|
597
|
+
}
|
|
598
|
+
/** Merges the remote changes into each checkout folder and updates the lock file. */
|
|
599
|
+
async function pullWorkspaces(context, options = {}) {
|
|
600
|
+
const lock = await readWorkspaceLock(context.rootDir);
|
|
601
|
+
if (options.dir) folderOf(context.rootDir, options.dir);
|
|
602
|
+
const created = options.workspace !== void 0 && !lock.workspaces[options.workspace];
|
|
603
|
+
if (options.workspace) checkoutEntry(context.rootDir, lock, options.workspace, options);
|
|
604
|
+
const results = [];
|
|
605
|
+
const touched = created ? [options.workspace] : [];
|
|
606
|
+
try {
|
|
607
|
+
for (const name of selected(lock, options.workspace)) {
|
|
608
|
+
if (!touched.includes(name)) touched.push(name);
|
|
609
|
+
const entry = lock.workspaces[name];
|
|
610
|
+
const result = await pullEntry(context, name, entry);
|
|
611
|
+
if (options.theirs?.length) await takeTheirs(context, name, entry, options.theirs, result);
|
|
612
|
+
results.push(result);
|
|
613
|
+
}
|
|
614
|
+
} catch (error) {
|
|
615
|
+
const entry = created ? lock.workspaces[options.workspace] : void 0;
|
|
616
|
+
if (entry && entry.head === null && !Object.keys(entry.files).length) delete lock.workspaces[options.workspace];
|
|
617
|
+
throw error;
|
|
618
|
+
} finally {
|
|
619
|
+
await saveWorkspaceLock(context.rootDir, lock, touched);
|
|
620
|
+
}
|
|
621
|
+
return results;
|
|
622
|
+
}
|
|
623
|
+
async function takeTheirs(context, workspace, entry, paths, result) {
|
|
624
|
+
const folder = folderOf(context.rootDir, entry.dir);
|
|
625
|
+
const directories = [];
|
|
626
|
+
const local = await scan(context.rootDir, folder, directories);
|
|
627
|
+
validateCheckoutPaths([
|
|
628
|
+
...Object.keys(entry.files),
|
|
629
|
+
...local.keys(),
|
|
630
|
+
...paths
|
|
631
|
+
], directories);
|
|
632
|
+
for (const path of paths) {
|
|
633
|
+
if (ignoredPath(path)) throw workspaceErrorDiagnostics.WORKSPACE_CHECKOUT_PATH({
|
|
634
|
+
path,
|
|
635
|
+
problem: "excluded"
|
|
636
|
+
});
|
|
637
|
+
const shown = entry.head === null ? void 0 : await context.call("workspace.show", {
|
|
638
|
+
workspace,
|
|
639
|
+
target: entry.head,
|
|
640
|
+
path
|
|
641
|
+
}, entry.remote);
|
|
642
|
+
const file = shown?.ok ? shown.value.file : void 0;
|
|
643
|
+
if (shown && !shown.ok && shown.status !== 404) throw remoteFailure(shown);
|
|
644
|
+
if (file) {
|
|
645
|
+
const bytes = decode(file);
|
|
646
|
+
await put(context.rootDir, folder, path, bytes);
|
|
647
|
+
entry.files[path] = digestOf(bytes);
|
|
648
|
+
} else {
|
|
649
|
+
await remove(context.rootDir, folder, path);
|
|
650
|
+
delete entry.files[path];
|
|
651
|
+
}
|
|
652
|
+
entry.conflicts = entry.conflicts?.filter((candidate) => candidate !== path);
|
|
653
|
+
if (!entry.conflicts?.length) delete entry.conflicts;
|
|
654
|
+
result.files = [...result.files.filter((candidate) => candidate.path !== path), {
|
|
655
|
+
path,
|
|
656
|
+
action: file ? "updated" : "deleted",
|
|
657
|
+
note: "Took the remote version."
|
|
658
|
+
}];
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
/** Pulls, then commits the local changes of each checkout folder to its ref. Refuses while a conflict is open. */
|
|
662
|
+
async function pushWorkspaces(context, options = {}) {
|
|
663
|
+
const lock = await readWorkspaceLock(context.rootDir);
|
|
664
|
+
const results = [];
|
|
665
|
+
const touched = [];
|
|
666
|
+
try {
|
|
667
|
+
for (const name of selected(lock, options.workspace)) {
|
|
668
|
+
touched.push(name);
|
|
669
|
+
results.push(await pushEntry(context, name, lock.workspaces[name], options));
|
|
670
|
+
}
|
|
671
|
+
} finally {
|
|
672
|
+
await saveWorkspaceLock(context.rootDir, lock, touched);
|
|
673
|
+
}
|
|
674
|
+
return results;
|
|
675
|
+
}
|
|
676
|
+
async function pushEntry(context, workspace, entry, options) {
|
|
677
|
+
const { message, overrideLease } = options;
|
|
678
|
+
const folder = folderOf(context.rootDir, entry.dir);
|
|
679
|
+
for (let attempt = 0;; attempt++) {
|
|
680
|
+
const pull = await pullEntry(context, workspace, entry);
|
|
681
|
+
const files = await scan(context.rootDir, folder);
|
|
682
|
+
const local = localChanges(entry, files);
|
|
683
|
+
if (local.conflicted.length) throw workspaceErrorDiagnostics.WORKSPACE_CHECKOUT_CONFLICT({
|
|
684
|
+
conflicted: local.conflicted.join(", "),
|
|
685
|
+
workspace
|
|
686
|
+
});
|
|
687
|
+
const pushed = [
|
|
688
|
+
...local.added,
|
|
689
|
+
...local.modified,
|
|
690
|
+
...local.deleted
|
|
691
|
+
].sort();
|
|
692
|
+
if (!pushed.length) return {
|
|
693
|
+
workspace,
|
|
694
|
+
ref: entry.ref,
|
|
695
|
+
pushed,
|
|
696
|
+
pull
|
|
697
|
+
};
|
|
698
|
+
const putFiles = Object.fromEntries([...local.added, ...local.modified].map((path) => [path, encode(files.get(path))]));
|
|
699
|
+
const input = {
|
|
700
|
+
workspace,
|
|
701
|
+
ref: entry.ref,
|
|
702
|
+
ifHead: entry.head,
|
|
703
|
+
...Object.keys(putFiles).length ? { put: putFiles } : {},
|
|
704
|
+
...local.deleted.length ? { delete: local.deleted } : {},
|
|
705
|
+
...message ? { message } : {},
|
|
706
|
+
...overrideLease ? { lease: "override" } : {}
|
|
707
|
+
};
|
|
708
|
+
assertCommitSize(workspace, input, putFiles);
|
|
709
|
+
const called = await context.call("workspace.commit", input, entry.remote);
|
|
710
|
+
if (!called.ok) {
|
|
711
|
+
if (called.code === "WORKSPACE_CONFLICT" && attempt < 3) continue;
|
|
712
|
+
throw remoteFailure(called);
|
|
713
|
+
}
|
|
714
|
+
const { revision, normalized } = called.value;
|
|
715
|
+
for (const path of [...local.added, ...local.modified]) {
|
|
716
|
+
const submitted = files.get(path);
|
|
717
|
+
const committed = normalized && Object.hasOwn(normalized, path) ? decode(normalized[path]) : submitted;
|
|
718
|
+
entry.files[path] = digestOf(committed);
|
|
719
|
+
if (entry.files[path] !== digestOf(submitted)) {
|
|
720
|
+
const current = await readFile(await localPath(context.rootDir, folder, path)).catch((error) => {
|
|
721
|
+
if (error.code !== "ENOENT") throw error;
|
|
722
|
+
});
|
|
723
|
+
if (current && digestOf(current) === digestOf(submitted)) await put(context.rootDir, folder, path, committed);
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
for (const path of local.deleted) delete entry.files[path];
|
|
727
|
+
const result = {
|
|
728
|
+
workspace,
|
|
729
|
+
ref: entry.ref,
|
|
730
|
+
revision: revision.id,
|
|
731
|
+
pushed,
|
|
732
|
+
pull
|
|
733
|
+
};
|
|
734
|
+
if (entry.head === null && revision.parentId !== null) {
|
|
735
|
+
const after = await pullEntry(context, workspace, entry);
|
|
736
|
+
result.after = {
|
|
737
|
+
...after,
|
|
738
|
+
files: after.files.filter((file) => !pushed.includes(file.path))
|
|
739
|
+
};
|
|
740
|
+
} else entry.head = revision.id;
|
|
741
|
+
return result;
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
function formatBytes(bytes) {
|
|
745
|
+
if (bytes >= 1048576) return `${Number((bytes / 1024 / 1024).toFixed(1))} MiB`;
|
|
746
|
+
if (bytes >= 1024) return `${Number((bytes / 1024).toFixed(1))} KiB`;
|
|
747
|
+
return `${bytes} bytes`;
|
|
748
|
+
}
|
|
749
|
+
/**
|
|
750
|
+
* A push is one revision, so it cannot be split into more calls. Fails before the call when the request body, as
|
|
751
|
+
* `callOperation()` sends it, is over the request limit of `workspace.commit`, and names the largest files.
|
|
752
|
+
*/
|
|
753
|
+
function assertCommitSize(workspace, input, putFiles) {
|
|
754
|
+
const bytes = Buffer.byteLength(JSON.stringify({
|
|
755
|
+
m: "workspace.commit",
|
|
756
|
+
a: [input],
|
|
757
|
+
t: "q",
|
|
758
|
+
i: "0".repeat(21)
|
|
759
|
+
}));
|
|
760
|
+
if (bytes <= 4194304) return;
|
|
761
|
+
const largest = Object.entries(putFiles).map(([path, file]) => ({
|
|
762
|
+
path,
|
|
763
|
+
bytes: Buffer.byteLength(file.content)
|
|
764
|
+
})).sort((left, right) => right.bytes - left.bytes).slice(0, 3).map((file) => `${file.path} (${formatBytes(file.bytes)})`);
|
|
765
|
+
throw workspaceErrorDiagnostics.WORKSPACE_CHECKOUT_TOO_LARGE({
|
|
766
|
+
largest: largest.join(", "),
|
|
767
|
+
limit: formatBytes(workspaceCommitRequestBytes),
|
|
768
|
+
size: formatBytes(bytes),
|
|
769
|
+
workspace
|
|
770
|
+
});
|
|
771
|
+
}
|
|
772
|
+
/** The local changes of each checkout folder, and with `remote`, the remote changes since the last pull. */
|
|
773
|
+
async function workspaceStatus(context, options = {}) {
|
|
774
|
+
const lock = await readWorkspaceLock(context.rootDir);
|
|
775
|
+
const results = [];
|
|
776
|
+
for (const name of selected(lock, options.workspace)) {
|
|
777
|
+
const entry = lock.workspaces[name];
|
|
778
|
+
const files = await scan(context.rootDir, folderOf(context.rootDir, entry.dir));
|
|
779
|
+
const status = {
|
|
780
|
+
workspace: name,
|
|
781
|
+
dir: entry.dir,
|
|
782
|
+
ref: entry.ref,
|
|
783
|
+
...entry.remote ? { remote: entry.remote } : {},
|
|
784
|
+
head: entry.head,
|
|
785
|
+
local: localChanges(entry, files),
|
|
786
|
+
stale: staleDerivedFiles(files)
|
|
787
|
+
};
|
|
788
|
+
if (options.remote) {
|
|
789
|
+
const changes = await callOrThrow(context, entry.remote, "workspace.changes", {
|
|
790
|
+
workspace: name,
|
|
791
|
+
ref: entry.ref,
|
|
792
|
+
since: entry.head,
|
|
793
|
+
content: false
|
|
794
|
+
});
|
|
795
|
+
status.remoteHead = changes.head?.id ?? null;
|
|
796
|
+
status.remoteChanges = changes.files.filter((file) => !ignoredPath(file.path)).map((file) => ({
|
|
797
|
+
path: file.path,
|
|
798
|
+
change: file.deleted ? "deleted" : entry.files[file.path] === void 0 ? "added" : "changed"
|
|
799
|
+
}));
|
|
800
|
+
}
|
|
801
|
+
results.push(status);
|
|
802
|
+
}
|
|
803
|
+
return results;
|
|
804
|
+
}
|
|
805
|
+
/** The state of one checkout as text: its ref and head, local changes and conflicts, and remote changes when read. */
|
|
806
|
+
function formatWorkspaceStatus(status) {
|
|
807
|
+
const lines = [`${status.workspace}: ${status.dir}/ is ${status.ref} at ${status.head ?? "(empty)"}${status.remote ? ` on ${status.remote}` : ""}`];
|
|
808
|
+
const { local } = status;
|
|
809
|
+
const rows = [
|
|
810
|
+
...local.conflicted.map((path) => ` conflict ${path}`),
|
|
811
|
+
...local.added.filter((path) => !local.conflicted.includes(path)).map((path) => ` added ${path}`),
|
|
812
|
+
...local.modified.filter((path) => !local.conflicted.includes(path)).map((path) => ` modified ${path}`),
|
|
813
|
+
...local.deleted.map((path) => ` deleted ${path}`)
|
|
814
|
+
];
|
|
815
|
+
lines.push(rows.length ? "Local changes:" : "No local changes.", ...rows);
|
|
816
|
+
if (status.stale.length) lines.push("Stale derived files (their source changed):", ...status.stale.map((file) => ` ${file.reason.padEnd(9)} ${file.path} <- ${file.derivedFrom.path}`));
|
|
817
|
+
if (status.remoteChanges) {
|
|
818
|
+
if (!status.remoteChanges.length) lines.push("No remote changes.");
|
|
819
|
+
else lines.push(`Remote changes since ${status.head ?? "(empty)"} (run \`vitehub pull\`):`, ...status.remoteChanges.map((change) => ` ${change.change.padEnd(9)} ${change.path}`));
|
|
820
|
+
}
|
|
821
|
+
return `${lines.join("\n")}\n`;
|
|
822
|
+
}
|
|
823
|
+
/**
|
|
824
|
+
* The local state of every checkout of `vitehub.lock`, without asking the remote, or undefined when the project has no
|
|
825
|
+
* lock file. `vitehub status` shows it.
|
|
826
|
+
*/
|
|
827
|
+
async function localCheckoutStatus(rootDir) {
|
|
828
|
+
const lock = await readWorkspaceLock(rootDir);
|
|
829
|
+
if (!Object.keys(lock.workspaces).length) return void 0;
|
|
830
|
+
return await workspaceStatus({
|
|
831
|
+
call: async () => ({
|
|
832
|
+
ok: false,
|
|
833
|
+
message: "The local status does not call the app."
|
|
834
|
+
}),
|
|
835
|
+
rootDir
|
|
836
|
+
}, {});
|
|
837
|
+
}
|
|
838
|
+
/** Marks conflicts without markers, such as binary files, as resolved: the local file is what the next push sends. */
|
|
839
|
+
async function resolveWorkspaceConflicts(rootDir, workspace, paths) {
|
|
840
|
+
const lock = await readWorkspaceLock(rootDir);
|
|
841
|
+
const entry = lock.workspaces[workspace];
|
|
842
|
+
if (!entry) throw workspaceErrorDiagnostics.WORKSPACE_CHECKOUT_MISSING({ workspace });
|
|
843
|
+
const resolved = (entry.conflicts ?? []).filter((path) => !paths.length || paths.includes(path));
|
|
844
|
+
entry.conflicts = (entry.conflicts ?? []).filter((path) => !resolved.includes(path));
|
|
845
|
+
await saveWorkspaceLock(rootDir, lock, [workspace]);
|
|
846
|
+
return resolved;
|
|
847
|
+
}
|
|
848
|
+
//#endregion
|
|
849
|
+
export { assertNoSymlinks, checkoutFailure, conflictMarkerPatterns, folderOf, formatWorkspaceStatus, ignoredName, localCheckoutStatus, mergeText, pullWorkspaces, pushWorkspaces, resolveWorkspaceConflicts, workspaceLockFile, workspaceStatus };
|