version.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  1. import {inspect} from "util"; // NodeJS library
  2. import { Buffer } from "buffer"; // NodeJS library
  3. import {findDFS} from "./util/dfs";
  4. import {permutations} from "./util/permutations";
  5. import {bufferXOR} from "./util/buffer_xor";
  6. import {PrimitiveDelta, Transaction} from "./delta";
  7. // import * as _ from "lodash";
  8. import {
  9. Delta,
  10. // isConflicting,
  11. // iterMissingDependencies,
  12. // iterConflicts,
  13. } from "./delta";
  14. // The difference between two consecutive versions.
  15. type DiffType = Delta;
  16. type OverridingsMap = Map<Delta,Delta>;
  17. export interface Embedding {
  18. version: Version; // the embedded ("guest") version
  19. overridings: OverridingsMap; // overridden deltas: mapping from guest delta to host delta.
  20. }
  21. export type Embeddings = Map<string, Embedding>; // key = a simple identifier for the kind of embedding, e.g., "cs", "as", ...
  22. export type ParentLink = [Version, DiffType];
  23. export type ChildLink = [Version, DiffType];
  24. // A typed link from one version to another.
  25. // There are two types: 'p' (parent) and 'c' (child)
  26. // The link also has a 'value', which is a Delta.
  27. type PathLink = [('p'|'c'), DiffType, Version];
  28. // not exported -> use VersionRegistry to create versions
  29. export class Version {
  30. readonly parents: Array<ParentLink>;
  31. readonly children: Array<ChildLink> = []; // reverse parents
  32. readonly embeddings: Embeddings; // (guest) versions embedded in this (host) version.
  33. readonly reverseEmbeddings: Map<string, Version[]> = new Map(); // (host) versions in which this (guest) version is embedded.
  34. // Unique ID of the version - XOR of all delta hashes - guarantees that Versions with equal (unordered) sets of Deltas have the same ID.
  35. readonly hash: Buffer;
  36. // Number of deltas that version consists of.
  37. readonly size: number;
  38. // DO NOT USE constructor directly - instead use VersionRegistry.createVersion.
  39. constructor(parents: Array<ParentLink>, hash: Buffer, size: number, embeddings: (Version) => Embeddings) {
  40. this.parents = parents;
  41. this.hash = hash;
  42. this.size = size;
  43. this.embeddings = embeddings(this);
  44. }
  45. implicitSelfEmbedding: Embedding = {
  46. version: this, // every version embeds itself for all undefined embeddings.
  47. overridings: new Map(), // no overrides
  48. };
  49. // Returns iterator that yields all deltas of this version, from recent to early.
  50. // Or put more precisely: a delta's dependencies will be yielded AFTER the delta itself.
  51. *[Symbol.iterator](): Iterator<DiffType> {
  52. let current: Version = this;
  53. while (current.parents.length !== 0) {
  54. // There may be multiple parents due to commutativity (multiple orders of deltas that yield the same version), but it doesn't matter which one we pick: all paths will yield the same set of deltas.
  55. const [parent, delta] = current.parents[0];
  56. yield delta;
  57. current = parent;
  58. }
  59. }
  60. *iterPrimitiveDeltas(): Iterable<PrimitiveDelta> {
  61. const executionOrder = [...this].reverse();
  62. for (const d of executionOrder) {
  63. yield* d.iterPrimitiveDeltas();
  64. }
  65. }
  66. [inspect.custom](depth: number, options: object): string {
  67. return "Version{" + [...this].map(d => inspect(d, options)).join(",") + "}";
  68. }
  69. isSubSetOf(otherVersion: Version): boolean {
  70. // current implementation is probably quite slow
  71. for (const delta of this) {
  72. if (!otherVersion.contains(delta)) {
  73. return false;
  74. }
  75. }
  76. return true;
  77. }
  78. contains(delta: Delta): boolean {
  79. for (const d of this) {
  80. if (d === delta) {
  81. return true;
  82. }
  83. }
  84. return false;
  85. }
  86. containsPrimitive(delta: PrimitiveDelta): boolean {
  87. for (const d of this) {
  88. for (const p of d.iterPrimitiveDeltas()) {
  89. if (p === delta) {
  90. return true;
  91. }
  92. }
  93. }
  94. return false;
  95. }
  96. // Returns a sequence of Delta's to be undone/redone to go from this version to the 'otherVersion'
  97. // Returned sequence is empty if otherVersion === this
  98. // Returns undefined when there is no path (which is impossible if both versions are part of the same VersionRegistry).
  99. // TODO: implement Breadth-First Search (BFS) for better performance.
  100. findPathTo(otherVersion: Version): Array<PathLink> | undefined {
  101. const getNeighbors = (v: Version) => {
  102. const parentVersions: [PathLink,Version][] = v.parents.map(([parentVersion, delta]) => [['p', delta, parentVersion], parentVersion]);
  103. const childVersions: [PathLink,Version][] = v.children.map(([childVersion, delta]) => [['c', delta, childVersion], childVersion]);
  104. // heuristic: look in newer or older versions first?
  105. if (v.size < otherVersion.size) {
  106. // make the common case fast: most of the time,
  107. // we just want to advance to the next version (i.e., after a user edit)
  108. return [...childVersions, ...parentVersions];
  109. } else {
  110. return [...parentVersions, ...childVersions];
  111. }
  112. }
  113. // console.time("findDFS")
  114. const result = findDFS<Version,PathLink>(this, otherVersion, getNeighbors);
  115. // console.timeEnd("findDFS");
  116. // if (result)
  117. // console.log("findPath:", result.map(([linkType])=>linkType));
  118. return result;
  119. }
  120. // Like findPathTo, but only searches 'down' (younger versions).
  121. findDescendant(otherVersion: Version): Array<PathLink> | undefined {
  122. const getNeighbors = (v: Version) => {
  123. const result: [PathLink,Version][] = v.children.map(([childVersion, delta]) =>
  124. [['c', delta, childVersion], childVersion]);
  125. return result;
  126. };
  127. return findDFS<Version,PathLink>(this, otherVersion, getNeighbors);
  128. }
  129. getEmbedding(key: string): Embedding {
  130. return this.embeddings.get(key) || this.implicitSelfEmbedding;
  131. }
  132. getReverseEmbeddings(key: string): Version[] {
  133. return this.reverseEmbeddings.get(key) || [this];
  134. }
  135. // Serialize a path of Deltas from a Version in alreadyHave, to fully reconstruct this version.
  136. serialize(alreadyHave: Set<Version> = new Set()) {
  137. const deltas = [];
  138. const versions = [];
  139. this.serializeInternal(new Set(alreadyHave), new Set<Delta>(), deltas, versions);
  140. return {
  141. externalDependencies: [...alreadyHave].map(v => v.hash.toString('hex')),
  142. deltas,
  143. versions,
  144. };
  145. }
  146. private serializeInternal(alreadyHaveVersions: Set<Version>, alreadyHaveDeltas: Set<Delta>, deltas, versions) {
  147. if (alreadyHaveVersions.has(this)) {
  148. return;
  149. }
  150. alreadyHaveVersions.add(this);
  151. const embeddings = new Array<{guestId: string, v: string, ovr: object}>();
  152. for (const [guestId, {version, overridings}] of this.embeddings) {
  153. version.serializeInternal(alreadyHaveVersions, alreadyHaveDeltas, deltas, versions);
  154. const ovr = {};
  155. for (const [key,val] of overridings.entries()) {
  156. ovr[key.hash.toString('hex')] = val.hash.toString('hex');
  157. }
  158. embeddings.push({guestId, v: version.hash.toString('hex'), ovr});
  159. }
  160. if (this.parents.length > 0) {
  161. const [parentVersion, delta] = this.parents[0];
  162. parentVersion.serializeInternal(alreadyHaveVersions, alreadyHaveDeltas, deltas, versions);
  163. function visitDelta(delta) {
  164. for (const d of delta.getDependencies()) {
  165. visitDelta(d);
  166. }
  167. if (!alreadyHaveDeltas.has(delta)) {
  168. deltas.push(delta.serialize());
  169. alreadyHaveDeltas.add(delta);
  170. }
  171. }
  172. visitDelta(delta);
  173. versions.push({
  174. id: this.hash.toString('hex'),
  175. parent: parentVersion.hash.toString('hex'),
  176. delta: delta.hash.toString('hex'),
  177. embeddings,
  178. })
  179. }
  180. }
  181. }
  182. const initialHash = Buffer.alloc(32); // all zeros
  183. function isConflicting(deltaA: Delta, deltaB: Delta) {
  184. // for performance, iterate over the delta that has the least conflicts:
  185. if (deltaA.conflictsWith.length < deltaB.conflictsWith.length) {
  186. return deltaA.conflictsWith.some(([d]) => d === deltaB);
  187. }
  188. else {
  189. return deltaB.conflictsWith.some(([d]) => d === deltaA);
  190. }
  191. }
  192. export class VersionRegistry {
  193. readonly initialVersion: Version = new Version([], initialHash, 0, () => new Map());
  194. // Maps version ID (as string, because a Buffer cannot be a map key) to Version
  195. readonly versionMap: Map<string, Version> = new Map([
  196. [initialHash.toString('hex'), this.initialVersion], // the initial version, always already there
  197. ]);
  198. lookupOptional(hash: Buffer): Version | undefined {
  199. return this.versionMap.get(hash.toString('hex'));
  200. }
  201. lookup(hash: Buffer): Version {
  202. const hex = hash.toString('hex');
  203. const version = this.versionMap.get(hex);
  204. if (version === undefined) {
  205. throw new Error("no such version: " + hex);
  206. }
  207. return version;
  208. }
  209. private putVersion(hash: Buffer, version: Version) {
  210. this.versionMap.set(hash.toString('hex'), version);
  211. }
  212. // Idempotent
  213. // Pre-condition 1: all of the dependencies of delta must exist in parent.
  214. // Pre-condition 2: delta must be non-conflicting with any delta in parent.
  215. // Pre-condition 3: if the to-be-created ("host") version embeds other ("guest") versions,
  216. // then all of the guest versions' deltas must exist in the host version, or be explicitly overridden.
  217. createVersion(parent: Version, delta: DiffType, embeddings: (Version) => Embeddings = () => new Map()): Version {
  218. // Check pre-condition 1:
  219. for (const [dep] of delta.getDependencies()) {
  220. if (!parent.contains(dep)) {
  221. throw new Error("createVersion: precondition failed: Missing dependency: " + dep.description);
  222. }
  223. }
  224. // Check pre-condition 2:
  225. for (const [conflictingDelta] of delta.conflictsWith) {
  226. if (parent.contains(conflictingDelta)) {
  227. throw new Error("createVersion: precondition failed: Delta " + delta.description + " conflicts with " + conflictingDelta.description);
  228. }
  229. }
  230. const newVersion = this.createVersionUnsafe(parent, delta, embeddings);
  231. // Check pre-condition 3:
  232. const primitiveDeltas = [...delta.iterPrimitiveDeltas()];
  233. for (const [guestId, {version: guest, overridings}] of newVersion.embeddings.entries()) {
  234. const {version: guestParent} = parent.getEmbedding(guestId);
  235. const guestDiff = guestParent.findDescendant(guest)!;
  236. for (const [_, guestDelta] of guestDiff) {
  237. for (const guestPDelta of guestDelta.iterPrimitiveDeltas()) {
  238. if (!primitiveDeltas.includes(overridings.get(guestPDelta) || guestPDelta)) {
  239. throw new Error("createVersion: precondition failed: Guest's primitive delta " + guestPDelta.description + " does not occur in host, nor is it overridden.");
  240. }
  241. }
  242. }
  243. }
  244. return newVersion;
  245. }
  246. // Faster than createVersion, but does not check pre-conditions.
  247. // Idempotent
  248. createVersionUnsafe(parent: Version, delta: DiffType, embeddings: (Version) => Embeddings = () => new Map()): Version {
  249. const newHash = bufferXOR(parent.hash, delta.hash);
  250. // TODO: include embeddings in hash digest.
  251. const existingVersion = this.lookupOptional(newHash);
  252. if (existingVersion !== undefined) {
  253. // this Version already exists
  254. const havePath = existingVersion.parents.some(([parentVersion, delta]) => parentVersion === parent);
  255. if (!havePath) {
  256. // but the path is new (there can be multiple 'paths' to the same version, because of commutation of deltas)
  257. existingVersion.parents.push([parent, delta]);
  258. parent.children.push([existingVersion, delta]);
  259. }
  260. for (const [guestId, {version, overridings}] of embeddings(existingVersion)) {
  261. const found = existingVersion.embeddings.get(guestId);
  262. if (!found) {
  263. existingVersion.embeddings.set(guestId, {version, overridings});
  264. // throw new Error("Assertion failed: created version already exists, but does not embed '" + guestId + "'");
  265. }
  266. else {
  267. const {version: v, overridings: o} = found;
  268. if (v !== version) {
  269. throw new Error("Assertion failed: created version already exists and embeds a differrent version '" + guestId + "'");
  270. }
  271. // Merge overridings:
  272. for (const [guestDelta, hostDelta] of overridings.entries()) {
  273. const alreadyHostDelta = o.get(guestDelta) || hostDelta;
  274. if (hostDelta !== alreadyHostDelta) {
  275. throw new Error("Assertion failed: created version already exists BUT overrides delta '" + guestDelta.description + "' with another delta.");
  276. }
  277. o.set(guestDelta, hostDelta);
  278. }
  279. }
  280. }
  281. return existingVersion;
  282. } else {
  283. const newVersion = new Version([[parent, delta]], newHash, parent.size + 1, embeddings);
  284. // Create reverse parent links:
  285. for (const [parent,delta] of newVersion.parents) {
  286. parent.children.push([newVersion, delta]);
  287. }
  288. // Create reverse embedding:
  289. for (const [key, embedding] of newVersion.embeddings.entries()) {
  290. const reverse = embedding.version.reverseEmbeddings.get(key);
  291. if (reverse !== undefined) {
  292. reverse.push(newVersion);
  293. }
  294. else {
  295. embedding.version.reverseEmbeddings.set(key, [newVersion]);
  296. }
  297. }
  298. this.putVersion(newHash, newVersion);
  299. return newVersion;
  300. }
  301. }
  302. // Mostly used for testing purposes.
  303. // Order of deltas should be recent -> early
  304. // Or put more precisely: a delta's dependencies should occur AFTER the delta in the array.
  305. quickVersion(deltas: Array<DiffType>): Version {
  306. return deltas.reduceRight((parentVersion, delta) => this.createVersion(parentVersion, delta), this.initialVersion);
  307. }
  308. // Get the version whose deltas are a subset of all given versions AKA the 'largest common ancestor'.
  309. getIntersection(versions: Array<Version>): Version {
  310. // treat special case first:
  311. if (versions.length === 0) {
  312. return this.initialVersion;
  313. }
  314. // sort versions (out place) from few deltas to many (FASTEST):
  315. const sortedVersions = versions.slice().sort((versionA,versionB) => versionA.size - versionB.size);
  316. const intersection: Array<DiffType> = [];
  317. for (const delta of sortedVersions[0]) {
  318. let allVersionsHaveIt = true;
  319. for (let i=1; i<sortedVersions.length; i++) {
  320. let thisVersionHasIt = false;
  321. for (const otherDelta of sortedVersions[i]) {
  322. if (delta === otherDelta) {
  323. thisVersionHasIt = true;
  324. break;
  325. }
  326. }
  327. if (!thisVersionHasIt) {
  328. allVersionsHaveIt = false;
  329. break;
  330. }
  331. }
  332. if (allVersionsHaveIt) {
  333. intersection.push(delta);
  334. }
  335. }
  336. return this.quickVersion(intersection);
  337. }
  338. private getLCAInternal(versionA: Version, versionB: Version): Version {
  339. const ancestorsA = [versionA];
  340. const ancestorsB = [versionB];
  341. while (true) {
  342. const a = ancestorsA[ancestorsA.length-1];
  343. // @ts-ignore: TypeScript doesn't know about 'findLast' method yet.
  344. if (ancestorsB.findLast(v => v === a)) {
  345. return a;
  346. }
  347. if (a.parents.length > 0) {
  348. const [parent] = a.parents[0];
  349. ancestorsA.push(parent);
  350. }
  351. const b = ancestorsB[ancestorsB.length-1];
  352. // @ts-ignore: TypeScript doesn't know about 'findLast' method yet.
  353. if (ancestorsA.findLast(v => v === b)) {
  354. return b;
  355. }
  356. if (b.parents.length > 0) {
  357. const [parent] = b.parents[0];
  358. ancestorsB.push(parent);
  359. }
  360. }
  361. }
  362. getLCA(versions: Array<Version>): Version {
  363. if (versions.length === 0) {
  364. return this.initialVersion;
  365. }
  366. return versions.reduce((a,b) => this.getLCAInternal(a,b));
  367. }
  368. // Idempotent
  369. // Of the union of all deltas of the versions given, compute the maximal left-closed conflict-free subsets.
  370. // These are the subsets to which no delta can be added without introducing a conflict or missing dependency.
  371. merge(versions: Array<Version>, debugNames?: (Delta) => string): Array<Version> {
  372. function printDebug(...args) {
  373. if (debugNames !== undefined) {
  374. for (const [i,arg] of args.entries()) {
  375. try {
  376. const name = debugNames(arg);
  377. if (name !== undefined) {
  378. args[i] = name;
  379. }
  380. }
  381. catch (e) {}
  382. }
  383. console.log(...args);
  384. }
  385. }
  386. const lca = this.getLCA(versions);
  387. // printDebug("lca:", ...[...lca].map(d => d.description));
  388. // Tuple
  389. // Delta: a delta that is at least one of 'versions' but not in 'lca'
  390. // Map: a mapping from all guest-IDs to 'diffs':
  391. // the Delta of the guest that corresponds to the Delta in the host.
  392. type DeltaWithEmbedding = [Delta, Map<string, [DeltaWithEmbedding|null, OverridingsMap]>];
  393. // ATTENTION: Constructing 'diff' must be made recursive (guest could also be a host)
  394. function visitEmbeddings(currentHost: Version, nextHost: Version) {
  395. const guestDeltaMap = new Map();
  396. for (const [guestId, {version: nextGuest, overridings}] of nextHost.embeddings.entries()) {
  397. const currentGuest = currentHost.getEmbedding(guestId).version;
  398. const guestPath = currentGuest.findDescendant(nextGuest)!;
  399. if (guestPath.length > 1) {
  400. throw new Error("Did not expect guestPath to be longer than one delta")
  401. }
  402. if (guestPath.length === 1) {
  403. const guestDelta = guestPath[0][1];
  404. if (currentHost === currentGuest && nextHost === nextGuest) {
  405. // prevent infinite recursion in case of self-embedding:
  406. guestDeltaMap.set(guestId, [[guestDelta, guestDeltaMap], overridings]);
  407. }
  408. else {
  409. const recursiveGuestDeltaMap = visitEmbeddings(currentGuest, nextGuest);
  410. guestDeltaMap.set(guestId, [[guestDelta, recursiveGuestDeltaMap], overridings]);
  411. }
  412. }
  413. else {
  414. guestDeltaMap.set(guestId, [null, new Map()]);
  415. }
  416. }
  417. return guestDeltaMap;
  418. }
  419. let diff: Array<DeltaWithEmbedding> = [];
  420. for (const v of versions) {
  421. const path = lca.findDescendant(v)!;
  422. // all deltas on path from lca to 'v':
  423. let currentVersion = lca;
  424. for (const [_, delta, nextVersion] of path) {
  425. const guestDeltaMap = visitEmbeddings(currentVersion, nextVersion);
  426. // The following condition may be wrong, check this later:
  427. if (!diff.some(([d]) => d === delta)) {
  428. diff.push([delta, guestDeltaMap]);
  429. }
  430. currentVersion = nextVersion;
  431. }
  432. }
  433. // Now we're ready to actually start merging...
  434. const result: Array<Version> = [];
  435. // Recursively attempts to add deltas from 'deltasToTry' to 'startVersion'
  436. // When nothing can be added anymore without introducing a conflict, we have a 'maximal version' (a result).
  437. // It's possible that there is more than one 'maximal version'.
  438. // Precondition: We assume that any single delta of 'deltasToTry' will not be conflicting with 'startVersion'.
  439. const depthFirst = (startVersion: Version, candidates: Array<DeltaWithEmbedding>, depth: number) => {
  440. function printIndent(...args) {
  441. printDebug(" ".repeat(depth), ...args);
  442. }
  443. // printIndent("deltasToTry=", ...candidates.map(([d])=>d));
  444. let couldNotRecurse = true;
  445. for (const [delta, guestDeltaMap] of candidates) {
  446. const haveMissingDependency = delta.getDependencies().some(([dependency]) => !startVersion.contains(dependency));
  447. if (haveMissingDependency) {
  448. printIndent("missing dependency, trying next delta")
  449. continue; // skip this delta, but keep it in deltasToTry (its missing dependency may be in deltasToTry)
  450. }
  451. // ATTENTION: Constructing embeddings must be made recursive (guest could also be a host)
  452. // 'delta' can be added
  453. // printIndent("including", delta, " => new version: ", delta, ...startVersion);
  454. const createMergedVersionRecursive = (startVersion, [delta, guestDeltaMap]) => {
  455. const embeddings = new Map();
  456. const selfEmbeddingKeys = new Set<string>();
  457. for (const [guestId, [guestDelta, overridings]] of guestDeltaMap.entries()) {
  458. const {version: guestStartVersion} = startVersion.getEmbedding(guestId);
  459. // console.log(guestId, "guestStartVersion: ", guestStartVersion);
  460. let nextGuestVersion;
  461. if (guestDelta === null) {
  462. nextGuestVersion = guestStartVersion;
  463. } else {
  464. if (guestStartVersion === startVersion && guestDelta[0] === delta && guestDelta[1] === guestDeltaMap) {
  465. selfEmbeddingKeys.add(guestId);
  466. continue;
  467. }
  468. else {
  469. nextGuestVersion = createMergedVersionRecursive(guestStartVersion, guestDelta);
  470. }
  471. }
  472. embeddings.set(guestId, {version: nextGuestVersion, overridings});
  473. }
  474. // printIndent("Creating version (", delta, ...[...startVersion].map(d => d), ") with embeddings", embeddings);
  475. const nextVersion = this.createVersion(startVersion, delta, newVersion => {
  476. // add self-embeddings:
  477. for (const guestId of selfEmbeddingKeys) {
  478. embeddings.set(guestId, {version: newVersion, overridings: new Map()});
  479. }
  480. return embeddings;
  481. });
  482. // printIndent("Created version (", ...[...nextVersion].map(d => d), ") with embeddings", embeddings);
  483. return nextVersion;
  484. }
  485. const nextVersion = createMergedVersionRecursive(startVersion, [delta, guestDeltaMap]);
  486. // current delta does not have to be included again in next loop iterations
  487. candidates = candidates.filter(([d]) => d !== delta);
  488. // const [conflicting, nonConflicting] = _.partition(deltasToTry, ([d]) => isConflicting(d, delta));
  489. const nonConflicting = candidates.filter(([candidate]) => !isConflicting(candidate, delta));
  490. // if (conflicting.length > 0)
  491. // printIndent("will be skipped (conflicts with", delta, "):", ...conflicting);
  492. depthFirst(nextVersion, nonConflicting, depth+1);
  493. couldNotRecurse = false;
  494. if (nonConflicting.length === candidates.length) {
  495. // all deltas from deltasToTry were included -> no need to try alternatives
  496. break;
  497. }
  498. }
  499. if (couldNotRecurse) {
  500. // possibly have a new maximal version
  501. if (!result.some(v => startVersion.isSubSetOf(v))) {
  502. // printIndent("new result");
  503. result.push(startVersion);
  504. }
  505. }
  506. };
  507. depthFirst(lca, diff, 0);
  508. // printDebug("result of merge:", ..._.flatten(result.map(v => [...v, ","])));
  509. return result;
  510. }
  511. // Idempotent
  512. // Calls the merge-function for every permutation of 'versions'
  513. // This is useful for didactic purposes: a path is created from every input to at least one output.
  514. // Of course it won't scale to many inputs.
  515. crazyMerge(versions: Array<Version>, debugNames?: (Delta) => string): Array<Version> {
  516. let result;
  517. for (const v of permutations(versions)) {
  518. // whatever the permutation, result will always be the same:
  519. result = this.merge(v, debugNames);
  520. }
  521. return result;
  522. }
  523. }