@statewalker/vcs-commands 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/dist/commands/archive/archive-command.d.ts +81 -7
  2. package/dist/commands/archive/archive-command.d.ts.map +1 -1
  3. package/dist/commands/archive/archive-entry.d.ts +48 -5
  4. package/dist/commands/archive/archive-entry.d.ts.map +1 -1
  5. package/dist/commands/archive/tar-archive.d.ts +5 -2
  6. package/dist/commands/archive/tar-archive.d.ts.map +1 -1
  7. package/dist/commands/archive/zip-archive.d.ts +9 -2
  8. package/dist/commands/archive/zip-archive.d.ts.map +1 -1
  9. package/dist/commands/attributes-source.d.ts +5 -0
  10. package/dist/commands/attributes-source.d.ts.map +1 -1
  11. package/dist/commands/cat-file/cat-file-command.d.ts.map +1 -1
  12. package/dist/commands/http-config.d.ts +4 -2
  13. package/dist/commands/http-config.d.ts.map +1 -1
  14. package/dist/commands/index.d.ts +1 -0
  15. package/dist/commands/index.d.ts.map +1 -1
  16. package/dist/commands/index.js +6 -6
  17. package/dist/commands/ls-files-command.d.ts.map +1 -1
  18. package/dist/commands/ls-tree-command.d.ts.map +1 -1
  19. package/dist/commands/mv-command.d.ts.map +1 -1
  20. package/dist/commands/pathspec.d.ts.map +1 -1
  21. package/dist/commands/plumbing-shared.d.ts +72 -0
  22. package/dist/commands/plumbing-shared.d.ts.map +1 -0
  23. package/dist/commands/repack-command.d.ts +12 -3
  24. package/dist/commands/repack-command.d.ts.map +1 -1
  25. package/dist/commands/replace-command.d.ts.map +1 -1
  26. package/dist/commands/rerere-command.d.ts +12 -0
  27. package/dist/commands/rerere-command.d.ts.map +1 -1
  28. package/dist/commands/rerere.d.ts +22 -0
  29. package/dist/commands/rerere.d.ts.map +1 -1
  30. package/dist/commands/revision-resolver.d.ts +9 -4
  31. package/dist/commands/revision-resolver.d.ts.map +1 -1
  32. package/dist/{commands-bQQ9OmCh.js → commands-C2E51T1z.js} +595 -223
  33. package/dist/{fsck-BHT9bUS-.js → fsck-BjlxStsM.js} +1 -1
  34. package/dist/git-command.d.ts +6 -4
  35. package/dist/git-command.d.ts.map +1 -1
  36. package/dist/index.js +6 -6
  37. package/dist/{maintenance-run-command-Cx2PlGV9.js → maintenance-run-command-G_eWdA8O.js} +42 -16
  38. package/dist/remote-config/remote-config-store.d.ts +4 -1
  39. package/dist/remote-config/remote-config-store.d.ts.map +1 -1
  40. package/dist/{remote-transport-BrQZfyHu.js → remote-transport-CSgTJ1BH.js} +3 -3
  41. package/dist/results/index.js +1 -1
  42. package/dist/{results-CNHQnU5Y.js → results-Dg1KHG8y.js} +351 -51
  43. package/dist/transport-command.d.ts.map +1 -1
  44. package/package.json +12 -12
  45. package/src/commands/archive/archive-command.ts +395 -59
  46. package/src/commands/archive/archive-entry.ts +88 -5
  47. package/src/commands/archive/tar-archive.ts +40 -9
  48. package/src/commands/archive/zip-archive.ts +72 -21
  49. package/src/commands/attributes-source.ts +13 -1
  50. package/src/commands/cat-file/cat-file-command.ts +18 -44
  51. package/src/commands/http-config.ts +14 -2
  52. package/src/commands/index.ts +1 -0
  53. package/src/commands/ls-files-command.ts +25 -33
  54. package/src/commands/ls-tree-command.ts +5 -21
  55. package/src/commands/mv-command.ts +37 -6
  56. package/src/commands/pathspec.ts +2 -4
  57. package/src/commands/plumbing-shared.ts +197 -0
  58. package/src/commands/repack-command.ts +44 -11
  59. package/src/commands/replace-command.ts +16 -4
  60. package/src/commands/rerere-command.ts +17 -0
  61. package/src/commands/rerere.ts +144 -3
  62. package/src/commands/revision-resolver.ts +32 -23
  63. package/src/git-command.ts +17 -20
  64. package/src/remote-config/remote-config-store.ts +11 -3
  65. package/src/transport-command.ts +4 -1
@@ -1,19 +1,19 @@
1
- import { E as fsckTree, I as __exportAll, T as fsckTag, _ as UnknownFsckMsgIdError, d as FsckCommand, g as FsckMessageTypes, h as FSCK_MSG_IDS, m as receiveFsckOf, n as VerifyPackCommand, p as fetchFsckOf, v as parseFsckMsgId, w as fsckCommit, x as checkSubmoduleName } from "./fsck-BHT9bUS-.js";
1
+ import { E as fsckTree, I as __exportAll, T as fsckTag, _ as UnknownFsckMsgIdError, d as FsckCommand, g as FsckMessageTypes, h as FSCK_MSG_IDS, m as receiveFsckOf, n as VerifyPackCommand, p as fetchFsckOf, v as parseFsckMsgId, w as fsckCommit, x as checkSubmoduleName } from "./fsck-BjlxStsM.js";
2
2
  import { BranchUsedByWorktreeError, CannotDeleteCurrentBranchError, CheckoutIndexFailedError, CloneCheckoutError, CloneDestinationError, CommitNotFoundError, DescribeError, EmptyCommitError, GitApiError, HookFailedError, IncompatibleOptionsError, IndexLockFailedError, InvalidArgumentError, InvalidConfigError, InvalidMainlineParentError, InvalidMergeHeadsError, InvalidPathError, InvalidRefNameError, InvalidRemoteError, InvalidStashIndexError, InvalidTagNameError, MissingArgumentError, MktagFailedError, MultipleParentsNotAllowedError, MvFailedError, NoFilepatternError, NoHeadError, NoMergeBaseError, NoMessageError, NoRebaseInProgressError, NonFastForwardError, NotACommitError, NotFastForwardError, NotMergedError, PushRejectedException, RebaseTodoMissingError, RefAlreadyExistsError, RefFilterError, RefNotFoundError, RemoteAlreadyExistsError, RemoteNotFoundError, RevisionError, RmFailedError, StashApplyFailedError, StashNotFoundError, StoreNotAvailableError, SwitchRefusedError, TransportError as TransportError$1, UnmergedPathsError, UpdateIndexFailedError, WorktreeError } from "./errors/index.js";
