/** * @module status-helper * * Pure status inspection helpers and pending `.ib.*.md` comment metadata detection. */ import { extractErrorMsg } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs'; import { joinPaths } from '@ibgib/helper-gib/dist/helpers/path-helper.mjs'; import { getIbGibAddr, getIbAndGib } from '@ibgib/ts-gib/dist/helper.mjs'; import { GLOBAL_LOG_A_LOT } from '../../../core-constants.mjs'; import { IbGibSpaceAny } from '../../../witness/space/space-base-v1.mjs'; import { MetaspaceService } from '../../../witness/space/metaspace/metaspace-types.mjs'; import { CMD_MODIFIER_WORKSPACE_SCAN } from '../../../witness/space/workspace-projection-space/workspace-projection-space-constants.mjs'; import { WorkspaceScanResultData } from '../../../witness/space/workspace-projection-space/workspace-projection-space-types.mjs'; import { B2tFSItemIbGib_V1, B2TFS_CHILD_ITEM_REL8N_NAME } from '../item/item-types.mjs'; import { getB2tFSGalaxyIbGib, } from '../b2tfs-galaxy/b2tfs-galaxy-helpers.mjs'; import { B2tFSStagedItemRecord, B2tFSGalaxyIbGib_V1 } from '../b2tfs-galaxy/b2tfs-galaxy-types.mjs'; import { resolveContextualBranchName, } from '../branch/branch-helpers.mjs'; import { getIbGibFromSpace } from '../../../common/other/ibgib-helper.mjs'; import { getFromSpace } from '../../../witness/space/space-helper.mjs'; import { getBranchAndRootItemInfosAndIbGibsAndSpaceFromGalaxyIbGib, getProjectedItemFilename } from '../item/item-helpers.mjs'; import { B2TFS_BRANCH_DEFAULT_NAME } from '../branch/branch-constants.mjs'; import { B2tFSBranchIbGib_V1 } from '../branch/branch-types.mjs'; import { getLatestBranchSnapshot } from '../snapshot/snapshot-helpers.mjs'; import { PendingCommentInfo, VcsStatusItem } from './status-types.mjs'; const logalot = GLOBAL_LOG_A_LOT; const lcFile = `[status-helper]`; /** * Returns true if filename is a `.ib.*.md` comment metadata file. */ export function isCommentMetadataFilename(filename: string): boolean { return filename.startsWith('.ib.') && filename.endsWith('.md') && filename.length > '.ib..md'.length; } /** * Extracts the inner topic / filename from `.ib..md`. */ export function extractCommentTopicName(filename: string): string { if (!isCommentMetadataFilename(filename)) { return ''; } return filename.slice(4, -3); // strips leading '.ib.' and trailing '.md' } /** * Pure helper to walk the branch graph items. */ export async function walkBranchGraph({ item, space, metaspace, currentRelPath, outMap, }: { item: B2tFSItemIbGib_V1; space: IbGibSpaceAny; metaspace?: MetaspaceService; currentRelPath: string; outMap: Map; }): Promise { const lc = `[${walkBranchGraph.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 2bcc48c4fdd884784497bee826fbe126)`); } if (!item || !item.data) { return; } const { fsType, fileHash } = item.data; if (currentRelPath) { outMap.set(currentRelPath, { relPath: currentRelPath, fileHash, fsType }); } if (fsType === 'folder') { if (!item.rel8ns) { throw new Error(`(UNEXPECTED) item.rel8ns falsy? item.data.fsType === 'folder', so we should at least have rel8ns.tjp (E: a1271821cef893c375f390755fc89626)`); } const childAddrs = item.rel8ns?.[B2TFS_CHILD_ITEM_REL8N_NAME] || []; if (childAddrs.length > 0) { const bareAddrs = childAddrs.map(a => a.includes('@') ? a.split('@').slice(1).join('@') : a); const batchMap = new Map(); const resGet = await getFromSpace({ addrs: bareAddrs, space }); if (resGet.success && resGet.ibGibs) { for (const child of resGet.ibGibs) { batchMap.set(getIbGibAddr({ ibGib: child }), child as B2tFSItemIbGib_V1); } } await Promise.all(childAddrs.map(async (childAddr, idx) => { const bareAddr = bareAddrs[idx]; const childItem = batchMap.get(bareAddr) ?? await getIbGibFromSpace({ addr: childAddr, space, }); if (childItem && childItem.data) { const childName = getProjectedItemFilename(childItem) || childItem.data.name; const childRelPath = currentRelPath ? joinPaths(currentRelPath, childName) : childName; await walkBranchGraph({ item: childItem, space, metaspace, currentRelPath: childRelPath, outMap, }); } })); } } } catch (error) { console.error(`${lc} ${extractErrorMsg(error)}`); throw error; } finally { if (logalot) { console.log(`${lc} complete.`); } } } /** * Opts for {@link getRepoStatus} */ export interface GetRepoStatusOpts { galaxyIbGib?: B2tFSGalaxyIbGib_V1; workspaceSpace?: any; localSpace?: any; activeBranchSpace?: any; metaspace?: any; b2tfsGalaxyRoot?: string; targetDir?: string; vcsPath?: string; vcsFolderName?: string; filterFilePatterns?: string[]; } /** * Result for {@link getRepoStatus} */ export interface RepoStatusResult { branchName: string; activeWorktreeDir: string; staged: VcsStatusItem[]; modified: VcsStatusItem[]; deleted: VcsStatusItem[]; untracked: VcsStatusItem[]; pendingComments: PendingCommentInfo[]; } /** * Computes complete repository status, including staged, modified, deleted, * untracked, and mapped pending `.ib.*.md` comment files via * WorkspaceProjectionSpace. * * @see {@link GetRepoStatusOpts} * @see {@link RepoStatusResult} */ export async function getRepoStatus({ galaxyIbGib, workspaceSpace, localSpace, activeBranchSpace: givenActiveBranchSpace, metaspace, b2tfsGalaxyRoot, targetDir, vcsFolderName = '.vcsgib', filterFilePatterns = [], }: GetRepoStatusOpts): Promise { const lc = `${lcFile}[${getRepoStatus.name}]`; galaxyIbGib ??= await getB2tFSGalaxyIbGib({ space: localSpace, metaspace, }); if (!galaxyIbGib) { throw new Error(`galaxyIbGib falsy and couldn't get any index ibgib in the localSpace (${localSpace.ib}) via metaspace (E: 8aaf983c3166024dead6ad7922161426)`); } const branchName = resolveContextualBranchName({ targetDir: targetDir ?? '', b2tfsGalaxyRoot: b2tfsGalaxyRoot ?? '', galaxyIbGib }); const activeWorktreeDir = branchName === B2TFS_BRANCH_DEFAULT_NAME ? (b2tfsGalaxyRoot || '') : (b2tfsGalaxyRoot ? joinPaths(b2tfsGalaxyRoot, 'b', branchName) : joinPaths('b', branchName)); let rootItem: B2tFSItemIbGib_V1 | undefined; let activeBranchSpace: any = givenActiveBranchSpace; let branchIbGib: B2tFSBranchIbGib_V1 | undefined; try { const branchAndRootRes = await getBranchAndRootItemInfosAndIbGibsAndSpaceFromGalaxyIbGib({ galaxyIbGib, branchName, metaspace, }); activeBranchSpace = activeBranchSpace || branchAndRootRes.branchSpace; rootItem = branchAndRootRes.rootItemIbGib_latest || branchAndRootRes.rootItemIbGib; branchIbGib = branchAndRootRes.branchIbGib; } catch (error) { // If branch is not yet in index, leave rootItem undefined if (logalot) { console.log(`${lc} (SUPPRESSED) error: ${extractErrorMsg(error)} (E: a88ab80c909d4307d8e68b5241935826)`); } } const stagedMap = new Map(); const galaxyStagedPaths = galaxyIbGib.data.stagedPaths || {}; for (const [relPath, itemRec] of Object.entries(galaxyStagedPaths)) { stagedMap.set(relPath, itemRec as B2tFSStagedItemRecord); } const branchItemsMap = new Map(); let physicalItemsMap = new Map(); let pendingComments: PendingCommentInfo[] = []; let targetWorkspaceSpace = workspaceSpace; if (!targetWorkspaceSpace && metaspace) { const localSpaces = (await metaspace.getLocalUserSpaces({ lock: false })) || []; targetWorkspaceSpace = localSpaces.find(s => s.data?.classname?.includes('WorkspaceProjectionSpace') && (!activeWorktreeDir || s.data?.workspaceRoot === activeWorktreeDir) ); } await Promise.all([ (async () => { const currentRootItemAddr = rootItem ? getIbGibAddr({ ibGib: rootItem }) : undefined; if (branchIbGib && activeBranchSpace) { const snapshot = await getLatestBranchSnapshot({ branchIbGib, space: activeBranchSpace, }).catch(() => undefined); const snapshotRootAddr = snapshot?.data?.items?.['']?.[0]; const isSnapshotFresh = !currentRootItemAddr || snapshotRootAddr === currentRootItemAddr; if (isSnapshotFresh && snapshot?.data?.items) { for (const [relPath, [itemAddr, binAddr]] of Object.entries(snapshot.data.items)) { if (!relPath || relPath === '' || relPath === '.') { continue; } if (binAddr) { const { ib } = getIbAndGib({ ibGibAddr: binAddr }); const fileHash = ib.startsWith('bin ') ? ib.slice(4) : undefined; branchItemsMap.set(relPath, { relPath, fileHash, fsType: 'file', }); } else { const item = await getIbGibFromSpace({ addr: itemAddr, space: activeBranchSpace, }).catch(() => undefined); const fsType = item?.data?.fsType ?? 'folder'; branchItemsMap.set(relPath, { relPath, fileHash: item?.data?.fileHash, fsType, }); } } return; } } if (rootItem && activeBranchSpace) { await walkBranchGraph({ item: rootItem, space: activeBranchSpace, metaspace, currentRelPath: '', outMap: branchItemsMap, }); } })(), (async () => { if (targetWorkspaceSpace) { const scanRes = await targetWorkspaceSpace.witness({ data: { cmd: 'get', cmdModifiers: [CMD_MODIFIER_WORKSPACE_SCAN], }, }); const scanData = (scanRes?.data as any)?.scanResult as WorkspaceScanResultData; if (scanData?.files) { physicalItemsMap = scanData.files; } if (scanData?.pendingComments) { pendingComments = scanData.pendingComments; } } })(), ]); if (logalot) { const rootItemAddr = rootItem ? getIbGibAddr({ ibGib: rootItem }) : undefined; console.log(`${lcFile}[getRepoStatus] branch: ${branchName}, branchSpace: ${activeBranchSpace?.data?.name || activeBranchSpace?.ib}, branchAddrs: ${JSON.stringify(galaxyIbGib?.data?.['$@branch'])}, rootItemAddr: ${rootItemAddr}`); console.log(`${lcFile}[getRepoStatus] branchItemsMap keys: ${JSON.stringify(Array.from(branchItemsMap.keys()))}`); for (const [k, v] of branchItemsMap.entries()) { console.log(`${lcFile}[getRepoStatus] branch item '${k}': fileHash=${v.fileHash}`); } console.log(`${lcFile}[getRepoStatus] physicalItemsMap keys: ${JSON.stringify(Array.from(physicalItemsMap.keys()))}`); for (const [k, v] of physicalItemsMap.entries()) { console.log(`${lcFile}[getRepoStatus] physical item '${k}': fileHash=${v.fileHash}`); } } const staged: VcsStatusItem[] = []; const modified: VcsStatusItem[] = []; const deleted: VcsStatusItem[] = []; const untracked: VcsStatusItem[] = []; for (const [relPath, stagedRec] of stagedMap.entries()) { const isBranchItem = branchItemsMap.has(relPath); const stagedType = stagedRec.isDeleted ? 'deleted' : (isBranchItem ? 'modified' : 'new'); staged.push({ path: relPath, fsType: stagedRec.fsType || 'file', status: 'staged', stagedType, }); } for (const [relPath, physItem] of physicalItemsMap.entries()) { // Directories themselves are not tracked as leaf items; empty directories are ignored (Git semantics) if (physItem.isDirectory) { continue; } const stagedRec = stagedMap.get(relPath); if (stagedRec) { // If path was staged for deletion but exists physically, it is untracked if (stagedRec.isDeleted) { untracked.push({ path: relPath, fsType: 'file', status: 'untracked', }); } continue; } const branchItem = branchItemsMap.get(relPath); if (!branchItem) { untracked.push({ path: relPath, fsType: 'file', status: 'untracked', }); } else { if (physItem.fileHash && branchItem.fileHash && physItem.fileHash !== branchItem.fileHash) { if (logalot) { console.log(`${lcFile}[getRepoStatus] MODIFIED: '${relPath}' phys=${physItem.fileHash} vs branch=${branchItem.fileHash}`); } modified.push({ path: relPath, fsType: 'file', status: 'modified', }); } } } for (const [relPath, branchItem] of branchItemsMap.entries()) { if (!relPath || relPath === '.' || relPath === '') { continue; } if (!physicalItemsMap.has(relPath) && !stagedMap.has(relPath)) { deleted.push({ path: relPath, fsType: branchItem.fsType, status: 'deleted', }); } } return { branchName, activeWorktreeDir, staged, modified, deleted, untracked, pendingComments, }; }