You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

repo_branch.go 7.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. // Copyright 2016 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "fmt"
  7. "time"
  8. "code.gitea.io/gitea/modules/git"
  9. "code.gitea.io/gitea/modules/setting"
  10. "github.com/Unknwon/com"
  11. )
  12. // discardLocalRepoBranchChanges discards local commits/changes of
  13. // given branch to make sure it is even to remote branch.
  14. func discardLocalRepoBranchChanges(localPath, branch string) error {
  15. if !com.IsExist(localPath) {
  16. return nil
  17. }
  18. // No need to check if nothing in the repository.
  19. if !git.IsBranchExist(localPath, branch) {
  20. return nil
  21. }
  22. refName := "origin/" + branch
  23. if err := git.ResetHEAD(localPath, true, refName); err != nil {
  24. return fmt.Errorf("git reset --hard %s: %v", refName, err)
  25. }
  26. return nil
  27. }
  28. // DiscardLocalRepoBranchChanges discards the local repository branch changes
  29. func (repo *Repository) DiscardLocalRepoBranchChanges(branch string) error {
  30. return discardLocalRepoBranchChanges(repo.LocalCopyPath(), branch)
  31. }
  32. // checkoutNewBranch checks out to a new branch from the a branch name.
  33. func checkoutNewBranch(repoPath, localPath, oldBranch, newBranch string) error {
  34. if err := git.Checkout(localPath, git.CheckoutOptions{
  35. Timeout: time.Duration(setting.Git.Timeout.Pull) * time.Second,
  36. Branch: newBranch,
  37. OldBranch: oldBranch,
  38. }); err != nil {
  39. return fmt.Errorf("git checkout -b %s %s: %v", newBranch, oldBranch, err)
  40. }
  41. return nil
  42. }
  43. // CheckoutNewBranch checks out a new branch
  44. func (repo *Repository) CheckoutNewBranch(oldBranch, newBranch string) error {
  45. return checkoutNewBranch(repo.RepoPath(), repo.LocalCopyPath(), oldBranch, newBranch)
  46. }
  47. // deleteLocalBranch deletes a branch from a local repo cache
  48. // First checks out default branch to avoid trying to delete the currently checked out branch
  49. func deleteLocalBranch(localPath, defaultBranch, deleteBranch string) error {
  50. if !com.IsExist(localPath) {
  51. return nil
  52. }
  53. if !git.IsBranchExist(localPath, deleteBranch) {
  54. return nil
  55. }
  56. // Must NOT have branch currently checked out
  57. // Checkout default branch first
  58. if err := git.Checkout(localPath, git.CheckoutOptions{
  59. Timeout: time.Duration(setting.Git.Timeout.Pull) * time.Second,
  60. Branch: defaultBranch,
  61. }); err != nil {
  62. return fmt.Errorf("git checkout %s: %v", defaultBranch, err)
  63. }
  64. cmd := git.NewCommand("branch")
  65. cmd.AddArguments("-D")
  66. cmd.AddArguments(deleteBranch)
  67. _, err := cmd.RunInDir(localPath)
  68. return err
  69. }
  70. // DeleteLocalBranch deletes a branch from the local repo
  71. func (repo *Repository) DeleteLocalBranch(branchName string) error {
  72. return deleteLocalBranch(repo.LocalCopyPath(), repo.DefaultBranch, branchName)
  73. }
  74. // Branch holds the branch information
  75. type Branch struct {
  76. Path string
  77. Name string
  78. }
  79. // GetBranchesByPath returns a branch by it's path
  80. func GetBranchesByPath(path string) ([]*Branch, error) {
  81. gitRepo, err := git.OpenRepository(path)
  82. if err != nil {
  83. return nil, err
  84. }
  85. brs, err := gitRepo.GetBranches()
  86. if err != nil {
  87. return nil, err
  88. }
  89. branches := make([]*Branch, len(brs))
  90. for i := range brs {
  91. branches[i] = &Branch{
  92. Path: path,
  93. Name: brs[i],
  94. }
  95. }
  96. return branches, nil
  97. }
  98. // CanCreateBranch returns true if repository meets the requirements for creating new branches.
  99. func (repo *Repository) CanCreateBranch() bool {
  100. return !repo.IsMirror
  101. }
  102. // GetBranch returns a branch by it's name
  103. func (repo *Repository) GetBranch(branch string) (*Branch, error) {
  104. if !git.IsBranchExist(repo.RepoPath(), branch) {
  105. return nil, ErrBranchNotExist{branch}
  106. }
  107. return &Branch{
  108. Path: repo.RepoPath(),
  109. Name: branch,
  110. }, nil
  111. }
  112. // GetBranches returns all the branches of a repository
  113. func (repo *Repository) GetBranches() ([]*Branch, error) {
  114. return GetBranchesByPath(repo.RepoPath())
  115. }
  116. // CheckBranchName validates branch name with existing repository branches
  117. func (repo *Repository) CheckBranchName(name string) error {
  118. gitRepo, err := git.OpenRepository(repo.RepoPath())
  119. if err != nil {
  120. return err
  121. }
  122. branches, err := repo.GetBranches()
  123. if err != nil {
  124. return err
  125. }
  126. for _, branch := range branches {
  127. if branch.Name == name {
  128. return ErrBranchAlreadyExists{branch.Name}
  129. } else if (len(branch.Name) < len(name) && branch.Name+"/" == name[0:len(branch.Name)+1]) ||
  130. (len(branch.Name) > len(name) && name+"/" == branch.Name[0:len(name)+1]) {
  131. return ErrBranchNameConflict{branch.Name}
  132. }
  133. }
  134. if _, err := gitRepo.GetTag(name); err == nil {
  135. return ErrTagAlreadyExists{name}
  136. }
  137. return nil
  138. }
  139. // CreateNewBranch creates a new repository branch
  140. func (repo *Repository) CreateNewBranch(doer *User, oldBranchName, branchName string) (err error) {
  141. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  142. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  143. // Check if branch name can be used
  144. if err := repo.CheckBranchName(branchName); err != nil {
  145. return err
  146. }
  147. localPath := repo.LocalCopyPath()
  148. if err = discardLocalRepoBranchChanges(localPath, oldBranchName); err != nil {
  149. return fmt.Errorf("discardLocalRepoChanges: %v", err)
  150. } else if err = repo.UpdateLocalCopyBranch(oldBranchName); err != nil {
  151. return fmt.Errorf("UpdateLocalCopyBranch: %v", err)
  152. }
  153. if err = repo.CheckoutNewBranch(oldBranchName, branchName); err != nil {
  154. return fmt.Errorf("CreateNewBranch: %v", err)
  155. }
  156. if err = git.Push(localPath, git.PushOptions{
  157. Remote: "origin",
  158. Branch: branchName,
  159. }); err != nil {
  160. return fmt.Errorf("Push: %v", err)
  161. }
  162. return nil
  163. }
  164. // updateLocalCopyToCommit pulls latest changes of given commit from repoPath to localPath.
  165. // It creates a new clone if local copy does not exist.
  166. // This function checks out target commit by default, it is safe to assume subsequent
  167. // operations are operating against target commit when caller has confidence for no race condition.
  168. func updateLocalCopyToCommit(repoPath, localPath, commit string) error {
  169. if !com.IsExist(localPath) {
  170. if err := git.Clone(repoPath, localPath, git.CloneRepoOptions{
  171. Timeout: time.Duration(setting.Git.Timeout.Clone) * time.Second,
  172. }); err != nil {
  173. return fmt.Errorf("git clone: %v", err)
  174. }
  175. } else {
  176. _, err := git.NewCommand("fetch", "origin").RunInDir(localPath)
  177. if err != nil {
  178. return fmt.Errorf("git fetch origin: %v", err)
  179. }
  180. if err := git.ResetHEAD(localPath, true, "HEAD"); err != nil {
  181. return fmt.Errorf("git reset --hard HEAD: %v", err)
  182. }
  183. }
  184. if err := git.Checkout(localPath, git.CheckoutOptions{
  185. Branch: commit,
  186. }); err != nil {
  187. return fmt.Errorf("git checkout %s: %v", commit, err)
  188. }
  189. return nil
  190. }
  191. // updateLocalCopyToCommit makes sure local copy of repository is at given commit.
  192. func (repo *Repository) updateLocalCopyToCommit(commit string) error {
  193. return updateLocalCopyToCommit(repo.RepoPath(), repo.LocalCopyPath(), commit)
  194. }
  195. // CreateNewBranchFromCommit creates a new repository branch
  196. func (repo *Repository) CreateNewBranchFromCommit(doer *User, commit, branchName string) (err error) {
  197. repoWorkingPool.CheckIn(com.ToStr(repo.ID))
  198. defer repoWorkingPool.CheckOut(com.ToStr(repo.ID))
  199. // Check if branch name can be used
  200. if err := repo.CheckBranchName(branchName); err != nil {
  201. return err
  202. }
  203. localPath := repo.LocalCopyPath()
  204. if err = repo.updateLocalCopyToCommit(commit); err != nil {
  205. return fmt.Errorf("UpdateLocalCopyBranch: %v", err)
  206. }
  207. if err = repo.CheckoutNewBranch(commit, branchName); err != nil {
  208. return fmt.Errorf("CheckoutNewBranch: %v", err)
  209. }
  210. if err = git.Push(localPath, git.PushOptions{
  211. Remote: "origin",
  212. Branch: branchName,
  213. }); err != nil {
  214. return fmt.Errorf("Push: %v", err)
  215. }
  216. return nil
  217. }
  218. // GetCommit returns all the commits of a branch
  219. func (branch *Branch) GetCommit() (*git.Commit, error) {
  220. gitRepo, err := git.OpenRepository(branch.Path)
  221. if err != nil {
  222. return nil, err
  223. }
  224. return gitRepo.GetBranchCommit(branch.Name)
  225. }