3
- import { $c as statFollowingLinks, $i as stripspace, $l as configValue, $n as applyMailmapToHeader, $r as trailerLinesOf, Ai as ApplyParser, Al as runPostCheckoutHook, Ao as rerereStatus, Ar as combineNotesCatSortUniq, At as AUTOSTASH_SAVED_LINES, Bc as sparseCheckoutConfig, Bl as worktreeModeTrust, Bo as detectRenames, Br as amendWithTrailers, Bt as squashMessage, C as patchRevisionOf, Cc as UnsupportedObjectStorageError, Cl as hookHostOf, Cr as expandNotesRef, D as PATCH_MODES, Dc as defaultRefFormat, Di as ApplyCommand, Dl as isKnownHook, Dn as readDiffSubmoduleConfig, Do as rerereGcLocation, Dr as readRef, Ds as quoteCStyleBody, Dt as relativeDate, Ec as defaultInitialBranch, Ei as readBlob, Eo as rerereForget, Er as initNotes, Fc as cleanTrackedSparseDirectories, Fi as latin1ToText, Ft as removeBranchState, G as SubmoduleSummaryCommand, Ga as signPayload, Gi as cleanupWith, Gl as wsBlankLine, Go as readGitlinkHead, H as readShowUntrackedFiles, Hc as sparsePathAdvice, Hl as WS_DEFAULT_RULE, Ho as isBinaryContent, Ic as entryList, Ii as pathToLatin1, Io as lowLevelMerge, Ir as mailFromHeader, It as removeMergeBranchState, J as StatusPrinter, Ji as commitMessageFromOption, Jn as verifyCommitBytes, K as readHeadDescription, Ka as signRequestOf, Ki as commentPrefixOf, Kl as wsCheckEmit, Kt as WorkingCopyStashProvider, L as TextconvCaches, Li as textToLatin1, Ll as abbrevLengths, Lr as mailSubjectLine, Lt as resetMerge, M as DiffCommand, Mi as cUnquote, Ml as sequencerPrepareMessage, Mn as parseGitmodules, Mt as cleanupMessage, Ni as latin1ToBytes, Nl as fsmonitorModeOf, No as MergeDriverFailedError, Nr as combineNotesOverwrite, Nt as createAutostash, O as patchModeFor, Oc as isValidBranchName$1, Or as updateNotesRef, Os as quotePath, Ot as sanitizedSubject, Pc as SparseUnpack, Pi as latin1ToPath, Pr as readNoteBytes, Pt as moveHeadAsReset, Qc as removeDirectoryIfEmpty, Qi as preparedMessageCleanup, Ql as configBool$1, Qn as GrepPatternError, Qr as trailerConfigOf, Qs as reflogMessages, R as StatusCommand, Ra as GitCommand, Rc as readSparseCheckoutFile, Ri as newFilePatch, Rl as coreBool, Ro as ortConfigOptions, Rt as resetUnmergedToHead, Si as GRAPH_COLUMN_COLORS_ANSI, So as RerereError, Sr as expandLooseNotesRef, St as loadRefDecorations, Su as listRemoteNames, T as runPatchSelection, Ti as ortResultEntries, To as rerereDiff, Tr as initCopyNotesForRewrite, Tt as parseColorSpec, Uc as sparseWarningText, Ui as isMergeSuccessful, Ul as checkBlankAtEof, Un as readStoredObjectBytes, Uo as IndexAdder, Ut as StashCreateCommand, Va as SigningFailedError, Vc as sparseDirectoriesOf, Vo as GIT_MAX_SCORE, Vr as appendSignoff, Wa as signCommit, Wc as updateSparsity, Wl as isGitSpace, Wr as ignoredLogMessageBytes, Xc as pruneEmptyParents, Xi as editorCleanupMode, Xl as attributesSourceResolver, Xn as verifyTagBytes, Xr as signoffLine, Y as formatStatusText, Yi as completeLine$1, Yn as verifyMergeSignature, Yr as processTrailers, Za as signingKeyIdOf, Zi as parseCleanupMode, Zl as bareAttributesResolver, Zs as reflogLine, _a as updateIndexCacheTree, _i as DEFAULT_DATE_MODE, _n as shortBranchName, _o as verifyFilename, _r as copyNoteForRewrite, _u as localTimezoneOffset, aa as indexChanges, ai as matchPathspecSeen, al as planFlatRestore, an as STASH_REF, ao as guessRemoteBranch, ar as storedBase, au as InvalidIdentError, b as collapsedSparseDirectories, bi as parseDateMode, bl as gitCommitMessageHooks, bn as worktreeAdminWorkingCopy, br as createNotesCommit, bu as moveRefs, ci as pathspecCommonPrefix, cl as writeTreeRestorePlan, co as pushTrackingPlan, cr as forkPointOf, ct as readDiffColorSettings, da as rewriteIndex, di as pathspecItemMayMatch, dl as withTreePathRefusal, dn as checkCandidatePath, do as upstreamMissingError, dr as patchIdOfChanges, dt as ConfigValueDeath, ea as FlatTreeCache, ec as updateHead, ei as validateTrailerArgs, el as statThroughLeadingLinks, eo as ambiguousRemoteAdvice, et as RevParseCommand, eu as conflictStyleOf, fa as storeFlatTree, fi as pathspecName, fl as worktreePathRules, fn as findLinkedWorktree, fo as worktreeAmbiguityHints, fr as patchIdsOfPatchText, ft as formatConfigValue, ga as treeDelta, gc as removeLegacyRemoteFile, gi as untrackedScanPathspec, gl as commonGitFileOf, gn as requireWorktrees, go as parseRevisionAndPathArgs, gr as commitNotes, gt as parseGitColor, gu as formatRfc2822Date, ha as switchTrees, hc as readRepositoryMailmap, hi as treePathspec, hn as repositoryPlaceOf, hr as NotesError, ht as normalizeConfigValue, hu as approxidateCareful$1, i as isRebaseSuccessful, ia as flatTree, ii as matchPathspec, il as checkoutFreshTree, in as StashApplyCommand, io as endOfSymbolicChain, ir as mergeStoredTrees, iu as InvalidDateError, ji as bytesToLatin1, jl as sequencerPostCommit, jo as runRerere, jr as combineNotesConcatenate, jt as applyAutostash, kc as unknownObjectStorageFormat, ki as ApplyEngine, ko as rerereRemaining, la as readIndex, li as pathspecErrors, ln as WorktreeListCommand, lo as trackableStart, lr as PathspecAttributes, lu as hostEnvironmentOf, ma as subjectOf, mc as readMailmapFile, mi as treeEntryInteresting, mn as refuseIfCheckedOut, mr as isFullHexObjectId, mt as gitConfigColorBool, mu as withoutCrud, na as conflictsComment, ni as latin1Bytes$3, nr as remergeObjectsView, oa as indexChangesFromTree, oc as promisorOf, oi as parsePathspec, on as StashListCommand, oo as installTracking, or as MergeBaseGraph, ou as authorIdentOf, pa as storeFlatTreeOver, pc as readMailmapBlob, pi as psEqual, pr as canonicalObjectId, pt as gitConfigBool, qa as signTagCompat, qi as commitCleanupMode, qo as strerror, qt as ResetCommand, ri as latin1String, rl as worktreeModified, rn as PathspecFile, ro as disableHint, rr as mergeBaseTree, rt as textconvRunnerOf, si as parsePathspecItem, sn as LogCommand, so as planTracking, sr as commitsBaseSource, su as committerIdentOf, ta as OperationState, tc as updateHeadExpecting, ti as globalPathspecMagic, to as applyRefspecs$1, tt as revisionMergeBases, tu as mergeVerbosityOf, ua as refsWatched, uc as promisorRemoteReplyOf, ui as pathspecItemBytes, ul as treePathRefusal, uo as uniqueTrackingName, ur as PatchIds, ut as CONFIG_VALUE_TYPES, v as AddCommand, va as writeIndexAsTree, vc as InvalidInitialBranchError, vn as useRelativePaths, vo as verifyNonFilename, vr as copyNotesForAmend, vu as parseGitDate, w as pathPatchMode, wc as checkDefaultObjectStorage, wl as hookRunnerOf, wo as rerereClear, wr as finishCopyNotesForRewrite, x as sparseIndexAsRead, xi as showDate, xl as gitFileOf, xn as worktreeUsingBranch, xo as unknownRevisionMessage, xr as defaultNotesRef, xu as RemoteConfigStore, y as SPARSE_INDEX_EXPANDED_HINT, yl as gitCommitAfterHooks, yn as usesBranch, yo as handleRevisionArg, yr as copyNotesForRebase, ys as formatStat, yt as formatCommitPretty, yu as deleteRefs, z as cutLine, za as SIGNING_FAILED_LINES, zc as readSparseCheckoutPatterns, zl as createIdAbbreviator, zr as reencodedCommitParts, zt as saveAutostash } from "./results-CNHQnU5Y.js";
4
- import { $ as relativeFilesPath, $t as BisectRunCommand, A as fetchBundleUri, An as pathCheckoutResult, Bt as signatureStart, C as strictUrlOrigin, Ct as shortlogIdent, D as TransportCommand, E as PlumbingError, En as CheckoutCommand, Et as fillAheadBehind, Ft as RefFormat, G as defaultRemoteOf, I as BundleList, It as RefKind, J as lstatKind, Jt as BisectCommand, K as isRelativeSubmoduleUrl, M as BundleListHeadsCommand, Mn as runPathCheckout, N as BundleUnbundleCommand, Nt as sortRefs, Ot as filterAndFormatRefs, P as BundleVerifyCommand, Q as physicalFilesPath, Qt as BisectResetCommand, R as parseBundleListLine, S as guardSubmoduleTransports, St as readShortlogInput, T as PlumbingCommand, U as SubmoduleGitDirError, W as SubmoduleModel, X as parentIsDirectory, Xt as BisectNextCommand, Y as openConfigFile, Yt as BisectLogCommand, Z as parseSubmoduleUpdateStrategy, Zt as BisectReplayCommand, _ as SubmoduleFetchRepository, a as ReflogCommand, at as setInConfigFile, b as submoduleTouchesInRange, bt as parseShortlogGroup, c as GuardedTransportCommand, ct as upPathOf, dt as validateSubmodulePath, en as BisectSkipCommand, ft as worktreeHostPath, g as uriProtocolsOption, gt as commitSubject$1, h as toTrackingRefUpdate, ht as Shortlog, i as RepackCommand, it as safeCreateLeadingDirectories, jt as parseRefSorting, k as fetchBundleList, kn as nonCommitSwitchError, kt as filterRefs, l as FetchCommand, lt as urlIsLocalNotSsh, m as toTagMode, n as MaintenanceRunCommand, nn as BisectStateCommand, nt as resolveFilesLinks, o as inLinkedWorktree, ot as submodulePathConfigOf, pt as BundleCreateCommand, q as joinFilesPath, qt as RevListCommand, rn as BisectTermsCommand, rt as resolveRelativeUrl, s as objectsDirectoryDisplay, st as submoduleUpdateTypeName, tn as BisectStartCommand, tt as remoteFromUrl, ut as validateSubmoduleGitDir, v as findUnpushedSubmodules, vt as inputLines$2, w as clientSessionIdOf, wt as splitIdent, x as createSubmoduleAuthPolicy, xt as parseShortlogWrap, yt as outputEncoderFor } from "./maintenance-run-command-Cx2PlGV9.js";
5
- import { C as WorktreePruneCommand, S as GarbageCollectCommand, _ as remoteHookSession, b as withReceiveTransactionHook, d as withRemoteUploadPack, f as createDuplexPair, g as receivePackSettingsOf, h as receiveFsckSettingsOf, l as withRemoteReceivePack, p as httpBackendEnv, u as withRemoteSession, v as servedMaxTreeDepth, w as BundlePrerequisitesError, x as ReadTreeCommand, y as servedUseBitmaps } from "./remote-transport-BrQZfyHu.js";
3
+ import { $i as stripspace, $n as applyMailmapToHeader, $r as trailerLinesOf, $s as reflogMessages, Ac as checkDefaultObjectStorage, Ai as ApplyParser, Al as hookRunnerOf, Ao as rerereRemaining, Ar as combineNotesCatSortUniq, At as AUTOSTASH_SAVED_LINES, Bc as SparseUnpack, Br as amendWithTrailers, Bt as squashMessage, C as patchRevisionOf, Cr as expandNotesRef, Cu as localTimezoneOffset, D as PATCH_MODES, Di as ApplyCommand, Dl as gitFileOf, Dn as readDiffSubmoduleConfig, Do as rerereForget, Dr as readRef, Dt as relativeDate, Du as RemoteConfigStore, Ei as readBlob, El as gitCommitMessageHooks, Eo as rerereEngineOf, Er as initNotes, Eu as moveRefs, Fc as unknownObjectStorageFormat, Fi as latin1ToText, Ft as removeBranchState, G as SubmoduleSummaryCommand, Ga as signPayload, Gc as readSparseCheckoutPatterns, Gi as cleanupWith, Gl as createIdAbbreviator, H as readShowUntrackedFiles, Hc as entryList, Ho as GIT_MAX_SCORE, Ii as pathToLatin1, Il as runPostCheckoutHook, Ir as mailFromHeader, It as removeMergeBranchState, J as StatusPrinter, Jc as sparsePathAdvice, Ji as commitMessageFromOption, Jl as WS_DEFAULT_RULE, Jn as verifyCommitBytes, Jo as strerror, K as readHeadDescription, Ka as signRequestOf, Kc as sparseCheckoutConfig, Ki as commentPrefixOf, Kl as worktreeModeTrust, Ko as readGitlinkHead, Kt as WorkingCopyStashProvider, L as TextconvCaches, Li as textToLatin1, Ll as sequencerPostCommit, Lo as lowLevelMerge, Lr as mailSubjectLine, Lt as resetMerge, M as DiffCommand, Mc as defaultInitialBranch, Mi as cUnquote, Mn as parseGitmodules, Mo as runRerere, Mt as cleanupMessage, Nc as defaultRefFormat, Ni as latin1ToBytes, Nl as isKnownHook, Nr as combineNotesOverwrite, Nt as createAutostash, O as patchModeFor, Oo as rerereGcLocation, Or as updateNotesRef, Os as quoteCStyleBody, Ot as sanitizedSubject, Ou as listRemoteNames, Pc as isValidBranchName$1, Pi as latin1ToPath, Po as MergeDriverFailedError, Pr as readNoteBytes, Pt as moveHeadAsReset, Qi as preparedMessageCleanup, Ql as wsCheckEmit, Qn as GrepPatternError, Qr as trailerConfigOf, Qs as reflogLine, R as StatusCommand, Ra as GitCommand, Ri as newFilePatch, Rl as sequencerPrepareMessage, Rt as resetUnmergedToHead, Sc as removeLegacyRemoteFile, Si as GRAPH_COLUMN_COLORS_ANSI, Sl as commonGitFileOf, So as RerereError, Sr as expandLooseNotesRef, St as loadRefDecorations, Su as formatRfc2822Date, T as runPatchSelection, Ti as ortResultEntries, Tl as gitCommitAfterHooks, To as rerereDiff, Tr as initCopyNotesForRewrite, Tt as parseColorSpec, Tu as deleteRefs, Ui as isMergeSuccessful, Ul as abbrevLengths, Un as readStoredObjectBytes, Uo as isBinaryContent, Ut as StashCreateCommand, Va as SigningFailedError, Vc as cleanTrackedSparseDirectories, Vo as detectRenames, Vr as appendSignoff, Wa as signCommit, Wc as readSparseCheckoutFile, Wl as coreBool, Wo as IndexAdder, Wr as ignoredLogMessageBytes, Xc as updateSparsity, Xi as editorCleanupMode, Xl as isGitSpace, Xn as verifyTagBytes, Xr as signoffLine, Y as formatStatusText, Yc as sparseWarningText, Yi as completeLine$1, Yl as checkBlankAtEof, Yn as verifyMergeSignature, Yr as processTrailers, Za as signingKeyIdOf, Zi as parseCleanupMode, Zl as wsBlankLine, _a as updateIndexCacheTree, _c as readAllBytes, _i as DEFAULT_DATE_MODE, _l as withTreePathRefusal, _n as shortBranchName, _o as verifyFilename, _r as copyNoteForRewrite, aa as indexChanges, ai as matchPathspecSeen, al as statFollowingLinks, an as STASH_REF, ao as guessRemoteBranch, ar as storedBase, au as configValue, b as collapsedSparseDirectories, bc as readMailmapFile, bi as parseDateMode, bn as worktreeAdminWorkingCopy, br as createNotesCommit, bs as formatStat, bu as withoutCrud, ci as pathspecCommonPrefix, co as pushTrackingPlan, cr as forkPointOf, ct as readDiffColorSettings, da as rewriteIndex, dc as promisorRemoteReplyOf, di as pathspecItemMayMatch, dl as planFlatRestore, dn as checkCandidatePath, do as upstreamMissingError, dr as patchIdOfChanges, dt as ConfigValueDeath, du as InvalidIdentError, ea as FlatTreeCache, ei as validateTrailerArgs, eo as ambiguousRemoteAdvice, et as RevParseCommand, fa as storeFlatTree, fi as pathspecName, fn as findLinkedWorktree, fo as worktreeAmbiguityHints, fr as patchIdsOfPatchText, ft as formatConfigValue, fu as authorIdentOf, ga as treeDelta, gc as objectTypeOfMode, gi as untrackedScanPathspec, gl as treePathRefusal, gn as requireWorktrees, go as parseRevisionAndPathArgs, gr as commitNotes, gt as parseGitColor, ha as switchTrees, hc as concatBytes, hi as treePathspec, hn as repositoryPlaceOf, hr as NotesError, ht as normalizeConfigValue, hu as hostEnvironmentOf, i as isRebaseSuccessful, ia as flatTree, ii as matchPathspec, il as removeDirectoryIfEmpty, in as StashApplyCommand, io as endOfSymbolicChain, ir as mergeStoredTrees, iu as configBool$1, ji as bytesToLatin1, jo as rerereStatus, jr as combineNotesConcatenate, jt as applyAutostash, kc as UnsupportedObjectStorageError, ki as ApplyEngine, kl as hookHostOf, ks as quotePath, la as readIndex, li as pathspecErrors, ll as worktreeModified, ln as WorktreeListCommand, lo as trackableStart, lr as PathspecAttributes, ma as subjectOf, mc as SHORT_MAGIC$1, mi as treeEntryInteresting, ml as writeTreeRestorePlan, mn as refuseIfCheckedOut, mr as isFullHexObjectId, mt as gitConfigColorBool, na as conflictsComment, nc as updateHeadExpecting, ni as latin1Bytes$3, nl as pruneEmptyParents, nr as remergeObjectsView, nu as attributesSourceResolver, oa as indexChangesFromTree, oi as parsePathspec, ol as statThroughLeadingLinks, on as StashListCommand, oo as installTracking, or as MergeBaseGraph, ou as conflictStyleOf, pa as storeFlatTreeOver, pc as CorruptTreeError, pi as psEqual, pr as canonicalObjectId, pt as gitConfigBool, pu as committerIdentOf, qa as signTagCompat, qc as sparseDirectoriesOf, qi as commitCleanupMode, qt as ResetCommand, ri as latin1String, rn as PathspecFile, ro as disableHint, rr as mergeBaseTree, rt as textconvRunnerOf, ru as bareAttributesResolver, sc as promisorOf, si as parsePathspecItem, sn as LogCommand, so as planTracking, sr as commitsBaseSource, su as mergeVerbosityOf, ta as OperationState, tc as updateHead, ti as globalPathspecMagic, to as applyRefspecs$1, tt as revisionMergeBases, ua as refsWatched, ui as pathspecItemBytes, ul as checkoutFreshTree, uo as uniqueTrackingName, ur as PatchIds, ut as CONFIG_VALUE_TYPES, uu as InvalidDateError, v as AddCommand, va as writeIndexAsTree, vl as worktreePathRules, vn as useRelativePaths, vo as verifyNonFilename, vr as copyNotesForAmend, w as pathPatchMode, wc as InvalidInitialBranchError, wo as rerereClear, wr as finishCopyNotesForRewrite, wu as parseGitDate, x as sparseIndexAsRead, xc as readRepositoryMailmap, xi as showDate, xn as worktreeUsingBranch, xo as unknownRevisionMessage, xr as defaultNotesRef, xu as approxidateCareful$1, y as SPARSE_INDEX_EXPANDED_HINT, yc as readMailmapBlob, yn as usesBranch, yo as handleRevisionArg, yr as copyNotesForRebase, yt as formatCommitPretty, z as cutLine, za as SIGNING_FAILED_LINES, zl as fsmonitorModeOf, zo as ortConfigOptions, zr as reencodedCommitParts, zt as saveAutostash } from "./results-Dg1KHG8y.js";
4
+ import { $ as relativeFilesPath, $t as BisectRunCommand, A as fetchBundleUri, An as pathCheckoutResult, Bt as signatureStart, C as strictUrlOrigin, Ct as shortlogIdent, D as TransportCommand, E as PlumbingError, En as CheckoutCommand, Et as fillAheadBehind, Ft as RefFormat, G as defaultRemoteOf, I as BundleList, It as RefKind, J as lstatKind, Jt as BisectCommand, K as isRelativeSubmoduleUrl, M as BundleListHeadsCommand, Mn as runPathCheckout, N as BundleUnbundleCommand, Nt as sortRefs, Ot as filterAndFormatRefs, P as BundleVerifyCommand, Q as physicalFilesPath, Qt as BisectResetCommand, R as parseBundleListLine, S as guardSubmoduleTransports, St as readShortlogInput, T as PlumbingCommand, U as SubmoduleGitDirError, W as SubmoduleModel, X as parentIsDirectory, Xt as BisectNextCommand, Y as openConfigFile, Yt as BisectLogCommand, Z as parseSubmoduleUpdateStrategy, Zt as BisectReplayCommand, _ as SubmoduleFetchRepository, a as ReflogCommand, at as setInConfigFile, b as submoduleTouchesInRange, bt as parseShortlogGroup, c as GuardedTransportCommand, ct as upPathOf, dt as validateSubmodulePath, en as BisectSkipCommand, ft as worktreeHostPath, g as uriProtocolsOption, gt as commitSubject$1, h as toTrackingRefUpdate, ht as Shortlog, i as RepackCommand, it as safeCreateLeadingDirectories, jt as parseRefSorting, k as fetchBundleList, kn as nonCommitSwitchError, kt as filterRefs, l as FetchCommand, lt as urlIsLocalNotSsh, m as toTagMode, n as MaintenanceRunCommand, nn as BisectStateCommand, nt as resolveFilesLinks, o as inLinkedWorktree, ot as submodulePathConfigOf, pt as BundleCreateCommand, q as joinFilesPath, qt as RevListCommand, rn as BisectTermsCommand, rt as resolveRelativeUrl, s as objectsDirectoryDisplay, st as submoduleUpdateTypeName, tn as BisectStartCommand, tt as remoteFromUrl, ut as validateSubmoduleGitDir, v as findUnpushedSubmodules, vt as inputLines$2, w as clientSessionIdOf, wt as splitIdent, x as createSubmoduleAuthPolicy, xt as parseShortlogWrap, yt as outputEncoderFor } from "./maintenance-run-command-G_eWdA8O.js";
5
+ import { C as WorktreePruneCommand, S as GarbageCollectCommand, _ as remoteHookSession, b as withReceiveTransactionHook, d as withRemoteUploadPack, f as createDuplexPair, g as receivePackSettingsOf, h as receiveFsckSettingsOf, l as withRemoteReceivePack, p as httpBackendEnv, u as withRemoteSession, v as servedMaxTreeDepth, w as BundlePrerequisitesError, x as ReadTreeCommand, y as servedUseBitmaps } from "./remote-transport-CSgTJ1BH.js";
6
6
  import { CorruptObjectError, DEFAULT_BIG_FILE_THRESHOLD, EMPTY_BLOB_ID, EMPTY_TREE_ID, FileMode, InvalidTreeEntryNameError, MemoryRawStorage, ObjectType, RefStorage, bloomFilterContains, bloomKey, collapseRefNameSlashes, collectTagBytes, compareRefNames, countAheadBehind, createGitObjects, createInMemoryFilesApi, createMemoryHistory, decodeTreeBytes, formatPersonIdent, historyWithoutLazyFetch, importPack, isSymbolicRef, isValidBranchName, isValidRefName, isValidTagName, isValidWorktreePath, joinPath, listObjectsWithPrefix, objectFormatOf, overlayMethods, overlayObjects, packNameOf, parseCoreAbbrev, parseGraftFile, parseObjectFilter, parsePersonIdent, rawStorageStaging, readFile, replacementOf, serializeCommit, serializeTag, unpackObjects } from "@statewalker/vcs-core";
