223 lines
9.8 KiB
JavaScript
223 lines
9.8 KiB
JavaScript
// 3-way merge of Roblox .rbxlx place files at instance level (by referent).
|
|
// Git cannot merge place files line by line; this merges whole instances instead.
|
|
// usage: node --max-old-space-size=12288 tools/merge-rbxlx.js base.rbxlx ours.rbxlx theirs.rbxlx out.rbxlx [--dry]
|
|
'use strict';
|
|
const fs = require('fs');
|
|
const crypto = require('crypto');
|
|
|
|
const [,, baseP, oursP, theirsP, outP, flag] = process.argv;
|
|
const DRY = flag === '--dry';
|
|
|
|
const OPEN_RE = /^\t*<Item class="([^"]+)" referent="([^"]+)">\s*$/;
|
|
|
|
function index(path) {
|
|
const fd = fs.openSync(path, 'r');
|
|
const size = fs.fstatSync(fd).size;
|
|
const CH = 1 << 24;
|
|
const buf = Buffer.alloc(CH);
|
|
let carry = Buffer.alloc(0);
|
|
let pos = 0;
|
|
const items = new Map();
|
|
const roots = [];
|
|
const stack = [];
|
|
let headerEnd = -1;
|
|
let tailStart = -1;
|
|
let inProps = null;
|
|
let propsHash = null;
|
|
let lineNo = 0;
|
|
const handle = (line, off, end) => {
|
|
lineNo++;
|
|
if (inProps) {
|
|
propsHash.update(line);
|
|
propsHash.update('\n');
|
|
if (line.length === inProps.closeLen && line.toString() === inProps.close) {
|
|
inProps.item.propsEnd = end;
|
|
inProps.item.hash = propsHash.digest('hex');
|
|
inProps = null;
|
|
}
|
|
return;
|
|
}
|
|
let t = 0; while (t < line.length && line[t] === 9) t++;
|
|
const rest = line.slice(t, t + 12).toString();
|
|
if (rest.startsWith('<Item ')) {
|
|
const m = OPEN_RE.exec(line.toString());
|
|
if (!m) throw new Error(path + ':' + lineNo + ' bad item line');
|
|
if (headerEnd < 0) headerEnd = off;
|
|
const parent = stack.length ? stack[stack.length - 1] : null;
|
|
const it = { cls: m[1], ref: m[2], parent: parent ? parent.ref : null, children: [], depth: t, propsStart: -1, propsEnd: -1, hash: '' };
|
|
if (items.has(it.ref)) throw new Error('duplicate referent ' + it.ref);
|
|
items.set(it.ref, it);
|
|
if (parent) parent.children.push(it.ref); else roots.push(it.ref);
|
|
stack.push(it);
|
|
} else if (rest.startsWith('<Properties>') && stack.length && t === stack[stack.length - 1].depth + 1) {
|
|
const it = stack[stack.length - 1];
|
|
it.propsStart = off;
|
|
const s = line.toString();
|
|
if (s.trimEnd().endsWith('</Properties>')) {
|
|
it.propsEnd = end; it.hash = crypto.createHash('md5').update(line).digest('hex');
|
|
} else {
|
|
const close = '\t'.repeat(t) + '</Properties>';
|
|
inProps = { item: it, close, closeLen: Buffer.byteLength(close) };
|
|
propsHash = crypto.createHash('md5');
|
|
}
|
|
} else if (rest.startsWith('</Item>')) {
|
|
const it = stack.pop();
|
|
if (!it || it.depth !== t) throw new Error(path + ':' + lineNo + ' unbalanced </Item>');
|
|
if (!stack.length) tailStart = end;
|
|
} else if (line.length >= 7 && (rest.startsWith('<<<<<<<') || rest.startsWith('>>>>>>>'))) {
|
|
throw new Error(path + ':' + lineNo + ' contains git conflict markers');
|
|
}
|
|
};
|
|
let fileOff = 0;
|
|
while (fileOff < size) {
|
|
const n = fs.readSync(fd, buf, 0, CH, fileOff);
|
|
fileOff += n;
|
|
const data = carry.length ? Buffer.concat([carry, buf.subarray(0, n)]) : buf.subarray(0, n);
|
|
let start = 0;
|
|
for (;;) {
|
|
const nl = data.indexOf(10, start);
|
|
if (nl < 0) break;
|
|
let lineEnd = nl; if (lineEnd > start && data[lineEnd - 1] === 13) lineEnd--;
|
|
handle(data.subarray(start, lineEnd), pos + start, pos + nl + 1);
|
|
start = nl + 1;
|
|
}
|
|
carry = Buffer.from(data.subarray(start));
|
|
pos += start;
|
|
}
|
|
if (carry.length) handle(carry, pos, pos + carry.length);
|
|
if (stack.length) throw new Error(path + ' has unclosed items');
|
|
return { path, fd, size, items, roots, headerEnd, tailStart };
|
|
}
|
|
|
|
function readRange(f, a, b) {
|
|
const out = Buffer.alloc(b - a);
|
|
fs.readSync(f.fd, out, 0, b - a, a);
|
|
return out;
|
|
}
|
|
const NAME_RE = /<string name="Name">([^<]*)<\/string>/;
|
|
function nameOf(f, ref) {
|
|
const it = f.items.get(ref); if (!it || it.propsStart < 0) return '?';
|
|
const len = Math.min(it.propsEnd - it.propsStart, 4000);
|
|
const m = NAME_RE.exec(readRange(f, it.propsStart, it.propsStart + len).toString());
|
|
return m ? m[1] : '(' + it.cls + ')';
|
|
}
|
|
function pathOf(f, ref) {
|
|
const parts = []; let r = ref; let guard = 0;
|
|
while (r && guard++ < 60) { if (!f.items.has(r)) break; parts.unshift(nameOf(f, r)); r = f.items.get(r).parent; }
|
|
return parts.join('.');
|
|
}
|
|
|
|
console.time('index');
|
|
const B = index(baseP), O = index(oursP), T = index(theirsP);
|
|
console.timeEnd('index');
|
|
console.log('items base/ours/theirs:', B.items.size, O.items.size, T.items.size);
|
|
|
|
const all = new Set([...B.items.keys(), ...O.items.keys(), ...T.items.keys()]);
|
|
const M = new Map(); // ref -> { src, parent }
|
|
const stats = { same: 0, oursOnly: 0, theirsOnly: 0, conflict: 0, addO: 0, addT: 0, delO: 0, delT: 0, delConflict: 0 };
|
|
const conflicts = [];
|
|
const theirsTouched = [];
|
|
for (const ref of all) {
|
|
const b = B.items.get(ref), o = O.items.get(ref), t = T.items.get(ref);
|
|
if (!b) {
|
|
if (o && t) { M.set(ref, { src: O, parent: o.parent }); if (o.hash !== t.hash) { stats.conflict++; conflicts.push(['added-both-differ', ref]); } }
|
|
else if (o) { M.set(ref, { src: O, parent: o.parent }); stats.addO++; }
|
|
else { M.set(ref, { src: T, parent: t.parent }); stats.addT++; theirsTouched.push(['added', ref]); }
|
|
continue;
|
|
}
|
|
if (!o && !t) continue;
|
|
if (!o) {
|
|
if (t.hash === b.hash && t.parent === b.parent) { stats.delO++; continue; }
|
|
stats.delConflict++; conflicts.push(['ours-deleted-theirs-changed (kept theirs)', ref]); M.set(ref, { src: T, parent: t.parent }); continue;
|
|
}
|
|
if (!t) {
|
|
if (o.hash === b.hash && o.parent === b.parent) { stats.delT++; theirsTouched.push(['deleted', ref]); continue; }
|
|
stats.delConflict++; conflicts.push(['theirs-deleted-ours-changed (kept ours)', ref]); M.set(ref, { src: O, parent: o.parent }); continue;
|
|
}
|
|
let src;
|
|
if (o.hash === t.hash) { src = O; stats.same++; }
|
|
else if (t.hash === b.hash) { src = O; stats.oursOnly++; }
|
|
else if (o.hash === b.hash) { src = T; stats.theirsOnly++; theirsTouched.push(['changed', ref]); }
|
|
else { src = O; stats.conflict++; conflicts.push(['both-changed (kept ours)', ref]); }
|
|
let parent;
|
|
if (o.parent === t.parent) parent = o.parent;
|
|
else if (t.parent === b.parent) parent = o.parent;
|
|
else if (o.parent === b.parent) { parent = t.parent; theirsTouched.push(['moved', ref]); }
|
|
else { parent = o.parent; conflicts.push(['moved-both (kept ours)', ref]); }
|
|
M.set(ref, { src, parent });
|
|
}
|
|
let dropped = 0;
|
|
for (const [ref, m] of M) {
|
|
let p = m.parent, ok = true, g = 0;
|
|
while (p && g++ < 200) { if (!M.has(p)) { ok = false; break; } p = M.get(p).parent; }
|
|
if (!ok) { M.delete(ref); dropped++; }
|
|
}
|
|
console.log(stats, 'droppedOrphans', dropped);
|
|
|
|
const where = (ref) => (O.items.has(ref) ? O : T.items.has(ref) ? T : B);
|
|
console.log('\n=== CONFLICTS (' + conflicts.length + ') ===');
|
|
for (const [k, ref] of conflicts.slice(0, 300)) { const f = where(ref); console.log(k.padEnd(44), f.items.get(ref).cls.padEnd(16), pathOf(f, ref)); }
|
|
const summ = new Map();
|
|
for (const [k, ref] of theirsTouched) {
|
|
const f = T.items.has(ref) ? T : B;
|
|
const p = pathOf(f, ref).split('.').slice(0, 4).join('.');
|
|
const key = k.padEnd(8) + ' ' + p; summ.set(key, (summ.get(key) || 0) + 1);
|
|
}
|
|
console.log('\n=== THEIRS CHANGES (grouped) ===');
|
|
for (const [k, n] of [...summ].sort((a, b) => b[1] - a[1]).slice(0, 120)) console.log(String(n).padStart(7), k);
|
|
|
|
if (DRY) process.exit(0);
|
|
|
|
function childList(parentRef) {
|
|
const out = [];
|
|
const seen = new Set();
|
|
const take = (ref) => { const m = M.get(ref); if (m && m.parent === parentRef && !seen.has(ref)) { seen.add(ref); out.push(ref); } };
|
|
const oc = parentRef === null ? O.roots : (O.items.has(parentRef) ? O.items.get(parentRef).children : []);
|
|
const tc = parentRef === null ? T.roots : (T.items.has(parentRef) ? T.items.get(parentRef).children : []);
|
|
for (const r of oc) take(r);
|
|
for (const r of tc) take(r);
|
|
return out;
|
|
}
|
|
const byParent = new Map();
|
|
for (const [ref, m] of M) { if (!byParent.has(m.parent)) byParent.set(m.parent, []); byParent.get(m.parent).push(ref); }
|
|
|
|
const outFd = fs.openSync(outP, 'w');
|
|
const chunks = []; let pendingLen = 0;
|
|
function write(b) { chunks.push(b); pendingLen += b.length; if (pendingLen > (64 << 20)) { fs.writeSync(outFd, Buffer.concat(chunks)); chunks.length = 0; pendingLen = 0; } }
|
|
write(readRange(O, 0, O.headerEnd));
|
|
let emitted = 0;
|
|
function emit(ref, depth) {
|
|
const m = M.get(ref); const it = m.src.items.get(ref);
|
|
const ind = '\t'.repeat(depth);
|
|
write(Buffer.from(ind + '<Item class="' + it.cls + '" referent="' + ref + '">\n'));
|
|
if (it.propsStart >= 0) write(readRange(m.src, it.propsStart, it.propsEnd));
|
|
emitted++;
|
|
const kids = childList(ref);
|
|
const kidSet = new Set(kids);
|
|
for (const c of kids) emit(c, depth + 1);
|
|
for (const c of (byParent.get(ref) || [])) if (!kidSet.has(c)) emit(c, depth + 1);
|
|
write(Buffer.from(ind + '</Item>\n'));
|
|
}
|
|
const top = childList(null);
|
|
const topSet = new Set(top);
|
|
for (const r of top) emit(r, 1);
|
|
for (const r of (byParent.get(null) || [])) if (!topSet.has(r)) emit(r, 1);
|
|
|
|
// tail: union of SharedStrings (meshes, unions etc. are referenced by md5)
|
|
const oTail = readRange(O, O.tailStart, O.size).toString();
|
|
const tTail = readRange(T, T.tailStart, T.size).toString();
|
|
const SS_RE = /<SharedString md5="([^"]+)">[\s\S]*?<\/SharedString>/g;
|
|
const have = new Set(); let mm;
|
|
while ((mm = SS_RE.exec(oTail))) have.add(mm[1]);
|
|
const extra = [];
|
|
while ((mm = SS_RE.exec(tTail))) if (!have.has(mm[1])) extra.push('\t\t' + mm[0]);
|
|
let tail = oTail;
|
|
if (extra.length) {
|
|
if (tail.includes('</SharedStrings>')) tail = tail.replace('</SharedStrings>', extra.join('\n') + '\n\t</SharedStrings>');
|
|
else tail = tail.replace('</roblox>', '\t<SharedStrings>\n' + extra.join('\n') + '\n\t</SharedStrings>\n</roblox>');
|
|
}
|
|
write(Buffer.from(tail));
|
|
fs.writeSync(outFd, Buffer.concat(chunks));
|
|
fs.closeSync(outFd);
|
|
console.log('\nwritten', outP, 'items', emitted, 'of', M.size, 'extraSharedStrings', extra.length);
|