/** * @module log-cmd * * Isomorphic execution engine for `vcs log`. * Walks active branch or item timeline history backward in batched operations, * and returns formatted commit and comment records. */ import { extractErrorMsg, unique } from '@ibgib/helper-gib/dist/helpers/utils-helper.mjs'; import { getIbGibAddr } from '@ibgib/ts-gib/dist/helper.mjs'; import { GLOBAL_LOG_A_LOT } from '../../../core-constants.mjs'; import { CommentIbGib_V1 } from '../../../common/comment/comment-types.mjs'; import { IbGibSpaceAny } from '../../../witness/space/space-base-v1.mjs'; import { resolveContextualBranchName } from '../branch/branch-helpers.mjs'; import { B2tFSItemIbGib_V1, B2TFS_CHILD_ITEM_REL8N_NAME } from '../item/item-types.mjs'; import { B2tFSBranchIbGib_V1 } from '../branch/branch-types.mjs'; import { getBranchAndRootItemInfosAndIbGibsAndSpaceFromGalaxyIbGib } from '../item/item-helpers.mjs'; import { normalizeRepoRelPath } from '../b2tfs-galaxy/b2tfs-galaxy-helpers.mjs'; import { logTreeHierarchyDiagnostic, shortAddr, TRACE_VCS_PREFIX } from '../branching-diagnostic-helpers.mjs'; import { VcsLogOpts, VcsLogResult, VcsLogItem } from './command-types.mjs'; import { getIbGibFromSpace, getIbGibsFromSpace, resolveLatestIbGibsInSpace } from '../../../common/other/ibgib-helper.mjs'; import { joinPaths } from '@ibgib/helper-gib/dist/helpers/path-helper.mjs'; const lcFile = `[log-cmd]`; const logalot = GLOBAL_LOG_A_LOT; export async function executeVcsLog({ metaspace, galaxyIbGib, filePath, branchName: explicitBranchName, allComments = false, b2tfsGalaxyRoot = '', targetDir = b2tfsGalaxyRoot, }: VcsLogOpts): Promise { const lc = `${lcFile}[${executeVcsLog.name}]`; try { if (logalot) { console.log(`${lc} starting... (I: 4f79a8c2c76b572e081d6e58a0338826)`); } const branchName = explicitBranchName || resolveContextualBranchName({ targetDir: targetDir || b2tfsGalaxyRoot, b2tfsGalaxyRoot, galaxyIbGib, }); if (!branchName) { throw new Error(`(UNEXPECTED) branchName falsy? (E: 3f236889705ddb4de8f88d080e6cc826)`); } const { branchIbGib, branchSpace, rootItemAddr, rootItemAddr_latest, rootItemIbGib, rootItemIbGib_latest, } = await getBranchAndRootItemInfosAndIbGibsAndSpaceFromGalaxyIbGib({ galaxyIbGib, branchName, metaspace, }); if (!branchIbGib) { throw new Error(`(UNEXPECTED) branchIbGib falsy for branch ${branchName}? (E: 4a2f8b9195ce40bb8e9c1db166a01826)`); } if (!branchSpace) { throw new Error(`(UNEXPECTED) branchSpace falsy for branch ${branchName}? (E: 9c28e9f50db84e6db582a87d0c3d9a26)`); } if (filePath) { return await executeVcsLogFile({ filePath, targetDir, b2tfsGalaxyRoot, branchName, branchSpace, rootItemIbGib, rootItemAddr, metaspace, }); } else { return await executeVcsLogBranch({ branchIbGib, branchSpace, branchName, allComments, metaspace, }); } } catch (error) { console.error(`${lc} ${extractErrorMsg(error)} (E: 70db81a942bc4e5781a74d49cf308b26)`); throw error; } finally { if (logalot) { console.log(`${lc} complete. (I: e5cf48c58e1c3018949e0d38e47ebc26)`); } } } async function executeVcsLogFile({ filePath, targetDir, b2tfsGalaxyRoot, branchName, branchSpace, rootItemIbGib, rootItemAddr, metaspace, }: { filePath: string; targetDir: string; b2tfsGalaxyRoot: string; branchName: string; branchSpace: IbGibSpaceAny; rootItemIbGib?: B2tFSItemIbGib_V1; rootItemAddr?: string; metaspace: any; }): Promise { const normalizedRelPath = normalizeRepoRelPath(filePath, targetDir, b2tfsGalaxyRoot); if (!rootItemIbGib && rootItemAddr) { rootItemIbGib = await getIbGibFromSpace({ addr: rootItemAddr, space: branchSpace, metaspace, }); } if (!rootItemIbGib) { throw new Error(`No root item found on branch ${branchName} (E: 8a1b6e4d9c7f4e28b8a531d04cb54a26)`); } if (logalot) { console.log(`${TRACE_VCS_PREFIX}[executeVcsLog] branchName: '${branchName}', rootItemAddr: ${shortAddr(rootItemAddr)}, space: ${branchSpace?.data?.name || branchSpace?.ib}`); await logTreeHierarchyDiagnostic({ label: `executeVcsLog for '${normalizedRelPath}' on branch '${branchName}'`, rootItemAddr: rootItemAddr || getIbGibAddr({ ibGib: rootItemIbGib }), space: branchSpace, metaspace, }); } const targetItem = await logCmd_findItemByPath({ rootItem: rootItemIbGib, targetRelPath: normalizedRelPath, space: branchSpace, metaspace, }); if (!targetItem) { throw new Error(`Path '${normalizedRelPath}' not found in active branch snapshot (E: 67b84a9e2d1f463c9b7e51c88d32a026)`); } const tipAddr = getIbGibAddr({ ibGib: targetItem }); const pastAddrs = targetItem.rel8ns?.past || []; const allTimelineAddrs = [...pastAddrs, tipAddr].reverse(); // ⚡ Fetch all file revisions in a single batch const fileFrames = await getIbGibsFromSpace({ addrs: allTimelineAddrs, space: branchSpace, }); const allCommentAddrs = unique(fileFrames.flatMap(f => f.rel8ns?.comment || [])); const commentMap = new Map(); if (allCommentAddrs.length > 0) { const rawComments = await getIbGibsFromSpace({ addrs: allCommentAddrs, space: branchSpace, }); const resolvedTips = await resolveLatestIbGibsInSpace({ ibGibs: rawComments, space: branchSpace, }); for (let i = 0; i < rawComments.length; i++) { const raw = rawComments[i]; const rawAddr = getIbGibAddr({ ibGib: raw }); const tip = resolvedTips[i] || raw; const tipAddr = getIbGibAddr({ ibGib: tip }); commentMap.set(rawAddr, { tip, tipAddr }); } } const commits: VcsLogItem[] = []; for (const frame of fileFrames) { const frameAddr = getIbGibAddr({ ibGib: frame }); const commentAddrs = frame.rel8ns?.comment || []; for (const cAddr of commentAddrs) { const commentEntry = commentMap.get(cAddr); if (commentEntry) { const { tip, tipAddr } = commentEntry; commits.push({ commitAddr: frameAddr, commentAddr: tipAddr, message: tip.data?.text || '', timestamp: tip.data?.textTimestamp || tip.data?.timestamp || '', author: 'vcs-user', }); } } } return { branchName, targetPath: normalizedRelPath, commits, }; } async function executeVcsLogBranch({ branchIbGib, branchSpace, branchName, allComments, metaspace, }: { branchIbGib: B2tFSBranchIbGib_V1; branchSpace: IbGibSpaceAny; branchName: string; allComments?: boolean; metaspace: any; }): Promise { const tipAddr = getIbGibAddr({ ibGib: branchIbGib }); const pastAddrs = branchIbGib.rel8ns?.past || []; const allTimelineAddrs = [...pastAddrs, tipAddr].reverse(); // ⚡ Fetch all branch frames across history in a single batch const branchFrames = await getIbGibsFromSpace({ addrs: allTimelineAddrs, space: branchSpace, }); const branchFrameMap = new Map(); for (const frame of branchFrames) { branchFrameMap.set(getIbGibAddr({ ibGib: frame }), frame); } // ⚡ Batch-fetch all root item snapshots for branch frames const allRootItemAddrs = unique( branchFrames .map(f => f.rel8ns?.b2tfs_item?.at(-1) || f.rel8ns?.b2tFS_item?.at(-1)) .filter(Boolean) as string[] ); const rootItems = allRootItemAddrs.length > 0 ? await getIbGibsFromSpace({ addrs: allRootItemAddrs, space: branchSpace, }) : []; const rootItemMap = new Map(); for (const item of rootItems) { rootItemMap.set(getIbGibAddr({ ibGib: item }), item); } // ⚡ Collect and batch-fetch all comment addresses across branch frames AND root items const allCommentAddrs = unique([ ...(branchIbGib.rel8ns?.comment || []), ...branchFrames.flatMap(f => { const rAddr = f.rel8ns?.b2tfs_item?.at(-1) || f.rel8ns?.b2tFS_item?.at(-1); const rItem = rAddr ? rootItemMap.get(rAddr) : undefined; return [ ...(f.rel8ns?.comment || []), ...(rItem?.rel8ns?.comment || []), ]; }), ].filter(Boolean) as string[]); const commentMap = new Map(); if (allCommentAddrs.length > 0) { const rawComments = await getIbGibsFromSpace({ addrs: allCommentAddrs, space: branchSpace, }); // ⚡ Resolve each comment to its latest timeline tip in branchSpace const resolvedCommentTips = await resolveLatestIbGibsInSpace({ ibGibs: rawComments, space: branchSpace, }); for (let i = 0; i < rawComments.length; i++) { const raw = rawComments[i]; const rawAddr = getIbGibAddr({ ibGib: raw }); const tip = resolvedCommentTips[i] || raw; const tipAddr = getIbGibAddr({ ibGib: tip }); commentMap.set(rawAddr, { tip, tipAddr }); } } // Map each frame address in history to its specific commit comment const chronologicalAddrs = [...pastAddrs, tipAddr]; const chronologicalComments = branchIbGib.rel8ns?.comment || []; const frameToCommentAddrMap = new Map(); for (let i = 0; i < chronologicalAddrs.length; i++) { const frameAddr = chronologicalAddrs[i]; const frame = branchFrameMap.get(frameAddr); const commentFromFrame = frame?.rel8ns?.comment?.at(-1); if (commentFromFrame) { frameToCommentAddrMap.set(frameAddr, commentFromFrame); } else if (i < chronologicalComments.length) { frameToCommentAddrMap.set(frameAddr, chronologicalComments[i]); } } const commits: VcsLogItem[] = []; const seenCommentTipAddrs = new Set(); for (const frameAddr of allTimelineAddrs) { const branchFrame = branchFrameMap.get(frameAddr); const rootItemAddr = branchFrame?.rel8ns?.b2tfs_item?.at(-1) || branchFrame?.rel8ns?.b2tFS_item?.at(-1); const rootItem = rootItemAddr ? rootItemMap.get(rootItemAddr) : undefined; const commentAddr = frameToCommentAddrMap.get(frameAddr); const commentEntry = commentAddr ? commentMap.get(commentAddr) : undefined; const commentTip = commentEntry?.tip; const commentTipAddr = commentEntry?.tipAddr || commentAddr; if (commentTipAddr) { seenCommentTipAddrs.add(commentTipAddr); } const message = commentTip?.data?.text || '(no commit message)'; const timestamp = commentTip?.data?.textTimestamp || commentTip?.data?.timestamp || branchFrame?.data?.committedAt || ''; const committedPaths = branchFrame?.data?.committedPaths || []; const itemComments: Array<{ path: string; name?: string; message: string }> = []; if (allComments && rootItem) { await logCmd_collectAllItemComments({ item: rootItem, space: branchSpace, metaspace, currentRelPath: '', outComments: itemComments, }); } commits.push({ branchAddr: frameAddr, commitAddr: frameAddr, commentAddr: commentTipAddr, message, timestamp, author: 'vcs-user', rootItemAddr, committedPaths, itemComments: itemComments.length > 0 ? itemComments : undefined, }); } // Collect any unassociated comments (e.g. attached only to rootItem or historical branches) for (const [commentRawAddr, entry] of commentMap.entries()) { if (!seenCommentTipAddrs.has(entry.tipAddr)) { seenCommentTipAddrs.add(entry.tipAddr); const message = entry.tip.data?.text || '(no commit message)'; const timestamp = entry.tip.data?.textTimestamp || entry.tip.data?.timestamp || ''; commits.push({ branchAddr: tipAddr, commitAddr: tipAddr, commentAddr: entry.tipAddr, message, timestamp, author: 'vcs-user', committedPaths: [], }); } } return { branchName, commits, }; } async function logCmd_findItemByPath({ rootItem, targetRelPath, space, metaspace, }: { rootItem: B2tFSItemIbGib_V1; targetRelPath: string; space: any; metaspace?: any; }): Promise { if (!rootItem) { return undefined; } if (!targetRelPath || targetRelPath === '.' || targetRelPath === '') { return rootItem; } const segments = targetRelPath.split('/').filter(Boolean); let currentItem: B2tFSItemIbGib_V1 = rootItem; for (const segment of segments) { if (currentItem.data?.fsType !== 'folder') { return undefined; } const childAddrs = currentItem.rel8ns?.[B2TFS_CHILD_ITEM_REL8N_NAME] || []; if (childAddrs.length === 0) { return undefined; } const children = await getIbGibsFromSpace({ addrs: childAddrs, space, }); const nextItem = children.find(child => child?.data?.name === segment); if (!nextItem) { return undefined; } currentItem = nextItem; } return currentItem; } async function logCmd_collectAllItemComments({ item, space, metaspace, currentRelPath, outComments, }: { item: B2tFSItemIbGib_V1; space: any; metaspace?: any; currentRelPath: string; outComments: Array<{ path: string; name?: string; message: string }>; }): Promise { if (!item || !item.data) { return; } const itemComments = item.rel8ns?.comment || []; for (const cAddr of itemComments) { const commentIbGib = await getIbGibFromSpace({ addr: cAddr, space, metaspace, }); if (commentIbGib && commentIbGib.data?.text) { outComments.push({ path: currentRelPath || '(root)', name: (commentIbGib.data as any)?.name, message: commentIbGib.data.text, }); } } if (item.data.fsType === 'folder') { const childAddrs = item.rel8ns?.[B2TFS_CHILD_ITEM_REL8N_NAME] || []; if (childAddrs.length > 0) { const children = await getIbGibsFromSpace({ addrs: childAddrs, space, }); for (const childItem of children) { const childRel = currentRelPath ? joinPaths(currentRelPath, childItem.data.name) : childItem.data.name; await logCmd_collectAllItemComments({ item: childItem, space, metaspace, currentRelPath: childRel, outComments, }); } } } }