@dsh-plugin/dsh-pack-plugin 0.0.0-stage → 0.0.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/LICENSE +21 -0
- package/README.md +178 -3
- package/cordis.patch.yml +9 -0
- package/icons/folder-zip-line.svg +1 -0
- package/lib/ball.js +597 -0
- package/lib/client.js +2934 -0
- package/lib/host.js +51745 -0
- package/lib/migrate-helper.js +35346 -0
- package/lib/progress-main.cjs +79 -0
- package/lib/progress-window.ps1 +114 -0
- package/lib/progress.html +126 -0
- package/lib/publish-to-github/SKILL.md +132 -0
- package/package.json +77 -4
- package/src/ball-entry.js +5 -0
- package/src/ball-host.js +99 -0
- package/src/ball-settings.js +352 -0
- package/src/ball.js +418 -0
- package/src/channel.js +12 -0
- package/src/client-plugin.js +58 -0
- package/src/client-rpc.js +14 -0
- package/src/client.js +5 -0
- package/src/core/discovery.js +192 -0
- package/src/core/dspack.js +93 -0
- package/src/core/extension-files.js +102 -0
- package/src/core/extension-install.js +295 -0
- package/src/core/extension-patch.js +369 -0
- package/src/core/extension-skills.js +164 -0
- package/src/core/extension-validate.js +127 -0
- package/src/core/extensions.js +207 -0
- package/src/core/home-store.js +32 -0
- package/src/core/host.js +149 -0
- package/src/core/index.js +59 -0
- package/src/core/inspect.js +162 -0
- package/src/core/install.js +775 -0
- package/src/core/managed-install.js +84 -0
- package/src/core/manifest.js +717 -0
- package/src/core/market.js +268 -0
- package/src/core/mcp-composition.js +189 -0
- package/src/core/mcp-install.js +112 -0
- package/src/core/mcp-transport.js +116 -0
- package/src/core/pack.js +371 -0
- package/src/core/plugin-metadata.js +355 -0
- package/src/core/registry.js +316 -0
- package/src/core/repo.js +339 -0
- package/src/core/scan.js +78 -0
- package/src/core/security.js +101 -0
- package/src/core/special.js +50 -0
- package/src/core/tar.js +103 -0
- package/src/core/update-config.js +234 -0
- package/src/core/update.js +792 -0
- package/src/core/vendored.js +715 -0
- package/src/core/workspace.js +95 -0
- package/src/endpoints.js +455 -0
- package/src/ensure-manager.js +186 -0
- package/src/host-node.js +625 -0
- package/src/host.js +17 -0
- package/src/index.d.ts +7 -0
- package/src/index.js +39 -0
- package/src/junction.js +142 -0
- package/src/migrate-helper.js +225 -0
- package/src/migrate.js +56 -0
- package/src/packaged.js +9 -0
- package/src/profiles.js +106 -0
- package/src/progress-main.cjs +79 -0
- package/src/progress-window.ps1 +114 -0
- package/src/progress.html +126 -0
- package/src/progress.js +132 -0
- package/src/rpc.js +157 -0
- package/src/runtime.js +43 -0
- package/src/section-gate.js +50 -0
- package/src/settings-nav-icon.js +188 -0
- package/src/settings.js +1611 -0
- package/src/skills/index.js +90 -0
- package/src/skills/publish-to-github/SKILL.md +132 -0
- package/src/tasks.js +145 -0
- package/src/v6-dialogs.js +312 -0
|
@@ -0,0 +1,792 @@
|
|
|
1
|
+
import { configBaseline, mergeConfig } from './update-config.js';
|
|
2
|
+
import { isExcluded } from './security.js';
|
|
3
|
+
import { isExactSemver } from './manifest.js';
|
|
4
|
+
|
|
5
|
+
const statePath = '.dsh-pack/updates';
|
|
6
|
+
const encoder = new TextEncoder();
|
|
7
|
+
const sha = /^[a-f0-9]{64}$/;
|
|
8
|
+
const own = (object, key) => Object.hasOwn(object, key);
|
|
9
|
+
|
|
10
|
+
function segment(name) {
|
|
11
|
+
if (typeof name !== 'string' || !name || /[\\/:*?"<>|\x00-\x1f]|[. ]$/.test(name) ||
|
|
12
|
+
/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|$)/i.test(name)) {
|
|
13
|
+
throw new Error('更新路径包含非法名称');
|
|
14
|
+
}
|
|
15
|
+
return name;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function relative(path) {
|
|
19
|
+
if (typeof path !== 'string') {
|
|
20
|
+
throw new Error('更新路径必须为相对路径');
|
|
21
|
+
}
|
|
22
|
+
for (const name of path.split('/')) {
|
|
23
|
+
segment(name);
|
|
24
|
+
}
|
|
25
|
+
return path;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function managed(path, profilesDir) {
|
|
29
|
+
const lower = path.toLowerCase();
|
|
30
|
+
const parts = lower.split('/');
|
|
31
|
+
if (parts.includes('.git') || parts.includes('node_modules') || parts.includes('attachments')) {
|
|
32
|
+
return false;
|
|
33
|
+
}
|
|
34
|
+
if (parts.includes('.dsh-pack') && !(parts[0] === '.dsh-pack' && ['skills', 'agent-presets'].includes(parts[1]))) {
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
if (parts[0] === profilesDir.toLowerCase() && ['vendor-blobs', '.dspack-sources'].includes(parts[2])) {
|
|
38
|
+
return parts.length < 4 || lower.endsWith('.tgz');
|
|
39
|
+
}
|
|
40
|
+
const slot = parts[0] === '.dsh-pack';
|
|
41
|
+
const offset = slot || parts[0] === profilesDir.toLowerCase() && parts.length >= 3 ? 2 : 0;
|
|
42
|
+
// 源文件扫描已约束导出范围;安装生成的配置、锁和下载资源也应参与更新。
|
|
43
|
+
const name = parts.at(-1);
|
|
44
|
+
const check = parts.slice(offset).join('/').replace(/\.(?:tgz|zip|dspack|tar\.gz)$/, '.artifact');
|
|
45
|
+
return !isExcluded(check) &&
|
|
46
|
+
!parts.includes('.credentials.yaml') && name !== '.dshpkcfg';
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function credentialPath(path) {
|
|
50
|
+
return /^(?:\.credentials\.ya?ml|credentials\.ya?ml)$/.test(path);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function typeAt(host, root, rel) {
|
|
54
|
+
let dir = root;
|
|
55
|
+
const parts = rel.split('/');
|
|
56
|
+
for (let i = 0; i < parts.length; i++) {
|
|
57
|
+
dir = host.joinPath(dir, segment(parts[i]));
|
|
58
|
+
const type = await host.packEntryType(dir);
|
|
59
|
+
if (!type) {
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
if (type === 'symlink' || i < parts.length - 1 && type !== 'dir') {
|
|
63
|
+
throw new Error('更新路径经过符号链接或非目录:' + rel);
|
|
64
|
+
}
|
|
65
|
+
if (i === parts.length - 1) {
|
|
66
|
+
return type;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async function requiredText(host, path) {
|
|
72
|
+
const value = await host.readTextFile(path);
|
|
73
|
+
if (value === null) {
|
|
74
|
+
throw new Error('无法读取更新文件:' + path);
|
|
75
|
+
}
|
|
76
|
+
return value;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function fileState(host, root, path) {
|
|
80
|
+
const type = await typeAt(host, root, path);
|
|
81
|
+
if (!type) {
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
if (type !== 'file') {
|
|
85
|
+
throw new Error('更新需要普通文件,已有路径类型不符:' + path);
|
|
86
|
+
}
|
|
87
|
+
const hash = await host.sha256File(host.joinPath(root, path));
|
|
88
|
+
if (!sha.test(hash)) {
|
|
89
|
+
throw new Error('无法计算文件摘要:' + path);
|
|
90
|
+
}
|
|
91
|
+
return hash;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function skillFile(path) {
|
|
95
|
+
return path.startsWith('skills/') || path.startsWith('.dsh-pack/skills/');
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function stageFiles(host, root, profilesDir, executablePaths = []) {
|
|
99
|
+
const result = Object.create(null);
|
|
100
|
+
const executable = new Set(executablePaths);
|
|
101
|
+
async function walk(dir, prefix) {
|
|
102
|
+
const entries = await host.readdir(dir);
|
|
103
|
+
if (!entries) {
|
|
104
|
+
throw new Error('无法读取安装暂存目录:' + dir);
|
|
105
|
+
}
|
|
106
|
+
const names = new Set();
|
|
107
|
+
for (const { name, type } of entries) {
|
|
108
|
+
const path = prefix + segment(name);
|
|
109
|
+
if (names.has(name.toLowerCase())) {
|
|
110
|
+
throw new Error('暂存文件存在大小写冲突:' + path);
|
|
111
|
+
}
|
|
112
|
+
names.add(name.toLowerCase());
|
|
113
|
+
if (path !== '.dsh-pack' && !managed(path, profilesDir)) {
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
const absolute = host.joinPath(dir, name);
|
|
117
|
+
if (type === 'dir') {
|
|
118
|
+
await walk(absolute, path + '/');
|
|
119
|
+
} else if (type === 'file') {
|
|
120
|
+
const hash = await host.sha256File(absolute);
|
|
121
|
+
let tree;
|
|
122
|
+
if (/\.(?:json|ya?ml)$/i.test(name) && name !== 'pnpm-lock.yaml') {
|
|
123
|
+
const size = (await host.stat(absolute))?.size;
|
|
124
|
+
if (size <= 4 * 1024 * 1024) {
|
|
125
|
+
tree = await configBaseline(host, path, await requiredText(host, absolute));
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
result[path] = tree ? { hash, tree } : { hash };
|
|
129
|
+
if (skillFile(path)) {
|
|
130
|
+
const mode = await host.packFileMode(absolute);
|
|
131
|
+
result[path].executable = executable.has(path) || (mode !== null && Boolean(mode & 0o111));
|
|
132
|
+
}
|
|
133
|
+
} else {
|
|
134
|
+
throw new Error('暂存目录包含符号链接或特殊文件:' + path);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
await walk(root, '');
|
|
139
|
+
return result;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function readState(host, home, key, profilesDir) {
|
|
143
|
+
const rel = statePath + '/baselines/' + key + '.json';
|
|
144
|
+
const type = await typeAt(host, home, rel);
|
|
145
|
+
if (!type) {
|
|
146
|
+
return null;
|
|
147
|
+
}
|
|
148
|
+
const state = JSON.parse(await requiredText(host, host.joinPath(home, rel)));
|
|
149
|
+
if (state.schema !== 1 || !state.files || typeof state.files !== 'object' || Array.isArray(state.files)) {
|
|
150
|
+
throw new Error('整合包更新基线格式无效');
|
|
151
|
+
}
|
|
152
|
+
for (const [path, entry] of Object.entries(state.files)) {
|
|
153
|
+
if (!managed(relative(path), segment(state.profilesDir || profilesDir)) || !sha.test(entry?.hash) ||
|
|
154
|
+
(entry.executable !== undefined && typeof entry.executable !== 'boolean')) {
|
|
155
|
+
throw new Error('整合包更新基线包含不受管的路径或无效摘要');
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
if (state.directories != null && (typeof state.directories !== 'object' || Array.isArray(state.directories) ||
|
|
159
|
+
Object.entries(state.directories).some(([path,owned]) => typeof owned !== 'boolean' ||
|
|
160
|
+
!managed(relative(path), segment(state.profilesDir || profilesDir))))) {
|
|
161
|
+
throw new Error('整合包更新基线包含无效的目录记录');
|
|
162
|
+
}
|
|
163
|
+
return state;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** 已安装技能沿用其原始目录,使桌面端与宿主插件交替更新时保持同一份数据。 */
|
|
167
|
+
export async function installedSkillLocation(host, home, profilesDir, profileName) {
|
|
168
|
+
const unit = segment(profilesDir) + '/' + segment(profileName);
|
|
169
|
+
const key = await host.sha256(encoder.encode('profile/' + unit.toLowerCase()));
|
|
170
|
+
const state = await readState(host, home, key, profilesDir);
|
|
171
|
+
const slot = '.dsh-pack/skills/' + profileName;
|
|
172
|
+
const files = Object.keys(state?.files || {});
|
|
173
|
+
if (files.some(file => file.startsWith(slot + '/'))) return slot;
|
|
174
|
+
if (files.some(file => file.startsWith('skills/'))) return 'skills';
|
|
175
|
+
if (await typeAt(host, home, slot) === 'dir') return slot;
|
|
176
|
+
return null;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
async function sharedPaths(host, home, key, profilesDir) {
|
|
180
|
+
const owners = new Set();
|
|
181
|
+
const rel = statePath + '/baselines';
|
|
182
|
+
if (!await typeAt(host, home, rel)) {
|
|
183
|
+
return owners;
|
|
184
|
+
}
|
|
185
|
+
const entries = await host.readdir(host.joinPath(home, rel));
|
|
186
|
+
if (!entries) {
|
|
187
|
+
throw new Error('无法读取共享文件的安装记录');
|
|
188
|
+
}
|
|
189
|
+
for (const entry of entries) {
|
|
190
|
+
if (!/^[0-9a-f]{64}\.json$/.test(entry.name) || entry.name === key + '.json') {
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
const state = await readState(host, home, entry.name.slice(0, -5), profilesDir);
|
|
194
|
+
for (const path of Object.keys(state.files)) {
|
|
195
|
+
owners.add(path.toLowerCase());
|
|
196
|
+
}
|
|
197
|
+
for (const [path,created] of Object.entries(state.directories ?? {})) {
|
|
198
|
+
owners.add(path.toLowerCase());
|
|
199
|
+
if (created) owners.add('directory:' + path.toLowerCase());
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
return owners;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function fields(manifest, profileName, profilesDir) {
|
|
206
|
+
const type = manifest.type ?? 'profile';
|
|
207
|
+
const names = type === 'profile' ? [segment(profileName || manifest.profileName || manifest.name)] :
|
|
208
|
+
Object.keys(manifest.profiles ?? {}).map(segment);
|
|
209
|
+
return { type, units: names.map(name => profilesDir + '/' + name) };
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
async function baselineKey(host, type, units) {
|
|
213
|
+
return host.sha256(encoder.encode(type === 'profile' ? 'profile/' + units[0].toLowerCase() : 'dshhome'));
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** 扩展配置在首次接管已有文件时需要保留原有配置项。 */
|
|
217
|
+
export async function packBaselineFiles(host, home, manifest, profileName, profilesDir) {
|
|
218
|
+
const {type,units} = fields(manifest,profileName,profilesDir);
|
|
219
|
+
return (await readState(host,home,await baselineKey(host,type,units),profilesDir))?.files;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// 同卷上别名的大小写由目录项决定。区分大小写的卷可以同时存放两个同名异形文件。
|
|
223
|
+
async function alignCase(host, opts, base, oldDirs, derived, next) {
|
|
224
|
+
const desired = new Map();
|
|
225
|
+
const spellings = paths => {
|
|
226
|
+
const result = new Set();
|
|
227
|
+
for (const path of paths) {
|
|
228
|
+
let prefix = '';
|
|
229
|
+
for (const part of path.split('/')) {
|
|
230
|
+
prefix = prefix ? prefix + '/' + part : part;
|
|
231
|
+
result.add(prefix);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
return result;
|
|
235
|
+
};
|
|
236
|
+
for (const path of spellings([...Object.keys(next), ...(opts.directories ?? [])])) {
|
|
237
|
+
desired.set(path.toLowerCase(), path);
|
|
238
|
+
}
|
|
239
|
+
const aliases = new Map(), renames = [];
|
|
240
|
+
const kept = (opts.preservePaths ?? []).map(path => relative(path).toLowerCase());
|
|
241
|
+
for (const path of spellings([...Object.keys(base), ...Object.keys(oldDirs), ...Object.keys(derived)])) {
|
|
242
|
+
const lower = path.toLowerCase(), target = desired.get(lower);
|
|
243
|
+
if (!target || target === path || kept.some(k => lower === k || lower.startsWith(k+'/'))) continue;
|
|
244
|
+
const parts = path.split('/'), to = target.split('/');
|
|
245
|
+
const name = parts.pop(), renamed = to.pop();
|
|
246
|
+
const parent = parts.join('/'), destParent = to.join('/');
|
|
247
|
+
if (parent !== destParent && aliases.get(parent) !== destParent) continue;
|
|
248
|
+
if (name !== renamed) {
|
|
249
|
+
const dir = host.joinPath(opts.home, parent);
|
|
250
|
+
const entries = (await host.readdir(dir) ?? []).filter(entry => entry.name.toLowerCase() === name.toLowerCase());
|
|
251
|
+
if (entries.length > 1) continue;
|
|
252
|
+
if (entries.length === 1) {
|
|
253
|
+
if (!await typeAt(host, opts.home, path) || !await typeAt(host, opts.home, target)) continue;
|
|
254
|
+
if (entries[0].name === name) {
|
|
255
|
+
const from = [...to, name].join('/');
|
|
256
|
+
renames.push({kind:'case', path:target, from});
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
aliases.set(path, target);
|
|
261
|
+
}
|
|
262
|
+
const align = record => Object.fromEntries(Object.entries(record).map(([path, value]) => [aliases.get(path) ?? path, value]));
|
|
263
|
+
return {base:align(base), oldDirs:align(oldDirs), derived:align(derived), renames};
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
async function moveCase(host, home, from, to, restoring = false) {
|
|
267
|
+
const parts = from.split('/'), name = parts.pop(), target = to.split('/').at(-1);
|
|
268
|
+
const entries = await host.readdir(host.joinPath(home, ...parts));
|
|
269
|
+
const found = entries?.filter(e => e.name.toLowerCase() === name.toLowerCase()) ?? [];
|
|
270
|
+
if (found.length !== 1) throw new Error('大小写重命名目标已发生变化:' + from);
|
|
271
|
+
if (restoring && found[0].name === target) return;
|
|
272
|
+
if (found[0].name !== name || found[0].type === 'symlink') throw new Error('大小写重命名源已发生变化:' + from);
|
|
273
|
+
await host.move(host.joinPath(home, from), host.joinPath(home, to));
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
async function compare(host, opts, key, next, otherOwners, base, derived, oldDirectories, profilesDir, renames) {
|
|
277
|
+
const changes = renames.map(({path, from}) => ({path, from, action:'rename', conflict:false}));
|
|
278
|
+
const conflicts = [];
|
|
279
|
+
const writes = [];
|
|
280
|
+
const checks = renames.map(({from,path}) => ['rename',from,path]);
|
|
281
|
+
const unmanaged = new Set();
|
|
282
|
+
const preserved = new Set();
|
|
283
|
+
const requested = opts.preservePaths ?? [];
|
|
284
|
+
if (!Array.isArray(requested)) {
|
|
285
|
+
throw new Error('保留路径必须是相对路径列表');
|
|
286
|
+
}
|
|
287
|
+
const prefixes = requested.map(path => relative(path).toLowerCase());
|
|
288
|
+
const choices = opts.resolutions ?? {};
|
|
289
|
+
for (const path of [...new Set([...Object.keys(base), ...Object.keys(next)])].sort()) {
|
|
290
|
+
const old = own(base, path) ? base[path] : null;
|
|
291
|
+
const incoming = own(next, path) ? next[path] : null;
|
|
292
|
+
if (prefixes.some(prefix => path.toLowerCase() === prefix || path.toLowerCase().startsWith(prefix + '/'))) {
|
|
293
|
+
checks.push([path, 'preserve', old?.hash ?? null]);
|
|
294
|
+
changes.push({ path, action: 'keep', preserved: true, conflict: false });
|
|
295
|
+
preserved.add(path);
|
|
296
|
+
continue;
|
|
297
|
+
}
|
|
298
|
+
const current = await fileState(host, opts.home, path);
|
|
299
|
+
const before = old?.hash ?? null;
|
|
300
|
+
const after = incoming?.hash ?? null;
|
|
301
|
+
const choice = own(choices, path) ? choices[path] : null;
|
|
302
|
+
checks.push([path, before, current, after]);
|
|
303
|
+
const trackMode = skillFile(path);
|
|
304
|
+
const mode = trackMode && current !== null ? await host.packFileMode(host.joinPath(opts.home, path)) : null;
|
|
305
|
+
const localExec = mode === null ? null : Boolean(mode & 0o111);
|
|
306
|
+
const oldExec = Boolean(old?.executable), nextExec = Boolean(incoming?.executable);
|
|
307
|
+
const desiredExec = localExec === null || !old || oldExec !== nextExec ? nextExec : localExec;
|
|
308
|
+
if (trackMode) checks.push([path,'executable',old?.executable,localExec,incoming?.executable]);
|
|
309
|
+
let merged;
|
|
310
|
+
let conflict = false;
|
|
311
|
+
let action;
|
|
312
|
+
const shared = otherOwners.has(path.toLowerCase());
|
|
313
|
+
const generated = current && own(derived, path) && derived[path] === current;
|
|
314
|
+
if (!old && current && !shared && !generated && choice !== 'upstream') {
|
|
315
|
+
unmanaged.add(path);
|
|
316
|
+
}
|
|
317
|
+
if (current === after) {
|
|
318
|
+
action = 'unchanged';
|
|
319
|
+
} else if (after === before || shared && !after) {
|
|
320
|
+
action = 'keep';
|
|
321
|
+
} else if ((current === before || generated) && !shared) {
|
|
322
|
+
action = after ? (current ? 'replace' : 'add') : 'remove';
|
|
323
|
+
} else {
|
|
324
|
+
if (before && current && after && old.tree && !shared) {
|
|
325
|
+
merged = await mergeConfig(host, path, old.tree,
|
|
326
|
+
await requiredText(host, host.joinPath(opts.home, path)),
|
|
327
|
+
await requiredText(host, host.joinPath(opts.stagedHome, path)), choice, choices);
|
|
328
|
+
}
|
|
329
|
+
conflict = !merged || merged.conflicts > 0;
|
|
330
|
+
if (conflict) {
|
|
331
|
+
conflicts.push({ path, base: before, local: current, upstream: after, shared, members: merged?.conflicts ?? 1, fields: merged?.fields });
|
|
332
|
+
}
|
|
333
|
+
action = merged ? 'merge' : choice === 'upstream' ? (after ? 'replace' : 'remove') : 'keep';
|
|
334
|
+
}
|
|
335
|
+
let exec = desiredExec;
|
|
336
|
+
const modeConflict = localExec !== null && ((!incoming && old && oldExec !== localExec && !shared) ||
|
|
337
|
+
(incoming && (!old || shared && oldExec !== nextExec) && localExec !== nextExec));
|
|
338
|
+
if (modeConflict) {
|
|
339
|
+
if (!conflict) conflicts.push({path, base:before, local:current, upstream:after, members:1});
|
|
340
|
+
conflict = true;
|
|
341
|
+
if (choice !== 'upstream') {
|
|
342
|
+
exec = localExec;
|
|
343
|
+
action = 'keep';
|
|
344
|
+
} else {
|
|
345
|
+
action = incoming ? 'replace' : 'remove';
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
const changeMode = incoming && localExec !== null && exec !== localExec && !unmanaged.has(path);
|
|
349
|
+
if (changeMode && (action === 'keep' || action === 'unchanged')) action = 'chmod';
|
|
350
|
+
if (action !== 'unchanged' || conflict) {
|
|
351
|
+
changes.push({ path, action, conflict });
|
|
352
|
+
}
|
|
353
|
+
if (['add', 'replace', 'remove', 'merge', 'chmod'].includes(action)) {
|
|
354
|
+
const data = merged ? encoder.encode(merged.text) : null;
|
|
355
|
+
const expected = action === 'chmod' ? current : data ? await host.sha256(data) : after;
|
|
356
|
+
if (current !== expected || changeMode) {
|
|
357
|
+
writes.push({ path, current, expected, data, localCopy:action === 'chmod',
|
|
358
|
+
...(trackMode ? {mode, executable:exec} : {}) });
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
const directories = Object.create(null);
|
|
363
|
+
const directoryOps = [];
|
|
364
|
+
if (!Array.isArray(opts.directories ?? [])) throw new Error('空目录声明必须为列表');
|
|
365
|
+
const selected = new Set(opts.directories ?? []);
|
|
366
|
+
for (const path of [...new Set([...Object.keys(oldDirectories), ...selected])].sort()) {
|
|
367
|
+
const lower = relative(path).toLowerCase();
|
|
368
|
+
const incoming = selected.has(path);
|
|
369
|
+
if (!managed(path, profilesDir) || (incoming && await typeAt(host, opts.stagedHome, path) !== 'dir')) {
|
|
370
|
+
throw new Error('空目录声明与暂存内容不符:' + path);
|
|
371
|
+
}
|
|
372
|
+
const had = own(oldDirectories, path);
|
|
373
|
+
const current = await typeAt(host, opts.home, path);
|
|
374
|
+
const created = had ? oldDirectories[path] : otherOwners.has('directory:' + lower);
|
|
375
|
+
const skip = prefixes.some(prefix => lower === prefix || lower.startsWith(prefix + '/'));
|
|
376
|
+
if (skip) {
|
|
377
|
+
if (had) directories[path] = created;
|
|
378
|
+
checks.push([path, 'directory', 'preserve', current]);
|
|
379
|
+
continue;
|
|
380
|
+
}
|
|
381
|
+
let action = 'keep';
|
|
382
|
+
let conflict = false;
|
|
383
|
+
let local = current;
|
|
384
|
+
if (incoming) {
|
|
385
|
+
directories[path] = created;
|
|
386
|
+
if (!current && !had) {
|
|
387
|
+
action = 'add';
|
|
388
|
+
directories[path] = true;
|
|
389
|
+
directoryOps.push({path, kind:'directory', existed:false});
|
|
390
|
+
} else if (current && current !== 'dir') {
|
|
391
|
+
if (current !== 'file') throw new Error('空目录目标已被特殊文件占用:' + path);
|
|
392
|
+
local = await fileState(host, opts.home, path);
|
|
393
|
+
const removed = writes.some(w => w.path === path && w.expected === null);
|
|
394
|
+
conflict = !removed;
|
|
395
|
+
if (conflict) conflicts.push({path, base:had ? 'directory' : null, local, upstream:'directory', members:1});
|
|
396
|
+
if (removed || choices[path] === 'upstream') {
|
|
397
|
+
action = 'replace';
|
|
398
|
+
directoryOps.push({path, kind:'directory', existed:false, ...(removed ? {} : {replaces:local})});
|
|
399
|
+
directories[path] = true;
|
|
400
|
+
}
|
|
401
|
+
} else if (current === 'dir') {
|
|
402
|
+
action = 'unchanged';
|
|
403
|
+
}
|
|
404
|
+
} else if (created && current === 'dir' && !otherOwners.has(lower)) {
|
|
405
|
+
const children = await host.readdir(host.joinPath(opts.home, path));
|
|
406
|
+
if (!children) throw new Error('无法读取待移除的目录:' + path);
|
|
407
|
+
local = children.length ? 'nonempty' : 'empty';
|
|
408
|
+
const prefix = lower + '/';
|
|
409
|
+
if (!children.length && ![...selected,...Object.keys(next)].some(p => p.toLowerCase().startsWith(prefix))) {
|
|
410
|
+
action = 'remove';
|
|
411
|
+
directoryOps.push({path, kind:'directory', existed:true});
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
checks.push([path, 'directory', had, created, local, incoming]);
|
|
415
|
+
if (action !== 'unchanged') changes.push({path, action, conflict, type:'directory'});
|
|
416
|
+
}
|
|
417
|
+
const token = await host.sha256(encoder.encode(JSON.stringify([key, opts.manifest.version, checks, [...otherOwners].sort()])));
|
|
418
|
+
return { changes, conflicts, writes, token, unmanaged, preserved, directories, directoryOps, renames };
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
async function restore(host, home, dir, journal) {
|
|
422
|
+
for (const [index, item] of [...journal.operations.entries()].reverse()) {
|
|
423
|
+
const path = relative(item.path);
|
|
424
|
+
if (!['file', 'modules', 'credential', 'directory', 'case'].includes(item.kind) ||
|
|
425
|
+
item.kind === 'case' && (!managed(path, journal.profilesDir) || relative(item.from).toLowerCase() !== path.toLowerCase() ||
|
|
426
|
+
item.from.split('/').slice(0,-1).join('/') !== path.split('/').slice(0,-1).join('/')) ||
|
|
427
|
+
item.kind === 'modules' && (path.split('/').length !== 3 || !path.endsWith('/node_modules')) ||
|
|
428
|
+
item.kind === 'credential' && !credentialPath(path) ||
|
|
429
|
+
(item.kind === 'file' || item.kind === 'directory') && !managed(path, journal.profilesDir)) {
|
|
430
|
+
throw new Error('更新恢复记录含非法目标');
|
|
431
|
+
}
|
|
432
|
+
if (journal.tracked && !await host.packEntryType(host.joinPath(dir, 'begun', String(index)))) {
|
|
433
|
+
continue;
|
|
434
|
+
}
|
|
435
|
+
const dest = host.joinPath(home, path);
|
|
436
|
+
const copy = host.joinPath(dir, 'old', String(index));
|
|
437
|
+
if (item.kind === 'case') {
|
|
438
|
+
await moveCase(host, home, path, item.from, true);
|
|
439
|
+
} else if (item.kind === 'directory') {
|
|
440
|
+
const current = await typeAt(host, home, path);
|
|
441
|
+
if (item.existed) {
|
|
442
|
+
if (!current) await host.mkdir(dest);
|
|
443
|
+
} else {
|
|
444
|
+
if (current === 'dir') await host.removePackDirIfEmpty(dest);
|
|
445
|
+
if (item.replaces) {
|
|
446
|
+
const remaining = await typeAt(host, home, path);
|
|
447
|
+
if (!remaining) await host.copyPackFile(copy, dest);
|
|
448
|
+
else if (remaining !== 'file' || await fileState(host, home, path) !== item.replaces) {
|
|
449
|
+
throw new Error('目录目标已被本机修改,原文件仍保存在恢复记录中:' + path);
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
} else if (item.kind === 'modules') {
|
|
454
|
+
if (item.existed && !await host.packEntryType(copy)) {
|
|
455
|
+
continue;
|
|
456
|
+
}
|
|
457
|
+
if (await typeAt(host, home, path)) {
|
|
458
|
+
await host.rm(dest, { recursive: true, force: true });
|
|
459
|
+
}
|
|
460
|
+
if (item.existed) {
|
|
461
|
+
await host.move(copy, dest);
|
|
462
|
+
}
|
|
463
|
+
} else if (item.existed) {
|
|
464
|
+
if (await typeAt(host, home, path) === 'dir') {
|
|
465
|
+
throw new Error('无法还原已变为目录的文件:' + path);
|
|
466
|
+
}
|
|
467
|
+
await host.copyPackFile(copy, dest, item.kind === 'credential');
|
|
468
|
+
} else if (await typeAt(host, home, path)) {
|
|
469
|
+
await host.rm(dest, { recursive: false, force: true });
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
async function removeCreatedDirs(host, home, directories) {
|
|
475
|
+
for (const dir of [...directories].sort((a,b) => b.length - a.length)) {
|
|
476
|
+
if (await typeAt(host, home, relative(dir)) === 'dir') {
|
|
477
|
+
await host.removePackDirIfEmpty(host.joinPath(home, dir));
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
async function recover(host, home, profilesDir, inspectOnly) {
|
|
483
|
+
const txn = statePath + '/transaction';
|
|
484
|
+
if (!await typeAt(host, home, txn)) {
|
|
485
|
+
return;
|
|
486
|
+
}
|
|
487
|
+
if (inspectOnly) {
|
|
488
|
+
throw new Error('上次更新尚未结束,请先恢复更新事务');
|
|
489
|
+
}
|
|
490
|
+
const dir = host.joinPath(home, txn);
|
|
491
|
+
if (await typeAt(host, home, txn + '/journal.json')) {
|
|
492
|
+
const journal = JSON.parse(await requiredText(host, host.joinPath(dir, 'journal.json')));
|
|
493
|
+
if (!sha.test(journal.key) || !journal.id || !Array.isArray(journal.operations)) {
|
|
494
|
+
throw new Error('更新恢复记录损坏');
|
|
495
|
+
}
|
|
496
|
+
segment(journal.profilesDir);
|
|
497
|
+
if ((await readState(host, home, journal.key, profilesDir))?.transaction !== journal.id) {
|
|
498
|
+
await restore(host, home, dir, journal);
|
|
499
|
+
await removeCreatedDirs(host, home, journal.directories ?? []);
|
|
500
|
+
}
|
|
501
|
+
await host.rm(host.joinPath(dir, 'journal.json'), { recursive: false, force: true });
|
|
502
|
+
}
|
|
503
|
+
await host.rm(dir, { recursive: true, force: true });
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/** 在持有同一安装目录锁时恢复被中断的依赖、配置文件和安装记录。 */
|
|
507
|
+
export async function recoverPackUpdate(host, home, profilesDir = 'profiles') {
|
|
508
|
+
if (!await typeAt(host, home, statePath + '/transaction')) return;
|
|
509
|
+
await typeAt(host, home, statePath + '/locks');
|
|
510
|
+
return host.withPackLock(host.joinPath(home, statePath), () => recover(host, home, segment(profilesDir), false));
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
async function dependenciesPresent(host, home, unit) {
|
|
514
|
+
const dir = host.joinPath(home, unit);
|
|
515
|
+
const raw = await host.readTextFile(host.joinPath(dir, 'package.json'));
|
|
516
|
+
if (raw === null) return false;
|
|
517
|
+
let pkg;
|
|
518
|
+
try { pkg = JSON.parse(raw); } catch { return false; }
|
|
519
|
+
if (!pkg || typeof pkg !== 'object' || Array.isArray(pkg)) return false;
|
|
520
|
+
const required = Object.entries(pkg.dependencies ?? {}).filter(([name]) => !own(pkg.optionalDependencies ?? {}, name));
|
|
521
|
+
if (!required.length) return true;
|
|
522
|
+
if (await typeAt(host, home, unit + '/node_modules') !== 'dir') return false;
|
|
523
|
+
for (const [name, spec] of required) {
|
|
524
|
+
if (!/^(?:@[a-z0-9._-]+\/)?[a-z0-9][a-z0-9._-]*$/i.test(name)) throw new Error('无效的依赖名称:' + name);
|
|
525
|
+
const file = await host.readTextFile(host.joinPath(dir, 'node_modules', ...name.split('/'), 'package.json'));
|
|
526
|
+
if (file === null) return false;
|
|
527
|
+
try {
|
|
528
|
+
const installed = JSON.parse(file);
|
|
529
|
+
if (!installed || typeof installed !== 'object' || (isExactSemver(spec) && installed.version !== spec.trim())) return false;
|
|
530
|
+
} catch {
|
|
531
|
+
return false;
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
return true;
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
async function planDependencies(host, opts, plan, units, state) {
|
|
538
|
+
const ready = new Set(state?.dependenciesReady ?? []), missing = [];
|
|
539
|
+
for (const unit of units) {
|
|
540
|
+
if (ready.has(unit) && !await dependenciesPresent(host, opts.home, unit)) {
|
|
541
|
+
ready.delete(unit);
|
|
542
|
+
missing.push(unit);
|
|
543
|
+
}
|
|
544
|
+
if (plan.writes.some(w => w.path.startsWith(unit + '/') &&
|
|
545
|
+
/^(?:package\.json|pnpm-(lock|workspace)\.yaml|(?:vendor-blobs|\.dspack-sources)\/.+\.tgz)$/.test(w.path.slice(unit.length + 1)))) {
|
|
546
|
+
ready.delete(unit);
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
const deps = opts.finalize ? units.filter(unit => !ready.has(unit)) : [];
|
|
550
|
+
for (const unit of deps) plan.changes.push({path:unit + '/node_modules', action:'install', conflict:false});
|
|
551
|
+
if (missing.length) plan.token = await host.sha256(encoder.encode(JSON.stringify([plan.token,missing])));
|
|
552
|
+
return {ready, deps};
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
async function commit(host, opts, key, next, plan, units, profilesDir, {base, derived}, {ready, deps}) {
|
|
556
|
+
const home = opts.home;
|
|
557
|
+
const dir = host.joinPath(home, statePath, 'transaction');
|
|
558
|
+
const id = globalThis.crypto.randomUUID();
|
|
559
|
+
const operations = [...plan.renames, ...plan.writes.map(w => ({ path: w.path, existed: w.current !== null, kind: 'file' }))];
|
|
560
|
+
operations.push(...plan.directoryOps);
|
|
561
|
+
for (const unit of deps) {
|
|
562
|
+
const modules = unit + '/node_modules';
|
|
563
|
+
const type = await typeAt(host, home, modules);
|
|
564
|
+
if (type && type !== 'dir') {
|
|
565
|
+
throw new Error('依赖目录不是普通目录:' + modules);
|
|
566
|
+
}
|
|
567
|
+
operations.push({ path: modules, existed: !!type, kind: 'modules' });
|
|
568
|
+
const lock = unit + '/pnpm-lock.yaml';
|
|
569
|
+
if (!operations.some(op => op.path === lock)) {
|
|
570
|
+
operations.push({ path: lock, existed: !!await typeAt(host, home, lock), kind: 'file' });
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
if (opts.commitCredentials) {
|
|
574
|
+
for (const unit of units) {
|
|
575
|
+
const patch = unit + '/cordis.patch.yml';
|
|
576
|
+
if (!operations.some(op => op.path === patch)) {
|
|
577
|
+
operations.push({ path: patch, existed: !!await typeAt(host, home, patch), kind: 'file' });
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
for (const path of new Set(opts.credentialPaths ?? ['.credentials.yaml'])) {
|
|
581
|
+
if (!credentialPath(path)) {
|
|
582
|
+
throw new Error('凭据事务路径无效');
|
|
583
|
+
}
|
|
584
|
+
operations.push({ path, existed: !!await typeAt(host, home, path), kind: 'credential' });
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
const directories = new Set();
|
|
588
|
+
for (const {path} of operations) {
|
|
589
|
+
const parts = path.split('/');
|
|
590
|
+
for (let i = 1; i < parts.length; i++) {
|
|
591
|
+
const dir = parts.slice(0, i).join('/');
|
|
592
|
+
if (!directories.has(dir) && !await typeAt(host, home, dir)) {
|
|
593
|
+
directories.add(dir);
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
const journal = { id, key, profilesDir, operations, directories: [...directories], tracked: true };
|
|
598
|
+
const mark = index => host.writeTextFile(host.joinPath(dir, 'begun', String(index)), '');
|
|
599
|
+
await host.mkdir(dir);
|
|
600
|
+
try {
|
|
601
|
+
for (const [index, item] of operations.entries()) {
|
|
602
|
+
if (item.replaces || (item.existed && item.kind !== 'modules' && item.kind !== 'directory')) {
|
|
603
|
+
await host.copyPackFile(host.joinPath(home, item.path), host.joinPath(dir, 'old', String(index)), item.kind === 'credential');
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
await host.writeTextFile(host.joinPath(dir, 'journal.tmp'), JSON.stringify(journal));
|
|
607
|
+
await host.move(host.joinPath(dir, 'journal.tmp'), host.joinPath(dir, 'journal.json'));
|
|
608
|
+
for (const [index, item] of operations.entries()) {
|
|
609
|
+
if (item.kind === 'case') {
|
|
610
|
+
await mark(index);
|
|
611
|
+
await moveCase(host, home, item.from, item.path);
|
|
612
|
+
} else if (item.kind === 'modules' && item.existed) {
|
|
613
|
+
await mark(index);
|
|
614
|
+
await host.move(host.joinPath(home, item.path), host.joinPath(dir, 'old', String(index)));
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
for (const [offset, write] of plan.writes.entries()) {
|
|
618
|
+
const index = plan.renames.length + offset;
|
|
619
|
+
if (await fileState(host, home, write.path) !== write.current ||
|
|
620
|
+
(write.mode != null && await host.packFileMode(host.joinPath(home, write.path)) !== write.mode)) {
|
|
621
|
+
throw new Error('文件在预览后发生变化:' + write.path);
|
|
622
|
+
}
|
|
623
|
+
const dest = host.joinPath(home, write.path);
|
|
624
|
+
if (write.expected === null) {
|
|
625
|
+
await mark(index);
|
|
626
|
+
await host.rm(dest, { recursive: false, force: true });
|
|
627
|
+
} else {
|
|
628
|
+
const temp = host.joinPath(dir, 'new', String(index));
|
|
629
|
+
if (write.data) {
|
|
630
|
+
await host.writeFile(temp, write.data);
|
|
631
|
+
} else {
|
|
632
|
+
await host.copyPackFile(host.joinPath(write.localCopy ? home : opts.stagedHome, write.path), temp);
|
|
633
|
+
}
|
|
634
|
+
if (write.executable !== undefined) {
|
|
635
|
+
const sourceMode = write.mode ?? await host.packFileMode(temp);
|
|
636
|
+
if (sourceMode !== null) {
|
|
637
|
+
const bits = write.executable ? (sourceMode & 0o111) || (0o100 | ((sourceMode & 0o044) >> 2)) : 0;
|
|
638
|
+
await host.chmodPackFile(temp, (sourceMode & 0o666) | bits);
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
if (await host.sha256File(temp) !== write.expected) {
|
|
642
|
+
throw new Error('暂存内容在预览后发生变化:' + write.path);
|
|
643
|
+
}
|
|
644
|
+
await mark(index);
|
|
645
|
+
await host.move(temp, dest);
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
for (const [index,item] of operations.entries()) {
|
|
649
|
+
if (item.kind !== 'directory') continue;
|
|
650
|
+
const dest = host.joinPath(home, item.path);
|
|
651
|
+
const current = await typeAt(host, home, item.path);
|
|
652
|
+
if (item.existed) {
|
|
653
|
+
if (current !== 'dir') throw new Error('目录在预览后发生变化:' + item.path);
|
|
654
|
+
await mark(index);
|
|
655
|
+
await host.removePackDirIfEmpty(dest);
|
|
656
|
+
} else {
|
|
657
|
+
if (item.replaces ? await fileState(host, home, item.path) !== item.replaces : !!current) {
|
|
658
|
+
throw new Error('目录目标在预览后发生变化:' + item.path);
|
|
659
|
+
}
|
|
660
|
+
await mark(index);
|
|
661
|
+
if (item.replaces) await host.rm(dest, {recursive:false, force:false});
|
|
662
|
+
await host.mkdir(dest);
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
if (opts.validateProfiles) await opts.validateProfiles(units.map(unit => host.joinPath(home, unit)));
|
|
666
|
+
if (deps.length) {
|
|
667
|
+
for (const [index,item] of operations.entries()) {
|
|
668
|
+
if (item.kind === 'modules' || deps.some(unit => item.path === unit + '/pnpm-lock.yaml')) {
|
|
669
|
+
await mark(index);
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
await opts.finalize({ affectedProfiles: deps.map(unit => host.joinPath(home, unit)) });
|
|
673
|
+
for (const unit of deps) {
|
|
674
|
+
ready.add(unit);
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
if (opts.verifyMcp) await opts.verifyMcp();
|
|
678
|
+
if (opts.commitCredentials) {
|
|
679
|
+
for (const [index,item] of operations.entries()) {
|
|
680
|
+
if (item.kind === 'credential' || units.some(unit => item.path === unit + '/cordis.patch.yml')) {
|
|
681
|
+
await mark(index);
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
await opts.commitCredentials();
|
|
685
|
+
}
|
|
686
|
+
const files = Object.assign(Object.create(null), Object.fromEntries(Object.entries(next).filter(([path]) => !plan.unmanaged.has(path) && !plan.preserved.has(path))));
|
|
687
|
+
for (const path of plan.preserved) {
|
|
688
|
+
if (own(base, path)) {
|
|
689
|
+
files[path] = base[path];
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
const derivedLocks = { ...derived };
|
|
693
|
+
for (const unit of deps) {
|
|
694
|
+
const lock = unit + '/pnpm-lock.yaml';
|
|
695
|
+
const hash = await fileState(host, home, lock);
|
|
696
|
+
const operation = operations.find(item => item.path === lock);
|
|
697
|
+
const owned = own(files, lock) || own(base, lock) || own(derivedLocks, lock) || !operation?.existed;
|
|
698
|
+
if (hash && owned && !plan.unmanaged.has(lock)) {
|
|
699
|
+
derivedLocks[lock] = hash;
|
|
700
|
+
} else {
|
|
701
|
+
delete derivedLocks[lock];
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
const state = { schema: 1, profilesDir, name: opts.manifest.name, version: opts.manifest.version,
|
|
705
|
+
transaction: id, files, directories: plan.directories, derivedLocks, dependenciesReady: units.filter(unit => ready.has(unit)) };
|
|
706
|
+
await host.writeTextFile(host.joinPath(dir, 'baseline.tmp'), JSON.stringify(state));
|
|
707
|
+
await host.move(host.joinPath(dir, 'baseline.tmp'), host.joinPath(home, statePath, 'baselines', key + '.json'));
|
|
708
|
+
} catch (error) {
|
|
709
|
+
try {
|
|
710
|
+
await recover(host, home, profilesDir, false);
|
|
711
|
+
} catch (recovery) {
|
|
712
|
+
throw new AggregateError([error, recovery], '更新失败,恢复未完成:' + recovery.message);
|
|
713
|
+
}
|
|
714
|
+
throw error;
|
|
715
|
+
}
|
|
716
|
+
await recover(host, home, profilesDir, false);
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
/** 将暂存 HOME 的受管文件与当前安装和上次发布内容三方比较,预览或以事务应用所选变更。 */
|
|
720
|
+
export async function syncPackTree(host, opts) {
|
|
721
|
+
const { home, stagedHome, manifest, previous } = opts;
|
|
722
|
+
const profilesDir = segment(opts.profilesDir || 'profiles');
|
|
723
|
+
if (host.resolvePath(home) === host.resolvePath(stagedHome) || !['install', 'update'].includes(opts.mode)) {
|
|
724
|
+
throw new Error('更新需要独立的暂存目录和明确的安装模式');
|
|
725
|
+
}
|
|
726
|
+
const { type, units } = fields(manifest, opts.profileName, profilesDir);
|
|
727
|
+
const key = await baselineKey(host, type, units);
|
|
728
|
+
const next = await stageFiles(host, stagedHome, profilesDir, opts.executablePaths);
|
|
729
|
+
await typeAt(host, home, statePath + '/locks');
|
|
730
|
+
async function run() {
|
|
731
|
+
await recover(host, home, profilesDir, opts.dryRun);
|
|
732
|
+
const state = await readState(host, home, key, profilesDir);
|
|
733
|
+
if (state && opts.mode === 'install' && !opts.dryRun) {
|
|
734
|
+
throw new Error('目标已安装整合包,请重新预览并选择更新');
|
|
735
|
+
}
|
|
736
|
+
if (state && state.name !== manifest.name) {
|
|
737
|
+
throw new Error('目标已绑定其他整合包:' + state.name);
|
|
738
|
+
}
|
|
739
|
+
let base = state?.files;
|
|
740
|
+
if (!base && previous) {
|
|
741
|
+
if (!sha.test(previous.sha256) || previous.sha256 !== previous.expectedSha256 ||
|
|
742
|
+
previous.manifest?.name !== manifest.name || (previous.manifest.type ?? 'profile') !== type) {
|
|
743
|
+
throw new Error('旧包的身份或 SHA-256 校验不匹配');
|
|
744
|
+
}
|
|
745
|
+
base = await stageFiles(host, previous.stagedHome, profilesDir);
|
|
746
|
+
}
|
|
747
|
+
const owners = await sharedPaths(host, home, key, profilesDir);
|
|
748
|
+
const aligned = await alignCase(host, opts, base ?? {}, state?.directories ?? {}, state?.derivedLocks ?? {}, next);
|
|
749
|
+
const plan = await compare(host, opts, key, next, owners, aligned.base, aligned.derived, aligned.oldDirs, profilesDir, aligned.renames);
|
|
750
|
+
const dependencies = await planDependencies(host, opts, plan, units, state);
|
|
751
|
+
const choices = opts.resolutions ?? {};
|
|
752
|
+
if (opts.previewToken && opts.previewToken !== plan.token) {
|
|
753
|
+
throw new Error('安装内容或本地文件已变化,请重新预览');
|
|
754
|
+
}
|
|
755
|
+
for (const [path, choice] of Object.entries(choices)) {
|
|
756
|
+
if (choice === 'upstream' && !opts.previewToken || !plan.conflicts.some(c => c.path === path || c.fields?.some(f => f.key === path)) || !['local', 'upstream'].includes(choice)) {
|
|
757
|
+
throw new Error('冲突选择无效或缺少对应的预览');
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
const result = {
|
|
761
|
+
applied: false, changes: plan.changes, conflicts: plan.conflicts, previewToken: plan.token,
|
|
762
|
+
previousVersion: state?.version ?? previous?.manifest?.version ?? null, version: manifest.version,
|
|
763
|
+
unknownBase: !base && opts.mode === 'update',
|
|
764
|
+
};
|
|
765
|
+
if (opts.dryRun) {
|
|
766
|
+
return result;
|
|
767
|
+
}
|
|
768
|
+
await commit(host, opts, key, next, plan, units, profilesDir, aligned, dependencies);
|
|
769
|
+
return { ...result, applied: true };
|
|
770
|
+
}
|
|
771
|
+
if (opts.dryRun) {
|
|
772
|
+
if (opts.recoverInterrupted) await recoverPackUpdate(host, home, profilesDir);
|
|
773
|
+
return run();
|
|
774
|
+
}
|
|
775
|
+
const homeExisted = await host.packEntryType(home);
|
|
776
|
+
const controlDirs = [statePath + '/locks', statePath, '.dsh-pack'];
|
|
777
|
+
const created = [];
|
|
778
|
+
for (const rel of controlDirs) {
|
|
779
|
+
if (!await typeAt(host, home, rel)) {
|
|
780
|
+
created.push(rel);
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
try {
|
|
784
|
+
return await host.withPackLock(host.joinPath(home, statePath), run);
|
|
785
|
+
} catch (error) {
|
|
786
|
+
await removeCreatedDirs(host, home, created);
|
|
787
|
+
if (!homeExisted) {
|
|
788
|
+
await host.removePackDirIfEmpty(home);
|
|
789
|
+
}
|
|
790
|
+
throw error;
|
|
791
|
+
}
|
|
792
|
+
}
|