7
7
  import { compareGitPaths, decodeGitPath, decodeGitPatternFile, encodeGitPath, foldAsciiCase, parseGitBool, parseGitInt, unquoteGitPath } from "@statewalker/vcs-utils/encoding";
8
- import { AttributesMemo, AttributesSourceError, DIR_COLLECT_KILLED_ONLY, DIR_HIDE_EMPTY_DIRECTORIES, DIR_SHOW_IGNORED, DIR_SHOW_OTHER_DIRECTORIES, FilterDriverError, FsmonitorState, IndexPathLookup, WorktreeFormatUpgradeError, attributesIndexOf, attributesIndexOfTree, basicStatMatches, cacheTreeOfTree, collectChunks, commandLineExcluded, compareWithWorktree, convAttrsOf, createCommandLineExcludes, createIgnoreNode, createMemoryCheckout, crlfToWorktree, entryStatOf, eolStatsAscii, expandUserPath, getWorktreeEntries, identToWorktree, invalidateCacheTreePath, isIndexUnborn, isValidAttributeName, modeFromWorktree, readConversionSettings, readIndexFileEntries, reencode, scanUntracked, smudgeContent, sparseFilterMatcher, sparsePatternsFromCone, sparsePatternsFromLines, splitPatternLines, storeWorktreeFile, unreadableDirectoryWarning, walkUntrackedScanHost, wholeSeconds, wildmatch, withWorktreeEntries, xdgConfigPath } from "@statewalker/vcs-working-tree";
9
- import { ByteLines, LineInterner, PosixRegexError, SHA1_OBJECT_FORMAT, URL_COMPONENTS, XDF_IGNORE_CR_AT_EOL, XDF_IGNORE_WHITESPACE, XDF_IGNORE_WHITESPACE_AT_EOL, XDF_IGNORE_WHITESPACE_CHANGE, approxidateCareful, compilePosixRegex, decodeGitPath as decodeGitPath$1, encodeGitPath as encodeGitPath$1, formatHunkHeader, funcnameFindFunction, gitStrWidth as gitStrWidth$1, isUrlNormalizeError, mergeLines, normalizeUrl, nullObjectIdLike, objectFormatByName, parseGitBool as parseGitBool$1, parseGitInt as parseGitInt$1, selectUrlMatches, unifiedDiff, unifiedDiffHunks, urlComponent, urlParse, whitespaceFlags, xdiffHunks, xdlHashRecord } from "@statewalker/vcs-utils";
8
+ import { AttributesMemo, AttributesSourceError, DIR_COLLECT_KILLED_ONLY, DIR_HIDE_EMPTY_DIRECTORIES, DIR_SHOW_IGNORED, DIR_SHOW_OTHER_DIRECTORIES, FilterDriverError, FilterDriverRunError, FsmonitorState, IndexPathLookup, WorktreeFormatUpgradeError, attributesIndexOf, attributesIndexOfTree, basicStatMatches, cacheTreeOfTree, collectChunks, commandLineExcluded, compareWithWorktree, convAttrsOf, createCommandLineExcludes, createIgnoreNode, createMemoryCheckout, crlfToWorktree, entryStatOf, eolStatsAscii, expandUserPath, getWorktreeEntries, identToWorktree, invalidateCacheTreePath, isCleanByStat, isIndexUnborn, isValidAttributeName, modeFromWorktree, readConversionSettings, readIndexFileEntries, reencode, scanUntracked, smudgeContent, sparseFilterMatcher, sparsePatternsFromCone, sparsePatternsFromLines, splitPatternLines, storeWorktreeFile, unreadableDirectoryWarning, walkUntrackedScanHost, wholeSeconds, wildmatch, withWorktreeEntries, xdgConfigPath } from "@statewalker/vcs-working-tree";
9
+ import { ByteLines, LineInterner, PosixRegexError, SHA1_OBJECT_FORMAT, URL_COMPONENTS, XDF_IGNORE_CR_AT_EOL, XDF_IGNORE_WHITESPACE, XDF_IGNORE_WHITESPACE_AT_EOL, XDF_IGNORE_WHITESPACE_CHANGE, approxidateCareful, compilePosixRegex, decodeGitPath as decodeGitPath$1, encodeGitPath as encodeGitPath$1, formatHunkHeader, funcnameFindFunction, gitStrWidth as gitStrWidth$1, isUrlNormalizeError, mergeLines, normalizeUrl, nullObjectIdLike, objectFormatByName, parseGitBool as parseGitBool$1, parseGitInt as parseGitInt$1, parseGitUlong, selectUrlMatches, unifiedDiff, unifiedDiffHunks, urlComponent, urlParse, whitespaceFlags, xdiffHunks, xdlHashRecord } from "@statewalker/vcs-utils";
10
10
  import { FileMode as FileMode$1, PERM_GROUP, adjustSharedPerm, dirname, joinPath as joinPath$1, normalizePath, parseSharedRepository as parseSharedRepository$1, readFile as readFile$1, sharedRepositoryConfigValue, sharedRepositoryOf, tryReadFile, withSharedPerm } from "@statewalker/vcs-utils/files";
11
11
  import { SHA1_OBJECT_FORMAT as SHA1_OBJECT_FORMAT$1, SHA256_OBJECT_FORMAT as SHA256_OBJECT_FORMAT$1, isNullObjectId as isNullObjectId$1 } from "@statewalker/vcs-utils/hash";
12
12
  import { CONFIG_REGEX_NONE, ConfigParseError, FileStagingStore, GitWorkingCopyConfig, HostPaths, MissingRootError, RefMigrationError, ReflogExpiryConfigError, computeAlternatePath, configFilesApiOf, createFileWorktree, createGitFilesHistoryFromFiles, createWorkingCopyConfig, hostPathOf, hostRootOf, isAbsoluteGitPath, isGitDirectory, migrateRefStorage, objectStorageFormatByUri, openGitLinkedWorktrees, parseConfigKey, parseExpiryDate, parseGitfile, prepareConfigComment, probeCaseFolding, prune, readConfigFileThroughLinks, readProtectedConfig, readReftableWriteOptions, readRepositoryFormat, refStoreRetirement, renameConfigSectionInFile, rerereGc, resolveLinkedGitDir, retireRefStore, setConfigMultivarInFile, setConfigMultivarText, setupGitDirectory, verifyRefStorage } from "@statewalker/vcs-store-files";
13
- import { FetchCheckError, ObjectFormatMismatchError, ObjectInfoError, PushCertificateError, PushRefspecError, PushRefusedByHookError, ReceivedObjects, ShallowRemoteRejectedError, anonymizeUrl, bundleUriLines, checkUnpackedObjects, countRefspecMatch, createDefaultTransports, createRepositoryFacade, createTransportRefStore, expandFromDestination, expandFromSource, fetchFromConnection, fetchObjectInfo, formatPushStatus, gitDaemonRequest, lsRefs, mapRefs, mapRejectReason, matchDestination, matchPushRefs, matchSource, missingSources, objectSource, packObjectsHookArgs, parseConfigInt, parseRefSpec, pushToConnection, refPrefixes, repositoryQuarantine, requestRemoteArchive, serveUploadArchive, servedGitFilesOf } from "@statewalker/vcs-transport";
13
+ import { FetchCheckError, ObjectFormatMismatchError, ObjectInfoError, PushCertificateError, PushRefspecError, PushRefusedByHookError, ReceivedObjects, ShallowRemoteRejectedError, anonymizeUrl, bundleUriLines, checkUnpackedObjects, countRefspecMatch, createByteQueue, createDefaultTransports, createRepositoryFacade, createTransportRefStore, expandFromDestination, expandFromSource, fetchFromConnection, fetchObjectInfo, formatPushStatus, gitDaemonRequest, lsRefs, mapRefs, mapRejectReason, matchDestination, matchPushRefs, matchSource, missingSources, objectSource, packObjectsHookArgs, parseConfigInt, parseRefSpec, pushToConnection, refPrefixes, repositoryQuarantine, requestRemoteArchive, serveUploadArchive, servedGitFilesOf } from "@statewalker/vcs-transport";
14
14
  import { MemoryStagingStore } from "@statewalker/vcs-store-mem";
15
- import { deflateSync } from "@statewalker/vcs-utils/compression";
16
- import { crc32 } from "@statewalker/vcs-utils/hash/crc32";
15
+ import { createDeflater, deflateSync } from "@statewalker/vcs-utils/compression";
16
+ import { CRC32, crc32 } from "@statewalker/vcs-utils/hash/crc32";
17
17
  import { unifiedDiff as unifiedDiff$1, userdiffFindFunction as userdiffFindFunction$1 } from "@statewalker/vcs-utils/diff";
18
18
  import { collect } from "@statewalker/vcs-utils/streams";
19
19
  import { computeObjectId } from "@statewalker/vcs-utils/pack";
@@ -3047,6 +3047,55 @@ function createDescriber(source) {
3047
3047
  }
3048
3048
  //#endregion
3049
3049
  //#region src/commands/archive/archive-entry.ts
3050
+ /** The size of the chunks a writer sends to its output. */
3051
+ const OUTPUT_CHUNK = 65536;
3052
+ /**
3053
+ * The bytes a writer has written: kept whole, or sent to an {@link ArchiveOutput} in chunks
3054
+ * of about {@link OUTPUT_CHUNK}.
3055
+ */
3056
+ var ArchiveSink = class {
3057
+ output;
3058
+ buffer;
3059
+ /** The bytes sent to the output so far */
3060
+ sent = 0;
3061
+ constructor(output, capacity = 16384) {
3062
+ this.output = output;
3063
+ this.buffer = new ByteBuffer(output ? OUTPUT_CHUNK * 2 : capacity);
3064
+ }
3065
+ /** The archive's length so far (sent and held). */
3066
+ get position() {
3067
+ return this.sent + this.buffer.length;
3068
+ }
3069
+ /** Sends what is held once it reaches a chunk (`force`: whatever is held). */
3070
+ async flush(force = false) {
3071
+ if (!this.output || this.buffer.length === 0) return;
3072
+ if (!force && this.buffer.length < 65536) return;
3073
+ const chunk = this.buffer.bytes().slice();
3074
+ this.sent += chunk.length;
3075
+ this.buffer.clear();
3076
+ await this.output(chunk);
3077
+ }
3078
+ /** Writes a large piece (a streamed blob's chunk), sent as it is when there is an output. */
3079
+ async write(bytes) {
3080
+ if (!this.output) {
3081
+ this.buffer.push(bytes);
3082
+ return;
3083
+ }
3084
+ if (this.buffer.length + bytes.length < 65536) {
3085
+ this.buffer.push(bytes);
3086
+ return;
3087
+ }
3088
+ await this.flush(true);
3089
+ this.sent += bytes.length;
3090
+ await this.output(bytes.slice());
3091
+ }
3092
+ /** The bytes held whole (no output), or empty once everything was sent. */
3093
+ async finish() {
3094
+ if (!this.output) return this.buffer.bytes();
3095
+ await this.flush(true);
3096
+ return /* @__PURE__ */ new Uint8Array(0);
3097
+ }
3098
+ };
3050
3099
  /** A growing byte buffer. */
