@@ -28,6 +28,21 @@ func getGitPorcelain(dirPath string) (git.Status, error) {
2828 return status , nil
2929}
3030
31+ func GetHeadBranch (repoPath string ) (string , error ) {
32+ repo , err := git .PlainOpen (repoPath )
33+ if err != nil {
34+ return "" , err
35+ }
36+
37+ head , err := repo .Head ()
38+ if err != nil {
39+ return "" , err
40+ }
41+ headBranchName := strings .Split (head .Name ().String (), "/" )[2 ]
42+
43+ return headBranchName , nil
44+ }
45+
3146func getCurrentCommit (ctx context.Context , client * github.Client , repo repository.Repository , branch string ) (* github.RepositoryCommit , error ) {
3247
3348 // Get the branch reference
@@ -110,12 +125,24 @@ func setBranchToCommit(ctx context.Context, client *github.Client, repo reposito
110125
111126 ref := fmt .Sprintf ("refs/heads/%s" , branch )
112127
113- return client .Git .UpdateRef (ctx , repo .Owner , repo .Name , & github.Reference {
114- Ref : github .String (ref ),
115- Object : & github.GitObject {
116- SHA : commit .SHA ,
117- },
118- }, true )
128+ refExists , _ , _ := client .Git .GetRef (ctx , repo .Owner , repo .Name , ref )
129+
130+ if refExists == nil {
131+ return client .Git .CreateRef (ctx , repo .Owner , repo .Name , & github.Reference {
132+ Ref : github .String (ref ),
133+ Object : & github.GitObject {
134+ SHA : commit .SHA ,
135+ },
136+ })
137+ } else {
138+ return client .Git .UpdateRef (ctx , repo .Owner , repo .Name , & github.Reference {
139+ Ref : github .String (ref ),
140+ Object : & github.GitObject {
141+ SHA : commit .SHA ,
142+ },
143+ }, true )
144+ }
145+
119146}
120147
121148func getGroupedFiles (fileStatuses git.Status ) ([]string , []string , []string , error ) {
@@ -145,10 +172,10 @@ func getGroupedFiles(fileStatuses git.Status) ([]string, []string, []string, err
145172 return addedFiles , updatedFiles , deletedFiles , nil
146173}
147174
148- func UploadToRepo (ctx context.Context , client * github.Client , repo repository.Repository , path string , deletePath string , branch string , message string ) (* github.Reference , * github.Response , error ) {
175+ func UploadToRepo (ctx context.Context , client * github.Client , repo repository.Repository , path string , deletePath string , branch string , headBranch string , message string ) (* github.Reference , * github.Response , error ) {
149176
150177 // Get the current currentCommit
151- currentCommit , err := getCurrentCommit (ctx , client , repo , branch )
178+ currentCommit , err := getCurrentCommit (ctx , client , repo , headBranch )
152179 if err != nil {
153180 return nil , nil , err
154181 }
@@ -207,5 +234,4 @@ func UploadToRepo(ctx context.Context, client *github.Client, repo repository.Re
207234 }
208235
209236 return setBranchToCommit (ctx , client , repo , branch , commit )
210-
211237}
0 commit comments