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.

hooks.go 6.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. // Copyright 2020 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 repository
  5. import (
  6. "context"
  7. "fmt"
  8. "io/ioutil"
  9. "os"
  10. "path/filepath"
  11. "code.gitea.io/gitea/models"
  12. "code.gitea.io/gitea/modules/log"
  13. "code.gitea.io/gitea/modules/setting"
  14. "code.gitea.io/gitea/modules/util"
  15. "github.com/unknwon/com"
  16. "xorm.io/builder"
  17. )
  18. func getHookTemplates() (hookNames, hookTpls, giteaHookTpls []string) {
  19. hookNames = []string{"pre-receive", "update", "post-receive"}
  20. hookTpls = []string{
  21. fmt.Sprintf("#!/usr/bin/env %s\ndata=$(cat)\nexitcodes=\"\"\nhookname=$(basename $0)\nGIT_DIR=${GIT_DIR:-$(dirname $0)}\n\nfor hook in ${GIT_DIR}/hooks/${hookname}.d/*; do\ntest -x \"${hook}\" && test -f \"${hook}\" || continue\necho \"${data}\" | \"${hook}\"\nexitcodes=\"${exitcodes} $?\"\ndone\n\nfor i in ${exitcodes}; do\n[ ${i} -eq 0 ] || exit ${i}\ndone\n", setting.ScriptType),
  22. fmt.Sprintf("#!/usr/bin/env %s\nexitcodes=\"\"\nhookname=$(basename $0)\nGIT_DIR=${GIT_DIR:-$(dirname $0)}\n\nfor hook in ${GIT_DIR}/hooks/${hookname}.d/*; do\ntest -x \"${hook}\" && test -f \"${hook}\" || continue\n\"${hook}\" $1 $2 $3\nexitcodes=\"${exitcodes} $?\"\ndone\n\nfor i in ${exitcodes}; do\n[ ${i} -eq 0 ] || exit ${i}\ndone\n", setting.ScriptType),
  23. fmt.Sprintf("#!/usr/bin/env %s\ndata=$(cat)\nexitcodes=\"\"\nhookname=$(basename $0)\nGIT_DIR=${GIT_DIR:-$(dirname $0)}\n\nfor hook in ${GIT_DIR}/hooks/${hookname}.d/*; do\ntest -x \"${hook}\" && test -f \"${hook}\" || continue\necho \"${data}\" | \"${hook}\"\nexitcodes=\"${exitcodes} $?\"\ndone\n\nfor i in ${exitcodes}; do\n[ ${i} -eq 0 ] || exit ${i}\ndone\n", setting.ScriptType),
  24. }
  25. giteaHookTpls = []string{
  26. fmt.Sprintf("#!/usr/bin/env %s\n%s hook --config=%s pre-receive\n", setting.ScriptType, util.ShellEscape(setting.AppPath), util.ShellEscape(setting.CustomConf)),
  27. fmt.Sprintf("#!/usr/bin/env %s\n%s hook --config=%s update $1 $2 $3\n", setting.ScriptType, util.ShellEscape(setting.AppPath), util.ShellEscape(setting.CustomConf)),
  28. fmt.Sprintf("#!/usr/bin/env %s\n%s hook --config=%s post-receive\n", setting.ScriptType, util.ShellEscape(setting.AppPath), util.ShellEscape(setting.CustomConf)),
  29. }
  30. return
  31. }
  32. // CreateDelegateHooks creates all the hooks scripts for the repo
  33. func CreateDelegateHooks(repoPath string) error {
  34. return createDelegateHooks(repoPath)
  35. }
  36. // createDelegateHooks creates all the hooks scripts for the repo
  37. func createDelegateHooks(repoPath string) (err error) {
  38. hookNames, hookTpls, giteaHookTpls := getHookTemplates()
  39. hookDir := filepath.Join(repoPath, "hooks")
  40. for i, hookName := range hookNames {
  41. oldHookPath := filepath.Join(hookDir, hookName)
  42. newHookPath := filepath.Join(hookDir, hookName+".d", "gitea")
  43. if err := os.MkdirAll(filepath.Join(hookDir, hookName+".d"), os.ModePerm); err != nil {
  44. return fmt.Errorf("create hooks dir '%s': %v", filepath.Join(hookDir, hookName+".d"), err)
  45. }
  46. // WARNING: This will override all old server-side hooks
  47. if err = util.Remove(oldHookPath); err != nil && !os.IsNotExist(err) {
  48. return fmt.Errorf("unable to pre-remove old hook file '%s' prior to rewriting: %v ", oldHookPath, err)
  49. }
  50. if err = ioutil.WriteFile(oldHookPath, []byte(hookTpls[i]), 0777); err != nil {
  51. return fmt.Errorf("write old hook file '%s': %v", oldHookPath, err)
  52. }
  53. if err = ensureExecutable(oldHookPath); err != nil {
  54. return fmt.Errorf("Unable to set %s executable. Error %v", oldHookPath, err)
  55. }
  56. if err = util.Remove(newHookPath); err != nil && !os.IsNotExist(err) {
  57. return fmt.Errorf("unable to pre-remove new hook file '%s' prior to rewriting: %v", newHookPath, err)
  58. }
  59. if err = ioutil.WriteFile(newHookPath, []byte(giteaHookTpls[i]), 0777); err != nil {
  60. return fmt.Errorf("write new hook file '%s': %v", newHookPath, err)
  61. }
  62. if err = ensureExecutable(newHookPath); err != nil {
  63. return fmt.Errorf("Unable to set %s executable. Error %v", oldHookPath, err)
  64. }
  65. }
  66. return nil
  67. }
  68. func checkExecutable(filename string) bool {
  69. fileInfo, err := os.Stat(filename)
  70. if err != nil {
  71. return false
  72. }
  73. return (fileInfo.Mode() & 0100) > 0
  74. }
  75. func ensureExecutable(filename string) error {
  76. fileInfo, err := os.Stat(filename)
  77. if err != nil {
  78. return err
  79. }
  80. if (fileInfo.Mode() & 0100) > 0 {
  81. return nil
  82. }
  83. mode := fileInfo.Mode() | 0100
  84. return os.Chmod(filename, mode)
  85. }
  86. // CheckDelegateHooks checks the hooks scripts for the repo
  87. func CheckDelegateHooks(repoPath string) ([]string, error) {
  88. hookNames, hookTpls, giteaHookTpls := getHookTemplates()
  89. hookDir := filepath.Join(repoPath, "hooks")
  90. results := make([]string, 0, 10)
  91. for i, hookName := range hookNames {
  92. oldHookPath := filepath.Join(hookDir, hookName)
  93. newHookPath := filepath.Join(hookDir, hookName+".d", "gitea")
  94. cont := false
  95. if !com.IsExist(oldHookPath) {
  96. results = append(results, fmt.Sprintf("old hook file %s does not exist", oldHookPath))
  97. cont = true
  98. }
  99. if !com.IsExist(oldHookPath + ".d") {
  100. results = append(results, fmt.Sprintf("hooks directory %s does not exist", oldHookPath+".d"))
  101. cont = true
  102. }
  103. if !com.IsExist(newHookPath) {
  104. results = append(results, fmt.Sprintf("new hook file %s does not exist", newHookPath))
  105. cont = true
  106. }
  107. if cont {
  108. continue
  109. }
  110. contents, err := ioutil.ReadFile(oldHookPath)
  111. if err != nil {
  112. return results, err
  113. }
  114. if string(contents) != hookTpls[i] {
  115. results = append(results, fmt.Sprintf("old hook file %s is out of date", oldHookPath))
  116. }
  117. if !checkExecutable(oldHookPath) {
  118. results = append(results, fmt.Sprintf("old hook file %s is not executable", oldHookPath))
  119. }
  120. contents, err = ioutil.ReadFile(newHookPath)
  121. if err != nil {
  122. return results, err
  123. }
  124. if string(contents) != giteaHookTpls[i] {
  125. results = append(results, fmt.Sprintf("new hook file %s is out of date", newHookPath))
  126. }
  127. if !checkExecutable(newHookPath) {
  128. results = append(results, fmt.Sprintf("new hook file %s is not executable", newHookPath))
  129. }
  130. }
  131. return results, nil
  132. }
  133. // SyncRepositoryHooks rewrites all repositories' pre-receive, update and post-receive hooks
  134. // to make sure the binary and custom conf path are up-to-date.
  135. func SyncRepositoryHooks(ctx context.Context) error {
  136. log.Trace("Doing: SyncRepositoryHooks")
  137. if err := models.Iterate(
  138. models.DefaultDBContext(),
  139. new(models.Repository),
  140. builder.Gt{"id": 0},
  141. func(idx int, bean interface{}) error {
  142. repo := bean.(*models.Repository)
  143. select {
  144. case <-ctx.Done():
  145. return models.ErrCancelledf("before sync repository hooks for %s", repo.FullName())
  146. default:
  147. }
  148. if err := createDelegateHooks(repo.RepoPath()); err != nil {
  149. return fmt.Errorf("SyncRepositoryHook: %v", err)
  150. }
  151. if repo.HasWiki() {
  152. if err := createDelegateHooks(repo.WikiPath()); err != nil {
  153. return fmt.Errorf("SyncRepositoryHook: %v", err)
  154. }
  155. }
  156. return nil
  157. },
  158. ); err != nil {
  159. return err
  160. }
  161. log.Trace("Finished: SyncRepositoryHooks")
  162. return nil
  163. }