3051
3100
  var ByteBuffer = class {
3052
3101
  buf;
@@ -3072,6 +3121,10 @@ var ByteBuffer = class {
3072
3121
  this.buf.fill(0, this.length, this.length + n);
3073
3122
  this.length += n;
3074
3123
  }
3124
+ /** Forgets the bytes written (the capacity kept). */
3125
+ clear() {
3126
+ this.length = 0;
3127
+ }
3075
3128
  /** The bytes written (a view: copy before writing more). */
3076
3129
  bytes() {
3077
3130
  return this.buf.subarray(0, this.length);
@@ -3151,11 +3204,14 @@ function pathPrefix(path, maxlen) {
3151
3204
  /** Writes git's tar archive (`git archive --format=tar`). */
3152
3205
  var TarArchiveWriter = class {
3153
3206
  settings;
3154
- out = new ByteBuffer(BLOCKSIZE);
3207
+ sink;
3208
+ out;
3155
3209
  umask;
3156
3210
  time;
3157
3211
  constructor(settings) {
3158
3212
  this.settings = settings;
3213
+ this.sink = new ArchiveSink(settings.output, BLOCKSIZE);
3214
+ this.out = this.sink.buffer;
3159
3215
  this.umask = settings.umask ?? 2;
3160
3216
  this.time = settings.time;
3161
3217
  this.writeGlobalExtendedHeader();
@@ -3166,6 +3222,23 @@ var TarArchiveWriter = class {
3166
3222
  const tail = data.length % RECORDSIZE$1;
3167
3223
  if (tail) this.out.zeros(RECORDSIZE$1 - tail);
3168
3224
  }
3225
+ /** `stream_blocked`: a streamed blob's bytes, padded to a whole record; false when short. */
3226
+ async streamBlocked(stream, size) {
3227
+ let total = 0;
3228
+ try {
3229
+ for await (const chunk of stream) {
3230
+ if (total + chunk.length > size) return false;
3231
+ total += chunk.length;
3232
+ await this.sink.write(chunk);
3233
+ }
3234
+ } catch {
3235
+ return false;
3236
+ }
3237
+ if (total !== size) return false;
3238
+ const tail = size % RECORDSIZE$1;
3239
+ if (tail) this.out.zeros(RECORDSIZE$1 - tail);
3240
+ return true;
3241
+ }
3169
3242
  /** `prepare_header`: the numeric fields, owner, magic and checksum. */
3170
3243
  prepareHeader(header, mode, size) {
3171
3244
  octal$1(header, MODE, 8, mode & 4095);
@@ -3207,8 +3280,10 @@ var TarArchiveWriter = class {
3207
3280
  this.writeBlocked(ext);
3208
3281
  }
3209
3282
  /** `write_tar_entry`. */
3210
- entry(entry) {
3283
+ async entry(entry) {
3211
3284
  const { path, id, content } = entry;
3285
+ const stream = isRegMode(entry.mode) ? entry.stream : void 0;
3286
+ const size = stream ? entry.size ?? 0 : content.length;
3212
3287
  let mode = entry.mode;
3213
3288
  const header = new Uint8Array(RECORDSIZE$1);
3214
3289
  const ext = new ByteBuffer(256);
@@ -3239,23 +3314,30 @@ var TarArchiveWriter = class {
3239
3314
  extRecord(ext, "linkpath", content);
3240
3315
  } else header.set(content, LINKNAME);
3241
3316
  }
3242
- let sizeInHeader = content.length;
3243
- if (isRegMode(mode) && content.length > USTAR_MAX) {
3317
+ let sizeInHeader = size;
3318
+ if (isRegMode(mode) && size > USTAR_MAX) {
3244
3319
  sizeInHeader = 0;
3245
- extRecord(ext, "size", asciiBytes(String(content.length)));
3320
+ extRecord(ext, "size", asciiBytes(String(size)));
3246
3321
  }
3247
3322
  this.prepareHeader(header, mode, sizeInHeader);
3248
3323
  if (ext.length > 0) this.writeExtendedHeader(id, ext.bytes());
3249
3324
  this.writeBlocked(header);
3250
- if (isRegMode(mode) && content.length > 0) this.writeBlocked(content);
3325
+ if (stream) {
3326
+ if (!await this.streamBlocked(stream, size)) return `cannot stream blob ${id}`;
3327
+ } else if (isRegMode(mode) && content.length > 0) {
3328
+ await this.sink.write(content);
3329
+ const tail = content.length % RECORDSIZE$1;
3330
+ if (tail) this.out.zeros(RECORDSIZE$1 - tail);
3331
+ }
3332
+ await this.sink.flush();
3251
3333
  }
3252
3334
  /** `write_trailer`: the last block filled, another one when fewer than two records remain. */
3253
- finish() {
3254
- const offset = this.out.length % BLOCKSIZE;
3335
+ async finish() {
3336
+ const offset = this.sink.position % BLOCKSIZE;
3255
3337
  const tail = BLOCKSIZE - offset;
3256
3338
  this.out.zeros(tail);
3257
3339
  if (tail < 2 * RECORDSIZE$1) this.out.zeros(BLOCKSIZE);
3258
- return this.out.bytes();
3340
+ return this.sink.finish();
3259
3341
  }
3260
3342
  };
3261
3343
  //#endregion
@@ -4103,7 +4185,7 @@ function relativePath$2(path, prefix) {
4103
4185
  while (k < a.length - 1 && k < b.length && a[k] === b[k]) k++;
4104
4186
  return [...b.slice(k).map(() => ".."), ...a.slice(k)].join("/");
4105
4187
  }
4106
- const SHORT_MAGIC$2 = /* @__PURE__ */ new Set([..."!\"#%&',-;<=>@_`~^/"]);
4188
+ const SHORT_MAGIC = /* @__PURE__ */ new Set([..."!\"#%&',-;<=>@_`~^/"]);
4107
4189
  /** The pathspec argument read against the prefix (`:(top)` and `:/` from the top). */
4108
4190
  function prefixedArg(arg, prefix) {
4109
4191
  if (!prefix) return arg;
@@ -4115,7 +4197,7 @@ function prefixedArg(arg, prefix) {
4115
4197
  }
4116
4198
  if (arg.startsWith(":")) {
4117
4199
  let i = 1;
4118
- while (i < arg.length && arg[i] !== ":" && SHORT_MAGIC$2.has(arg[i])) i++;
4200
+ while (i < arg.length && arg[i] !== ":" && SHORT_MAGIC.has(arg[i])) i++;
4119
4201
  const magic = arg.slice(1, i);
4120
4202
  if (arg[i] === ":") i++;
4121
4203
  if (magic.includes("/")) return arg;
@@ -4131,7 +4213,7 @@ function afterMagic(arg) {
4131
4213
  }
4132
4214
  if (arg.startsWith(":")) {
4133
4215
  let i = 1;
4134
- while (i < arg.length && arg[i] !== ":" && SHORT_MAGIC$2.has(arg[i])) i++;
4216
+ while (i < arg.length && arg[i] !== ":" && SHORT_MAGIC.has(arg[i])) i++;
4135
4217
  if (arg[i] === ":") i++;
4136
4218
  return arg.slice(i);
4137
4219
  }
@@ -4920,6 +5002,8 @@ const METHOD_DEFLATE = 8;
4920
5002
  const EXTRA_MTIME_SIZE = 9;
4921
5003
  const ZIP64_EXTRA_SIZE = 20;
4922
5004
  const MAX32 = 4294967295;
5005
+ /** archive-zip.c's `STREAM_BUFFER_SIZE`: a streamed blob's reads. */
5006
+ const STREAM_BUFFER_SIZE = 16384;
4923
5007
  /** Little-endian fields appended to a buffer. */
4924
5008
  var LeWriter = class {
4925
5009
  out;
@@ -4970,9 +5054,10 @@ function dosTime(time, localTzOffset = (t) => -(/* @__PURE__ */ new Date(t * 1e3
4970
5054
  /** Writes git's zip archive (`git archive --format=zip`). */
4971
5055
  var ZipArchiveWriter = class {
4972
5056
  settings;
4973
- out = new ByteBuffer(65536);
5057
+ sink;
5058
+ out;
4974
5059
  dir = new ByteBuffer(4096);
4975
- le = new LeWriter(this.out);
5060
+ le;
4976
5061
  dirLe = new LeWriter(this.dir);
4977
5062
  entries = 0;
4978
5063
  maxCreatorVersion = 0;
@@ -4980,14 +5065,17 @@ var ZipArchiveWriter = class {
4980
5065
  dosTimeOfDay;
4981
5066
  constructor(settings) {
4982
5067
  this.settings = settings;
5068
+ this.sink = new ArchiveSink(settings.output, 65536);
5069
+ this.out = this.sink.buffer;
5070
+ this.le = new LeWriter(this.out);
4983
5071
  const dos = dosTime(settings.time, settings.localTzOffset);
4984
5072
  this.dosDate = dos.date;
4985
5073
  this.dosTimeOfDay = dos.time;
4986
5074
  }
4987
5075
  /** `write_zip_entry`. */
4988
- entry(entry) {
5076
+ async entry(entry) {
4989
5077
  const { path, mode, id } = entry;
4990
- const offset = this.out.length;
5078
+ const offset = this.sink.position;
4991
5079
  let flags = 0;
4992
5080
  let crc = 0;
4993
5081
  let isBinary;
@@ -4997,8 +5085,8 @@ var ZipArchiveWriter = class {
4997
5085
  let attr2;
4998
5086
  let out;
4999
5087
  let compressedSize;
5000
- const size = entry.content.length;
5001
5088
  const streamed = entry.streamed === true && isRegMode(mode);
5089
+ const size = streamed && entry.stream ? entry.size ?? 0 : entry.content.length;
5002
5090
  if (!onlyAscii(path)) {
5003
5091
  if (isUtf8$1(path)) flags |= ZIP_UTF8;
5004
5092
  else this.settings.onWarning?.(`warning: path is not valid UTF-8: ${latin1$6(path)}`);
@@ -5072,19 +5160,11 @@ var ZipArchiveWriter = class {
5072
5160
  le.u64(compressedSize);
5073
5161
  }
5074
5162
  if (streamed) {
5075
- crc = crc32(entry.content);
5076
- isBinary = entry.binary ?? bufferIsBinary(entry.content.subarray(0, 16384));
5077
- if (method === METHOD_STORE) {
5078
- this.out.push(entry.content);
5079
- compressedSize = size;
5080
- } else {
5081
- const deflated = deflateSync([entry.content], {
5082
- format: "raw",
5083
- level
5084
- });
5085
- this.out.push(deflated);
5086
- compressedSize = deflated.length;
5087
- }
5163
+ const streamedOut = await this.writeStreamed(entry, size, method === METHOD_STORE, level);
5164
+ if (!streamedOut) return `cannot stream blob ${id}`;
5165
+ crc = streamedOut.crc;
5166
+ isBinary = streamedOut.isBinary;
5167
+ compressedSize = streamedOut.compressedSize;
5088
5168
  le.u32(134695760);
5089
5169
  le.u32(crc);
5090
5170
  if (size >= MAX32 || compressedSize >= MAX32) {
@@ -5094,7 +5174,7 @@ var ZipArchiveWriter = class {
5094
5174
  le.u32(compressedSize);
5095
5175
  le.u32(size);
5096
5176
  }
5097
- } else if (compressedSize > 0 && out) this.out.push(out);
5177
+ } else if (compressedSize > 0 && out) await this.sink.write(out);
5098
5178
  let zip64DirPayload = 0;
5099
5179
  let dirExtraSize = EXTRA_MTIME_SIZE;
5100
5180
  if (compressedSize > MAX32 || size > MAX32 || offset > MAX32) {
@@ -5131,10 +5211,54 @@ var ZipArchiveWriter = class {
5131
5211
  if (offset >= MAX32) d.u64(offset);
5132
5212
  }
5133
5213
  this.entries++;
5214
+ await this.sink.flush();
5215
+ }
5216
+ /**
5217
+ * A streamed blob's data (archive-zip.c's `stream` loops): the CRC-32 and the deflate
5218
+ * computed as it is read, `entry_is_binary` asked of its first read (16 KiB); undefined
5219
+ * when it cannot be read whole.
5220
+ */
5221
+ async writeStreamed(entry, size, store, level) {
5222
+ const crc = new CRC32();
5223
+ const deflater = store ? void 0 : createDeflater({
5224
+ format: "raw",
5225
+ level
5226
+ });
5227
+ const head = new ByteBuffer(STREAM_BUFFER_SIZE);
5228
+ let total = 0;
5229
+ let compressedSize = 0;
5230
+ const emit = async (chunks) => {
5231
+ for (const c of chunks) {
5232
+ compressedSize += c.length;
5233
+ await this.sink.write(c);
5234
+ }
5235
+ };
5236
+ try {
5237
+ for await (const chunk of entry.stream ?? [entry.content]) {
5238
+ if (total + chunk.length > size) return void 0;
5239
+ total += chunk.length;
5240
+ crc.update(chunk);
5241
+ if (head.length < STREAM_BUFFER_SIZE) head.push(chunk.subarray(0, STREAM_BUFFER_SIZE - head.length));
5242
+ if (deflater) await emit(deflater.push(chunk));
5243
+ else {
5244
+ compressedSize += chunk.length;
5245
+ await this.sink.write(chunk);
5246
+ }
5247
+ }
5248
+ } catch {
5249
+ return;
5250
+ }
5251
+ if (total !== size) return void 0;
5252
+ if (deflater) await emit(deflater.finish());
5253
+ return {
5254
+ crc: crc.getValue(),
5255
+ isBinary: entry.binary ?? bufferIsBinary(head.bytes()),
5256
+ compressedSize
5257
+ };
5134
5258
  }
5135
5259
  /** `write_zip_trailer`. */
5136
- finish() {
5137
- const zipOffset = this.out.length;
5260
+ async finish() {
5261
+ const zipOffset = this.sink.position;
5138
5262
  const dirBytes = this.dir.bytes();
5139
5263
  const clamped = this.entries > 65535 || zipOffset > MAX32;
5140
5264
  this.out.push(dirBytes);
@@ -5165,7 +5289,7 @@ var ZipArchiveWriter = class {
5165
5289
  le.u32(clamp32(zipOffset));
5166
5290
  le.u16(commitId ? this.settings.hexLength ?? commitId.length : 0);
5167
5291
  if (commitId) this.out.push(asciiBytes(commitId));
5168
- return this.out.bytes();
5292
+ return this.sink.finish();
5169
5293
  }
5170
5294
  };
5171
5295
  /** Bytes as one character each (git prints paths as their bytes). */
@@ -5178,6 +5302,8 @@ function latin1$6(bytes) {
5178
5302
  //#region src/commands/archive/archive-command.ts
5179
5303
  /** git's builtin gzip filter (`tar.tgz.command`, `tar.tar.gz.command`). */
5180
5304
  const INTERNAL_GZIP_COMMAND = "git archive gzip";
5305
+ /** How many bytes {@link ArchiveCommand.callStream} holds before the writer waits. */
5306
+ const STREAM_HIGH_WATER_MARK = 1 << 20;
5181
5307
  const USAGE$11 = "usage: git archive [<options>] <tree-ish> [<path>...]\n or: git archive --list\n or: git archive --remote <repo> [--exec <cmd>] [<options>] <tree-ish> [<path>...]\n or: git archive --remote <repo> [--exec <cmd>] --list";
5182
5308
  /** git's default `core.bigFileThreshold` (512 MiB). */
5183
5309
  const DEFAULT_BIG_FILE_THRESHOLD$1 = 536870912;
@@ -5213,6 +5339,8 @@ var ArchiveCommand = class extends GitCommand {
5213
5339
  worktreeAttributes = false;
5214
5340
  currentDirectory = "";
5215
5341
  filterRunner;
5342
+ streamFilterRunner;
5343
+ bigFileThreshold;
5216
5344
  userUmask = 18;
5217
5345
  localTzOffset;
5218
5346
  filterDrivers;
@@ -5248,8 +5376,12 @@ var ArchiveCommand = class extends GitCommand {
5248
5376
  return this;
5249
5377
  }
5250
5378
  /**
5251
- * `--add-file=<file>`: a file of the worktree (relative to {@link setCurrentDirectory}),
5252
- * added under the current prefix and its base name; `content` gives its bytes instead.
5379
+ * `--add-file=<file>`: a file added under the current prefix and its base name, read as
5380
+ * git reads it: an absolute path as it stands, a relative one from the worktree's top (and
5381
+ * {@link setCurrentDirectory}), through the host environment (`GitHostEnvironment`'s
5382
+ * `realPath`/`hostFilesOf`: files outside the repository, symbolic links followed as
5383
+ * `stat` follows them), else from the worktree itself; git's `File not found` and `Not a
5384
+ * regular file` deaths. `content` gives its bytes instead.
5253
5385
  */
5254
5386
  addFile(path, content, options = {}) {
5255
5387
  this.checkCallable();
@@ -5337,6 +5469,16 @@ var ArchiveCommand = class extends GitCommand {
5337
5469
  this.filterRunner = runner;
5338
5470
  return this;
5339
5471
  }
5472
+ /**
5473
+ * Runs the tar filters' commands as pipes, the archive streamed through them (git's
5474
+ * `write_tar_filter_archive`); preferred over {@link setFilterRunner}, which is handed the
5475
+ * whole tar archive.
5476
+ */
5477
+ setStreamFilterRunner(runner) {
5478
+ this.checkCallable();
5479
+ this.streamFilterRunner = runner;
5480
+ return this;
5481
+ }
5340
5482
  /** The umask `tar.umask=user` stands for (default 022). */
5341
5483
  setUserUmask(umask) {
5342
5484
  this.checkCallable();
@@ -5365,6 +5507,8 @@ var ArchiveCommand = class extends GitCommand {
5365
5507
  }
5366
5508
  /** `git archive --list`: the formats, as git lists them. */
5367
5509
  listFormats() {
5510
+ this.checkTarConfig();
5511
+ if (this.compatibility === "2.43") this.archiveBigFileThreshold();
5368
5512
  return this.archivers().map((a) => a.name);
5369
5513
  }
5370
5514
  /**
@@ -5426,28 +5570,111 @@ var ArchiveCommand = class extends GitCommand {
5426
5570
  ];
5427
5571
  return this.uploadArchive ? all.filter((a) => a.remote) : all;
5428
5572
  }
5429
- /** The `tar.*` variables in configuration order. */
5573
+ /** The `tar.*` variables in configuration order, with where each was read. */
5430
5574
  tarConfig() {
5431
5575
  return RemoteConfigStore.from(this._workingCopy).entriesWithPrefix("tar.") ?? [];
5432
5576
  }
5433
- /** `tar.umask`. */
5577
+ /**
5578
+ * `init_tar_archiver`'s `git_config(git_tar_config)`, which every `git archive` runs
5579
+ * first (`--list` and zip included): the first variable it refuses, in configuration
5580
+ * order, dies (a `tar.<format>.command` without a value, a `tar.umask` that is no number).
5581
+ */
5582
+ checkTarConfig() {
5583
+ this.tarUmask();
5584
+ }
5585
+ /** `tar.umask`, the tar config's deaths checked on the way. */
5434
5586
  tarUmask() {
5435
5587
  let umask = 2;
5436
- for (const { key, value } of this.tarConfig()) {
5588
+ for (const { key, value, file, line } of this.tarConfig()) {
5589
+ const last = key.lastIndexOf(".");
5590
+ if (last > 4 && key.slice(last + 1) === "command" && value === void 0) {
5591
+ const fatal = file !== void 0 && line !== void 0 ? `fatal: bad config variable '${key}' in file '${file}' at line ${line}` : `fatal: unable to parse '${key}' from command-line config`;
5592
+ throw new GitApiError(`error: missing value for '${key}'\n${fatal}`);
5593
+ }
5437
5594
  if (key !== "tar.umask") continue;
5438
5595
  if (value === "user") umask = this.userUmask;
5439
5596
  else {
5440
- const n = parseGitInt$1(value);
5441
- if (n === void 0) throw new GitApiError(`fatal: bad numeric config value '${value}' for 'tar.umask': invalid unit`);
5597
+ const n = parseGitInt$1(value ?? "");
5598
+ if (n === void 0) {
5599
+ const where = file !== void 0 ? ` in file ${file}` : "";
5600
+ throw new GitApiError(`fatal: bad numeric config value '${value ?? ""}' for 'tar.umask'${where}: invalid unit`);
5601
+ }
5442
5602
  umask = n;
5443
5603
  }
5444
5604
  }
5445
5605
  return umask;
5446
5606
  }
5607
+ /**
5608
+ * `core.bigFileThreshold` (git's `unsigned long`, default 512 MiB): git 2.43 reads it with
5609
+ * the core settings when it starts (every value in order, the first it refuses dying), 2.5x
5610
+ * at the first regular file it archives (the last value only).
5611
+ *
5612
+ * @internal
5613
+ */
5614
+ archiveBigFileThreshold() {
5615
+ if (this.bigFileThreshold !== void 0) return this.bigFileThreshold;
5616
+ const key = "core.bigfilethreshold";
5617
+ const values = RemoteConfigStore.from(this._workingCopy).valuesWithOrigin(key);
5618
+ let threshold = DEFAULT_BIG_FILE_THRESHOLD$1;
5619
+ const checked = this.compatibility === "2.43" ? values : values.slice(-1);
5620
+ for (const { text, file } of checked) {
5621
+ const n = parseGitUlong(text);
5622
+ if (typeof n !== "number") {
5623
+ const where = file !== void 0 ? ` in file ${file}` : "";
5624
+ throw new GitApiError(`fatal: bad numeric config value '${text ?? ""}' for '${key}'${where}: ${n}`);
5625
+ }
5626
+ threshold = n;
5627
+ }
5628
+ this.bigFileThreshold = threshold;
5629
+ return threshold;
5630
+ }
5447
5631
  /** The archive's bytes. */
5448
5632
  async call() {
5449
5633
  this.checkCallable();
5450
5634
  this.setCallable(false);
5635
+ const chunks = [];
5636
+ await this.produce((chunk) => {
5637
+ chunks.push(chunk);
5638
+ });
5639
+ return join$1(chunks);
5640
+ }
5641
+ /**
5642
+ * The archive's bytes as they are written, in chunks of about 64 KiB, the same bytes
5643
+ * {@link call} returns: blobs above `core.bigFileThreshold` are streamed from the store
5644
+ * and never held whole, and a tar filter (the builtin gzip, or a command through
5645
+ * {@link setStreamFilterRunner}) filters as the archive is written. The writer waits while
5646
+ * a mebibyte is unread. Nothing runs until the iteration starts; where git dies the
5647
+ * iteration throws a {@link GitApiError} (after the bytes git would have written).
5648
+ *
5649
+ * @example
5650
+ * ```typescript
5651
+ * for await (const chunk of git.archive().setFormat("zip").setTree("HEAD").callStream()) {
5652
+ * await sink.write(chunk);
5653
+ * }
5654
+ * ```
5655
+ */
5656
+ callStream() {
5657
+ this.checkCallable();
5658
+ this.setCallable(false);
5659
+ const queue = createByteQueue({
5660
+ highWaterMark: STREAM_HIGH_WATER_MARK,
5661
+ coalesce: 0
5662
+ });
5663
+ let started = false;
5664
+ const start = () => {
5665
+ if (started) return;
5666
+ started = true;
5667
+ this.produce((chunk) => queue.push(chunk)).then(() => queue.end(), (error) => queue.end(error instanceof Error ? error : new Error(String(error))));
5668
+ };
5669
+ return { [Symbol.asyncIterator]() {
5670
+ start();
5671
+ return queue.stream;
5672
+ } };
5673
+ }
5674
+ /** `write_archive`: the archive written to `output`. */
5675
+ async produce(output) {
5676
+ this.checkTarConfig();
5677
+ if (this.compatibility === "2.43") this.archiveBigFileThreshold();
5451
5678
  const extras = await this.readExtraFiles();
5452
5679
  let format = this.format;
5453
5680
  if (format === void 0 && this.outputName !== void 0) format = this.formatFromFilename(this.outputName);
@@ -5462,11 +5689,13 @@ var ArchiveCommand = class extends GitCommand {
5462
5689
  if (levelsOk && (this.compressionLevel <= 9 || highOk)) level = this.compressionLevel;
5463
5690
  else throw new GitApiError(`fatal: Argument not supported for format '${format}': -${this.compressionLevel}`);
5464
5691
  }
5465
- return this.inOneOperation(async () => {
5692
+ await this.inOneOperation(async () => {
5466
5693
  const target = await this.resolveTreeish(this.tree);
5694
+ const filter = archiver.command === void 0 ? void 0 : this.openFilter(archiver.command, level, output);
5467
5695
  const settings = {
5468
5696
  time: target.time,
5469
5697
  compressionLevel: level,
5698
+ output: filter?.input ?? output,
5470
5699
  ...target.commitId ? { commitId: target.commitId } : {}
5471
5700
  };
5472
5701
  const writer = archiver.name === "zip" ? new ZipArchiveWriter({
@@ -5483,60 +5712,168 @@ var ArchiveCommand = class extends GitCommand {
5483
5712
  await run.prepare();
5484
5713
  await run.writeEntries();
5485
5714
  }, (refusal) => refusal instanceof InvalidPathError ? new GitApiError(refusal.message, { exitCode: 255 }) : refusal);
5486
- const archive = writer.finish();
5487
- if (archiver.command === void 0) return archive;
5488
- return this.filter(archiver.command, archive, level);
5715
+ await writer.finish();
5716
+ await filter?.finish();
5489
5717
  });
5490
5718
  }
5491
- async filter(command, archive, level) {
5719
+ /**
5720
+ * `write_tar_filter_archive`: the tar archive's bytes through the filter (the builtin
5721
+ * gzip, else the command, started before anything is written).
5722
+ */
5723
+ openFilter(command, level, output) {
5492
5724
  if (command === "git archive gzip") {
5493
5725
  if (level > 9) throw new GitApiError("fatal: deflateInit2: stream consistency error (no message)");
5494
- return deflateSync([archive], {
5726
+ const deflater = createDeflater({
5495
5727
  format: "gzip",
5496
5728
  level
5497
5729
  });
5730
+ const send = async (chunks) => {
5731
+ for (const chunk of chunks) await output(chunk);
5732
+ };
5733
+ return {
5734
+ input: (chunk) => send(deflater.push(chunk)),
5735
+ finish: () => send(deflater.finish())
5736
+ };
5498
5737
  }
5499
5738
  const cmd = level >= 0 ? `${command} -${level}` : command;
5500
5739
  if (!cmd) throw new GitApiError("fatal: unable to start '' filter: No such file or directory");
5501
- if (!this.filterRunner) throw new GitApiError(`fatal: unable to start '${cmd}' filter`);
5502
- try {
5503
- return await this.filterRunner(cmd, archive);
5504
- } catch {
5505
- throw new GitApiError(`fatal: '${cmd}' filter reported error`);
5740
+ const failed = () => new GitApiError(`fatal: '${cmd}' filter reported error`);
5741
+ const streamRunner = this.streamFilterRunner;
5742
+ if (streamRunner) {
5743
+ const queue = createByteQueue({
5744
+ highWaterMark: STREAM_HIGH_WATER_MARK,
5745
+ coalesce: 0
5746
+ });
5747
+ let failure;
5748
+ const pump = (async () => {
5749
+ try {
5750
+ for await (const chunk of streamRunner(cmd, queue.stream)) await output(chunk);
5751
+ } catch {
5752
+ failure = failed();
5753
+ queue.end(failure);
5754
+ }
5755
+ })();
5756
+ return {
5757
+ input: async (chunk) => {
5758
+ if (failure) throw failure;
5759
+ try {
5760
+ await queue.push(chunk);
5761
+ } catch (error) {
5762
+ throw failure ?? error;
5763
+ }
5764
+ },
5765
+ finish: async () => {
5766
+ queue.end();
5767
+ await pump;
5768
+ if (failure) throw failure;
5769
+ }
5770
+ };
5506
5771
  }
5772
+ const runner = this.filterRunner;
5773
+ if (!runner) throw new GitApiError(`fatal: unable to start '${cmd}' filter`);
5774
+ const chunks = [];
5775
+ return {
5776
+ input: (chunk) => {
5777
+ chunks.push(chunk);
5778
+ },
5779
+ finish: async () => {
5780
+ let filtered;
5781
+ try {
5782
+ filtered = await runner(cmd, join$1(chunks));
5783
+ } catch {
5784
+ throw failed();
5785
+ }
5786
+ await output(filtered);
5787
+ }
5788
+ };
5507
5789
  }
5508
- /** `--add-file`'s files read (git stats them while parsing its options). */
5790
+ /**
5791
+ * `--add-file`'s files checked as git stats them while parsing its options (their content
5792
+ * is read when they are written).
5793
+ */
5509
5794
  async readExtraFiles() {
5510
5795
  const out = [];
5511
5796
  for (const extra of this.extraFiles) {
5512
- const path = `${this.currentDirectory}${extra.path}`;
5797
+ const path = !extra.virtual && extra.path.startsWith("/") ? extra.path : `${this.currentDirectory}${extra.path}`;
5513
5798
  if (extra.content) {
5799
+ const content = extra.content;
5514
5800
  out.push({
5515
5801
  path,
5516
5802
  base: extra.base,
5517
- content: extra.content,
5803
+ read: async () => content,
5518
5804
  mode: extra.executable ? 33261 : 33188,
5519
5805
  virtual: extra.virtual
5520
5806
  });
5521
5807
  continue;
5522
5808
  }
5809
+ const host = await this.hostExtraFile(path);
5810
+ if (host === "missing") throw new GitApiError(`fatal: File not found: ${path}`);
5811
+ if (host === "not-regular") throw new GitApiError(`fatal: Not a regular file: ${path}`);
5812
+ if (host) {
5813
+ out.push({
5814
+ path,
5815
+ base: extra.base,
5816
+ read: host.read,
5817
+ mode: host.mode,
5818
+ virtual: false
5819
+ });
5820
+ continue;
5821
+ }
5523
5822
  const worktree = this.worktreeAccess;
5524
5823
  const resolved = normalizeWorktreePath(path);
5525
5824
  const entry = resolved === void 0 ? void 0 : await worktree?.getEntry(resolved).catch(() => void 0);
5526
5825
  if (!entry) throw new GitApiError(`fatal: File not found: ${path}`);
5527
5826
  if (entry.isDirectory || (entry.mode & 61440) !== 32768) throw new GitApiError(`fatal: Not a regular file: ${path}`);
5528
- const chunks = [];
5529
- for await (const c of worktree.readContent(resolved)) chunks.push(c);
5530
5827
  out.push({
5531
5828
  path,
5532
5829
  base: extra.base,
5533
- content: join$1(chunks),
5830
+ read: async () => {
5831
+ const chunks = [];
5832
+ for await (const c of worktree.readContent(resolved)) chunks.push(c);
5833
+ return join$1(chunks);
5834
+ },
5534
5835
  mode: entry.mode & 64 ? 33261 : 33188,
5535
5836
  virtual: false
5536
5837
  });
5537
5838
  }
5538
5839
  return out;
5539
5840
  }
5841
+ /**
5842
+ * `--add-file`'s `stat` through the host environment: the path from the worktree's top
5843
+ * (a bare repository's git directory), links followed (`realPath`), the file read through
5844
+ * `hostFilesOf`; undefined when the host gives no access to its files (the worktree is
5845
+ * read instead).
5846
+ */
5847
+ async hostExtraFile(path) {
5848
+ const environment = hostEnvironmentOf(this._workingCopy);
5849
+ if (!environment?.hostFilesOf) return void 0;
5850
+ let top;
5851
+ if (!path.startsWith("/")) {
5852
+ top = this.archiveWorktree?.hostPath ?? this._workingCopy.config?.hostGitDir;
5853
+ if (top === void 0) return void 0;
5854
+ }
5855
+ const hostPath = top === void 0 ? path : `${top.replace(/\/+$/, "")}/${path}`;
5856
+ const real = environment.realPath ? await environment.realPath(hostPath).catch(() => void 0) : hostPath;
5857
+ if (real === void 0) return "missing";
5858
+ const location = await environment.hostFilesOf(real).catch(() => void 0);
5859
+ if (!location) return void 0;
5860
+ const stats = (environment.statFile ? await environment.statFile(real).catch(() => void 0) : void 0) ?? await location.files.stats(location.path).catch(() => void 0);
5861
+ if (!stats) return "missing";
5862
+ if (stats.kind !== "file") return "not-regular";
5863
+ const { files, path: inFiles } = location;
5864
+ return {
5865
+ mode: (stats.mode ?? 420) & 64 ? 33261 : 33188,
5866
+ read: async () => {
5867
+ const chunks = [];
5868
+ try {
5869
+ for await (const c of files.read(inFiles)) chunks.push(c);
5870
+ } catch {
5871
+ throw new GitApiError(`error: cannot read '${path}'`, { exitCode: 255 });
5872
+ }
5873
+ return join$1(chunks);
5874
+ }
5875
+ };
5876
+ }
5540
5877
  /** `parse_treeish_arg`: the tree, the commit (if any) and the archive's time. */
5541
5878
  async resolveTreeish(name) {
5542
5879
  const resolver = this.revisionResolver();
@@ -5547,6 +5884,9 @@ var ArchiveCommand = class extends GitCommand {
5547
5884
  }
5548
5885
  const id = await resolver.resolve(name).catch(() => void 0);
5549
5886
  if (id === void 0) throw new GitApiError(`fatal: not a valid object name: ${name}`);
5887
+ const colon = name.indexOf(":");
5888
+ const refName = this.uploadArchive && !this.uploadArchive.allowUnreachable && colon >= 0 ? name.slice(0, colon) : name;
5889
+ const ref = (await resolver.dwimRef(refName).catch(() => []))[0]?.ref;
5550
5890
  const peeled = await resolver.peelTags(id);
5551
5891
  let commitId;
5552
5892
  let time;
@@ -5568,7 +5908,8 @@ var ArchiveCommand = class extends GitCommand {
5568
5908
  return {
5569
5909
  tree,
5570
5910
  time,
5571
- ...commitId ? { commitId } : {}
5911
+ ...commitId ? { commitId } : {},
5912
+ ...ref ? { ref } : {}
5572
5913
  };
5573
5914
  }
5574
5915
  /** @internal */
@@ -5590,6 +5931,18 @@ var ArchiveCommand = class extends GitCommand {
5590
5931
  archiveEntries(id) {
5591
5932
  return this.treeEntries(id);
5592
5933
  }
5934
+ /** @internal The size of a blob (`oid_object_info`), undefined when it cannot be read. */
5935
+ archiveBlobSize(id) {
5936
+ return this.blobs.size(id).catch(() => void 0);
5937
+ }
5938
+ /** @internal A blob's bytes as the store reads them (`open_istream`). */
5939
+ async archiveBlobStream(id) {
5940
+ return await this.blobs.load(id).catch(() => void 0) ?? void 0;
5941
+ }
5942
+ /** @internal */
5943
+ archiveCompatibility() {
5944
+ return this.compatibility;
5945
+ }
5593
5946
  /** @internal */
5594
5947
  async archiveBlob(id) {
5595
5948
  const content = await this.blobs.load(id).catch(() => void 0);
@@ -5623,14 +5976,19 @@ var ArchiveCommand = class extends GitCommand {
5623
5976
  archiveConfig(key) {
5624
5977
  return configValue(this._workingCopy, key);
5625
5978
  }
5626
- /** @internal The attributes git reads without a worktree (bare, or `GIT_ATTR_INDEX`). */
5979
+ /**
5980
+ * @internal The attributes git reads without a worktree (bare, or `GIT_ATTR_INDEX`). git
5981
+ * 2.43 reads a bare repository's in-tree files from HEAD when no attribute source is set
5982
+ * (2.5x reads none): `--worktree-attributes` in a bare repository sees them there.
5983
+ */
5627
5984
  archiveBareAttributes(indexTree) {
5628
5985
  return bareAttributesResolver({
5629
5986
  workingCopy: this._workingCopy,
5630
5987
  trees: this.trees,
5631
5988
  blobs: this.blobs,
5632
5989
  revisions: () => this.revisionResolver(),
5633
- ...indexTree ? { indexTree } : {}
5990
+ ...indexTree ? { indexTree } : {},
5991
+ ...this.compatibility === "2.43" && !("worktree" in this._workingCopy) ? { defaultSource: "HEAD" } : {}
5634
5992
  });
5635
5993
  }
5636
5994
  /** @internal `%h` and friends, `%(describe)`, for `export-subst`. */
@@ -5668,6 +6026,7 @@ function matchExtension(filename, ext) {
5668
6026
  }
5669
6027
  function join$1(chunks) {
5670
6028
  if (chunks.length === 1) return chunks[0];
6029
+ if (chunks.length === 0) return /* @__PURE__ */ new Uint8Array(0);
5671
6030
  let size = 0;
5672
6031
  for (const c of chunks) size += c.length;
5673
6032
  const out = new Uint8Array(size);
@@ -5724,7 +6083,6 @@ var ArchiveRun = class {
5724
6083
  attrCache = /* @__PURE__ */ new Map();
5725
6084
  bareResolver;
5726
6085
  filterContext;
5727
- bigFileThreshold = DEFAULT_BIG_FILE_THRESHOLD$1;
5728
6086
  describeBudget = 1;
5729
6087
  conversionSettings;
5730
6088
  base;
@@ -5743,8 +6101,6 @@ var ArchiveRun = class {
5743
6101
  }
5744
6102
  /** `parse_pathspec_arg` and the attribute sources. */
5745
6103
  async prepare() {
5746
- const threshold = parseGitInt$1(this.cmd.archiveConfig("core.bigFileThreshold"));
5747
- if (threshold !== void 0 && threshold > 0) this.bigFileThreshold = threshold;
5748
6104
  const worktree = this.worktree;
5749
6105
  if (!this.settings.worktreeAttributes) {
5750
6106
  if (worktree?.contentFilter) this.filterContext = {
@@ -5838,8 +6194,8 @@ var ArchiveRun = class {
5838
6194
  report(path) {
5839
6195
  if (this.settings.verbose) this.settings.messages.push(decodeGitPath(path));
5840
6196
  }
5841
- emit(entry) {
5842
- const error = this.writer.entry(entry);
6197
+ async emit(entry) {
6198
+ const error = await this.writer.entry(entry);
5843
6199
  if (error) throw new GitApiError(`error: ${error}`, { exitCode: 255 });
5844
6200
  }
5845
6201
  /** `write_archive_entries`. */
@@ -5850,7 +6206,7 @@ var ArchiveRun = class {
5850
6206
  while (len > 1 && base[len - 2] === "/") len--;
5851
6207
  const path = this.base.subarray(0, encodeGitPath(base.slice(0, len)).length);
5852
6208
  this.report(path);
5853
- this.emit({
6209
+ await this.emit({
5854
6210
  path,
5855
6211
  mode: 16895,
5856
6212
  id: this.target.tree,
@@ -5869,7 +6225,7 @@ var ArchiveRun = class {
5869
6225
  path,
5870
6226
  mode: extra.mode,
5871
6227
  id,
5872
- content: extra.content
6228
+ content: /* @__PURE__ */ new Uint8Array(0)
5873
6229
  };
5874
6230
  binaries.push(this.binaryOf(decodeGitPath(path.subarray(this.base.length))));
5875
6231
  entries.push(entry);
@@ -5878,7 +6234,8 @@ var ArchiveRun = class {
5878
6234
  const entry = entries[i];
5879
6235
  const binary = await binaries[i];
5880
6236
  if (binary !== void 0) entry.binary = binary;
5881
- this.emit(entry);
6237
+ entry.content = await this.extras[i].read();
6238
+ await this.emit(entry);
5882
6239
  }
5883
6240
  }
5884
6241
  /** `read_tree` with `queue_or_write_archive_entry`. */
@@ -5926,7 +6283,7 @@ var ArchiveRun = class {
5926
6283
  const convertPath = rel;
5927
6284
  this.report(archivePath);
5928
6285
  if (isDir) {
5929
- this.emit({
6286
+ await this.emit({
5930
6287
  path: archivePath,
5931
6288
  mode,
5932
6289
  id,
@@ -5934,25 +6291,53 @@ var ArchiveRun = class {
5934
6291
  });
5935
6292
  return;
5936
6293
  }
5937
- let content = await this.cmd.archiveBlob(id);
5938
- if (!content) throw new GitApiError(`error: cannot read '${id}'`, { exitCode: 255 });
5939
- const streamed = isRegMode(mode) && !convert && content.length > this.bigFileThreshold;
5940
- if (isRegMode(mode) && !streamed) {
5941
- content = await this.smudge(convertPath, id, content, mode);
5942
- if (convert && this.target.commitId) content = await this.substitute(content);
6294
+ let size;
6295
+ if (isRegMode(mode) && !convert) {
6296
+ const threshold = this.cmd.archiveBigFileThreshold();
6297
+ size = await this.cmd.archiveBlobSize(id);
6298
+ if (size !== void 0 && size <= threshold) size = void 0;
6299
+ }
6300
+ let entry;
6301
+ if (size !== void 0) {
6302
+ const stream = await this.cmd.archiveBlobStream(id);
6303
+ if (!stream) throw new GitApiError(`error: cannot stream blob ${id}`, { exitCode: 255 });
6304
+ entry = {
6305
+ path: archivePath,
6306
+ mode,
6307
+ id,
6308
+ content: /* @__PURE__ */ new Uint8Array(0),
6309
+ streamed: true,
6310
+ stream,
6311
+ size
6312
+ };
6313
+ } else {
6314
+ let content = await this.cmd.archiveBlob(id);
6315
+ if (!content) throw new GitApiError(`error: cannot read '${id}'`, { exitCode: 255 });
6316
+ if (isRegMode(mode)) {
6317
+ content = await this.smudge(convertPath, id, content, mode);
6318
+ if (convert && this.target.commitId) content = await this.substitute(content);
6319
+ }
6320
+ entry = {
6321
+ path: archivePath,
6322
+ mode,
6323
+ id,
6324
+ content
6325
+ };
5943
6326
  }
5944
- const entry = {
5945
- path: archivePath,
5946
- mode,
5947
- id,
5948
- content
5949
- };
5950
- if (streamed) entry.streamed = true;
5951
6327
  if (this.writer instanceof ZipArchiveWriter && (isRegMode(mode) || isLinkMode(mode))) {
5952
6328
  const binary = await this.binaryOf(convertPath);
5953
6329
  if (binary !== void 0) entry.binary = binary;
5954
6330
  }
5955
- this.emit(entry);
6331
+ await this.emit(entry);
6332
+ }
6333
+ /** archive.c's `init_checkout_metadata`: the ref, the commit (else the tree), the blob. */
6334
+ metadata(blob) {
6335
+ const treeish = this.target.commitId ?? this.target.tree;
6336
+ return {
6337
+ ...this.target.ref ? { ref: this.target.ref } : {},
6338
+ treeish,
6339
+ blob
6340
+ };
5956
6341
  }
5957
6342
  /** zip's `entry_is_binary`: the diff driver's `binary`, undefined to look at the content. */
5958
6343
  async binaryOf(path) {
@@ -5979,24 +6364,36 @@ var ArchiveRun = class {
5979
6364
  else this.settings.messages.push(`error: failed to encode '${path}' from UTF-8 to ${ca.workingTreeEncoding}`);
5980
6365
  }
5981
6366
  const smudge = ca.driver?.host?.smudge;
6367
+ const command = ca.driver?.smudge;
5982
6368
  let filtered;
5983
- if (smudge) filtered = await smudge.call(ca.driver?.host, out, { path }).catch(() => void 0);
6369
+ if (smudge && command !== "") try {
6370
+ filtered = await smudge.call(ca.driver?.host, out, {
6371
+ path,
6372
+ ...command !== void 0 ? { command } : {},
6373
+ metadata: this.metadata(id)
6374
+ });
6375
+ } catch (error) {
6376
+ if (command !== void 0 && !ca.driver?.required) {
6377
+ const own = error instanceof FilterDriverRunError ? error.lines : [];
6378
+ for (const line of [...own, `external filter '${command}' failed`]) this.settings.messages.push(`error: ${line}`);
6379
+ }
6380
+ }
5984
6381
  if (filtered === void 0 && ca.driver?.required) throw new GitApiError(`fatal: ${path}: smudge filter ${ca.driver.name} failed`);
5985
6382
  return filtered ?? out;
5986
6383
  }
5987
6384
  const filter = this.worktree?.contentFilter;
5988
- if (!filter) return content;
5989
- let out;
6385
+ if (!filter || !isRegMode(mode)) return content;
5990
6386
  try {
5991
- out = await smudgeContent(filter, path, content, mode, this.filterContext);
6387
+ const conversion = await filter.checkout(path, this.filterContext);
6388
+ if (!conversion) return content;
6389
+ return await conversion.apply(content, {
6390
+ onWarning: (message) => this.settings.messages.push(message),
6391
+ metadata: this.metadata(id)
6392
+ });
5992
6393
  } catch (error) {
5993
6394
  if (error instanceof FilterDriverError || isEncodingAttributeError(error)) throw new GitApiError(`fatal: ${error.message}`);
5994
6395
  throw error;
5995
6396
  }
5996
- if (out instanceof Uint8Array) return out;
5997
- const chunks = [];
5998
- for await (const c of out) chunks.push(c);
5999
- return join$1(chunks);
6000
6397
  }
6001
6398
  /** `format_subst`: each `$Format:<fmt>$` expanded for the commit. */
6002
6399
  async substitute(content) {
@@ -11111,19 +11508,6 @@ var RemoteObjectInfoCommand = class extends TransportCommand {
11111
11508
  };
11112
11509
  //#endregion
11113
11510
  //#region src/commands/cat-file/cat-file-command.ts
11114
- /**
11115
- * `git cat-file` (builtin/cat-file.c): an object's type, size, existence or content, one
11116
- * object named on the command line (`-t`, `-s`, `-e`, `-p`, `<type> <object>`) or many read
11117
- * from stdin (`--batch`, `--batch-check`, `--batch-command`, `--batch-all-objects`).
11118
- *
11119
- * @example
11120
- * ```typescript
11121
- * // git cat-file -p HEAD:README.md
11122
- * await git.catFile().setMode("pretty").setObject("HEAD:README.md").setStdout(write).call();
11123
- * // printf 'HEAD\nHEAD:a.txt\n' | git cat-file --batch-check
11124
- * const { stdout } = await git.catFile().setBatch("info").setStdin("HEAD\nHEAD:a.txt\n").callOutput();
11125
- * ```
11126
- */
11127
11511
  const OBJECT_TYPES = /* @__PURE__ */ new Set([
11128
11512
  "blob",
11129
11513
  "tree",
@@ -11327,7 +11711,7 @@ var CatFileCommand = class extends PlumbingCommand {
11327
11711
  for await (const c of object.content) chunks.push(c.slice());
11328
11712
  return {
11329
11713
  type: object.type,
11330
- bytes: concat$10(chunks)
11714
+ bytes: concatBytes(chunks)
11331
11715
  };
11332
11716
  }
11333
11717
  /** `stream_blob`: the blob's content written chunk by chunk. */
@@ -11410,19 +11794,7 @@ var CatFileCommand = class extends PlumbingCommand {
11410
11794
  return 0;
11411
11795
  case "pretty":
11412
11796
  if (object.type === "tree") {
11413
- const config = RemoteConfigStore.from(this._workingCopy);
11414
- const quoteFully = parseGitBool$1(config.value("core.quotePath")) ?? true;
11415
- let out = "";
11416
- for (const entry of decodeTreeBytes(object.content, {
11417
- idLength: compat.compat.rawLength,
11418
- checkNames: false
11419
- })) {
11420
- const kind = entry.mode & S_IFMT$8;
11421
- const type = kind === 16384 ? "tree" : kind === S_IFGITLINK$5 ? "commit" : "blob";
11422
- const mode = entry.mode.toString(8).padStart(6, "0");
11423
- out += `${mode} ${type} ${entry.id}\t${quotePath(entry.name, quoteFully)}\n`;
11424
- }
11425
- await this.write(out);
11797
+ await this.listTree(name);
11426
11798
  return 0;
11427
11799
  }
11428
11800
  await this.write(object.type === "blob" ? object.content : await this.mapIdents(object.content));
@@ -11468,17 +11840,18 @@ var CatFileCommand = class extends PlumbingCommand {
11468
11840
  const entries = await this.listedTreeEntries(id);
11469
11841
  if (!entries) throw new PlumbingError(`fatal: Cannot read object ${id}`);
11470
11842
  let out = "";
11471
- for (const entry of entries) {
11472
- const kind = entry.mode & S_IFMT$8;
11473
- const type = kind === 16384 ? "tree" : kind === S_IFGITLINK$5 ? "commit" : "blob";
11474
- const mode = entry.mode.toString(8).padStart(6, "0");
11475
- out += `${mode} ${type} ${entry.id}\t${quotePath(entry.name, quoteFully)}\n`;
11476
- if (out.length >= 65536) {
11477
- await this.write(out);
11478
- out = "";
11843
+ try {
11844
+ for (const entry of entries) {
11845
+ const mode = entry.mode.toString(8).padStart(6, "0");
11846
+ out += `${mode} ${objectTypeOfMode(entry.mode)} ${entry.id}\t${quotePath(entry.name, quoteFully)}\n`;
11847
+ if (out.length >= 65536) {
11848
+ await this.write(out);
11849
+ out = "";
11850
+ }
11479
11851
  }
11852
+ } finally {
11853
+ await this.write(out);
11480
11854
  }
11481
- await this.write(out);
11482
11855
  }
11483
11856
  /** `<type> <object>` */
11484
11857
  async catTyped(name, id, type) {
@@ -11785,18 +12158,6 @@ function splitCmdline(line) {
11785
12158
  function modeLetter(mode) {
11786
12159
  return mode === "type" ? "t" : mode === "size" ? "s" : mode === "exists" ? "e" : "p";
11787
12160
  }
11788
- function concat$10(chunks) {
11789
- if (chunks.length === 1) return chunks[0];
11790
- let size = 0;
11791
- for (const c of chunks) size += c.length;
11792
- const out = new Uint8Array(size);
11793
- let at = 0;
11794
- for (const c of chunks) {
11795
- out.set(c, at);
11796
- at += c.length;
11797
- }
11798
- return out;
11799
- }
11800
12161
  /**
11801
12162
  * `strbuf_getline` (`strbuf_getdelim_strip_crlf`) over the input as it arrives: each record
11802
12163
  * without its delimiter, and for newline-terminated input without a CR before it (`-z`'s
@@ -11818,14 +12179,14 @@ async function* readLines(input, delimiter) {
11818
12179
  const at = chunk.indexOf(delimiter, start);
11819
12180
  if (at < 0) break;
11820
12181
  const piece = chunk.subarray(start, at);
11821
- const line = pending.length > 0 ? concat$10([...pending, piece]) : piece;
12182
+ const line = pending.length > 0 ? concatBytes([...pending, piece]) : piece;
11822
12183
  pending = [];
11823
12184
  yield emit(line);
11824
12185
  start = at + 1;
11825
12186
  }
11826
12187
  if (start < chunk.length) pending.push(chunk.slice(start));
11827
12188
  }
11828
- if (pending.length > 0) yield emit(concat$10(pending));
12189
+ if (pending.length > 0) yield emit(concatBytes(pending));
11829
12190
  }
11830
12191
  //#endregion
11831
12192
  //#region src/commands/git-paths.ts
@@ -37551,7 +37912,7 @@ var DiffTreeCommand = class extends DiffPlumbingCommand {
37551
37912
  } else if (kind === "commit") out.push(await this.commitOrTree(first, rest.length ? rest : void 0, formats));
37552
37913
  }
37553
37914
  }
37554
- return concat$9(out);
37915
+ return concat$8(out);
37555
37916
  }
37556
37917
  /** The tree walk the run asks for (diff_setup_done: a patch or a stat recurses) */
37557
37918
  walk(formats) {
@@ -37682,7 +38043,7 @@ function parseStdinLine(line, hexLength) {
37682
38043
  }
37683
38044
  return ids.length > 0 ? ids : void 0;
37684
38045
  }
37685
- function concat$9(parts) {
38046
+ function concat$8(parts) {
37686
38047
  let n = 0;
37687
38048
  for (const p of parts) n += p.length;
37688
38049
  const out = new Uint8Array(n);
@@ -37814,7 +38175,7 @@ var DiffPairsCommand = class extends DiffPlumbingCommand {
37814
38175
  }
37815
38176
  }
37816
38177
  await flush();
37817
- return concat$8(out);
38178
+ return concat$7(out);
37818
38179
  }
37819
38180
  };
37820
38181
  function fatal(message) {
@@ -37839,7 +38200,7 @@ function latin1$4(bytes) {
37839
38200
  for (const b of bytes) s += String.fromCharCode(b);
37840
38201
  return s;
37841
38202
  }
37842
- function concat$8(parts) {
38203
+ function concat$7(parts) {
37843
38204
  let n = 0;
37844
38205
  for (const p of parts) n += p.length;
37845
38206
  const out = new Uint8Array(n);
@@ -42029,7 +42390,7 @@ var FormatPatchCommand = class extends RangeDiffBase {
42029
42390
  if (cover) {
42030
42391
  if (thread) ownId = messageId("cover");
42031
42392
  nr = 0;
42032
- const content = concat$7([
42393
+ const content = concat$6([
42033
42394
  await this.coverLetterText(list, origin, {
42034
42395
  subject: subjectOf(),
42035
42396
  thread: threadHeaders(),
@@ -42117,7 +42478,7 @@ Content-Disposition: ${mime.inline ? "inline" : "attachment"}; filename="${part}
42117
42478
  shownOne = true;
42118
42479
  parts.push(bytes, ...diffOfDiff.afterPatch, latin(bases.text), latin(mime ? `\n--${MIME_BOUNDARY_LEADER}${mime.boundary}--\n\n\n` : sig()));
42119
42480
  bases.text = "";
42120
- emit(fileName(subject), concat$7(parts));
42481
+ emit(fileName(subject), concat$6(parts));
42121
42482
  }
42122
42483
  if (!this.stdout && this.writeFiles) {
42123
42484
  const worktree = this.worktreeAccess;
@@ -42128,7 +42489,7 @@ Content-Disposition: ${mime.inline ? "inline" : "attachment"}; filename="${part}
42128
42489
  }
42129
42490
  return {
42130
42491
  patches,
42131
- output: this.stdout ? concat$7(stdoutParts) : new TextEncoder().encode(out.join("")),
42492
+ output: this.stdout ? concat$6(stdoutParts) : new TextEncoder().encode(out.join("")),
42132
42493
  ...this.warnings.length ? { warnings: this.warnings } : {}
42133
42494
  };
42134
42495
  }
@@ -42206,7 +42567,7 @@ Content-Disposition: ${mime.inline ? "inline" : "attachment"}; filename="${part}
42206
42567
  };
42207
42568
  return {
42208
42569
  ...none,
42209
- commentary: blocks.map((b) => concat$7([enc.encode(`${b.title}\n`), b.indented]))
42570
+ commentary: blocks.map((b) => concat$6([enc.encode(`${b.title}\n`), b.indented]))
42210
42571
  };
42211
42572
  }
42212
42573
  /** The subject for the file name (`%f`). */
@@ -42457,7 +42818,7 @@ Content-Disposition: ${mime.inline ? "inline" : "attachment"}; filename="${part}
42457
42818
  text += "\n";
42458
42819
  }
42459
42820
  parts.push(new TextEncoder().encode(text));
42460
- return concat$7(parts);
42821
+ return concat$6(parts);
42461
42822
  }
42462
42823
  /** The commit as stored (its fields encoded again when the store has no raw bytes). */
42463
42824
  async rawCommitBytes(id) {
@@ -42468,7 +42829,7 @@ Content-Disposition: ${mime.inline ? "inline" : "attachment"}; filename="${part}
42468
42829
  if (obj.bytes) return obj.bytes;
42469
42830
  const chunks = [];
42470
42831
  for await (const c of obj.content) chunks.push(c);
42471
- return concat$7(chunks);
42832
+ return concat$6(chunks);
42472
42833
  }
42473
42834
  } catch {}
42474
42835
  const commit = await this.commits.load(id);
@@ -42592,7 +42953,7 @@ function cleanMessageId(id) {
42592
42953
  function latin(text) {
42593
42954
  return new TextEncoder().encode(text);
42594
42955
  }
42595
- function concat$7(parts) {
42956
+ function concat$6(parts) {
42596
42957
  let size = 0;
42597
42958
  for (const p of parts) size += p.length;
42598
42959
  const out = new Uint8Array(size);
@@ -43621,7 +43982,7 @@ var InterpretTrailersCommand = class extends GitCommand {
43621
43982
  if (!file || stats?.kind !== "file") throw new GitApiError(`fatal: could not read input file '${name}': ${stats ? "Is a directory" : "No such file or directory"}`, { exitCode: 128 });
43622
43983
  const chunks = [];
43623
43984
  for await (const chunk of file.files.read(file.path)) chunks.push(chunk);
43624
- const output = await process(decoder$3.decode(concat$6(chunks)));
43985
+ const output = await process(decoder$3.decode(concat$5(chunks)));
43625
43986
  if (this.inPlace) await file.files.write(file.path, [encoder$5.encode(output)]);
43626
43987
  else stdout += output;
43627
43988
  }
@@ -43631,7 +43992,7 @@ var InterpretTrailersCommand = class extends GitCommand {
43631
43992
  };
43632
43993
  }
43633
43994
  };
43634
- function concat$6(chunks) {
43995
+ function concat$5(chunks) {
43635
43996
  if (chunks.length === 1) return chunks[0];
43636
43997
  const out = new Uint8Array(chunks.reduce((n, c) => n + c.length, 0));
43637
43998
  let at = 0;
@@ -44097,18 +44458,25 @@ var LsFilesCommand = class extends PlumbingCommand {
44097
44458
  let id;
44098
44459
  try {
44099
44460
  id = await this.resolveRevision(name);
44100
- } catch {
44461
+ } catch (e) {
44462
+ if (e instanceof CorruptTreeError) throw e;
44101
44463
  throw new PlumbingError(`fatal: tree-ish ${name} not found.`);
44102
44464
  }
44103
44465
  let tree;
44104
44466
  try {
44105
44467
  tree = await this.resolveRevision(`${id}^{tree}`);
44106
- } catch {
44468
+ } catch (e) {
44469
+ if (e instanceof CorruptTreeError) throw e;
44107
44470
  throw new PlumbingError(`fatal: bad tree-ish ${name}`);
44108
44471
  }
44109
44472
  for (const e of list) if (e.stage !== 0) e.stage = 3;
44110
44473
  const add = async (treeId, base) => {
44111
- for (const entry of await this.treeEntries(treeId)) {
44474
+ const entries = await this.listedTreeEntries(treeId);
44475
+ if (!entries) {
44476
+ this.warn(`error: Could not read ${treeId}`);
44477
+ throw new PlumbingError(`fatal: unable to read tree entries ${name}`);
44478
+ }
44479
+ for (const entry of entries) {
44112
44480
  const path = base + entry.name;
44113
44481
  const nameBytes = pathspecName(path);
44114
44482
  if ((entry.mode & S_IFMT$4) === 16384) {
@@ -44193,7 +44561,7 @@ var LsFilesCommand = class extends PlumbingCommand {
44193
44561
  }
44194
44562
  if (!path.startsWith("/") && worktree) {
44195
44563
  if (path.startsWith(".git/") && worktree.readGitDirFile) return worktree.readGitDirFile(path.slice(5)).catch(() => void 0);
44196
- return readAll$1(worktree.readContent(path)).catch(() => void 0);
44564
+ return readAllBytes(worktree.readContent(path)).catch(() => void 0);
44197
44565
  }
44198
44566
  };
44199
44567
  const files = [];
@@ -44225,7 +44593,7 @@ var LsFilesCommand = class extends PlumbingCommand {
44225
44593
  if (worktree) {
44226
44594
  const entry = await worktree.getEntry(path).catch(() => void 0);
44227
44595
  if (entry && !entry.isDirectory && entry.mode !== FileMode$1.SYMLINK) {
44228
- const bytes = await readAll$1(worktree.readContent(path)).catch(() => void 0);
44596
+ const bytes = await readAllBytes(worktree.readContent(path)).catch(() => void 0);
44229
44597
  if (bytes) return decodeGitPatternFile(bytes);
44230
44598
  }
44231
44599
  if (entry) return void 0;
@@ -44233,7 +44601,7 @@ var LsFilesCommand = class extends PlumbingCommand {
44233
44601
  const id = skipWorktree.get(path);
44234
44602
  if (!id) return void 0;
44235
44603
  const content = await this.blobs.load(id).catch(() => void 0);
44236
- return content ? decodeGitPatternFile(await readAll$1(content)) : void 0;
44604
+ return content ? decodeGitPatternFile(await readAllBytes(content)) : void 0;
44237
44605
  };
44238
44606
  return new ExcludeRules(this.excludes.length > 0 ? createCommandLineExcludes(this.excludes) : void 0, files, perDir, coreBool(this.workingCopy, "ignorecase", false), readPerDir);
44239
44607
  }
@@ -44263,7 +44631,7 @@ var LsFilesCommand = class extends PlumbingCommand {
44263
44631
  }
44264
44632
  if (!found) return eolStatsAscii(void 0);
44265
44633
  const content = await this.blobs.load(found.objectId).catch(() => void 0);
44266
- return eolStatsAscii(content ? await readAll$1(content) : void 0);
44634
+ return eolStatsAscii(content ? await readAllBytes(content) : void 0);
44267
44635
  }
44268
44636
  /** show_ce_fmt: one entry through `--format`. */
44269
44637
  async formatEntry(e, worktree, list, nameText) {
@@ -44300,7 +44668,7 @@ var LsFilesCommand = class extends PlumbingCommand {
44300
44668
  if (end < 0) throw new PlumbingError(`fatal: bad ls-files format: element '${rest}' does not end in ')'`);
44301
44669
  const atom = rest.slice(0, end + 1);
44302
44670
  i = pct + 1 + atom.length;
44303
- const type = objectTypeOfMode$1(e.mode);
44671
+ const type = objectTypeOfMode(e.mode);
44304
44672
  switch (atom) {
44305
44673
  case "(objectmode)":
44306
44674
  out += e.mode.toString(8).padStart(6, "0");
@@ -44410,12 +44778,6 @@ function lowerTag(tag) {
44410
44778
  if (c === "?") return `!${tag.slice(1)}`;
44411
44779
  return `v${c} `;
44412
44780
  }
44413
- /** object_type of an index mode. */
44414
- function objectTypeOfMode$1(mode) {
44415
- if ((mode & S_IFMT$4) === 16384) return "tree";
44416
- if (mode === FileMode$1.GITLINK) return "commit";
44417
- return "blob";
44418
- }
44419
44781
  /**
44420
44782
  * show_killed_files' test of one walked path: a leading directory of it is an index file, or
44421
44783
  * (for the last component) the index has entries below it.
@@ -44462,25 +44824,9 @@ async function worktreeEolInfo(worktree, path) {
44462
44824
  if (path.endsWith("/")) return "";
44463
44825
  const entry = await worktree.getEntry(path).catch(() => void 0);
44464
44826
  if (!entry || entry.isDirectory || entry.mode === FileMode$1.SYMLINK || entry.mode === FileMode$1.GITLINK) return "";
44465
- const bytes = await readAll$1(worktree.readContent(path)).catch(() => void 0);
44827
+ const bytes = await readAllBytes(worktree.readContent(path)).catch(() => void 0);
44466
44828
  return bytes ? eolStatsAscii(bytes) : "";
44467
44829
  }
44468
- async function readAll$1(content) {
44469
- const chunks = [];
44470
- let size = 0;
44471
- for await (const c of content) {
44472
- chunks.push(c);
44473
- size += c.length;
44474
- }
44475
- const out = new Uint8Array(size);
44476
- let at = 0;
44477
- for (const c of chunks) {
44478
- out.set(c, at);
44479
- at += c.length;
44480
- }
44481
- return out;
44482
- }
44483
- const SHORT_MAGIC$1 = /* @__PURE__ */ new Set([..."!\"#%&',-;<=>@_`~^/"]);
44484
44830
  /**
44485
44831
  * A pathspec element read against the current directory, as parse_pathspec's
44486
44832
  * `prefix_path_gently` reads it (`:(top)` and `:/` from the top; an absolute path against the
@@ -46362,8 +46708,6 @@ const MAGIC$2 = [
46362
46708
  mnemonic: ""
46363
46709
  }
46364
46710
  ];
46365
- /** ctype.c's GIT_PATHSPEC_MAGIC characters (and `/`, `^`) */
46366
- const SHORT_MAGIC = /* @__PURE__ */ new Set([..."!\"#%&',-;<=>@_`~^/"]);
46367
46711
  const FLUSH_AT = 65536;
46368
46712
  /**
46369
46713
  * `git ls-tree [<options>] <tree-ish> [<path>...]`.
@@ -46715,11 +47059,11 @@ var LsTreeCommand = class extends PlumbingCommand {
46715
47059
  async entryLine(ctx, id, mode, type, path) {
46716
47060
  const modeText = mode.toString(8).padStart(6, "0");
46717
47061
  switch (ctx.fn) {
46718
- case "default": return concat$5(latin1Bytes$3(`${modeText} ${type} ${await this.abbreviated(id)}\t`), this.fastPath(ctx, path));
47062
+ case "default": return concatBytes([latin1Bytes$3(`${modeText} ${type} ${await this.abbreviated(id)}\t`), this.fastPath(ctx, path)]);
46719
47063
  case "long": {
46720
47064
  let size = "-";
46721
47065
  if (type === "blob") size = String(await this.blobSize(id) ?? "BAD");
46722
- return concat$5(latin1Bytes$3(`${modeText} ${type} ${await this.abbreviated(id)} ${size.padStart(7)}\t`), this.fastPath(ctx, path));
47066
+ return concatBytes([latin1Bytes$3(`${modeText} ${type} ${await this.abbreviated(id)} ${size.padStart(7)}\t`), this.fastPath(ctx, path)]);
46723
47067
  }
46724
47068
  case "name-only": return this.fastPath(ctx, path);
46725
47069
  case "object-only": return latin1Bytes$3(`${await this.abbreviated(id)}${this.nul ? "\0" : "\n"}`);
@@ -46796,18 +47140,6 @@ var LsTreeCommand = class extends PlumbingCommand {
46796
47140
  return out;
46797
47141
  }
46798
47142
  };
46799
- function objectTypeOfMode(mode) {
46800
- const kind = mode & 61440;
46801
- if (kind === 16384) return "tree";
46802
- if (kind === 57344) return "commit";
46803
- return "blob";
46804
- }
46805
- function concat$5(a, b) {
46806
- const out = new Uint8Array(a.length + b.length);
46807
- out.set(a);
46808
- out.set(b, a.length);
46809
- return out;
46810
- }
46811
47143
  /** A byte string as git prints it in an error message (bytes as they are). */
46812
47144
  function decodeLatin1Path(s) {
46813
47145
  return new TextDecoder().decode(latin1Bytes$3(s));
@@ -46861,7 +47193,7 @@ function parseElementMagic(elem) {
46861
47193
  magic.add("exclude");
46862
47194
  continue;
46863
47195
  }
46864
- if (!SHORT_MAGIC.has(ch)) break;
47196
+ if (!SHORT_MAGIC$1.has(ch)) break;
46865
47197
  const m = MAGIC$2.find((x) => x.mnemonic === ch);
46866
47198
  if (!m) throw new PlumbingError(`fatal: Unimplemented pathspec magic '${ch}' in '${elem}'`);
46867
47199
  magic.add(m.name);
@@ -48121,6 +48453,8 @@ var MvCommand = class extends GitCommand {
48121
48453
  const adder = await IndexAdder.open(this.staging, this.blobs, trust, { pathRules: worktreePathRules(this.workingCopy) });
48122
48454
  const current = /* @__PURE__ */ new Map();
48123
48455
  for (const e of cache) if (e.stage === 0) current.set(e.path, e);
48456
+ const fsm = await this.fsmonitorRefresh(this.staging);
48457
+ const validMoves = [];
48124
48458
  const dirtyPaths = [];
48125
48459
  let gitmodulesModified = false;
48126
48460
  let changed = false;
@@ -48158,13 +48492,22 @@ var MvCommand = class extends GitCommand {
48158
48492
  ...entry,
48159
48493
  path: dst
48160
48494
  };
48161
- if (!entry.skipWorktree && !entry.assumeValid && !entry.intentToAdd && entry.mode !== FileMode.GITLINK) {
48495
+ let valid = !!fsm && fsm.state.isValid(entry);
48496
+ if (!entry.skipWorktree && !entry.assumeValid && !valid && !entry.intentToAdd && entry.mode !== FileMode.GITLINK) {
48162
48497
  const file = await lstat(dst);
48163
- if (file && !await entryModified(worktree, moved, trust, indexTime, true)) moved = {
48164
- ...moved,
48165
- ...entryStatOf(file)
48166
- };
48498
+ if (file && isCleanByStat(moved, file, trust, indexTime)) valid = true;
48499
+ else if (file && !await entryModified(worktree, moved, trust, indexTime, true)) {
48500
+ if (basicStatMatches(moved, file, trust)) valid = true;
48501
+ else {
48502
+ moved = {
48503
+ ...moved,
48504
+ ...entryStatOf(file)
48505
+ };
48506
+ valid = !file.isDirectory && file.mode !== FileMode.SYMLINK;
48507
+ }
48508
+ }
48167
48509
  }
48510
+ if (current.has(dst)) valid = false;
48168
48511
  let checkout = false;
48169
48512
  if (this.sparse && sparseConfig.enabled && sparseConfig.cone) {
48170
48513
  if (mode & SPARSE && inSparse(dst)) {
@@ -48198,6 +48541,7 @@ var MvCommand = class extends GitCommand {
48198
48541
  const { skipWorktree: _drop, ...rest } = moved;
48199
48542
  moved = rest;
48200
48543
  }
48544
+ if (fsm && valid) validMoves.push(dst);
48201
48545
  current.delete(src);
48202
48546
  current.set(dst, moved);
48203
48547
  adder.remove(src);
@@ -48218,7 +48562,12 @@ var MvCommand = class extends GitCommand {
48218
48562
  result.warnings.push("The following paths have been moved outside the", "sparse-checkout definition but are not sparse due to local", "modifications.", ...dirtyPaths);
48219
48563
  if (configBool$1(this.workingCopy, "advice.updateSparsePath", true)) result.warnings.push("hint: To correct the sparsity of these paths, do the following:", "hint: * Use \"git add --sparse <paths>\" to update the index", "hint: * Use \"git sparse-checkout reapply\" to apply the sparsity rules", `hint: Disable this message with "${this.compatibility === "2.43" ? "git config" : "git config set"} advice.updateSparsePath false"`);
48220
48564
  }
48221
- if (changed || gitmodulesModified) await this.writeMoves(adder, worktree, gitmodulesModified);
48565
+ if (changed || gitmodulesModified) await this.writeMoves(adder, worktree, gitmodulesModified, async () => {
48566
+ for (const path of validMoves) {
48567
+ const entry = await this.staging.getEntry(path);
48568
+ if (entry && entry.stage === 0) fsm?.state.markValid(entry);
48569
+ }
48570
+ });
48222
48571
  return result;
48223
48572
  }
48224
48573
  /** The index's entries in its order. */
@@ -48230,12 +48579,13 @@ var MvCommand = class extends GitCommand {
48230
48579
  return out;
48231
48580
  }
48232
48581
  /** `stage_updated_gitmodules` when needed, then the index written. */
48233
- async writeMoves(adder, worktree, gitmodulesModified) {
48582
+ async writeMoves(adder, worktree, gitmodulesModified, markValid) {
48234
48583
  if (gitmodulesModified) {
48235
48584
  const entry = await worktree.getEntry(".gitmodules");
48236
48585
  if (entry && !entry.isDirectory) await adder.add(worktree, ".gitmodules", entry);
48237
48586
  }
48238
48587
  await adder.finish();
48588
+ await markValid();
48239
48589
  await this.staging.write();
48240
48590
  }
48241
48591
  /** `checkout_entry` (forced) of the entries moved into the sparse cone. */
@@ -54354,7 +54704,9 @@ var ReplaceCommand = class extends PlumbingCommand {
54354
54704
  }
54355
54705
  /** repo_get_oid with replace refs off; undefined when it names nothing. */
54356
54706
  async getOid(name) {
54357
- return this.revisionResolver().resolve(name).catch(() => void 0);
54707
+ return this.revisionResolver().resolve(name).catch((e) => {
54708
+ if (e instanceof CorruptTreeError) throw e;
54709
+ });
54358
54710
  }
54359
54711
  /** odb_read_object_info: the object's type, undefined when it is missing. */
54360
54712
  async typeOf(id) {
@@ -54518,9 +54870,15 @@ var ReplaceCommand = class extends PlumbingCommand {
54518
54870
  const entries = await this.listedTreeEntries(id);
54519
54871
  if (!entries) this.fail("cat-file reported failure");
54520
54872
  let out = "";
54521
- for (const entry of entries) {
54522
- const mode = entry.mode.toString(8).padStart(6, "0");
54523
- out += `${mode} ${modeType(entry.mode)} ${entry.id}\t${quotePath(entry.name, quoteFully)}\n`;
54873
+ try {
54874
+ for (const entry of entries) {
54875
+ const mode = entry.mode.toString(8).padStart(6, "0");
54876
+ out += `${mode} ${modeType(entry.mode)} ${entry.id}\t${quotePath(entry.name, quoteFully)}\n`;
54877
+ }
54878
+ } catch (e) {
54879
+ if (!(e instanceof CorruptTreeError)) throw e;
54880
+ this.warn(e.message);
54881
+ this.fail("cat-file reported failure");
54524
54882
  }
54525
54883
  return encodeGitPath(out);
54526
54884
  }
@@ -56915,6 +57273,20 @@ var RerereCommand = class extends GitCommand {
56915
57273
  this.autoUpdate = value;
56916
57274
  return this;
56917
57275
  }
57276
+ /**
57277
+ * git's rerere for a resolution store (vcs-store-files `GitResolutionStore`): its records
57278
+ * written and replayed as `git rerere` does ({@link rerereEngineOf}); undefined without a
57279
+ * worktree. Give the store the index this command reads (`workingCopy.checkout.staging`).
57280
+ *
57281
+ * @example
57282
+ * ```typescript
57283
+ * const store = createResolutionStore(files, staging, blobs, ".git", "", git.rerere().engine());
57284
+ * ```
57285
+ */
57286
+ engine() {
57287
+ const host = this.rerereHost();
57288
+ return host && rerereEngineOf(host);
57289
+ }
56918
57290
  async call() {
56919
57291
  this.checkCallable();
56920
57292
  this.setCallable(false);