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 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  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. if branchName == repo.DefaultBranch && newCommitID == git.EmptySHA {
  190. log.Warn("Forbidden: Branch: %s is the default branch in %-v and cannot be deleted", branchName, repo)
  191. ctx.JSON(http.StatusForbidden, map[string]interface{}{
  192. "err": fmt.Sprintf("branch %s is the default branch and cannot be deleted", branchName),
  193. })
  194. return
  195. }
  196. protectBranch, err := models.GetProtectedBranchBy(repo.ID, branchName)
  197. if err != nil {
  198. log.Error("Unable to get protected branch: %s in %-v Error: %v", branchName, repo, err)
  199. ctx.JSON(500, map[string]interface{}{
  200. "err": err.Error(),
  201. })
  202. return
  203. }
  204. if protectBranch != nil && protectBranch.IsProtected() {
  205. // detect and prevent deletion
  206. if newCommitID == git.EmptySHA {
  207. log.Warn("Forbidden: Branch: %s in %-v is protected from deletion", branchName, repo)
  208. ctx.JSON(http.StatusForbidden, map[string]interface{}{
  209. "err": fmt.Sprintf("branch %s is protected from deletion", branchName),
  210. })
  211. return
  212. }
  213. // detect force push
  214. if git.EmptySHA != oldCommitID {
  215. output, err := git.NewCommand("rev-list", "--max-count=1", oldCommitID, "^"+newCommitID).RunInDirWithEnv(repo.RepoPath(), env)
  216. if err != nil {
  217. log.Error("Unable to detect force push between: %s and %s in %-v Error: %v", oldCommitID, newCommitID, repo, err)
  218. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  219. "err": fmt.Sprintf("Fail to detect force push: %v", err),
  220. })
  221. return
  222. } else if len(output) > 0 {
  223. log.Warn("Forbidden: Branch: %s in %-v is protected from force push", branchName, repo)
  224. ctx.JSON(http.StatusForbidden, map[string]interface{}{
  225. "err": fmt.Sprintf("branch %s is protected from force push", branchName),
  226. })
  227. return
  228. }
  229. }
  230. // Require signed commits
  231. if protectBranch.RequireSignedCommits {
  232. err := verifyCommits(oldCommitID, newCommitID, gitRepo, env)
  233. if err != nil {
  234. if !isErrUnverifiedCommit(err) {
  235. log.Error("Unable to check commits from %s to %s in %-v: %v", oldCommitID, newCommitID, repo, err)
  236. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  237. "err": fmt.Sprintf("Unable to check commits from %s to %s: %v", oldCommitID, newCommitID, err),
  238. })
  239. return
  240. }
  241. unverifiedCommit := err.(*errUnverifiedCommit).sha
  242. log.Warn("Forbidden: Branch: %s in %-v is protected from unverified commit %s", branchName, repo, unverifiedCommit)
  243. ctx.JSON(http.StatusForbidden, map[string]interface{}{
  244. "err": fmt.Sprintf("branch %s is protected from unverified commit %s", branchName, unverifiedCommit),
  245. })
  246. return
  247. }
  248. }
  249. // Detect Protected file pattern
  250. globs := protectBranch.GetProtectedFilePatterns()
  251. if len(globs) > 0 {
  252. err := checkFileProtection(oldCommitID, newCommitID, globs, gitRepo, env)
  253. if err != nil {
  254. if !models.IsErrFilePathProtected(err) {
  255. log.Error("Unable to check file protection for commits from %s to %s in %-v: %v", oldCommitID, newCommitID, repo, err)
  256. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  257. "err": fmt.Sprintf("Unable to check file protection for commits from %s to %s: %v", oldCommitID, newCommitID, err),
  258. })
  259. return
  260. }
  261. protectedFilePath := err.(models.ErrFilePathProtected).Path
  262. log.Warn("Forbidden: Branch: %s in %-v is protected from changing file %s", branchName, repo, protectedFilePath)
  263. ctx.JSON(http.StatusForbidden, map[string]interface{}{
  264. "err": fmt.Sprintf("branch %s is protected from changing file %s", branchName, protectedFilePath),
  265. })
  266. return
  267. }
  268. }
  269. canPush := false
  270. if opts.IsDeployKey {
  271. canPush = protectBranch.CanPush && (!protectBranch.EnableWhitelist || protectBranch.WhitelistDeployKeys)
  272. } else {
  273. canPush = protectBranch.CanUserPush(opts.UserID)
  274. }
  275. if !canPush && opts.ProtectedBranchID > 0 {
  276. // Merge (from UI or API)
  277. pr, err := models.GetPullRequestByID(opts.ProtectedBranchID)
  278. if err != nil {
  279. log.Error("Unable to get PullRequest %d Error: %v", opts.ProtectedBranchID, err)
  280. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  281. "err": fmt.Sprintf("Unable to get PullRequest %d Error: %v", opts.ProtectedBranchID, err),
  282. })
  283. return
  284. }
  285. user, err := models.GetUserByID(opts.UserID)
  286. if err != nil {
  287. log.Error("Unable to get User id %d Error: %v", opts.UserID, err)
  288. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  289. "err": fmt.Sprintf("Unable to get User id %d Error: %v", opts.UserID, err),
  290. })
  291. return
  292. }
  293. perm, err := models.GetUserRepoPermission(repo, user)
  294. if err != nil {
  295. log.Error("Unable to get Repo permission of repo %s/%s of User %s", repo.OwnerName, repo.Name, user.Name, err)
  296. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  297. "err": fmt.Sprintf("Unable to get Repo permission of repo %s/%s of User %s: %v", repo.OwnerName, repo.Name, user.Name, err),
  298. })
  299. return
  300. }
  301. allowedMerge, err := pull_service.IsUserAllowedToMerge(pr, perm, user)
  302. if err != nil {
  303. log.Error("Error calculating if allowed to merge: %v", err)
  304. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  305. "err": fmt.Sprintf("Error calculating if allowed to merge: %v", err),
  306. })
  307. return
  308. }
  309. if !allowedMerge {
  310. 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)
  311. ctx.JSON(http.StatusForbidden, map[string]interface{}{
  312. "err": fmt.Sprintf("Not allowed to push to protected branch %s", branchName),
  313. })
  314. return
  315. }
  316. // Check all status checks and reviews is ok, unless repo admin which can bypass this.
  317. if !perm.IsAdmin() {
  318. if err := pull_service.CheckPRReadyToMerge(pr); err != nil {
  319. if models.IsErrNotAllowedToMerge(err) {
  320. 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())
  321. ctx.JSON(http.StatusForbidden, map[string]interface{}{
  322. "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()),
  323. })
  324. return
  325. }
  326. log.Error("Unable to check if mergable: protected branch %s in %-v and pr #%d. Error: %v", opts.UserID, branchName, repo, pr.Index, err)
  327. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  328. "err": fmt.Sprintf("Unable to get status of pull request %d. Error: %v", opts.ProtectedBranchID, err),
  329. })
  330. }
  331. }
  332. } else if !canPush {
  333. log.Warn("Forbidden: User %d is not allowed to push to protected branch: %s in %-v", opts.UserID, branchName, repo)
  334. ctx.JSON(http.StatusForbidden, map[string]interface{}{
  335. "err": fmt.Sprintf("Not allowed to push to protected branch %s", branchName),
  336. })
  337. return
  338. }
  339. }
  340. }
  341. ctx.PlainText(http.StatusOK, []byte("ok"))
  342. }
  343. // HookPostReceive updates services and users
  344. func HookPostReceive(ctx *macaron.Context, opts private.HookOptions) {
  345. ownerName := ctx.Params(":owner")
  346. repoName := ctx.Params(":repo")
  347. var repo *models.Repository
  348. updates := make([]*repofiles.PushUpdateOptions, 0, len(opts.OldCommitIDs))
  349. wasEmpty := false
  350. for i := range opts.OldCommitIDs {
  351. refFullName := opts.RefFullNames[i]
  352. // Only trigger activity updates for changes to branches or
  353. // tags. Updates to other refs (eg, refs/notes, refs/changes,
  354. // or other less-standard refs spaces are ignored since there
  355. // may be a very large number of them).
  356. if strings.HasPrefix(refFullName, git.BranchPrefix) || strings.HasPrefix(refFullName, git.TagPrefix) {
  357. if repo == nil {
  358. var err error
  359. repo, err = models.GetRepositoryByOwnerAndName(ownerName, repoName)
  360. if err != nil {
  361. log.Error("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err)
  362. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
  363. Err: fmt.Sprintf("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err),
  364. })
  365. return
  366. }
  367. if repo.OwnerName == "" {
  368. repo.OwnerName = ownerName
  369. }
  370. wasEmpty = repo.IsEmpty
  371. }
  372. option := repofiles.PushUpdateOptions{
  373. RefFullName: refFullName,
  374. OldCommitID: opts.OldCommitIDs[i],
  375. NewCommitID: opts.NewCommitIDs[i],
  376. PusherID: opts.UserID,
  377. PusherName: opts.UserName,
  378. RepoUserName: ownerName,
  379. RepoName: repoName,
  380. }
  381. updates = append(updates, &option)
  382. if repo.IsEmpty && option.IsBranch() && option.BranchName() == "master" {
  383. // put the master branch first
  384. copy(updates[1:], updates)
  385. updates[0] = &option
  386. }
  387. }
  388. }
  389. if repo != nil && len(updates) > 0 {
  390. if err := repofiles.PushUpdates(repo, updates); err != nil {
  391. log.Error("Failed to Update: %s/%s Total Updates: %d", ownerName, repoName, len(updates))
  392. for i, update := range updates {
  393. log.Error("Failed to Update: %s/%s Update: %d/%d: Branch: %s", ownerName, repoName, i, len(updates), update.BranchName())
  394. }
  395. log.Error("Failed to Update: %s/%s Error: %v", ownerName, repoName, err)
  396. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
  397. Err: fmt.Sprintf("Failed to Update: %s/%s Error: %v", ownerName, repoName, err),
  398. })
  399. return
  400. }
  401. }
  402. results := make([]private.HookPostReceiveBranchResult, 0, len(opts.OldCommitIDs))
  403. // We have to reload the repo in case its state is changed above
  404. repo = nil
  405. var baseRepo *models.Repository
  406. for i := range opts.OldCommitIDs {
  407. refFullName := opts.RefFullNames[i]
  408. newCommitID := opts.NewCommitIDs[i]
  409. branch := git.RefEndName(opts.RefFullNames[i])
  410. if newCommitID != git.EmptySHA && strings.HasPrefix(refFullName, git.BranchPrefix) {
  411. if repo == nil {
  412. var err error
  413. repo, err = models.GetRepositoryByOwnerAndName(ownerName, repoName)
  414. if err != nil {
  415. log.Error("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err)
  416. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
  417. Err: fmt.Sprintf("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err),
  418. RepoWasEmpty: wasEmpty,
  419. })
  420. return
  421. }
  422. if repo.OwnerName == "" {
  423. repo.OwnerName = ownerName
  424. }
  425. if !repo.AllowsPulls() {
  426. // We can stop there's no need to go any further
  427. ctx.JSON(http.StatusOK, private.HookPostReceiveResult{
  428. RepoWasEmpty: wasEmpty,
  429. })
  430. return
  431. }
  432. baseRepo = repo
  433. if repo.IsFork {
  434. if err := repo.GetBaseRepo(); err != nil {
  435. log.Error("Failed to get Base Repository of Forked repository: %-v Error: %v", repo, err)
  436. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
  437. Err: fmt.Sprintf("Failed to get Base Repository of Forked repository: %-v Error: %v", repo, err),
  438. RepoWasEmpty: wasEmpty,
  439. })
  440. return
  441. }
  442. baseRepo = repo.BaseRepo
  443. }
  444. }
  445. if !repo.IsFork && branch == baseRepo.DefaultBranch {
  446. results = append(results, private.HookPostReceiveBranchResult{})
  447. continue
  448. }
  449. pr, err := models.GetUnmergedPullRequest(repo.ID, baseRepo.ID, branch, baseRepo.DefaultBranch)
  450. if err != nil && !models.IsErrPullRequestNotExist(err) {
  451. log.Error("Failed to get active PR in: %-v Branch: %s to: %-v Branch: %s Error: %v", repo, branch, baseRepo, baseRepo.DefaultBranch, err)
  452. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
  453. Err: fmt.Sprintf(
  454. "Failed to get active PR in: %-v Branch: %s to: %-v Branch: %s Error: %v", repo, branch, baseRepo, baseRepo.DefaultBranch, err),
  455. RepoWasEmpty: wasEmpty,
  456. })
  457. return
  458. }
  459. if pr == nil {
  460. if repo.IsFork {
  461. branch = fmt.Sprintf("%s:%s", repo.OwnerName, branch)
  462. }
  463. results = append(results, private.HookPostReceiveBranchResult{
  464. Message: setting.Git.PullRequestPushMessage && repo.AllowsPulls(),
  465. Create: true,
  466. Branch: branch,
  467. URL: fmt.Sprintf("%s/compare/%s...%s", baseRepo.HTMLURL(), util.PathEscapeSegments(baseRepo.DefaultBranch), util.PathEscapeSegments(branch)),
  468. })
  469. } else {
  470. results = append(results, private.HookPostReceiveBranchResult{
  471. Message: setting.Git.PullRequestPushMessage && repo.AllowsPulls(),
  472. Create: false,
  473. Branch: branch,
  474. URL: fmt.Sprintf("%s/pulls/%d", baseRepo.HTMLURL(), pr.Index),
  475. })
  476. }
  477. }
  478. }
  479. ctx.JSON(http.StatusOK, private.HookPostReceiveResult{
  480. Results: results,
  481. RepoWasEmpty: wasEmpty,
  482. })
  483. }
  484. // SetDefaultBranch updates the default branch
  485. func SetDefaultBranch(ctx *macaron.Context) {
  486. ownerName := ctx.Params(":owner")
  487. repoName := ctx.Params(":repo")
  488. branch := ctx.Params(":branch")
  489. repo, err := models.GetRepositoryByOwnerAndName(ownerName, repoName)
  490. if err != nil {
  491. log.Error("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err)
  492. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  493. "Err": fmt.Sprintf("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err),
  494. })
  495. return
  496. }
  497. if repo.OwnerName == "" {
  498. repo.OwnerName = ownerName
  499. }
  500. repo.DefaultBranch = branch
  501. gitRepo, err := git.OpenRepository(repo.RepoPath())
  502. if err != nil {
  503. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  504. "Err": fmt.Sprintf("Failed to get git repository: %s/%s Error: %v", ownerName, repoName, err),
  505. })
  506. return
  507. }
  508. if err := gitRepo.SetDefaultBranch(repo.DefaultBranch); err != nil {
  509. if !git.IsErrUnsupportedVersion(err) {
  510. gitRepo.Close()
  511. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  512. "Err": fmt.Sprintf("Unable to set default branch onrepository: %s/%s Error: %v", ownerName, repoName, err),
  513. })
  514. return
  515. }
  516. }
  517. gitRepo.Close()
  518. if err := repo.UpdateDefaultBranch(); err != nil {
  519. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  520. "Err": fmt.Sprintf("Unable to set default branch onrepository: %s/%s Error: %v", ownerName, repoName, err),
  521. })
  522. return
  523. }
  524. ctx.PlainText(200, []byte("success"))
  525. }