1- import type { GitStackedAction , NativeApi } from "@t3tools/contracts" ;
1+ import type { GitListBranchesResult , GitStackedAction , NativeApi } from "@t3tools/contracts" ;
22import { mutationOptions , queryOptions , type QueryClient } from "@tanstack/react-query" ;
33
44export const gitQueryKeys = {
@@ -11,6 +11,50 @@ export function invalidateGitQueries(queryClient: QueryClient) {
1111 return queryClient . invalidateQueries ( { queryKey : gitQueryKeys . all } ) ;
1212}
1313
14+ export function projectGitBranchesToCurrent (
15+ existing : GitListBranchesResult | undefined ,
16+ currentBranch : string ,
17+ ) : GitListBranchesResult | undefined {
18+ if ( ! existing ) return existing ;
19+
20+ let nextCurrent : GitListBranchesResult [ "branches" ] [ number ] | null = null ;
21+ const remaining : GitListBranchesResult [ "branches" ] = [ ] ;
22+
23+ for ( const branch of existing . branches ) {
24+ if ( branch . name === currentBranch ) {
25+ nextCurrent = branch . current ? branch : { ...branch , current : true } ;
26+ continue ;
27+ }
28+ remaining . push ( branch . current ? { ...branch , current : false } : branch ) ;
29+ }
30+
31+ if ( ! nextCurrent ) {
32+ nextCurrent = {
33+ name : currentBranch ,
34+ current : true ,
35+ isDefault : false ,
36+ worktreePath : null ,
37+ } ;
38+ }
39+
40+ return {
41+ ...existing ,
42+ branches : [ nextCurrent , ...remaining ] ,
43+ } ;
44+ }
45+
46+ export function setGitBranchesCurrentBranch (
47+ queryClient : QueryClient ,
48+ cwd : string | null ,
49+ currentBranch : string ,
50+ ) {
51+ if ( ! cwd ) return ;
52+
53+ queryClient . setQueryData < GitListBranchesResult > ( gitQueryKeys . branches ( cwd ) , ( existing ) =>
54+ projectGitBranchesToCurrent ( existing , currentBranch ) ,
55+ ) ;
56+ }
57+
1458export function gitStatusQueryOptions ( api : NativeApi | undefined , cwd : string | null ) {
1559 return queryOptions ( {
1660 queryKey : gitQueryKeys . status ( cwd ) ,
@@ -63,7 +107,8 @@ export function gitCheckoutMutationOptions(input: {
63107 if ( ! input . api || ! input . cwd ) throw new Error ( "Git checkout is unavailable." ) ;
64108 return input . api . git . checkout ( { cwd : input . cwd , branch } ) ;
65109 } ,
66- onSuccess : async ( ) => {
110+ onSuccess : async ( _result , branch ) => {
111+ setGitBranchesCurrentBranch ( input . queryClient , input . cwd , branch ) ;
67112 await invalidateGitQueries ( input . queryClient ) ;
68113 } ,
69114 } ) ;
@@ -80,7 +125,8 @@ export function gitCreateBranchAndCheckoutMutationOptions(input: {
80125 await input . api . git . createBranch ( { cwd : input . cwd , branch } ) ;
81126 return input . api . git . checkout ( { cwd : input . cwd , branch } ) ;
82127 } ,
83- onSuccess : async ( ) => {
128+ onSuccess : async ( _result , branch ) => {
129+ setGitBranchesCurrentBranch ( input . queryClient , input . cwd , branch ) ;
84130 await invalidateGitQueries ( input . queryClient ) ;
85131 } ,
86132 } ) ;
0 commit comments