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

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