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.

586 lines
20 KiB

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