/** * @module galaxy-helper * * B2tFS Galaxy Helper functions: space-qualified address formatting, branch tracking, * unstaging, and restoring committed snapshot paths. * * 100% isomorphic and space-based (zero Node fs/path dependencies). */ import { UUID_REGEXP } from '@ibgib/helper-gib/dist/constants.mjs'; import { getUUID, extractErrorMsg } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs'; import { joinPaths } from '@ibgib/helper-gib/dist/helpers/path-helper.mjs'; import { ROOT } from '@ibgib/ts-gib/dist/V1/constants.mjs'; import { Factory_V1 } from '@ibgib/ts-gib/dist/V1/factory.mjs'; import { mut8 } from '@ibgib/ts-gib/dist/V1/transforms/mut8.mjs'; import { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs'; import { Ib } from '@ibgib/ts-gib/dist/types.mjs'; import { GLOBAL_LOG_A_LOT } from '../../../core-constants.mjs'; import { getIbGibFromSpace, getTjpAddr, isSpaceQualifiedAddr, parseSpaceQualifiedIbGibAddr, resolveLatestIbGibInSpace } from '../../../common/other/ibgib-helper.mjs'; import { MetaspaceService } from '../../../witness/space/metaspace/metaspace-types.mjs'; import { IbGibSpaceAny } from '../../../witness/space/space-base-v1.mjs'; import { putInSpace, } from '../../../witness/space/space-helper.mjs'; import { B2TFS_GALAXY_ATOM, B2TFS_GALAXY_REL8N_NAME, B2tFSGalaxyIbGib_V1, B2tFSGalaxyData_V1, B2tFSGalaxyIb_V1 } from './b2tfs-galaxy-types.mjs'; import { B2tFSItemIbGib_V1, B2TFS_CHILD_ITEM_REL8N_NAME } from '../item/item-types.mjs'; import { parseBranchIb } from '../branch/branch-helpers.mjs'; import { B2TFS_BRANCH_DEFAULT_NAME } from '../branch/branch-constants.mjs'; import { getBranchAndRootItemInfosAndIbGibsAndSpaceFromGalaxyIbGib, getProjectedItemFilename } from '../item/item-helpers.mjs'; import { getSpaceIdFromIb } from '../../../witness/space/metaspace/metaspace-innerspace/metaspace-innerspace-helper.mjs'; import { getGalaxyIb } from '../../galaxy/galaxy-helpers.mjs'; import { GalaxyPresetType, getGalaxyPresetConfig } from '../../galaxy/galaxy-configs.mjs'; import { GalaxyPolicy } from '../../galaxy/galaxy-types.mjs'; const lcFile = `[b2tfs-galaxy-helpers]`; const logalot = GLOBAL_LOG_A_LOT; export const SOFT_ADDR_DATA_KEY_PREFIX = '@'; export const SOFT_ADDR_DATA_KEY_PREFIX_SPACE_QUALIFIED = '$@'; /** * Normalizes repository relative paths without OS-dependent path modules. */ export function normalizeRepoRelPath(p: string, targetDir?: string, worktreeDir?: string): string { let rel = (p || '').replace(/\\/g, '/'); // Strip leading ./ if present (e.g. "./file", ".\file", "././file") rel = rel.replace(/^(\.\/)+/, ''); if (rel === '.') { rel = ''; } let wasAbsolute = false; if (worktreeDir) { const normWorktree = worktreeDir.replace(/\\/g, '/').replace(/\/+$/, ''); if (normWorktree && rel.startsWith(normWorktree)) { rel = rel.slice(normWorktree.length).replace(/^\/+/, ''); wasAbsolute = true; } } if (!wasAbsolute && targetDir) { const normTarget = targetDir.replace(/\\/g, '/').replace(/\/+$/, ''); if (normTarget && rel.startsWith(normTarget)) { rel = rel.slice(normTarget.length).replace(/^\/+/, ''); wasAbsolute = true; if (worktreeDir && targetDir !== worktreeDir) { const normWorktree = worktreeDir.replace(/\\/g, '/').replace(/\/+$/, ''); if (normTarget.startsWith(normWorktree)) { const prefix = normTarget.slice(normWorktree.length).replace(/^\/+/, ''); if (prefix) { rel = rel ? joinPaths(prefix, rel) : prefix; } } } } } if (!wasAbsolute && targetDir && worktreeDir && targetDir !== worktreeDir) { const normTarget = targetDir.replace(/\\/g, '/').replace(/\/+$/, ''); const normWorktree = worktreeDir.replace(/\\/g, '/').replace(/\/+$/, ''); if (normTarget.startsWith(normWorktree)) { const prefix = normTarget.slice(normWorktree.length).replace(/^\/+/, ''); if (prefix) { rel = rel ? joinPaths(prefix, rel) : prefix; } } } rel = rel.replace(/\\/g, '/').replace(/^\/+/, '').replace(/\/+$/, '').replace(/^(\.\/)+/, ''); if (rel === '.') { rel = ''; } return rel; } /** * {@link getB2tFSGalaxyIb} and {@link parseB2tFSGalaxyIb} MUST MATCH. IF EITHER * IS CHANGED, YOU MUST UPDATE THE OTHER * */ export function getB2tFSGalaxyIb({ galaxyId }: { galaxyId: string }): Ib { const lc = `[${getB2tFSGalaxyIb.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 8bc9166ddaa83d56572fae1290559126)`); } if (!UUID_REGEXP.test(galaxyId)) { throw new Error(`invalid galaxyId. Must match UUID_REGEXP: ${UUID_REGEXP.source} (E: 2e5d3e06aceb6f2ec807f6a19b1f8a26)`); } /** * {@link getB2tFSGalaxyIb} and {@link parseB2tFSGalaxyIb} MUST MATCH. IF * EITHER IS CHANGED, YOU MUST UPDATE THE OTHER */ return `${B2TFS_GALAXY_ATOM} ${galaxyId}`; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * {@link getB2tFSGalaxyIb} and {@link parseB2tFSGalaxyIb} MUST MATCH. IF * EITHER IS CHANGED, YOU MUST UPDATE THE OTHER */ export function parseB2tFSGalaxyIb({ ib }: { ib: Ib }): B2tFSGalaxyIb_V1 { const lc = `[${parseB2tFSGalaxyIb.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 9f2bb8f0406459ddd8e360b81c3d3826)`); } /** * {@link getB2tFSGalaxyIb} and {@link parseB2tFSGalaxyIb} MUST MATCH. IF EITHER * IS CHANGED, YOU MUST UPDATE THE OTHER */ const pieces = ib.split(' '); // do we care about the length, even if the atom is right? if (pieces.length !== 2) { throw new Error(`invalid ib. expected to have 2 pieces. (E: b03dd85ff17224b8983fa5c86dd88826)`); } const [atom, galaxyId] = pieces; if (atom !== B2TFS_GALAXY_ATOM) { throw new Error(`invalid ib. atom (${atom}) is not B2TFS_GALAXY_ATOM (${B2TFS_GALAXY_ATOM}) (E: f688b6fa2f983440a85d47f8f5a64826)`); } if (!UUID_REGEXP.test(galaxyId)) { throw new Error(`invalid galaxyId. Must match UUID_REGEXP: ${UUID_REGEXP.source} (E: cfdc38767bedbcf1785626a816c12726)`); } return { atom, galaxyId }; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * Creates a new B2tFSGalaxyIbGib special meta object for a space. */ export async function createB2tFSGalaxyIbGib({ galaxyName = 'code-1', defaultBranch = B2TFS_BRANCH_DEFAULT_NAME, space, metaspace, sqBranchAddr, discriminator, policy, cosmosName, }: { galaxyName?: string; defaultBranch?: string; space: IbGibSpaceAny; metaspace: MetaspaceService; sqBranchAddr: string; discriminator?: string; policy?: GalaxyPolicy; cosmosName?: string; }): Promise { const lc = `${lcFile}[${createB2tFSGalaxyIbGib.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 7b2118e6beeefd9658c9a94a89bb1826)`); } if (!isSpaceQualifiedAddr(sqBranchAddr)) { throw new Error(`invalid sqBranchAddr (${sqBranchAddr}) (E: d905089debc8983077b7172767f8c926)`); } const spaceId = getSpaceIdFromIb(space.ib); const preset = getGalaxyPresetConfig(galaxyName); const resolvedDiscriminator = discriminator || preset?.discriminator || GalaxyPresetType.code; const resolvedPolicy: GalaxyPolicy = policy || preset?.policy || { topology: 'branching', role: 'intrinsic', storageMode: 'text', defaultBranch: defaultBranch || B2TFS_BRANCH_DEFAULT_NAME, }; const data: B2tFSGalaxyData_V1 = { galaxyName, cosmosName, discriminator: resolvedDiscriminator, policy: resolvedPolicy, mySpaceId: spaceId, uuid: await getUUID(), classname: 'B2tFSGalaxyIbGib_V1', trunkBranchSqAddr: sqBranchAddr, '$@branch': [sqBranchAddr], stagedPaths: {}, staged_item: [], }; const res = await Factory_V1.firstGen({ parentIbGib: ROOT, ib: getGalaxyIb({ galaxyName, topology: resolvedPolicy.topology, storageMode: resolvedPolicy.storageMode ?? 'text', concreteClassname: 'B2tFSGalaxyIbGib_V1', }), data, tjp: { timestamp: true }, dna: true, nCounter: true, }); const galaxyIbGib = res.newIbGib as B2tFSGalaxyIbGib_V1; await metaspace.persistTransformResult({ resTransform: res, space }); await metaspace.registerNewIbGib({ ibGib: galaxyIbGib, space }); // Ensure special anchor exists in space await metaspace.getSpecialIbGib({ type: B2TFS_GALAXY_ATOM, initialize: true, space, }); // Link repository galaxy timeline to special ibgib anchor await metaspace.rel8ToSpecialIbGib({ type: B2TFS_GALAXY_ATOM, rel8nName: B2TFS_GALAXY_REL8N_NAME, ibGibsToRel8: [galaxyIbGib], space, linked: true, }); if (logalot) { console.log(`${lc} Created galaxy IbGib: ${galaxyIbGib.ib} (I: 039e9e584d6a11e1b85797b89a0c6826)`); } return galaxyIbGib; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)} (E: fa3da104817ebf8db14172884ff2c426)`); throw error; } finally { if (logalot) { console.log(`${lc} complete. (I: 40f5d280cfd8ec0ce39386a85ce8f826)`); } } } /** * Retrieves authoritative B2tFSGalaxyIbGib_V1 from space by address or via * special ibgib anchor. */ export async function getB2tFSGalaxyIbGib({ space, metaspace, galaxyAddr, }: { /** * space for galaxy. atow (09/2026), should be the default local user space * (not a branch space). */ space: IbGibSpaceAny; /** * ref to metaspace to driving getting at the galaxy via the "special" ibgib. * * @throws if both this and {@link galaxyAddr} are falsy * * @see {@link MetaspaceService.getSpecialRel8dIbGibs} */ metaspace?: MetaspaceService; /** * if provided, this will drive getting the galaxy. if not, will get the * "special" anchor ibgib via {@link metaspace} * * @throws if both this and {@link metaspace} are falsy */ galaxyAddr?: string; }): Promise { const lc = `${lcFile}[${getB2tFSGalaxyIbGib.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: bddb12b7b10ddc9b86e57cae9958f826)`); } let baseGalaxyIbGib: B2tFSGalaxyIbGib_V1 | undefined; if (galaxyAddr) { baseGalaxyIbGib = await getIbGibFromSpace({ addr: galaxyAddr, space, }); } else if (metaspace) { const specialIbGibs = await metaspace.getSpecialRel8dIbGibs({ type: B2TFS_GALAXY_ATOM, rel8nName: B2TFS_GALAXY_REL8N_NAME, space, }); baseGalaxyIbGib = specialIbGibs?.at(0); } else { throw new Error(`(UNEXPECTED) both galaxyAddr and metaspace falsy? one of these is required. (E: fd8e58f46f668ba605fc20186a5a1626)`); } if (!baseGalaxyIbGib) { if (galaxyAddr) { if (logalot) { console.log(`Could not get galaxyAddr (${galaxyAddr}) from space (${space.ib}). Not initialized? (I: d7da7f279a08d9c2a8971ac8d14e0826)`); } } else { if (logalot) { console.log(`Could not get galaxyIbGib via metaspace special anchor type ${B2TFS_GALAXY_ATOM} and rel8nName ${B2TFS_GALAXY_REL8N_NAME}. Not initialized? (I: a1a26c3ac9086522db895d783999e826)`); } } return undefined; /* <<<< returns early */ } const baseGalaxyAddr = getIbGibAddr({ ibGib: baseGalaxyIbGib }); const galaxyTjpAddr = getTjpAddr({ ibGib: baseGalaxyIbGib }); if (logalot) { console.log(`${lc} baseGalaxyAddr: ${baseGalaxyAddr}, tjpAddr: ${galaxyTjpAddr} (I: 0640288ad6a6ca19b8578e6e841b4826)`); console.log(`${lc} baseGalaxyIbGib stagedPaths: ${JSON.stringify(baseGalaxyIbGib.data.stagedPaths)}`); } // Resolve latest tip of the galaxy timeline in space using pure helper const latestGalaxyIbGib = await resolveLatestIbGibInSpace({ ibGib: baseGalaxyIbGib, space, }); if (!latestGalaxyIbGib) { throw new Error(`(UNEXPECTED) baseGalaxyIbGib (${baseGalaxyAddr}) exists but we couldn't get the latest galaxy ibGib? (E: d1adc82a8cc82fe3f8aa8d136aede826)`); } if (logalot) { console.log(`${lc} foundLatest stagedPaths: ${JSON.stringify(latestGalaxyIbGib.data.stagedPaths)}, latestAddr: ${getIbGibAddr({ ibGib: latestGalaxyIbGib })} (I: e7fcf8ebba68e907a8378935eb10d626)`); } return latestGalaxyIbGib; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)} (E: 3d2b1875548836a2f18fc698abfbb326)`); throw error; } finally { if (logalot) { console.log(`${lc} complete. (I: e3822fa5a5085fcb52826018b4ca2826)`); } } } /** * Deduplicates branch entries by branch name and merges new branch addresses * into existing addresses without dropping other registered branches. */ export function mergeBranchAddrs({ existingSqAddrs, newSqAddrs, }: { existingSqAddrs: string[], newSqAddrs: string[], }): string[] { const lc = `[${mergeBranchAddrs.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 4d36e8695c2354f2e8dd64e82707d826)`); } const map = new Map(); const extractBranchNameFromBranchAddr = (sqAddr: string) => { const sqInfo = parseSpaceQualifiedIbGibAddr({ sqAddr }); const { ib } = sqInfo; const { branchName } = parseBranchIb({ ib }) return branchName; } for (const addr of existingSqAddrs) { if (!addr) { throw new Error(`(UNEXPECTED) addr falsy in existingAddrs? (E: 9759f198d83888f5db428e182388b826)`); } const branchName = extractBranchNameFromBranchAddr(addr); map.set(branchName, addr); } for (const addr of newSqAddrs) { if (!addr) { throw new Error(`(UNEXPECTED) addr falsy in newAddrs? (E: 46b6380cc5582735c814d4584555d826)`); } const branchName = extractBranchNameFromBranchAddr(addr); map.set(branchName, addr); } return Array.from(map.values()); } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * Updates B2tFSGalaxyIbGib_V1 in space purely via single-pass mut8 transform. * Cross-space branch pointers are merged into data['$@branch'] soft links. */ export async function updateB2tFSGalaxyIbGib({ space, metaspace, galaxyIbGib, dataToUpdate, }: { space: IbGibSpaceAny; metaspace: MetaspaceService; galaxyIbGib: B2tFSGalaxyIbGib_V1; /** * ## Note on data['@branch'] * * if you are updating data['@branch'], then this should be the entire new * array. This will delete the old value completely, and set it to this new * array. */ dataToUpdate?: Partial; }): Promise { const lc = `${lcFile}[${updateB2tFSGalaxyIbGib.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 5536885f77b88e42741b55c890efe826)`); } /** * when mut8 is called, we have to be careful about the merge process. * the mut8 uses a naive merge strategy, so we need to take hold of it * manually. * * We use dataToRemove, which happens first, so that dataToPatch is * cleanly added. */ const dataToRemove: Record = {}; /** * see {@link dataToRemove} */ const dataToPatch: Partial = { ...dataToUpdate, }; if (!dataToUpdate || Object.keys(dataToUpdate).length === 0) { throw new Error(`(UNEXPECTED) no dataToUpdate? this may be correct, but atow (08/2026), I'm assuming this is the whole point of calling this function. I don't know why the agents made it optional, so if this error surfaces, re-examine this. (E: d0e06daa7748d6def7cd7a08b9d1d826)`); } if (!!dataToUpdate?.['$@branch'] && !!galaxyIbGib.data['$@branch']) { dataToRemove['$@branch'] = ''; } // I think an agent did this in an attempt to green a test. not sure if it's needed, since the patch process does not try to merge strings, rather, it just replaces them (so removing them before patching would not be needed) if (dataToUpdate.stagedPaths) { dataToRemove.stagedPaths = ''; } // I started to add this, until I thought of the above comment about stagedPaths. So hmm. should try the tests with the above commented out. (though I don't think it hurts per se) // if (dataToUpdate.staged_item) { dataToRemove.staged_item = ''; } const resTransform = await mut8({ src: galaxyIbGib, dataToRemove: Object.keys(dataToRemove).length > 0 ? dataToRemove : undefined, dataToAddOrPatch: dataToPatch, dna: true, nCounter: true, }); const currentGalaxyIbGib = resTransform.newIbGib as B2tFSGalaxyIbGib_V1; if (logalot) { console.log(`[updateB2tFSGalaxyIbGib] immediately after mut8: newIbGib.data: ${JSON.stringify(currentGalaxyIbGib?.data)}, n: ${currentGalaxyIbGib?.data?.n}, addr: ${getIbGibAddr({ ibGib: currentGalaxyIbGib })}, srcAddr: ${getIbGibAddr({ ibGib: galaxyIbGib })}`); } await metaspace.persistTransformResult({ resTransform, space }); await metaspace.registerNewIbGib({ ibGib: currentGalaxyIbGib, space }); // Diagnostic: verify resolveLatestIbGibInSpace finds the newly written frame if (logalot) { try { const diagResolved = await resolveLatestIbGibInSpace({ ibGib: galaxyIbGib, space }); const newAddr = getIbGibAddr({ ibGib: currentGalaxyIbGib }); const resolvedAddr = getIbGibAddr({ ibGib: diagResolved }); console.log(`[updateB2tFSGalaxyIbGib] after persist+register resolveLatestIbGibInSpace: resolvedAddr=${resolvedAddr}, newAddr=${newAddr}, match=${resolvedAddr === newAddr}, resolvedN=${diagResolved?.data?.n}`); } catch (diagErr) { console.error(`[updateB2tFSGalaxyIbGib] resolveLatestIbGibInSpace diagnostic error: ${diagErr} (E: 8e2293ff521be749c46ad1255acb2826)`); } } return currentGalaxyIbGib; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)} (E: 480608b166b811f81334d59506bf4726)`); throw error; } finally { if (logalot) { console.log(`${lc} complete. (I: 7c77287267d81c503d9d814a1936de26)`); } } } export interface UnstagePathsFromGalaxyOpts { galaxyIbGib: B2tFSGalaxyIbGib_V1; paths?: string[]; targetDir?: string; activeWorktreeDir?: string; /** * space that has the {@link galaxyIbGib} */ space: IbGibSpaceAny; metaspace: MetaspaceService; all?: boolean; } export interface UnstagePathsFromGalaxyResult { updatedGalaxy: B2tFSGalaxyIbGib_V1; unstagedPaths: string[]; } /** * Unstages specified paths (or all paths if `all` or empty `paths`) from `galaxyIbGib.data.stagedPaths` * and `galaxyIbGib.data.staged_item`. */ export async function unstagePathsFromGalaxy({ galaxyIbGib, paths = [], targetDir = '', activeWorktreeDir, space, metaspace, all = false, }: UnstagePathsFromGalaxyOpts): Promise { const lc = `${lcFile}[${unstagePathsFromGalaxy.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: adf91a3648a734701d01b1010a8c4826)`); } const currentStagedPaths = { ...(galaxyIbGib.data?.stagedPaths || {}) }; let currentStagedItems = [...(galaxyIbGib.data?.staged_item || [])]; const unstagedPaths: string[] = []; const worktreeDir = activeWorktreeDir || targetDir; if (all || paths.length === 0 || (paths.length === 1 && (paths[0] === '.' || paths[0] === ''))) { for (const relPath of Object.keys(currentStagedPaths)) { unstagedPaths.push(relPath); } const updatedGalaxy = await updateB2tFSGalaxyIbGib({ space, metaspace, galaxyIbGib, dataToUpdate: { stagedPaths: {}, staged_item: [], }, }); return { updatedGalaxy, unstagedPaths }; } for (const p of paths) { const relPath = normalizeRepoRelPath(p, targetDir, worktreeDir); const targetKeys = Object.keys(currentStagedPaths).filter((k) => { return k === relPath || k.startsWith(relPath + '/'); }); for (const key of targetKeys) { const record = currentStagedPaths[key]; if (record && record.itemAddr) { currentStagedItems = currentStagedItems.filter((addr) => addr !== record.itemAddr); } delete currentStagedPaths[key]; if (!unstagedPaths.includes(key)) { unstagedPaths.push(key); } } } const updatedGalaxy = await updateB2tFSGalaxyIbGib({ space, metaspace, galaxyIbGib, dataToUpdate: { stagedPaths: currentStagedPaths, staged_item: currentStagedItems, }, }); return { updatedGalaxy, unstagedPaths }; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)} (E: f839a88fb40ab2c808bf7f7807ba4826)`); throw error; } finally { if (logalot) { console.log(`${lc} complete. (I: 3d75881c0a3404fd73241bc3744dcc26)`); } } } export interface RestoreWorktreePathsFromSnapshotOpts { paths: string[]; targetDir?: string; activeWorktreeDir: string; branchName: string; workspaceSpace?: IbGibSpaceAny; metaspace: MetaspaceService; galaxyIbGib: B2tFSGalaxyIbGib_V1; } export interface RestoreWorktreePathsFromSnapshotResult { restoredPaths: string[]; } /** * Restores specified paths in the working tree from the committed snapshot of * the active branch. */ export async function restoreWorktreePathsFromSnapshot({ paths, targetDir, activeWorktreeDir, branchName, workspaceSpace, metaspace, galaxyIbGib, }: RestoreWorktreePathsFromSnapshotOpts): Promise { const lc = `${lcFile}[${restoreWorktreePathsFromSnapshot.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: fa43a9fa775855dfd8378ca631417826)`); } const { branchIbGib, branchInfo, branchSpace, rootItemAddr_latest, rootItemIbGib_latest: rootItem, } = await getBranchAndRootItemInfosAndIbGibsAndSpaceFromGalaxyIbGib({ galaxyIbGib, branchName, metaspace, }); const committedItemMap = new Map(); await restoreCmd_collectCommittedItems({ item: rootItem, parentRelPath: '', isRoot: true, space: branchSpace, metaspace, outMap: committedItemMap, }); let targetWorkspaceSpace = workspaceSpace; if (!targetWorkspaceSpace && metaspace) { const spaces: any[] = (await metaspace.getLocalUserSpaces({ lock: false })) || []; targetWorkspaceSpace = spaces.find(s => s.data?.classname?.includes('WorkspaceProjectionSpace') && (!activeWorktreeDir || s.data?.workspaceRoot === activeWorktreeDir) ); } const restoredPaths: string[] = []; if (paths.length === 0 || (paths.length === 1 && (paths[0] === '.' || paths[0] === ''))) { if (targetWorkspaceSpace) { await putInSpace({ space: targetWorkspaceSpace, ibGib: rootItem, }); } for (const entry of committedItemMap.values()) { restoredPaths.push(entry.relPath); } } else { for (const p of paths) { const relPath = normalizeRepoRelPath(p, targetDir, activeWorktreeDir); let matchedCount = 0; for (const entry of committedItemMap.values()) { if (entry.relPath === relPath || (entry.rawRelPath && entry.rawRelPath === relPath) || entry.relPath.startsWith(relPath + '/')) { if (targetWorkspaceSpace) { await targetWorkspaceSpace.witness({ data: { cmd: 'put', subPath: entry.parentRelPath || undefined, }, ibGibs: [entry.item], }); } if (!restoredPaths.includes(entry.relPath)) { restoredPaths.push(entry.relPath); } matchedCount++; } } if (matchedCount === 0) { throw new Error(`pathspec '${p}' did not match any committed file(s) in snapshot (E: eab774c126885663183fede7ec5d2926)`); } } } return { restoredPaths }; } catch (error) { console.error(`${lc} ${extractErrorMsg(error)} (E: f962a38c605a44d3251d3e8883b3c826)`); throw error; } finally { if (logalot) { console.log(`${lc} complete. (I: 93460761e9786170d861f75827a5c726)`); } } } // #region restoreCmd_collectCommittedItems async function restoreCmd_collectCommittedItems({ item, parentRelPath, isRoot = false, space, metaspace, outMap, }: { item: B2tFSItemIbGib_V1; parentRelPath: string; isRoot?: boolean; space: IbGibSpaceAny; metaspace: MetaspaceService; outMap: Map; }): Promise { if (!item || !item.data) { return; } const { fsType, name } = item.data; if (isRoot) { const childAddrs = item.rel8ns?.[B2TFS_CHILD_ITEM_REL8N_NAME] || []; for (const childAddr of childAddrs) { const childItem = await getIbGibFromSpace({ addr: childAddr, space, metaspace, }); if (childItem) { await restoreCmd_collectCommittedItems({ item: childItem, parentRelPath: '', isRoot: false, space, metaspace, outMap, }); } } } else { const itemName = getProjectedItemFilename(item) || name; const relPath = parentRelPath ? joinPaths(parentRelPath, itemName) : itemName; const rawRelPath = (name && name !== itemName) ? (parentRelPath ? joinPaths(parentRelPath, name) : name) : undefined; outMap.set(relPath, { relPath, rawRelPath, parentRelPath, item }); if (fsType === 'folder') { const childAddrs = item.rel8ns?.[B2TFS_CHILD_ITEM_REL8N_NAME] || []; for (const childAddr of childAddrs) { const childItem = await getIbGibFromSpace({ addr: childAddr, space, metaspace, }); if (childItem) { await restoreCmd_collectCommittedItems({ item: childItem, parentRelPath: relPath, isRoot: false, space, metaspace, outMap, }); } } } } } // #endregion