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.

hook.go 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. // Copyright 2019 The Gitea 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 private includes all internal routes. The package name internal is ideal but Golang is not allowed, so we use private as package name instead.
  5. package private
  6. import (
  7. "bufio"
  8. "context"
  9. "fmt"
  10. "io"
  11. "net/http"
  12. "os"
  13. "strings"
  14. "code.gitea.io/gitea/models"
  15. "code.gitea.io/gitea/modules/git"
  16. "code.gitea.io/gitea/modules/log"
  17. "code.gitea.io/gitea/modules/private"
  18. "code.gitea.io/gitea/modules/repofiles"
  19. "code.gitea.io/gitea/modules/setting"
  20. "code.gitea.io/gitea/modules/util"
  21. pull_service "code.gitea.io/gitea/services/pull"
  22. "gitea.com/macaron/macaron"
  23. "github.com/go-git/go-git/v5/plumbing"
  24. "github.com/gobwas/glob"
  25. )
  26. func verifyCommits(oldCommitID, newCommitID string, repo *git.Repository, env []string) error {
  27. stdoutReader, stdoutWriter, err := os.Pipe()
  28. if err != nil {
  29. log.Error("Unable to create os.Pipe for %s", repo.Path)
  30. return err
  31. }
  32. defer func() {
  33. _ = stdoutReader.Close()
  34. _ = stdoutWriter.Close()
  35. }()
  36. err = git.NewCommand("rev-list", oldCommitID+"..."+newCommitID).
  37. RunInDirTimeoutEnvFullPipelineFunc(env, -1, repo.Path,
  38. stdoutWriter, nil, nil,
  39. func(ctx context.Context, cancel context.CancelFunc) error {
  40. _ = stdoutWriter.Close()
  41. err := readAndVerifyCommitsFromShaReader(stdoutReader, repo, env)
  42. if err != nil {
  43. log.Error("%v", err)
  44. cancel()
  45. }
  46. _ = stdoutReader.Close()
  47. return err
  48. })
  49. if err != nil && !isErrUnverifiedCommit(err) {
  50. log.Error("Unable to check commits from %s to %s in %s: %v", oldCommitID, newCommitID, repo.Path, err)
  51. }
  52. return err
  53. }
  54. func checkFileProtection(oldCommitID, newCommitID string, patterns []glob.Glob, repo *git.Repository, env []string) error {
  55. stdoutReader, stdoutWriter, err := os.Pipe()
  56. if err != nil {
  57. log.Error("Unable to create os.Pipe for %s", repo.Path)
  58. return err
  59. }
  60. defer func() {
  61. _ = stdoutReader.Close()
  62. _ = stdoutWriter.Close()
  63. }()
  64. err = git.NewCommand("diff", "--name-only", oldCommitID+"..."+newCommitID).
  65. RunInDirTimeoutEnvFullPipelineFunc(env, -1, repo.Path,
  66. stdoutWriter, nil, nil,
  67. func(ctx context.Context, cancel context.CancelFunc) error {
  68. _ = stdoutWriter.Close()
  69. scanner := bufio.NewScanner(stdoutReader)
  70. for scanner.Scan() {
  71. path := strings.TrimSpace(scanner.Text())
  72. if len(path) == 0 {
  73. continue
  74. }
  75. lpath := strings.ToLower(path)
  76. for _, pat := range patterns {
  77. if pat.Match(lpath) {
  78. cancel()
  79. return models.ErrFilePathProtected{
  80. Path: path,
  81. }
  82. }
  83. }
  84. }
  85. if err := scanner.Err(); err != nil {
  86. return err
  87. }
  88. _ = stdoutReader.Close()
  89. return err
  90. })
  91. if err != nil && !models.IsErrFilePathProtected(err) {
  92. log.Error("Unable to check file protection for commits from %s to %s in %s: %v", oldCommitID, newCommitID, repo.Path, err)
  93. }
  94. return err
  95. }
  96. func readAndVerifyCommitsFromShaReader(input io.ReadCloser, repo *git.Repository, env []string) error {
  97. scanner := bufio.NewScanner(input)
  98. for scanner.Scan() {
  99. line := scanner.Text()
  100. err := readAndVerifyCommit(line, repo, env)
  101. if err != nil {
  102. log.Error("%v", err)
  103. return err
  104. }
  105. }
  106. return scanner.Err()
  107. }
  108. func readAndVerifyCommit(sha string, repo *git.Repository, env []string) error {
  109. stdoutReader, stdoutWriter, err := os.Pipe()
  110. if err != nil {
  111. log.Error("Unable to create pipe for %s: %v", repo.Path, err)
  112. return err
  113. }
  114. defer func() {
  115. _ = stdoutReader.Close()
  116. _ = stdoutWriter.Close()
  117. }()
  118. hash := plumbing.NewHash(sha)
  119. return git.NewCommand("cat-file", "commit", sha).
  120. RunInDirTimeoutEnvFullPipelineFunc(env, -1, repo.Path,
  121. stdoutWriter, nil, nil,
  122. func(ctx context.Context, cancel context.CancelFunc) error {
  123. _ = stdoutWriter.Close()
  124. commit, err := git.CommitFromReader(repo, hash, stdoutReader)
  125. if err != nil {
  126. return err
  127. }
  128. verification := models.ParseCommitWithSignature(commit)
  129. if !verification.Verified {
  130. cancel()
  131. return &errUnverifiedCommit{
  132. commit.ID.String(),
  133. }
  134. }
  135. return nil
  136. })
  137. }
  138. type errUnverifiedCommit struct {
  139. sha string
  140. }
  141. func (e *errUnverifiedCommit) Error() string {
  142. return fmt.Sprintf("Unverified commit: %s", e.sha)
  143. }
  144. func isErrUnverifiedCommit(err error) bool {
  145. _, ok := err.(*errUnverifiedCommit)
  146. return ok
  147. }
  148. // HookPreReceive checks whether a individual commit is acceptable
  149. func HookPreReceive(ctx *macaron.Context, opts private.HookOptions) {
  150. ownerName := ctx.Params(":owner")
  151. repoName := ctx.Params(":repo")
  152. repo, err := models.GetRepositoryByOwnerAndName(ownerName, repoName)
  153. if err != nil {
  154. log.Error("Unable to get repository: %s/%s Error: %v", ownerName, repoName, err)
  155. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  156. "err": err.Error(),
  157. })
  158. return
  159. }
  160. repo.OwnerName = ownerName
  161. gitRepo, err := git.OpenRepository(repo.RepoPath())
  162. if err != nil {
  163. log.Error("Unable to get git repository for: %s/%s Error: %v", ownerName, repoName, err)
  164. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  165. "err": err.Error(),
  166. })
  167. return
  168. }
  169. defer gitRepo.Close()
  170. // Generate git environment for checking commits
  171. env := os.Environ()
  172. if opts.GitAlternativeObjectDirectories != "" {
  173. env = append(env,
  174. private.GitAlternativeObjectDirectories+"="+opts.GitAlternativeObjectDirectories)
  175. }
  176. if opts.GitObjectDirectory != "" {
  177. env = append(env,
  178. private.GitObjectDirectory+"="+opts.GitObjectDirectory)
  179. }
  180. if opts.GitQuarantinePath != "" {
  181. env = append(env,
  182. private.GitQuarantinePath+"="+opts.GitQuarantinePath)
  183. }
  184. for i := range opts.OldCommitIDs {
  185. oldCommitID := opts.OldCommitIDs[i]
  186. newCommitID := opts.NewCommitIDs[i]
  187. refFullName := opts.RefFullNames[i]
  188. branchName := strings.TrimPrefix(refFullName, git.BranchPrefix)
  189. protectBranch, err := models.GetProtectedBranchBy(repo.ID, branchName)
  190. if err != nil {
  191. log.Error("Unable to get protected branch: %s in %-v Error: %v", branchName, repo, err)
  192. ctx.JSON(500, map[string]interface{}{
  193. "err": err.Error(),
  194. })
  195. return
  196. }
  197. if protectBranch != nil && protectBranch.IsProtected() {
  198. // detect and prevent deletion
  199. if newCommitID == git.EmptySHA {
  200. log.Warn("Forbidden: Branch: %s in %-v is protected from deletion", branchName, repo)
  201. ctx.JSON(http.StatusForbidden, map[string]interface{}{
  202. "err": fmt.Sprintf("branch %s is protected from deletion", branchName),
  203. })
  204. return
  205. }
  206. // detect force push
  207. if git.EmptySHA != oldCommitID {
  208. output, err := git.NewCommand("rev-list", "--max-count=1", oldCommitID, "^"+newCommitID).RunInDirWithEnv(repo.RepoPath(), env)
  209. if err != nil {
  210. log.Error("Unable to detect force push between: %s and %s in %-v Error: %v", oldCommitID, newCommitID, repo, err)
  211. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  212. "err": fmt.Sprintf("Fail to detect force push: %v", err),
  213. })
  214. return
  215. } else if len(output) > 0 {
  216. log.Warn("Forbidden: Branch: %s in %-v is protected from force push", branchName, repo)
  217. ctx.JSON(http.StatusForbidden, map[string]interface{}{
  218. "err": fmt.Sprintf("branch %s is protected from force push", branchName),
  219. })
  220. return
  221. }
  222. }
  223. // Require signed commits
  224. if protectBranch.RequireSignedCommits {
  225. err := verifyCommits(oldCommitID, newCommitID, gitRepo, env)
  226. if err != nil {
  227. if !isErrUnverifiedCommit(err) {
  228. log.Error("Unable to check commits from %s to %s in %-v: %v", oldCommitID, newCommitID, repo, err)
  229. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  230. "err": fmt.Sprintf("Unable to check commits from %s to %s: %v", oldCommitID, newCommitID, err),
  231. })
  232. return
  233. }
  234. unverifiedCommit := err.(*errUnverifiedCommit).sha
  235. log.Warn("Forbidden: Branch: %s in %-v is protected from unverified commit %s", branchName, repo, unverifiedCommit)
  236. ctx.JSON(http.StatusForbidden, map[string]interface{}{
  237. "err": fmt.Sprintf("branch %s is protected from unverified commit %s", branchName, unverifiedCommit),
  238. })
  239. return
  240. }
  241. }
  242. // Detect Protected file pattern
  243. globs := protectBranch.GetProtectedFilePatterns()
  244. if len(globs) > 0 {
  245. err := checkFileProtection(oldCommitID, newCommitID, globs, gitRepo, env)
  246. if err != nil {
  247. if !models.IsErrFilePathProtected(err) {
  248. log.Error("Unable to check file protection for commits from %s to %s in %-v: %v", oldCommitID, newCommitID, repo, err)
  249. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  250. "err": fmt.Sprintf("Unable to check file protection for commits from %s to %s: %v", oldCommitID, newCommitID, err),
  251. })
  252. return
  253. }
  254. protectedFilePath := err.(models.ErrFilePathProtected).Path
  255. log.Warn("Forbidden: Branch: %s in %-v is protected from changing file %s", branchName, repo, protectedFilePath)
  256. ctx.JSON(http.StatusForbidden, map[string]interface{}{
  257. "err": fmt.Sprintf("branch %s is protected from changing file %s", branchName, protectedFilePath),
  258. })
  259. return
  260. }
  261. }
  262. canPush := false
  263. if opts.IsDeployKey {
  264. canPush = protectBranch.CanPush && (!protectBranch.EnableWhitelist || protectBranch.WhitelistDeployKeys)
  265. } else {
  266. canPush = protectBranch.CanUserPush(opts.UserID)
  267. }
  268. if !canPush && opts.ProtectedBranchID > 0 {
  269. // Merge (from UI or API)
  270. pr, err := models.GetPullRequestByID(opts.ProtectedBranchID)
  271. if err != nil {
  272. log.Error("Unable to get PullRequest %d Error: %v", opts.ProtectedBranchID, err)
  273. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  274. "err": fmt.Sprintf("Unable to get PullRequest %d Error: %v", opts.ProtectedBranchID, err),
  275. })
  276. return
  277. }
  278. user, err := models.GetUserByID(opts.UserID)
  279. if err != nil {
  280. log.Error("Unable to get User id %d Error: %v", opts.UserID, err)
  281. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  282. "err": fmt.Sprintf("Unable to get User id %d Error: %v", opts.UserID, err),
  283. })
  284. return
  285. }
  286. perm, err := models.GetUserRepoPermission(repo, user)
  287. if err != nil {
  288. log.Error("Unable to get Repo permission of repo %s/%s of User %s", repo.OwnerName, repo.Name, user.Name, err)
  289. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  290. "err": fmt.Sprintf("Unable to get Repo permission of repo %s/%s of User %s: %v", repo.OwnerName, repo.Name, user.Name, err),
  291. })
  292. return
  293. }
  294. allowedMerge, err := pull_service.IsUserAllowedToMerge(pr, perm, user)
  295. if err != nil {
  296. log.Error("Error calculating if allowed to merge: %v", err)
  297. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  298. "err": fmt.Sprintf("Error calculating if allowed to merge: %v", err),
  299. })
  300. return
  301. }
  302. if !allowedMerge {
  303. log.Warn("Forbidden: User %d is not allowed to push to protected branch: %s in %-v and is not allowed to merge pr #%d", opts.UserID, branchName, repo, pr.Index)
  304. ctx.JSON(http.StatusForbidden, map[string]interface{}{
  305. "err": fmt.Sprintf("Not allowed to push to protected branch %s", branchName),
  306. })
  307. return
  308. }
  309. // Check all status checks and reviews is ok, unless repo admin which can bypass this.
  310. if !perm.IsAdmin() {
  311. if err := pull_service.CheckPRReadyToMerge(pr); err != nil {
  312. if models.IsErrNotAllowedToMerge(err) {
  313. log.Warn("Forbidden: User %d is not allowed push to protected branch %s in %-v and pr #%d is not ready to be merged: %s", opts.UserID, branchName, repo, pr.Index, err.Error())
  314. ctx.JSON(http.StatusForbidden, map[string]interface{}{
  315. "err": fmt.Sprintf("Not allowed to push to protected branch %s and pr #%d is not ready to be merged: %s", branchName, opts.ProtectedBranchID, err.Error()),
  316. })
  317. return
  318. }
  319. log.Error("Unable to check if mergable: protected branch %s in %-v and pr #%d. Error: %v", opts.UserID, branchName, repo, pr.Index, err)
  320. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  321. "err": fmt.Sprintf("Unable to get status of pull request %d. Error: %v", opts.ProtectedBranchID, err),
  322. })
  323. }
  324. }
  325. } else if !canPush {
  326. log.Warn("Forbidden: User %d is not allowed to push to protected branch: %s in %-v", opts.UserID, branchName, repo)
  327. ctx.JSON(http.StatusForbidden, map[string]interface{}{
  328. "err": fmt.Sprintf("Not allowed to push to protected branch %s", branchName),
  329. })
  330. return
  331. }
  332. }
  333. }
  334. ctx.PlainText(http.StatusOK, []byte("ok"))
  335. }
  336. // HookPostReceive updates services and users
  337. func HookPostReceive(ctx *macaron.Context, opts private.HookOptions) {
  338. ownerName := ctx.Params(":owner")
  339. repoName := ctx.Params(":repo")
  340. var repo *models.Repository
  341. updates := make([]*repofiles.PushUpdateOptions, 0, len(opts.OldCommitIDs))
  342. wasEmpty := false
  343. for i := range opts.OldCommitIDs {
  344. refFullName := opts.RefFullNames[i]
  345. // Only trigger activity updates for changes to branches or
  346. // tags. Updates to other refs (eg, refs/notes, refs/changes,
  347. // or other less-standard refs spaces are ignored since there
  348. // may be a very large number of them).
  349. if strings.HasPrefix(refFullName, git.BranchPrefix) || strings.HasPrefix(refFullName, git.TagPrefix) {
  350. if repo == nil {
  351. var err error
  352. repo, err = models.GetRepositoryByOwnerAndName(ownerName, repoName)
  353. if err != nil {
  354. log.Error("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err)
  355. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
  356. Err: fmt.Sprintf("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err),
  357. })
  358. return
  359. }
  360. if repo.OwnerName == "" {
  361. repo.OwnerName = ownerName
  362. }
  363. wasEmpty = repo.IsEmpty
  364. }
  365. option := repofiles.PushUpdateOptions{
  366. RefFullName: refFullName,
  367. OldCommitID: opts.OldCommitIDs[i],
  368. NewCommitID: opts.NewCommitIDs[i],
  369. PusherID: opts.UserID,
  370. PusherName: opts.UserName,
  371. RepoUserName: ownerName,
  372. RepoName: repoName,
  373. }
  374. updates = append(updates, &option)
  375. if repo.IsEmpty && option.IsBranch() && option.BranchName() == "master" {
  376. // put the master branch first
  377. copy(updates[1:], updates)
  378. updates[0] = &option
  379. }
  380. }
  381. }
  382. if repo != nil && len(updates) > 0 {
  383. if err := repofiles.PushUpdates(repo, updates); err != nil {
  384. log.Error("Failed to Update: %s/%s Total Updates: %d", ownerName, repoName, len(updates))
  385. for i, update := range updates {
  386. log.Error("Failed to Update: %s/%s Update: %d/%d: Branch: %s", ownerName, repoName, i, len(updates), update.BranchName())
  387. }
  388. log.Error("Failed to Update: %s/%s Error: %v", ownerName, repoName, err)
  389. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
  390. Err: fmt.Sprintf("Failed to Update: %s/%s Error: %v", ownerName, repoName, err),
  391. })
  392. return
  393. }
  394. }
  395. results := make([]private.HookPostReceiveBranchResult, 0, len(opts.OldCommitIDs))
  396. // We have to reload the repo in case its state is changed above
  397. repo = nil
  398. var baseRepo *models.Repository
  399. for i := range opts.OldCommitIDs {
  400. refFullName := opts.RefFullNames[i]
  401. newCommitID := opts.NewCommitIDs[i]
  402. branch := git.RefEndName(opts.RefFullNames[i])
  403. if newCommitID != git.EmptySHA && strings.HasPrefix(refFullName, git.BranchPrefix) {
  404. if repo == nil {
  405. var err error
  406. repo, err = models.GetRepositoryByOwnerAndName(ownerName, repoName)
  407. if err != nil {
  408. log.Error("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err)
  409. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
  410. Err: fmt.Sprintf("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err),
  411. RepoWasEmpty: wasEmpty,
  412. })
  413. return
  414. }
  415. if repo.OwnerName == "" {
  416. repo.OwnerName = ownerName
  417. }
  418. if !repo.AllowsPulls() {
  419. // We can stop there's no need to go any further
  420. ctx.JSON(http.StatusOK, private.HookPostReceiveResult{
  421. RepoWasEmpty: wasEmpty,
  422. })
  423. return
  424. }
  425. baseRepo = repo
  426. if repo.IsFork {
  427. if err := repo.GetBaseRepo(); err != nil {
  428. log.Error("Failed to get Base Repository of Forked repository: %-v Error: %v", repo, err)
  429. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
  430. Err: fmt.Sprintf("Failed to get Base Repository of Forked repository: %-v Error: %v", repo, err),
  431. RepoWasEmpty: wasEmpty,
  432. })
  433. return
  434. }
  435. baseRepo = repo.BaseRepo
  436. }
  437. }
  438. if !repo.IsFork && branch == baseRepo.DefaultBranch {
  439. results = append(results, private.HookPostReceiveBranchResult{})
  440. continue
  441. }
  442. pr, err := models.GetUnmergedPullRequest(repo.ID, baseRepo.ID, branch, baseRepo.DefaultBranch)
  443. if err != nil && !models.IsErrPullRequestNotExist(err) {
  444. log.Error("Failed to get active PR in: %-v Branch: %s to: %-v Branch: %s Error: %v", repo, branch, baseRepo, baseRepo.DefaultBranch, err)
  445. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
  446. Err: fmt.Sprintf(
  447. "Failed to get active PR in: %-v Branch: %s to: %-v Branch: %s Error: %v", repo, branch, baseRepo, baseRepo.DefaultBranch, err),
  448. RepoWasEmpty: wasEmpty,
  449. })
  450. return
  451. }
  452. if pr == nil {
  453. if repo.IsFork {
  454. branch = fmt.Sprintf("%s:%s", repo.OwnerName, branch)
  455. }
  456. results = append(results, private.HookPostReceiveBranchResult{
  457. Message: setting.Git.PullRequestPushMessage && repo.AllowsPulls(),
  458. Create: true,
  459. Branch: branch,
  460. URL: fmt.Sprintf("%s/compare/%s...%s", baseRepo.HTMLURL(), util.PathEscapeSegments(baseRepo.DefaultBranch), util.PathEscapeSegments(branch)),
  461. })
  462. } else {
  463. results = append(results, private.HookPostReceiveBranchResult{
  464. Message: setting.Git.PullRequestPushMessage && repo.AllowsPulls(),
  465. Create: false,
  466. Branch: branch,
  467. URL: fmt.Sprintf("%s/pulls/%d", baseRepo.HTMLURL(), pr.Index),
  468. })
  469. }
  470. }
  471. }
  472. ctx.JSON(http.StatusOK, private.HookPostReceiveResult{
  473. Results: results,
  474. RepoWasEmpty: wasEmpty,
  475. })
  476. }
  477. // SetDefaultBranch updates the default branch
  478. func SetDefaultBranch(ctx *macaron.Context) {
  479. ownerName := ctx.Params(":owner")
  480. repoName := ctx.Params(":repo")
  481. branch := ctx.Params(":branch")
  482. repo, err := models.GetRepositoryByOwnerAndName(ownerName, repoName)
  483. if err != nil {
  484. log.Error("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err)
  485. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  486. "Err": fmt.Sprintf("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err),
  487. })
  488. return
  489. }
  490. if repo.OwnerName == "" {
  491. repo.OwnerName = ownerName
  492. }
  493. repo.DefaultBranch = branch
  494. gitRepo, err := git.OpenRepository(repo.RepoPath())
  495. if err != nil {
  496. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  497. "Err": fmt.Sprintf("Failed to get git repository: %s/%s Error: %v", ownerName, repoName, err),
  498. })
  499. return
  500. }
  501. if err := gitRepo.SetDefaultBranch(repo.DefaultBranch); err != nil {
  502. if !git.IsErrUnsupportedVersion(err) {
  503. gitRepo.Close()
  504. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  505. "Err": fmt.Sprintf("Unable to set default branch onrepository: %s/%s Error: %v", ownerName, repoName, err),
  506. })
  507. return
  508. }
  509. }
  510. gitRepo.Close()
  511. if err := repo.UpdateDefaultBranch(); err != nil {
  512. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  513. "Err": fmt.Sprintf("Unable to set default branch onrepository: %s/%s Error: %v", ownerName, repoName, err),
  514. })
  515. return
  516. }
  517. ctx.PlainText(200, []byte("success"))
  518. }