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

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