/** * @module branch-cmd * * Isomorphic execution engine for `vcs branch [branchName]`. * Lists registered branches or creates a new B2tFSBranchIbGib_V1 node registered in B2tFSGalaxyIbGib_V1. */ import { extractErrorMsg, getUUID } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs'; import { joinPaths } from '@ibgib/helper-gib/dist/helpers/path-helper.mjs'; import { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs'; import { GLOBAL_LOG_A_LOT } from '../../../core-constants.mjs'; import { mut8 } from '@ibgib/ts-gib/dist/V1/transforms/mut8.mjs'; import { persistTransformResult } from '../../../witness/space/space-helper.mjs'; import { createBranchSnapshotIbGib } from '../snapshot/snapshot-helpers.mjs'; import { OriginSnapshotInfo } from '../snapshot/snapshot-types.mjs'; import { B2tFSBranchIbGib_V1 } from '../branch/branch-types.mjs'; import { createB2tFSBranchIbGib, getAllBranchIbGibsFromGalaxy, getAllBranchInfosFromGalaxy, getOrCreateBranchSpace, registerSubBranchOnParent, validateBranchName, } from '../branch/branch-helpers.mjs'; import { B2TFS_BRANCH_DEFAULT_NAME } from '../branch/branch-constants.mjs'; import { populateBranchSpaceFromGraph } from '../branch/branch-graph-helpers.mjs'; import { B2tFSItemIbGib_V1, B2TFS_CHILD_ITEM_REL8N_NAME } from '../item/item-types.mjs'; import { updateB2tFSGalaxyIbGib, } from '../b2tfs-galaxy/b2tfs-galaxy-helpers.mjs'; import { VcsBranchOpts, VcsBranchResult, VcsBranchItemInfo } from './command-types.mjs'; import { getIbGibFromSpace, getSpaceQualifiedIbGibAddr } from '../../../common/other/ibgib-helper.mjs'; import { getSpaceIdFromIb } from '../../../witness/space/metaspace/metaspace-innerspace/metaspace-innerspace-helper.mjs'; import { getBranchAndRootItemInfosAndIbGibsAndSpaceFromGalaxyIbGib } from '../item/item-helpers.mjs'; const lcFile = `[branch-cmd]`; const logalot = GLOBAL_LOG_A_LOT; export async function executeVcsBranch(opts: VcsBranchOpts): Promise { const lc = `${lcFile}[${executeVcsBranch.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: cf8e88cca798e6cb48267f950007e826)`); } const trimmedBranchName = opts.branchName?.trim(); const result = trimmedBranchName ? await executeVcsBranch_createNewBranch(opts) : await executeVcsBranch_listBranches(opts); return result; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)} (E: ae6e9841d2283328f891f3f6b1a25226)`); throw error; } finally { if (logalot) { console.log(`${lc} complete. (I: 3376f633d188c591816c9058ab659426)`); } } } async function executeVcsBranch_createNewBranch(opts: VcsBranchOpts): Promise { const lc = `[${executeVcsBranch_createNewBranch.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 672388ad93a52955c8147b4f76b8cb26)`); } let { metaspace, localSpace, activeBranchSpace, sourceBranchSpace, galaxyIbGib, branchName, sourceBranchName, itemPath, } = opts; const validation = validateBranchName(branchName); if (!validation.isValid || !branchName) { throw new Error(`Invalid branch name "${branchName ?? ''}": ${validation.error} (E: 5d1208912ba80526aaf32bf3dd6b5c26)`); } const cleanBranchName = branchName.trim(); const effectiveSourceBranch = sourceBranchName?.trim() || galaxyIbGib.data.policy?.defaultBranch || B2TFS_BRANCH_DEFAULT_NAME; // first ensure that the branchName is unique in the local galaxy. const allBranchInfos = await getAllBranchInfosFromGalaxy({ galaxyIbGib, metaspace }); if (allBranchInfos.some(x => x.branchName.toLowerCase() === cleanBranchName.toLowerCase())) { throw new Error(`branch with branchName "${cleanBranchName}" already exists. (E: 507808912ba80526aaf32bf3dd6b5c26)`); } // get the root from the source branch const { branchIbGib: sourceBranchIbGib, branchSpace: resolvedSourceBranchSpace, rootItemAddr_latest: rootItemAddr, rootItemIbGib_latest: rootItemIbGib, } = await getBranchAndRootItemInfosAndIbGibsAndSpaceFromGalaxyIbGib({ galaxyIbGib, branchName: effectiveSourceBranch, metaspace, }); const effectiveSourceSpace = sourceBranchSpace || activeBranchSpace || resolvedSourceBranchSpace; if (!effectiveSourceSpace) { throw new Error(`(UNEXPECTED) effectiveSourceSpace falsy for branch "${effectiveSourceBranch}". (E: 4b4e62d93288dbb593a1011cdf05ce9b)`); } let targetRootItem: B2tFSItemIbGib_V1 = rootItemIbGib; let normalizedItemPath: string | undefined; if (itemPath && itemPath.trim().length > 0) { normalizedItemPath = itemPath.trim().replace(/\\/g, '/').replace(/^\.\//, ''); /** * this map will be populated by proceding call to walk the branch * graph, which walks the entire branch from rootItem to find the * corresponding itemPath. V2 can optimize this. */ const committedBranchItemsMap = new Map(); await branchCmd_walkBranchGraphForItems({ item: rootItemIbGib, space: effectiveSourceSpace, metaspace, currentRelPath: '', outMap: committedBranchItemsMap, }); const targetItemIbGib = committedBranchItemsMap.get(normalizedItemPath); if (!targetItemIbGib) { throw new Error(`Item '${itemPath}' not found in active branch (source branch: '${effectiveSourceBranch}') (E: ca1617c6476aaecbe8cc78db2c3ca826)`); } targetRootItem = targetItemIbGib; } // create new branch space with predetermined branchId const branchId = await getUUID(); const { space: effectiveTargetSpace, spaceId: newBranchSpaceId } = await getOrCreateBranchSpace({ metaspace, branchName: cleanBranchName, // guaranteed to be new from previous exception check galaxyName: galaxyIbGib.data?.galaxyName, cosmosName: opts.cosmosInfo?.name || galaxyIbGib.data?.cosmosName, spaceId: branchId, }); // Populate new branch space from live dependency graph of targetRootItem await populateBranchSpaceFromGraph({ controlSpace: localSpace, sourceSpace: effectiveSourceSpace, targetBranchSpace: effectiveTargetSpace, rootItemIbGib: targetRootItem, metaspace, }); // At this point, the targetRootItem's entire dependency graph should // exist in both the originating space (activeBrancheSpace) and the new // effectiveTargetSpace // todo: if this is failing, we can do a getDependencyGraph check of the above assertion in both spaces // Create new Branch IbGib and associated addrs. Note that this saves // and registers the new branch ibgib. const sourceBranchAddr = getIbGibAddr({ ibGib: sourceBranchIbGib }); const sourceBranchSpaceId = getSpaceIdFromIb(effectiveSourceSpace.ib); const sourceBranchSqAddr = getSpaceQualifiedIbGibAddr({ spaceId: sourceBranchSpaceId, ibGibAddr: sourceBranchAddr, }); let newBranchIbGib = await createB2tFSBranchIbGib({ branchName: cleanBranchName, rootItem: targetRootItem, space: effectiveTargetSpace, metaspace, parentBranchSqAddr: sourceBranchSqAddr, parentBranchName: sourceBranchIbGib.data.name, scopedItemPath: normalizedItemPath, uuid: branchId, }); // Generate initial snapshot with provenance if identity provided let snapshotIbGib: any; let snapshotAddr: string | undefined; let evolvedAuthorDelegateKeystone: any; if (opts.deviceDelegate && opts.primaryIdentityTjpAddr) { const sourceLatestSnapshotAddr = sourceBranchIbGib.data?.['@snapshot']?.at(-1); const originSnapshotInfos: OriginSnapshotInfo[] | undefined = sourceLatestSnapshotAddr ? [{ snapshotAddr: sourceLatestSnapshotAddr, branchName: sourceBranchIbGib.data.name, branchAddr: sourceBranchAddr, branchTjpAddr: sourceBranchIbGib.rel8ns?.tjp?.[0] || sourceBranchAddr, galaxyName: galaxyIbGib.data.name, galaxyAddr: getIbGibAddr({ ibGib: galaxyIbGib }), galaxyTjpAddr: galaxyIbGib.rel8ns?.tjp?.[0], }] : undefined; const snapRes = await createBranchSnapshotIbGib({ branchIbGib: newBranchIbGib, rootItem: targetRootItem, cosmosInfo: opts.cosmosInfo || { name: (galaxyIbGib.data as any)?.cosmosName }, galaxyInfo: opts.galaxyInfo || { name: galaxyIbGib.data?.name, addr: getIbGibAddr({ ibGib: galaxyIbGib }), tjpAddr: galaxyIbGib.rel8ns?.tjp?.[0], }, originSnapshotInfos, primaryIdentityTjpAddr: opts.primaryIdentityTjpAddr, deviceDelegate: opts.deviceDelegate, space: effectiveTargetSpace, controlSpace: localSpace, metaspace, }); snapshotIbGib = snapRes.snapshotIbGib; snapshotAddr = snapRes.snapshotAddr; evolvedAuthorDelegateKeystone = snapRes.evolvedAuthorDelegateKeystone; // Mutate new branch to record snapshot const mut8Res = await mut8({ src: newBranchIbGib, dataToAddOrPatch: { '@snapshot': [snapshotAddr], }, dna: true, nCounter: true, }); newBranchIbGib = mut8Res.newIbGib as B2tFSBranchIbGib_V1; await persistTransformResult({ resTransform: mut8Res, space: effectiveTargetSpace }); await metaspace.registerNewIbGib({ ibGib: newBranchIbGib, space: effectiveTargetSpace }); } const newBranchAddr = getIbGibAddr({ ibGib: newBranchIbGib }); const newBranchSqAddr = getSpaceQualifiedIbGibAddr({ spaceId: newBranchSpaceId, ibGibAddr: newBranchAddr, }); // Register new sub-branch on the source branch (parent branch) const evolvedSourceBranchIbGib = await registerSubBranchOnParent({ parentBranchIbGib: sourceBranchIbGib, childBranchSqAddr: newBranchSqAddr, space: effectiveSourceSpace, metaspace, }); // If the source branch was the canonical trunk branch (default 'main'), evolve the galaxyIbGib // so its trunkBranchSqAddr points to the evolved trunk branch stone. // Sub-branches branched off non-trunk branches do NOT evolve galaxyIbGib. let updatedGalaxy = galaxyIbGib; const trunkBranchName = (galaxyIbGib.data.policy?.defaultBranch || B2TFS_BRANCH_DEFAULT_NAME).toLowerCase(); if (effectiveSourceBranch.toLowerCase() === trunkBranchName) { const evolvedSourceBranchAddr = getIbGibAddr({ ibGib: evolvedSourceBranchIbGib }); const evolvedTrunkSqAddr = getSpaceQualifiedIbGibAddr({ spaceId: sourceBranchSpaceId, ibGibAddr: evolvedSourceBranchAddr, }); updatedGalaxy = await updateB2tFSGalaxyIbGib({ space: localSpace, metaspace, galaxyIbGib, dataToUpdate: { trunkBranchSqAddr: evolvedTrunkSqAddr, '$@branch': [evolvedTrunkSqAddr], }, }); } const { branches } = await executeVcsBranch_listBranches({ ...opts, branchName: undefined, galaxyIbGib: updatedGalaxy, }); return { branches, createdBranchName: cleanBranchName, createdBranchAddr: newBranchAddr, updatedGalaxy, snapshotIbGib, snapshotAddr, evolvedAuthorDelegateKeystone, }; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } async function executeVcsBranch_listBranches(opts: VcsBranchOpts): Promise { const lc = `[${executeVcsBranch_listBranches.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 265118f9fc182b4e0802b926eb83c826)`); } let { metaspace, galaxyIbGib, currentBranchName, } = opts; const effectiveCurrentBranch = currentBranchName || galaxyIbGib.data.policy?.defaultBranch || B2TFS_BRANCH_DEFAULT_NAME; const allBranchIbGibs = await getAllBranchIbGibsFromGalaxy({ galaxyIbGib, metaspace, }); // no branchName passed in, so we are just listing branches, not // creating a new branch const branches: VcsBranchItemInfo[] = []; for (const branchIbGib of allBranchIbGibs) { const { name } = branchIbGib.data; const branchAddr = getIbGibAddr({ ibGib: branchIbGib }); // #region sanity if (!branchIbGib.rel8ns) { throw new Error(`(UNEXPECTED) branchIbGib.rel8ns falsy? branchAddr: ${branchAddr} (E: 3a0f47a46fb858e6f5ddfb684ceb7826)`); } if (!branchIbGib.rel8ns.b2tfs_item) { throw new Error(`(UNEXPECTED) branchIbGib.rel8ns.b2tfs_item falsy? branchAddr: ${branchAddr} (E: aaa7583adf555e9218a5cfae47540126)`); } if (branchIbGib.rel8ns.b2tfs_item.length === 0) { throw new Error(`(UNEXPECTED) branchIbGib.rel8ns.b2tfs_item empty? branchAddr: ${branchAddr} (E: 4823e871cc889a90e86bbf85f5a00826)`); } // #endregion sanity const rootItemAddr = branchIbGib.rel8ns.b2tfs_item[0]; branches.push({ name, isActive: name === effectiveCurrentBranch, branchAddr, rootItemAddr, }); } return { branches }; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * builds a map of FS path -> B2tFSItemIbGib_V1 */ async function branchCmd_walkBranchGraphForItems({ item, space, metaspace, currentRelPath, outMap, }: { item: B2tFSItemIbGib_V1; space: any; metaspace?: any; currentRelPath: string; outMap: Map; }): Promise { const lc = `[${branchCmd_walkBranchGraphForItems.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: c82a58edda64ffbb550b93cfdbad6826)`); } const { fsType } = item.data; if (currentRelPath) { // set the outMap regardless of item type. outMap.set(currentRelPath, item); } // recursively call if it's a folder if (fsType === 'folder') { if (item.rel8ns) { const childAddrs = item.rel8ns?.[B2TFS_CHILD_ITEM_REL8N_NAME] || []; for (const childAddr of childAddrs) { const childItemIbGib = await getIbGibFromSpace({ addr: childAddr, space, metaspace, }); if (childItemIbGib) { const childRelPath = currentRelPath ? joinPaths(currentRelPath, childItemIbGib.data.name) : childItemIbGib.data.name; await branchCmd_walkBranchGraphForItems({ item: childItemIbGib, space, metaspace, currentRelPath: childRelPath, outMap, }); } else { console.warn(`${lc} (UNEXPECTED) childAddr (${childAddr}) not found in space (${space.ib})? Is this an error? What's up here? We need to investigate this. (W: 732698e07198dd17b9927c089c820826)`) } } } else { console.warn(`${lc} (UNEXPECTED) item.rel8ns falsy? item addr (${getIbGibAddr({ ibGib: item })}). Not sure when this would happen, so investigate this and update this warning if it comes up. (W: 59f9587f0118e0ce371ef1a8dbf7e626)`); } } } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } }