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

hook.go 21 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  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. log.Info("Git pre start..................................")
  151. ownerName := ctx.Params(":owner")
  152. repoName := ctx.Params(":repo")
  153. repo, err := models.GetRepositoryByOwnerAndName(ownerName, repoName)
  154. if err != nil {
  155. log.Error("Unable to get repository: %s/%s Error: %v", ownerName, repoName, err)
  156. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  157. "err": err.Error(),
  158. })
  159. return
  160. }
  161. repo.OwnerName = ownerName
  162. gitRepo, err := git.OpenRepository(repo.RepoPath())
  163. if err != nil {
  164. log.Error("Unable to get git repository for: %s/%s Error: %v", ownerName, repoName, err)
  165. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  166. "err": err.Error(),
  167. })
  168. return
  169. }
  170. defer gitRepo.Close()
  171. // Generate git environment for checking commits
  172. env := os.Environ()
  173. if opts.GitAlternativeObjectDirectories != "" {
  174. env = append(env,
  175. private.GitAlternativeObjectDirectories+"="+opts.GitAlternativeObjectDirectories)
  176. }
  177. if opts.GitObjectDirectory != "" {
  178. env = append(env,
  179. private.GitObjectDirectory+"="+opts.GitObjectDirectory)
  180. }
  181. if opts.GitQuarantinePath != "" {
  182. env = append(env,
  183. private.GitQuarantinePath+"="+opts.GitQuarantinePath)
  184. }
  185. for i := range opts.OldCommitIDs {
  186. oldCommitID := opts.OldCommitIDs[i]
  187. newCommitID := opts.NewCommitIDs[i]
  188. refFullName := opts.RefFullNames[i]
  189. branchName := strings.TrimPrefix(refFullName, git.BranchPrefix)
  190. if branchName == repo.DefaultBranch && newCommitID == git.EmptySHA {
  191. log.Warn("Forbidden: Branch: %s is the default branch in %-v and cannot be deleted", branchName, repo)
  192. ctx.JSON(http.StatusForbidden, map[string]interface{}{
  193. "err": fmt.Sprintf("branch %s is the default branch and cannot be deleted", branchName),
  194. })
  195. return
  196. }
  197. protectBranch, err := models.GetProtectedBranchBy(repo.ID, branchName)
  198. if err != nil {
  199. log.Error("Unable to get protected branch: %s in %-v Error: %v", branchName, repo, err)
  200. ctx.JSON(500, map[string]interface{}{
  201. "err": err.Error(),
  202. })
  203. return
  204. }
  205. if protectBranch != nil && protectBranch.IsProtected() {
  206. // detect and prevent deletion
  207. if newCommitID == git.EmptySHA {
  208. log.Warn("Forbidden: Branch: %s in %-v is protected from deletion", branchName, repo)
  209. ctx.JSON(http.StatusForbidden, map[string]interface{}{
  210. "err": fmt.Sprintf("branch %s is protected from deletion", branchName),
  211. })
  212. return
  213. }
  214. // detect force push
  215. if git.EmptySHA != oldCommitID {
  216. output, err := git.NewCommand("rev-list", "--max-count=1", oldCommitID, "^"+newCommitID).RunInDirWithEnv(repo.RepoPath(), env)
  217. if err != nil {
  218. log.Error("Unable to detect force push between: %s and %s in %-v Error: %v", oldCommitID, newCommitID, repo, err)
  219. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  220. "err": fmt.Sprintf("Fail to detect force push: %v", err),
  221. })
  222. return
  223. } else if len(output) > 0 {
  224. log.Warn("Forbidden: Branch: %s in %-v is protected from force push", branchName, repo)
  225. ctx.JSON(http.StatusForbidden, map[string]interface{}{
  226. "err": fmt.Sprintf("branch %s is protected from force push", branchName),
  227. })
  228. return
  229. }
  230. }
  231. // Require signed commits
  232. if protectBranch.RequireSignedCommits {
  233. err := verifyCommits(oldCommitID, newCommitID, gitRepo, env)
  234. if err != nil {
  235. if !isErrUnverifiedCommit(err) {
  236. log.Error("Unable to check commits from %s to %s in %-v: %v", oldCommitID, newCommitID, repo, err)
  237. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  238. "err": fmt.Sprintf("Unable to check commits from %s to %s: %v", oldCommitID, newCommitID, err),
  239. })
  240. return
  241. }
  242. unverifiedCommit := err.(*errUnverifiedCommit).sha
  243. log.Warn("Forbidden: Branch: %s in %-v is protected from unverified commit %s", branchName, repo, unverifiedCommit)
  244. ctx.JSON(http.StatusForbidden, map[string]interface{}{
  245. "err": fmt.Sprintf("branch %s is protected from unverified commit %s", branchName, unverifiedCommit),
  246. })
  247. return
  248. }
  249. }
  250. // Detect Protected file pattern
  251. globs := protectBranch.GetProtectedFilePatterns()
  252. if len(globs) > 0 {
  253. err := checkFileProtection(oldCommitID, newCommitID, globs, gitRepo, env)
  254. if err != nil {
  255. if !models.IsErrFilePathProtected(err) {
  256. log.Error("Unable to check file protection for commits from %s to %s in %-v: %v", oldCommitID, newCommitID, repo, err)
  257. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  258. "err": fmt.Sprintf("Unable to check file protection for commits from %s to %s: %v", oldCommitID, newCommitID, err),
  259. })
  260. return
  261. }
  262. protectedFilePath := err.(models.ErrFilePathProtected).Path
  263. log.Warn("Forbidden: Branch: %s in %-v is protected from changing file %s", branchName, repo, protectedFilePath)
  264. ctx.JSON(http.StatusForbidden, map[string]interface{}{
  265. "err": fmt.Sprintf("branch %s is protected from changing file %s", branchName, protectedFilePath),
  266. })
  267. return
  268. }
  269. }
  270. canPush := false
  271. if opts.IsDeployKey {
  272. canPush = protectBranch.CanPush && (!protectBranch.EnableWhitelist || protectBranch.WhitelistDeployKeys)
  273. } else {
  274. canPush = protectBranch.CanUserPush(opts.UserID)
  275. }
  276. if !canPush && opts.ProtectedBranchID > 0 {
  277. // Merge (from UI or API)
  278. pr, err := models.GetPullRequestByID(opts.ProtectedBranchID)
  279. if err != nil {
  280. log.Error("Unable to get PullRequest %d Error: %v", opts.ProtectedBranchID, err)
  281. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  282. "err": fmt.Sprintf("Unable to get PullRequest %d Error: %v", opts.ProtectedBranchID, err),
  283. })
  284. return
  285. }
  286. user, err := models.GetUserByID(opts.UserID)
  287. if err != nil {
  288. log.Error("Unable to get User id %d Error: %v", opts.UserID, err)
  289. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  290. "err": fmt.Sprintf("Unable to get User id %d Error: %v", opts.UserID, err),
  291. })
  292. return
  293. }
  294. perm, err := models.GetUserRepoPermission(repo, user)
  295. if err != nil {
  296. log.Error("Unable to get Repo permission of repo %s/%s of User %s", repo.OwnerName, repo.Name, user.Name, err)
  297. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  298. "err": fmt.Sprintf("Unable to get Repo permission of repo %s/%s of User %s: %v", repo.OwnerName, repo.Name, user.Name, err),
  299. })
  300. return
  301. }
  302. allowedMerge, err := pull_service.IsUserAllowedToMerge(pr, perm, user)
  303. if err != nil {
  304. log.Error("Error calculating if allowed to merge: %v", err)
  305. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  306. "err": fmt.Sprintf("Error calculating if allowed to merge: %v", err),
  307. })
  308. return
  309. }
  310. if !allowedMerge {
  311. 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)
  312. ctx.JSON(http.StatusForbidden, map[string]interface{}{
  313. "err": fmt.Sprintf("Not allowed to push to protected branch %s", branchName),
  314. })
  315. return
  316. }
  317. // Check all status checks and reviews is ok, unless repo admin which can bypass this.
  318. if !perm.IsAdmin() {
  319. if err := pull_service.CheckPRReadyToMerge(pr); err != nil {
  320. if models.IsErrNotAllowedToMerge(err) {
  321. 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())
  322. ctx.JSON(http.StatusForbidden, map[string]interface{}{
  323. "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()),
  324. })
  325. return
  326. }
  327. log.Error("Unable to check if mergable: protected branch %s in %-v and pr #%d. Error: %v", opts.UserID, branchName, repo, pr.Index, err)
  328. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  329. "err": fmt.Sprintf("Unable to get status of pull request %d. Error: %v", opts.ProtectedBranchID, err),
  330. })
  331. }
  332. }
  333. } else if !canPush {
  334. log.Warn("Forbidden: User %d is not allowed to push to protected branch: %s in %-v", opts.UserID, branchName, repo)
  335. ctx.JSON(http.StatusForbidden, map[string]interface{}{
  336. "err": fmt.Sprintf("Not allowed to push to protected branch %s", branchName),
  337. })
  338. return
  339. }
  340. }
  341. }
  342. ctx.PlainText(http.StatusOK, []byte("ok"))
  343. }
  344. // HookPostReceive updates services and users
  345. func HookPostReceive(ctx *macaron.Context, opts private.HookOptions) {
  346. log.Info("Git post start..................................")
  347. ownerName := ctx.Params(":owner")
  348. repoName := ctx.Params(":repo")
  349. var repo *models.Repository
  350. updates := make([]*repofiles.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 := repofiles.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 := repofiles.PushUpdates(repo, 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. results := make([]private.HookPostReceiveBranchResult, 0, len(opts.OldCommitIDs))
  405. // We have to reload the repo in case its state is changed above
  406. repo = nil
  407. var baseRepo *models.Repository
  408. for i := range opts.OldCommitIDs {
  409. refFullName := opts.RefFullNames[i]
  410. newCommitID := opts.NewCommitIDs[i]
  411. branch := git.RefEndName(opts.RefFullNames[i])
  412. if newCommitID != git.EmptySHA && strings.HasPrefix(refFullName, git.BranchPrefix) {
  413. if repo == nil {
  414. var err error
  415. repo, err = models.GetRepositoryByOwnerAndName(ownerName, repoName)
  416. if err != nil {
  417. log.Error("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err)
  418. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
  419. Err: fmt.Sprintf("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err),
  420. RepoWasEmpty: wasEmpty,
  421. })
  422. return
  423. }
  424. if repo.OwnerName == "" {
  425. repo.OwnerName = ownerName
  426. }
  427. if !repo.AllowsPulls() {
  428. // We can stop there's no need to go any further
  429. ctx.JSON(http.StatusOK, private.HookPostReceiveResult{
  430. RepoWasEmpty: wasEmpty,
  431. })
  432. return
  433. }
  434. baseRepo = repo
  435. if repo.IsFork {
  436. if err := repo.GetBaseRepo(); err != nil {
  437. log.Error("Failed to get Base Repository of Forked repository: %-v Error: %v", repo, err)
  438. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
  439. Err: fmt.Sprintf("Failed to get Base Repository of Forked repository: %-v Error: %v", repo, err),
  440. RepoWasEmpty: wasEmpty,
  441. })
  442. return
  443. }
  444. baseRepo = repo.BaseRepo
  445. }
  446. }
  447. if !repo.IsFork && branch == baseRepo.DefaultBranch {
  448. results = append(results, private.HookPostReceiveBranchResult{})
  449. continue
  450. }
  451. pr, err := models.GetUnmergedPullRequest(repo.ID, baseRepo.ID, branch, baseRepo.DefaultBranch)
  452. if err != nil && !models.IsErrPullRequestNotExist(err) {
  453. log.Error("Failed to get active PR in: %-v Branch: %s to: %-v Branch: %s Error: %v", repo, branch, baseRepo, baseRepo.DefaultBranch, err)
  454. ctx.JSON(http.StatusInternalServerError, private.HookPostReceiveResult{
  455. Err: fmt.Sprintf(
  456. "Failed to get active PR in: %-v Branch: %s to: %-v Branch: %s Error: %v", repo, branch, baseRepo, baseRepo.DefaultBranch, err),
  457. RepoWasEmpty: wasEmpty,
  458. })
  459. return
  460. }
  461. if pr == nil {
  462. if repo.IsFork {
  463. branch = fmt.Sprintf("%s:%s", repo.OwnerName, branch)
  464. }
  465. results = append(results, private.HookPostReceiveBranchResult{
  466. Message: setting.Git.PullRequestPushMessage && repo.AllowsPulls(),
  467. Create: true,
  468. Branch: branch,
  469. URL: fmt.Sprintf("%s/compare/%s...%s", baseRepo.HTMLURL(), util.PathEscapeSegments(baseRepo.DefaultBranch), util.PathEscapeSegments(branch)),
  470. })
  471. } else {
  472. results = append(results, private.HookPostReceiveBranchResult{
  473. Message: setting.Git.PullRequestPushMessage && repo.AllowsPulls(),
  474. Create: false,
  475. Branch: branch,
  476. URL: fmt.Sprintf("%s/pulls/%d", baseRepo.HTMLURL(), pr.Index),
  477. })
  478. }
  479. }
  480. }
  481. if err := updateRepoCommitCnt(ctx, repo); err != nil {
  482. log.Error("updateRepoCommitCnt failed:%v", err.Error(), ctx.Data["MsgID"])
  483. }
  484. ctx.JSON(http.StatusOK, private.HookPostReceiveResult{
  485. Results: results,
  486. RepoWasEmpty: wasEmpty,
  487. })
  488. }
  489. func updateRepoCommitCnt(ctx *macaron.Context, repo *models.Repository) error {
  490. gitRepo, err := git.OpenRepository(repo.RepoPath())
  491. if err != nil {
  492. log.Error("OpenRepository failed:%v", err.Error(), ctx.Data["MsgID"])
  493. return err
  494. }
  495. defer gitRepo.Close()
  496. count, err := gitRepo.GetAllCommitsCount()
  497. if err != nil {
  498. log.Error("GetAllCommitsCount failed:%v", err.Error(), ctx.Data["MsgID"])
  499. return err
  500. }
  501. repo.NumCommit = count
  502. if err = models.UpdateRepositoryCommitNum(repo); err != nil {
  503. log.Error("UpdateRepositoryCommitNum failed:%v", err.Error(), ctx.Data["MsgID"])
  504. return err
  505. }
  506. return nil
  507. }
  508. // SetDefaultBranch updates the default branch
  509. func SetDefaultBranch(ctx *macaron.Context) {
  510. ownerName := ctx.Params(":owner")
  511. repoName := ctx.Params(":repo")
  512. branch := ctx.Params(":branch")
  513. repo, err := models.GetRepositoryByOwnerAndName(ownerName, repoName)
  514. if err != nil {
  515. log.Error("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err)
  516. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  517. "Err": fmt.Sprintf("Failed to get repository: %s/%s Error: %v", ownerName, repoName, err),
  518. })
  519. return
  520. }
  521. if repo.OwnerName == "" {
  522. repo.OwnerName = ownerName
  523. }
  524. repo.DefaultBranch = branch
  525. gitRepo, err := git.OpenRepository(repo.RepoPath())
  526. if err != nil {
  527. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  528. "Err": fmt.Sprintf("Failed to get git repository: %s/%s Error: %v", ownerName, repoName, err),
  529. })
  530. return
  531. }
  532. if err := gitRepo.SetDefaultBranch(repo.DefaultBranch); err != nil {
  533. if !git.IsErrUnsupportedVersion(err) {
  534. gitRepo.Close()
  535. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  536. "Err": fmt.Sprintf("Unable to set default branch onrepository: %s/%s Error: %v", ownerName, repoName, err),
  537. })
  538. return
  539. }
  540. }
  541. gitRepo.Close()
  542. if err := repo.UpdateDefaultBranch(); err != nil {
  543. ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
  544. "Err": fmt.Sprintf("Unable to set default branch onrepository: %s/%s Error: %v", ownerName, repoName, err),
  545. })
  546. return
  547. }
  548. ctx.PlainText(200, []byte("success"))
  549. }