@@ -13,27 +13,22 @@ import {
1313 getWorkspaceGitInfo ,
1414 convertGitUrlToHttps ,
1515 getGitStatus ,
16+ getCommitContext ,
1617} from "../git"
1718import { truncateOutput } from "../../integrations/misc/extract-text"
1819
19- type ExecFunction = (
20- command : string ,
21- options : { cwd ?: string } ,
22- callback : ( error : ExecException | null , result ?: { stdout : string ; stderr : string } ) => void ,
23- ) => void
24-
25- type PromisifiedExec = ( command : string , options ?: { cwd ?: string } ) => Promise < { stdout : string ; stderr : string } >
26-
2720// Mock child_process.exec
2821vitest . mock ( "child_process" , ( ) => ( {
2922 exec : vitest . fn ( ) ,
23+ execFile : vitest . fn ( ) ,
3024} ) )
3125
3226// Mock fs.promises
3327vitest . mock ( "fs" , ( ) => ( {
3428 promises : {
3529 access : vitest . fn ( ) ,
3630 readFile : vitest . fn ( ) ,
31+ open : vitest . fn ( ) ,
3732 } ,
3833} ) )
3934
@@ -49,21 +44,27 @@ vitest.mock("vscode", () => ({
4944
5045// Mock util.promisify to return our own mock function
5146vitest . mock ( "util" , ( ) => ( {
52- promisify : vitest . fn ( ( fn : ExecFunction ) : PromisifiedExec => {
53- return async ( command : string , options ?: { cwd ?: string } ) => {
47+ promisify : vitest . fn ( ( fn : ( ... args : unknown [ ] ) => void ) => {
48+ return async ( ... args : unknown [ ] ) => {
5449 // Call the original mock to maintain the mock implementation
5550 return new Promise ( ( resolve , reject ) => {
56- fn (
57- command ,
58- options || { } ,
59- ( error : ExecException | null , result ?: { stdout : string ; stderr : string } ) => {
60- if ( error ) {
61- reject ( error )
62- } else {
63- resolve ( result ! )
64- }
65- } ,
66- )
51+ const callback = ( error : ExecException | null , result ?: { stdout : string ; stderr : string } ) => {
52+ if ( error ) {
53+ reject ( error )
54+ } else {
55+ resolve ( result ! )
56+ }
57+ }
58+
59+ // `exec(command, options, cb)` and `execFile(file, args, options, cb)` differ in
60+ // arity, so both shapes are normalized here rather than mocking promisify twice.
61+ const [ first , second , third ] = args
62+
63+ if ( Array . isArray ( second ) ) {
64+ fn ( first , second , third || { } , callback )
65+ } else {
66+ fn ( first , second || { } , callback )
67+ }
6768 } )
6869 }
6970 } ) ,
@@ -76,7 +77,7 @@ vitest.mock("../../integrations/misc/extract-text", () => ({
7677 } ) ,
7778} ) )
7879
79- import { exec } from "child_process"
80+ import { exec , execFile } from "child_process"
8081
8182describe ( "git utils" , ( ) => {
8283 const cwd = "/test/path"
@@ -351,6 +352,252 @@ describe("git utils", () => {
351352 } )
352353 } )
353354
355+ describe ( "getCommitContext" , ( ) => {
356+ const NUL = "\0"
357+ const mockDiff = "@@ -1,1 +1,2 @@\n-old line\n+new line"
358+
359+ type ExecResult = { stdout : string ; stderr : string }
360+ type ExecCallback = ( error : Error | null , result ?: ExecResult ) => void
361+
362+ // `checkGitInstalled` and `checkGitRepo` are fixed strings, so they still run through `exec`.
363+ const mockProbes = ( { installed = true , repo = true } = { } ) => {
364+ vitest . mocked ( exec ) . mockImplementation ( ( ( command : string , _options : unknown , callback : ExecCallback ) => {
365+ const available = command === "git --version" ? installed : repo
366+
367+ if ( available ) {
368+ callback ( null , { stdout : "ok" , stderr : "" } )
369+ } else {
370+ callback ( new Error ( `unavailable: ${ command } ` ) )
371+ }
372+
373+ return { } as ReturnType < typeof exec >
374+ } ) as unknown as typeof exec )
375+ }
376+
377+ // Keyed by the joined argument array, since that is what the collector passes now. Anything
378+ // not listed rejects, which is how the failure paths are exercised.
379+ const mockGit = ( responses : Record < string , string > ) => {
380+ const calls : Array < { file : string ; args : string [ ] } > = [ ]
381+
382+ vitest . mocked ( execFile ) . mockImplementation ( ( (
383+ file : string ,
384+ args : string [ ] ,
385+ _options : unknown ,
386+ callback : ExecCallback ,
387+ ) => {
388+ calls . push ( { file, args } )
389+ const stdout = responses [ args . join ( " " ) ]
390+
391+ if ( stdout === undefined ) {
392+ callback ( new Error ( `unexpected command: git ${ args . join ( " " ) } ` ) )
393+ } else {
394+ callback ( null , { stdout, stderr : "" } )
395+ }
396+
397+ return { } as ReturnType < typeof execFile >
398+ } ) as unknown as typeof execFile )
399+
400+ return calls
401+ }
402+
403+ const staged = ( nameStatus : string , diff = mockDiff ) : Record < string , string > => ( {
404+ "diff --cached --name-status -z" : nameStatus ,
405+ "diff --cached --unified=1" : diff ,
406+ "branch --show-current" : "feature/x\n" ,
407+ "log -n5 --format=%s" : "earlier subject\n" ,
408+ } )
409+
410+ const workingTree = ( status : string , diff = mockDiff ) : Record < string , string > => ( {
411+ "diff --cached --name-status -z" : "" ,
412+ "status --porcelain=v1 -z --untracked-files=all" : status ,
413+ "diff --unified=1" : diff ,
414+ "rev-parse --show-toplevel" : `${ cwd } \n` ,
415+ "branch --show-current" : "main\n" ,
416+ "log -n5 --format=%s" : "earlier subject\n" ,
417+ } )
418+
419+ // Narrows the result so a failure reports its reason instead of a property-of-undefined.
420+ const expectContext = async ( ) => {
421+ const result = await getCommitContext ( cwd )
422+
423+ if ( ! result . ok ) {
424+ throw new Error ( `expected a context, got "${ result . reason } "` )
425+ }
426+
427+ return result . context
428+ }
429+
430+ const mockUntrackedFile = ( contents : Buffer | null ) => {
431+ vitest . mocked ( fs . promises . open ) . mockImplementation ( ( async ( ) => {
432+ if ( ! contents ) {
433+ throw new Error ( "ENOENT" )
434+ }
435+
436+ return {
437+ read : async ( buffer : Buffer ) => ( { bytesRead : contents . copy ( buffer ) } ) ,
438+ close : async ( ) => { } ,
439+ }
440+ } ) as unknown as typeof fs . promises . open )
441+ }
442+
443+ it ( "should collect staged changes as structured entries" , async ( ) => {
444+ mockProbes ( )
445+ mockGit ( staged ( `M${ NUL } src/file1.ts${ NUL } A${ NUL } src/new.ts${ NUL } D${ NUL } src/gone.ts${ NUL } ` ) )
446+
447+ const context = await expectContext ( )
448+ expect ( context . staged ) . toBe ( true )
449+ expect ( context . files ) . toEqual ( [
450+ { status : "modified" , path : "src/file1.ts" } ,
451+ { status : "added" , path : "src/new.ts" } ,
452+ { status : "deleted" , path : "src/gone.ts" } ,
453+ ] )
454+ expect ( context . branch ) . toBe ( "feature/x" )
455+ expect ( context . recentCommits ) . toEqual ( [ "earlier subject" ] )
456+ expect ( context . diff ) . toContain ( "+new line" )
457+ } )
458+
459+ // A rename or copy record carries two paths. Reading one where there are two would shift
460+ // every later record onto the wrong file, so the trailing entry is the real assertion.
461+ it ( "should parse renames and copies without desyncing later entries" , async ( ) => {
462+ mockProbes ( )
463+ mockGit (
464+ staged (
465+ `R100${ NUL } old name.ts${ NUL } new name.ts${ NUL } ` +
466+ `C075${ NUL } src/base.ts${ NUL } src/copy.ts${ NUL } ` +
467+ `M${ NUL } src/after.ts${ NUL } ` ,
468+ ) ,
469+ )
470+
471+ expect ( ( await expectContext ( ) ) . files ) . toEqual ( [
472+ { status : "renamed" , path : "new name.ts" , oldPath : "old name.ts" } ,
473+ { status : "copied" , path : "src/copy.ts" , oldPath : "src/base.ts" } ,
474+ { status : "modified" , path : "src/after.ts" } ,
475+ ] )
476+ } )
477+
478+ it ( "should keep paths with spaces and unusual characters verbatim" , async ( ) => {
479+ mockProbes ( )
480+ mockGit ( staged ( `A${ NUL } src/a "quoted" & odd (file).ts${ NUL } ` ) )
481+
482+ expect ( ( await expectContext ( ) ) . files ) . toEqual ( [ { status : "added" , path : 'src/a "quoted" & odd (file).ts' } ] )
483+ } )
484+
485+ // Replaces an older test that checked the command string for shell metacharacters. With
486+ // `execFile` there is no shell at all, so the guard is that arguments stay separate values.
487+ it ( "should pass every argument as an array element rather than a shell string" , async ( ) => {
488+ mockProbes ( )
489+ const calls = mockGit ( staged ( `M${ NUL } src/file1.ts${ NUL } ` ) )
490+
491+ await getCommitContext ( cwd )
492+
493+ expect ( calls . length ) . toBeGreaterThan ( 0 )
494+ expect ( calls . every ( ( call ) => call . file === "git" ) ) . toBe ( true )
495+ expect ( calls . map ( ( call ) => call . args ) ) . toContainEqual ( [ "diff" , "--cached" , "--name-status" , "-z" ] )
496+ expect ( calls . map ( ( call ) => call . args ) ) . toContainEqual ( [ "diff" , "--cached" , "--unified=1" ] )
497+ } )
498+
499+ it ( "should fall back to the working tree when nothing is staged" , async ( ) => {
500+ mockProbes ( )
501+ mockGit ( workingTree ( ` M src/file1.ts${ NUL } ?? src/untracked.ts${ NUL } ` ) )
502+ mockUntrackedFile ( Buffer . from ( "export const value = 1\n" ) )
503+
504+ const context = await expectContext ( )
505+ expect ( context . staged ) . toBe ( false )
506+ expect ( context . files ) . toEqual ( [
507+ { status : "modified" , path : "src/file1.ts" } ,
508+ { status : "untracked" , path : "src/untracked.ts" } ,
509+ ] )
510+ } )
511+
512+ // Porcelain reverses the field order of `diff --name-status`: here the new path comes first.
513+ it ( "should parse porcelain renames, where the new path comes first" , async ( ) => {
514+ mockProbes ( )
515+ mockGit ( workingTree ( `R new name.ts${ NUL } old name.ts${ NUL } M after.ts${ NUL } ` ) )
516+
517+ expect ( ( await expectContext ( ) ) . files ) . toEqual ( [
518+ { status : "renamed" , path : "new name.ts" , oldPath : "old name.ts" } ,
519+ { status : "modified" , path : "after.ts" } ,
520+ ] )
521+ } )
522+
523+ it ( "should include bounded contents for untracked files" , async ( ) => {
524+ mockProbes ( )
525+ mockGit ( workingTree ( `?? src/untracked.ts${ NUL } ` ) )
526+ mockUntrackedFile ( Buffer . from ( "export const answer = 42\n" ) )
527+
528+ const context = await expectContext ( )
529+ expect ( context . diff ) . toContain ( "New file: src/untracked.ts" )
530+ expect ( context . diff ) . toContain ( "export const answer = 42" )
531+ } )
532+
533+ it ( "should skip untracked files that look binary" , async ( ) => {
534+ mockProbes ( )
535+ mockGit ( workingTree ( `?? assets/logo.png${ NUL } ` ) )
536+ mockUntrackedFile ( Buffer . from ( [ 0x89 , 0x50 , 0x00 , 0x4e , 0x47 ] ) )
537+
538+ const context = await expectContext ( )
539+ expect ( context . files ) . toEqual ( [ { status : "untracked" , path : "assets/logo.png" } ] )
540+ expect ( context . diff ) . not . toContain ( "New file: assets/logo.png" )
541+ } )
542+
543+ it ( "should work in a repository without an initial commit" , async ( ) => {
544+ mockProbes ( )
545+ // `git log` fails before the first commit, and must not take the collection down with it.
546+ const responses = workingTree ( `?? file.txt${ NUL } ` )
547+ delete responses [ "log -n5 --format=%s" ]
548+ mockGit ( responses )
549+ mockUntrackedFile ( Buffer . from ( "hello\n" ) )
550+
551+ const context = await expectContext ( )
552+ expect ( context . recentCommits ) . toEqual ( [ ] )
553+ expect ( context . files ) . toEqual ( [ { status : "untracked" , path : "file.txt" } ] )
554+ } )
555+
556+ // A line limit alone is not a bound: one generated file can be a single enormous line.
557+ it ( "should cap output by characters as well as by lines" , async ( ) => {
558+ mockProbes ( )
559+ mockGit ( staged ( `M${ NUL } dist/bundle.js${ NUL } ` , `+${ "a" . repeat ( 200_000 ) } ` ) )
560+
561+ await getCommitContext ( cwd )
562+
563+ expect ( vitest . mocked ( truncateOutput ) ) . toHaveBeenCalledWith ( expect . any ( String ) , 500 , 102_400 )
564+ } )
565+
566+ it ( "should report no-changes on a clean tree" , async ( ) => {
567+ mockProbes ( )
568+ mockGit ( workingTree ( "" ) )
569+
570+ expect ( await getCommitContext ( cwd ) ) . toEqual ( { ok : false , reason : "no-changes" } )
571+ } )
572+
573+ it ( "should report git-missing when git is not installed" , async ( ) => {
574+ mockProbes ( { installed : false } )
575+ mockGit ( { } )
576+
577+ expect ( await getCommitContext ( cwd ) ) . toEqual ( { ok : false , reason : "git-missing" } )
578+ } )
579+
580+ it ( "should report not-a-repo outside a repository" , async ( ) => {
581+ mockProbes ( { repo : false } )
582+ mockGit ( { } )
583+
584+ expect ( await getCommitContext ( cwd ) ) . toEqual ( { ok : false , reason : "not-a-repo" } )
585+ } )
586+
587+ // An oversized diff exceeding `maxBuffer` is expected, not exceptional: the documented
588+ // contract is a reason, never a rejection.
589+ it ( "should report failed instead of rejecting when a git command fails" , async ( ) => {
590+ mockProbes ( )
591+ const responses = staged ( `M${ NUL } src/file1.ts${ NUL } ` )
592+ delete responses [ "diff --cached --unified=1" ]
593+ mockGit ( responses )
594+
595+ const result = await getCommitContext ( cwd )
596+ expect ( result . ok ) . toBe ( false )
597+ expect ( result ) . toMatchObject ( { reason : "failed" } )
598+ } )
599+ } )
600+
354601 describe ( "getWorkingState" , ( ) => {
355602 const mockStatus = " M src/file1.ts\n?? src/file2.ts"
356603 const mockDiff = "@@ -1,1 +1,2 @@\n-old line\n+new line"
0 commit comments