nemu-cli 1.4.0 → 1.6.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/CHANGELOG.md +54 -0
- package/LICENSE +0 -0
- package/README.md +38 -0
- package/dist/args.js +9 -1
- package/dist/auth/token.js +1 -1
- package/dist/commands/key.js +95 -0
- package/dist/commands/login.js +3 -0
- package/dist/commands/mcp.js +2 -2
- package/dist/commands/sync.js +197 -0
- package/dist/commands/vault.js +189 -0
- package/dist/commands/whoami.js +19 -0
- package/dist/config.js +5 -0
- package/dist/context/api.js +9 -9
- package/dist/device.js +1 -1
- package/dist/http.js +36 -19
- package/dist/index.js +14 -0
- package/dist/ui.js +35 -0
- package/dist/vault/api.js +204 -0
- package/dist/vault/connect.js +41 -0
- package/dist/vault/engine.js +634 -0
- package/dist/vault/files.js +187 -0
- package/dist/vault/ignore.js +100 -0
- package/dist/vault/lock.js +85 -0
- package/dist/vault/merge.js +236 -0
- package/dist/vault/paths.js +99 -0
- package/dist/vault/plan.js +279 -0
- package/dist/vault/state.js +112 -0
- package/dist/vault/watch.js +101 -0
- package/dist/version.js +1 -1
- package/package.json +4 -2
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
+
import { lstat, mkdir, readdir, readFile, realpath, rename, rm, rmdir, unlink, writeFile } from "node:fs/promises";
|
|
3
|
+
import { basename, dirname, join, sep } from "node:path";
|
|
4
|
+
import { check_path, normalize_path, path_key } from "./paths.js";
|
|
5
|
+
import { is_ignored } from "./ignore.js";
|
|
6
|
+
export function hash_of(content) {
|
|
7
|
+
return createHash("sha256").update(content).digest("hex");
|
|
8
|
+
}
|
|
9
|
+
export function disk_path(root, relative) {
|
|
10
|
+
return join(root, ...relative.split("/"));
|
|
11
|
+
}
|
|
12
|
+
function megabytes(bytes) {
|
|
13
|
+
return `${(bytes / 1024 / 1024).toFixed(bytes < 10 * 1024 * 1024 ? 1 : 0)} MB`;
|
|
14
|
+
}
|
|
15
|
+
export async function scan_folder(root, ignore, max_file_bytes, preferred = () => undefined) {
|
|
16
|
+
const files = new Map();
|
|
17
|
+
const skipped = [];
|
|
18
|
+
const clashes = new Map();
|
|
19
|
+
const walk = async (relative_folder) => {
|
|
20
|
+
const absolute = relative_folder === "" ? root : disk_path(root, relative_folder);
|
|
21
|
+
const entries = await readdir(absolute, { withFileTypes: true }).catch(() => []);
|
|
22
|
+
entries.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));
|
|
23
|
+
for (const entry of entries) {
|
|
24
|
+
const disk = relative_folder === "" ? entry.name : `${relative_folder}/${entry.name}`;
|
|
25
|
+
const path = normalize_path(disk);
|
|
26
|
+
if (entry.isSymbolicLink()) {
|
|
27
|
+
if (!is_ignored(path, ignore))
|
|
28
|
+
skipped.push({ path, reason: "a symbolic link, never followed" });
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
if (entry.isDirectory()) {
|
|
32
|
+
if (relative_folder === "" && entry.name === ".nemu")
|
|
33
|
+
continue;
|
|
34
|
+
if (is_ignored(path, ignore, true))
|
|
35
|
+
continue;
|
|
36
|
+
await walk(disk);
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
if (!entry.isFile())
|
|
40
|
+
continue;
|
|
41
|
+
if (is_ignored(path, ignore))
|
|
42
|
+
continue;
|
|
43
|
+
const checked = check_path(path);
|
|
44
|
+
if (!checked.ok) {
|
|
45
|
+
skipped.push({ path, reason: `not synced: ${checked.error}` });
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
const info = await lstat(disk_path(root, disk)).catch(() => null);
|
|
49
|
+
if (info === null || !info.isFile())
|
|
50
|
+
continue;
|
|
51
|
+
if (info.size > max_file_bytes) {
|
|
52
|
+
skipped.push({
|
|
53
|
+
path,
|
|
54
|
+
reason: `${megabytes(info.size)}, above the ${megabytes(max_file_bytes)} your plan allows per file`,
|
|
55
|
+
});
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
const content = await readFile(disk_path(root, disk)).catch(() => null);
|
|
59
|
+
if (content === null)
|
|
60
|
+
continue;
|
|
61
|
+
const local = { path, disk, hash: hash_of(content), size: content.length };
|
|
62
|
+
const key = path_key(path);
|
|
63
|
+
const group = clashes.get(key) ?? [];
|
|
64
|
+
group.push(local);
|
|
65
|
+
clashes.set(key, group);
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
await walk("");
|
|
69
|
+
for (const [key, group] of clashes) {
|
|
70
|
+
if (group.length === 1) {
|
|
71
|
+
files.set(key, group[0]);
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
const wanted = preferred(key);
|
|
75
|
+
const keep = group.find((entry) => entry.path === wanted) ?? group[0];
|
|
76
|
+
files.set(key, keep);
|
|
77
|
+
for (const entry of group) {
|
|
78
|
+
if (entry === keep)
|
|
79
|
+
continue;
|
|
80
|
+
skipped.push({
|
|
81
|
+
path: entry.path,
|
|
82
|
+
reason: `differs from "${keep.path}" only by case, which macOS and Windows cannot hold side by side`,
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return { files, skipped };
|
|
87
|
+
}
|
|
88
|
+
export async function read_hash(root, disk) {
|
|
89
|
+
const content = await readFile(disk_path(root, disk)).catch(() => null);
|
|
90
|
+
return content === null ? null : hash_of(content);
|
|
91
|
+
}
|
|
92
|
+
export async function read_if(root, disk, expected_hash) {
|
|
93
|
+
const content = await readFile(disk_path(root, disk)).catch(() => null);
|
|
94
|
+
if (content === null || hash_of(content) !== expected_hash)
|
|
95
|
+
return null;
|
|
96
|
+
return content;
|
|
97
|
+
}
|
|
98
|
+
async function nearest_real(path) {
|
|
99
|
+
let current = path;
|
|
100
|
+
while (true) {
|
|
101
|
+
const resolved = await realpath(current).catch(() => null);
|
|
102
|
+
if (resolved !== null)
|
|
103
|
+
return resolved;
|
|
104
|
+
const parent = dirname(current);
|
|
105
|
+
if (parent === current)
|
|
106
|
+
return null;
|
|
107
|
+
current = parent;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
export async function stays_inside(root, target) {
|
|
111
|
+
const [real_root, real_folder] = await Promise.all([realpath(root).catch(() => null), nearest_real(dirname(target))]);
|
|
112
|
+
if (real_root === null || real_folder === null)
|
|
113
|
+
return false;
|
|
114
|
+
return real_folder === real_root || real_folder.startsWith(real_root.endsWith(sep) ? real_root : `${real_root}${sep}`);
|
|
115
|
+
}
|
|
116
|
+
export async function write_atomic_file(root, relative, content, expected) {
|
|
117
|
+
const target = disk_path(root, relative);
|
|
118
|
+
if (!(await stays_inside(root, target)))
|
|
119
|
+
return false;
|
|
120
|
+
if (expected === null) {
|
|
121
|
+
const exists = await lstat(target).then(() => true, () => false);
|
|
122
|
+
if (exists)
|
|
123
|
+
return false;
|
|
124
|
+
}
|
|
125
|
+
else if ((await read_hash(root, expected.disk)) !== expected.hash) {
|
|
126
|
+
return false;
|
|
127
|
+
}
|
|
128
|
+
await mkdir(dirname(target), { recursive: true });
|
|
129
|
+
const temporary = join(dirname(target), `.${basename(target)}.${randomBytes(4).toString("hex")}.nemu.tmp`);
|
|
130
|
+
try {
|
|
131
|
+
await writeFile(temporary, content);
|
|
132
|
+
if (expected !== null && expected.disk !== relative) {
|
|
133
|
+
await unlink(disk_path(root, expected.disk)).catch(() => undefined);
|
|
134
|
+
}
|
|
135
|
+
await rename(temporary, target);
|
|
136
|
+
}
|
|
137
|
+
catch (error) {
|
|
138
|
+
await rm(temporary, { force: true });
|
|
139
|
+
throw error;
|
|
140
|
+
}
|
|
141
|
+
return true;
|
|
142
|
+
}
|
|
143
|
+
export async function rename_local(root, from, to) {
|
|
144
|
+
const source = disk_path(root, from);
|
|
145
|
+
const target = disk_path(root, to);
|
|
146
|
+
if (!(await stays_inside(root, source)) || !(await stays_inside(root, target)))
|
|
147
|
+
return false;
|
|
148
|
+
const same_key = path_key(normalize_path(from)) === path_key(normalize_path(to));
|
|
149
|
+
if (!same_key) {
|
|
150
|
+
const occupied = await lstat(target).then(() => true, () => false);
|
|
151
|
+
if (occupied)
|
|
152
|
+
return false;
|
|
153
|
+
}
|
|
154
|
+
await mkdir(dirname(target), { recursive: true });
|
|
155
|
+
try {
|
|
156
|
+
await rename(source, target);
|
|
157
|
+
}
|
|
158
|
+
catch {
|
|
159
|
+
return false;
|
|
160
|
+
}
|
|
161
|
+
await prune_folders(root, dirname(from));
|
|
162
|
+
return true;
|
|
163
|
+
}
|
|
164
|
+
export async function delete_local(root, disk, expected_hash) {
|
|
165
|
+
if (!(await stays_inside(root, disk_path(root, disk))))
|
|
166
|
+
return false;
|
|
167
|
+
if ((await read_hash(root, disk)) !== expected_hash)
|
|
168
|
+
return false;
|
|
169
|
+
await unlink(disk_path(root, disk));
|
|
170
|
+
await prune_folders(root, dirname(disk));
|
|
171
|
+
return true;
|
|
172
|
+
}
|
|
173
|
+
async function prune_folders(root, relative_folder) {
|
|
174
|
+
let current = relative_folder.split("\\").join("/");
|
|
175
|
+
while (current !== "." && current !== "" && current !== "/") {
|
|
176
|
+
try {
|
|
177
|
+
await rmdir(disk_path(root, current));
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
const parent = dirname(current);
|
|
183
|
+
if (parent === current)
|
|
184
|
+
return;
|
|
185
|
+
current = parent;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
const IGNORED_SEGMENTS = new Set([
|
|
2
|
+
".git",
|
|
3
|
+
".trash",
|
|
4
|
+
".nemu",
|
|
5
|
+
"node_modules",
|
|
6
|
+
".DS_Store",
|
|
7
|
+
"Thumbs.db",
|
|
8
|
+
"desktop.ini",
|
|
9
|
+
".claude",
|
|
10
|
+
".codex",
|
|
11
|
+
".cursor",
|
|
12
|
+
".vscode",
|
|
13
|
+
".idea",
|
|
14
|
+
".husky",
|
|
15
|
+
]);
|
|
16
|
+
const EXECUTABLE_FOLDERS = [".github/workflows", ".git/hooks"];
|
|
17
|
+
function glob_source(glob) {
|
|
18
|
+
let source = "";
|
|
19
|
+
for (let index = 0; index < glob.length; index += 1) {
|
|
20
|
+
const character = glob[index];
|
|
21
|
+
if (character === "*") {
|
|
22
|
+
if (glob[index + 1] === "*") {
|
|
23
|
+
const slash = glob[index + 2] === "/";
|
|
24
|
+
source += slash ? "(?:.*/)?" : ".*";
|
|
25
|
+
index += slash ? 2 : 1;
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
source += "[^/]*";
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
if (character === "?") {
|
|
32
|
+
source += "[^/]";
|
|
33
|
+
continue;
|
|
34
|
+
}
|
|
35
|
+
source += character.replace(/[.+^${}()|[\]\\]/g, "\\$&");
|
|
36
|
+
}
|
|
37
|
+
return source;
|
|
38
|
+
}
|
|
39
|
+
export function parse_ignore(text) {
|
|
40
|
+
const rules = [];
|
|
41
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
42
|
+
const line = raw.trim();
|
|
43
|
+
if (line.length === 0 || line.startsWith("#"))
|
|
44
|
+
continue;
|
|
45
|
+
const negated = line.startsWith("!");
|
|
46
|
+
let body = negated ? line.slice(1) : line;
|
|
47
|
+
const folder_only = body.endsWith("/");
|
|
48
|
+
if (folder_only)
|
|
49
|
+
body = body.replace(/\/+$/, "");
|
|
50
|
+
const anchored = body.startsWith("/") || body.includes("/");
|
|
51
|
+
body = body.replace(/^\/+/, "");
|
|
52
|
+
if (body.length === 0)
|
|
53
|
+
continue;
|
|
54
|
+
const source = glob_source(body.normalize("NFC"));
|
|
55
|
+
const prefix = anchored ? "^" : "^(?:.*/)?";
|
|
56
|
+
rules.push({ pattern: new RegExp(`${prefix}${source}$`, "i"), negated, folder_only });
|
|
57
|
+
}
|
|
58
|
+
return rules;
|
|
59
|
+
}
|
|
60
|
+
function rule_matches(rule, path, is_folder) {
|
|
61
|
+
const segments = path.split("/");
|
|
62
|
+
const limit = rule.folder_only && !is_folder ? segments.length - 1 : segments.length;
|
|
63
|
+
for (let length = 1; length <= limit; length += 1) {
|
|
64
|
+
if (rule.pattern.test(segments.slice(0, length).join("/")))
|
|
65
|
+
return true;
|
|
66
|
+
}
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
function is_obsidian_noise(segments) {
|
|
70
|
+
if (segments[0] !== ".obsidian")
|
|
71
|
+
return false;
|
|
72
|
+
if (segments.length === 2 && /^workspace.*\.json$/i.test(segments[1]))
|
|
73
|
+
return true;
|
|
74
|
+
return segments.includes("cache");
|
|
75
|
+
}
|
|
76
|
+
export function is_default_ignored(path, obsidian) {
|
|
77
|
+
const segments = path.split("/");
|
|
78
|
+
if (segments.some((segment) => IGNORED_SEGMENTS.has(segment)))
|
|
79
|
+
return true;
|
|
80
|
+
if (segments.some((segment) => segment.startsWith("._")))
|
|
81
|
+
return true;
|
|
82
|
+
if (EXECUTABLE_FOLDERS.some((folder) => path === folder || path.startsWith(`${folder}/`)))
|
|
83
|
+
return true;
|
|
84
|
+
if (segments[0] === ".obsidian" && (!obsidian || is_obsidian_noise(segments)))
|
|
85
|
+
return true;
|
|
86
|
+
return /\.(tmp|swp|crdownload|part)$/i.test(path) || path.endsWith("~");
|
|
87
|
+
}
|
|
88
|
+
export function is_ignored(path, options, is_folder = false) {
|
|
89
|
+
if (is_default_ignored(path, options.obsidian))
|
|
90
|
+
return true;
|
|
91
|
+
let ignored = false;
|
|
92
|
+
for (const rule of options.rules) {
|
|
93
|
+
if (rule.negated === ignored && rule_matches(rule, path, is_folder))
|
|
94
|
+
ignored = !rule.negated;
|
|
95
|
+
}
|
|
96
|
+
return ignored;
|
|
97
|
+
}
|
|
98
|
+
export function ignore_fingerprint(options, source) {
|
|
99
|
+
return `${options.obsidian ? "obsidian" : "plain"}:${source.length}:${source}`;
|
|
100
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { hostname } from "node:os";
|
|
2
|
+
import { mkdir, open, readFile, rm, stat } from "node:fs/promises";
|
|
3
|
+
import { dirname } from "node:path";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import { CliError } from "../errors.js";
|
|
6
|
+
import { lock_path } from "./state.js";
|
|
7
|
+
const lock_schema = z.object({
|
|
8
|
+
pid: z.number().int(),
|
|
9
|
+
host: z.string(),
|
|
10
|
+
started_at: z.string(),
|
|
11
|
+
token: z.string(),
|
|
12
|
+
});
|
|
13
|
+
function parse_lock(raw) {
|
|
14
|
+
if (raw === null)
|
|
15
|
+
return lock_schema.safeParse(null);
|
|
16
|
+
try {
|
|
17
|
+
return lock_schema.safeParse(JSON.parse(raw));
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return lock_schema.safeParse(null);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
function is_alive(pid) {
|
|
24
|
+
try {
|
|
25
|
+
process.kill(pid, 0);
|
|
26
|
+
return true;
|
|
27
|
+
}
|
|
28
|
+
catch (error) {
|
|
29
|
+
return error.code === "EPERM";
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
async function try_create(path, contents) {
|
|
33
|
+
try {
|
|
34
|
+
const handle = await open(path, "wx", 0o644);
|
|
35
|
+
try {
|
|
36
|
+
await handle.writeFile(contents, "utf-8");
|
|
37
|
+
}
|
|
38
|
+
finally {
|
|
39
|
+
await handle.close();
|
|
40
|
+
}
|
|
41
|
+
return true;
|
|
42
|
+
}
|
|
43
|
+
catch (error) {
|
|
44
|
+
if (error.code === "EEXIST")
|
|
45
|
+
return false;
|
|
46
|
+
throw error;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
export async function acquire_lock(root, token) {
|
|
50
|
+
const path = lock_path(root);
|
|
51
|
+
await mkdir(dirname(path), { recursive: true });
|
|
52
|
+
const contents = JSON.stringify({
|
|
53
|
+
pid: process.pid,
|
|
54
|
+
host: hostname(),
|
|
55
|
+
started_at: new Date().toISOString(),
|
|
56
|
+
token,
|
|
57
|
+
});
|
|
58
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
59
|
+
if (await try_create(path, contents)) {
|
|
60
|
+
return {
|
|
61
|
+
release: async () => {
|
|
62
|
+
const current = parse_lock(await readFile(path, "utf-8").catch(() => null));
|
|
63
|
+
if (current.success && current.data.token === token)
|
|
64
|
+
await rm(path, { force: true });
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
const raw = await readFile(path, "utf-8").catch(() => null);
|
|
69
|
+
const existing = parse_lock(raw);
|
|
70
|
+
if (!existing.success) {
|
|
71
|
+
const info = await stat(path).catch(() => null);
|
|
72
|
+
if (info !== null && Date.now() - info.mtimeMs < 5_000) {
|
|
73
|
+
throw new CliError("Another nemu sync is starting on this folder.", "sync_locked");
|
|
74
|
+
}
|
|
75
|
+
await rm(path, { force: true });
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
const stale = existing.data.host === hostname() && !is_alive(existing.data.pid);
|
|
79
|
+
if (!stale) {
|
|
80
|
+
throw new CliError(`Another nemu sync (process ${existing.data.pid} on ${existing.data.host}) is running on this folder. If it is not, delete ${path}.`, "sync_locked");
|
|
81
|
+
}
|
|
82
|
+
await rm(path, { force: true });
|
|
83
|
+
}
|
|
84
|
+
throw new CliError(`Could not take the sync lock at ${path}.`, "sync_locked");
|
|
85
|
+
}
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
const MAX_EDIT_DISTANCE = 3000;
|
|
2
|
+
function split_lines(text) {
|
|
3
|
+
const keys = [];
|
|
4
|
+
const terminators = [];
|
|
5
|
+
let start = 0;
|
|
6
|
+
while (start < text.length) {
|
|
7
|
+
const newline = text.indexOf("\n", start);
|
|
8
|
+
if (newline === -1) {
|
|
9
|
+
keys.push(text.slice(start));
|
|
10
|
+
terminators.push("");
|
|
11
|
+
break;
|
|
12
|
+
}
|
|
13
|
+
const has_return = newline > start && text[newline - 1] === "\r";
|
|
14
|
+
keys.push(text.slice(start, has_return ? newline - 1 : newline));
|
|
15
|
+
terminators.push(has_return ? "\r\n" : "\n");
|
|
16
|
+
start = newline + 1;
|
|
17
|
+
}
|
|
18
|
+
return { keys, terminators };
|
|
19
|
+
}
|
|
20
|
+
function line_ending_of(lines) {
|
|
21
|
+
let crlf = 0;
|
|
22
|
+
let lf = 0;
|
|
23
|
+
for (const terminator of lines.terminators) {
|
|
24
|
+
if (terminator === "\r\n")
|
|
25
|
+
crlf += 1;
|
|
26
|
+
if (terminator === "\n")
|
|
27
|
+
lf += 1;
|
|
28
|
+
}
|
|
29
|
+
if (crlf === 0 && lf === 0)
|
|
30
|
+
return null;
|
|
31
|
+
return crlf > lf ? "\r\n" : "\n";
|
|
32
|
+
}
|
|
33
|
+
function ends_with_newline(lines) {
|
|
34
|
+
const last = lines.terminators[lines.terminators.length - 1];
|
|
35
|
+
return last !== undefined && last !== "";
|
|
36
|
+
}
|
|
37
|
+
function shortest_edit(a, b, max) {
|
|
38
|
+
const n = a.length;
|
|
39
|
+
const m = b.length;
|
|
40
|
+
const limit = Math.min(max, n + m);
|
|
41
|
+
const offset = limit + 1;
|
|
42
|
+
const frontier = new Int32Array(2 * limit + 3);
|
|
43
|
+
const trace = [];
|
|
44
|
+
let found = -1;
|
|
45
|
+
for (let depth = 0; depth <= limit; depth += 1) {
|
|
46
|
+
trace.push(frontier.slice(offset - depth - 1, offset + depth + 2));
|
|
47
|
+
for (let k = -depth; k <= depth; k += 2) {
|
|
48
|
+
const go_down = k === -depth || (k !== depth && frontier[offset + k - 1] < frontier[offset + k + 1]);
|
|
49
|
+
let x = go_down ? frontier[offset + k + 1] : frontier[offset + k - 1] + 1;
|
|
50
|
+
let y = x - k;
|
|
51
|
+
while (x < n && y < m && a[x] === b[y]) {
|
|
52
|
+
x += 1;
|
|
53
|
+
y += 1;
|
|
54
|
+
}
|
|
55
|
+
frontier[offset + k] = x;
|
|
56
|
+
if (x >= n && y >= m) {
|
|
57
|
+
found = depth;
|
|
58
|
+
break;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
if (found !== -1)
|
|
62
|
+
break;
|
|
63
|
+
}
|
|
64
|
+
if (found === -1)
|
|
65
|
+
return null;
|
|
66
|
+
const matches = [];
|
|
67
|
+
let x = n;
|
|
68
|
+
let y = m;
|
|
69
|
+
for (let depth = found; depth > 0; depth -= 1) {
|
|
70
|
+
const snapshot = trace[depth];
|
|
71
|
+
const at = (k) => snapshot[k + depth + 1];
|
|
72
|
+
const k = x - y;
|
|
73
|
+
const go_down = k === -depth || (k !== depth && at(k - 1) < at(k + 1));
|
|
74
|
+
const previous_k = go_down ? k + 1 : k - 1;
|
|
75
|
+
const previous_x = at(previous_k);
|
|
76
|
+
const previous_y = previous_x - previous_k;
|
|
77
|
+
while (x > previous_x && y > previous_y) {
|
|
78
|
+
x -= 1;
|
|
79
|
+
y -= 1;
|
|
80
|
+
matches.push([x, y]);
|
|
81
|
+
}
|
|
82
|
+
x = previous_x;
|
|
83
|
+
y = previous_y;
|
|
84
|
+
}
|
|
85
|
+
while (x > 0 && y > 0) {
|
|
86
|
+
x -= 1;
|
|
87
|
+
y -= 1;
|
|
88
|
+
matches.push([x, y]);
|
|
89
|
+
}
|
|
90
|
+
return matches.reverse();
|
|
91
|
+
}
|
|
92
|
+
export function matching_lines(a, b) {
|
|
93
|
+
let prefix = 0;
|
|
94
|
+
while (prefix < a.length && prefix < b.length && a[prefix] === b[prefix])
|
|
95
|
+
prefix += 1;
|
|
96
|
+
let suffix = 0;
|
|
97
|
+
while (suffix < a.length - prefix &&
|
|
98
|
+
suffix < b.length - prefix &&
|
|
99
|
+
a[a.length - 1 - suffix] === b[b.length - 1 - suffix]) {
|
|
100
|
+
suffix += 1;
|
|
101
|
+
}
|
|
102
|
+
const middle = shortest_edit(a.slice(prefix, a.length - suffix), b.slice(prefix, b.length - suffix), MAX_EDIT_DISTANCE);
|
|
103
|
+
if (middle === null)
|
|
104
|
+
return null;
|
|
105
|
+
const matches = [];
|
|
106
|
+
for (let index = 0; index < prefix; index += 1)
|
|
107
|
+
matches.push([index, index]);
|
|
108
|
+
for (const [left, right] of middle)
|
|
109
|
+
matches.push([left + prefix, right + prefix]);
|
|
110
|
+
for (let index = suffix; index > 0; index -= 1) {
|
|
111
|
+
matches.push([a.length - index, b.length - index]);
|
|
112
|
+
}
|
|
113
|
+
return matches;
|
|
114
|
+
}
|
|
115
|
+
function hunks_of(base, other, side) {
|
|
116
|
+
const matches = matching_lines(base, other);
|
|
117
|
+
if (matches === null)
|
|
118
|
+
return null;
|
|
119
|
+
const hunks = [];
|
|
120
|
+
let base_at = 0;
|
|
121
|
+
let other_at = 0;
|
|
122
|
+
for (const [base_match, other_match] of [...matches, [base.length, other.length]]) {
|
|
123
|
+
if (base_match > base_at || other_match > other_at) {
|
|
124
|
+
hunks.push({
|
|
125
|
+
side,
|
|
126
|
+
base_start: base_at,
|
|
127
|
+
base_length: base_match - base_at,
|
|
128
|
+
side_start: other_at,
|
|
129
|
+
side_length: other_match - other_at,
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
base_at = base_match + 1;
|
|
133
|
+
other_at = other_match + 1;
|
|
134
|
+
}
|
|
135
|
+
return hunks;
|
|
136
|
+
}
|
|
137
|
+
function same(left, right) {
|
|
138
|
+
return left.length === right.length && left.every((line, index) => line === right[index]);
|
|
139
|
+
}
|
|
140
|
+
function side_range(hunks, side, region_start, region_end) {
|
|
141
|
+
const own = hunks.filter((hunk) => hunk.side === side);
|
|
142
|
+
if (own.length === 0)
|
|
143
|
+
return [-1, -1];
|
|
144
|
+
const first = own[0];
|
|
145
|
+
const last = own[own.length - 1];
|
|
146
|
+
const start = first.side_start - (first.base_start - region_start);
|
|
147
|
+
const end = last.side_start + last.side_length + (region_end - (last.base_start + last.base_length));
|
|
148
|
+
return [start, end];
|
|
149
|
+
}
|
|
150
|
+
function merge_pieces(base, local, remote) {
|
|
151
|
+
const local_hunks = hunks_of(base, local, "local");
|
|
152
|
+
const remote_hunks = hunks_of(base, remote, "remote");
|
|
153
|
+
if (local_hunks === null || remote_hunks === null)
|
|
154
|
+
return null;
|
|
155
|
+
const hunks = [...local_hunks, ...remote_hunks].sort((left, right) => left.base_start - right.base_start || (left.side === "local" ? -1 : 1));
|
|
156
|
+
const pieces = [];
|
|
157
|
+
let cursor = 0;
|
|
158
|
+
let index = 0;
|
|
159
|
+
while (index < hunks.length) {
|
|
160
|
+
const first = hunks[index];
|
|
161
|
+
const region_start = first.base_start;
|
|
162
|
+
let region_end = first.base_start + first.base_length;
|
|
163
|
+
const region = [first];
|
|
164
|
+
index += 1;
|
|
165
|
+
while (index < hunks.length && hunks[index].base_start <= region_end) {
|
|
166
|
+
const next = hunks[index];
|
|
167
|
+
region_end = Math.max(region_end, next.base_start + next.base_length);
|
|
168
|
+
region.push(next);
|
|
169
|
+
index += 1;
|
|
170
|
+
}
|
|
171
|
+
if (region_start > cursor)
|
|
172
|
+
pieces.push({ side: "base", start: cursor, end: region_start });
|
|
173
|
+
const sides = new Set(region.map((hunk) => hunk.side));
|
|
174
|
+
if (sides.size === 1) {
|
|
175
|
+
const side = first.side;
|
|
176
|
+
const [start, end] = side_range(region, side, region_start, region_end);
|
|
177
|
+
pieces.push({ side, start, end });
|
|
178
|
+
}
|
|
179
|
+
else {
|
|
180
|
+
const [local_start, local_end] = side_range(region, "local", region_start, region_end);
|
|
181
|
+
const [remote_start, remote_end] = side_range(region, "remote", region_start, region_end);
|
|
182
|
+
const local_part = local.slice(local_start, local_end);
|
|
183
|
+
const remote_part = remote.slice(remote_start, remote_end);
|
|
184
|
+
const base_part = base.slice(region_start, region_end);
|
|
185
|
+
if (same(local_part, remote_part)) {
|
|
186
|
+
pieces.push({ side: "local", start: local_start, end: local_end });
|
|
187
|
+
}
|
|
188
|
+
else if (same(local_part, base_part)) {
|
|
189
|
+
pieces.push({ side: "remote", start: remote_start, end: remote_end });
|
|
190
|
+
}
|
|
191
|
+
else if (same(remote_part, base_part)) {
|
|
192
|
+
pieces.push({ side: "local", start: local_start, end: local_end });
|
|
193
|
+
}
|
|
194
|
+
else {
|
|
195
|
+
return null;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
cursor = region_end;
|
|
199
|
+
}
|
|
200
|
+
if (cursor < base.length)
|
|
201
|
+
pieces.push({ side: "base", start: cursor, end: base.length });
|
|
202
|
+
return pieces;
|
|
203
|
+
}
|
|
204
|
+
function trailing_newline(base, local, remote) {
|
|
205
|
+
const base_has = ends_with_newline(base);
|
|
206
|
+
const local_has = ends_with_newline(local);
|
|
207
|
+
return local_has !== base_has ? local_has : ends_with_newline(remote);
|
|
208
|
+
}
|
|
209
|
+
export function merge_text(base_text, local_text, remote_text) {
|
|
210
|
+
if (local_text === remote_text)
|
|
211
|
+
return { kind: "clean", text: local_text };
|
|
212
|
+
const base = split_lines(base_text);
|
|
213
|
+
const local = split_lines(local_text);
|
|
214
|
+
const remote = split_lines(remote_text);
|
|
215
|
+
if (same(local.keys, remote.keys) && ends_with_newline(local) === ends_with_newline(remote)) {
|
|
216
|
+
return { kind: "clean", text: local_text };
|
|
217
|
+
}
|
|
218
|
+
if (same(base.keys, remote.keys) && ends_with_newline(base) === ends_with_newline(remote)) {
|
|
219
|
+
return { kind: "clean", text: local_text };
|
|
220
|
+
}
|
|
221
|
+
const pieces = merge_pieces(base.keys, local.keys, remote.keys);
|
|
222
|
+
if (pieces === null)
|
|
223
|
+
return { kind: "conflict" };
|
|
224
|
+
const lines = [];
|
|
225
|
+
const sources = { base: base.keys, local: local.keys, remote: remote.keys };
|
|
226
|
+
for (const piece of pieces) {
|
|
227
|
+
lines.push(...sources[piece.side].slice(piece.start, piece.end));
|
|
228
|
+
}
|
|
229
|
+
const ending = line_ending_of(local) ?? line_ending_of(remote) ?? line_ending_of(base) ?? "\n";
|
|
230
|
+
const body = lines.join(ending);
|
|
231
|
+
const text = lines.length > 0 && trailing_newline(base, local, remote) ? `${body}${ending}` : body;
|
|
232
|
+
return { kind: "clean", text };
|
|
233
|
+
}
|
|
234
|
+
export function has_conflict_markers(text) {
|
|
235
|
+
return /^(<{7}|>{7})(\s|$)/m.test(text);
|
|
236
|
+
}
|