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.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  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. "github.com/unknwon/com"
  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, setting.AppPath, setting.CustomConf),
  26. fmt.Sprintf("#!/usr/bin/env %s\n\"%s\" hook --config='%s' update $1 $2 $3\n", setting.ScriptType, setting.AppPath, setting.CustomConf),
  27. fmt.Sprintf("#!/usr/bin/env %s\n\"%s\" hook --config='%s' post-receive\n", setting.ScriptType, setting.AppPath, 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 = os.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 = os.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. if !com.IsExist(oldHookPath) {
  95. results = append(results, fmt.Sprintf("old hook file %s does not exist", oldHookPath))
  96. cont = true
  97. }
  98. if !com.IsExist(oldHookPath + ".d") {
  99. results = append(results, fmt.Sprintf("hooks directory %s does not exist", oldHookPath+".d"))
  100. cont = true
  101. }
  102. if !com.IsExist(newHookPath) {
  103. results = append(results, fmt.Sprintf("new hook file %s does not exist", newHookPath))
  104. cont = true
  105. }
  106. if cont {
  107. continue
  108. }
  109. contents, err := ioutil.ReadFile(oldHookPath)
  110. if err != nil {
  111. return results, err
  112. }
  113. if string(contents) != hookTpls[i] {
  114. results = append(results, fmt.Sprintf("old hook file %s is out of date", oldHookPath))
  115. }
  116. if !checkExecutable(oldHookPath) {
  117. results = append(results, fmt.Sprintf("old hook file %s is not executable", oldHookPath))
  118. }
  119. contents, err = ioutil.ReadFile(newHookPath)
  120. if err != nil {
  121. return results, err
  122. }
  123. if string(contents) != giteaHookTpls[i] {
  124. results = append(results, fmt.Sprintf("new hook file %s is out of date", newHookPath))
  125. }
  126. if !checkExecutable(newHookPath) {
  127. results = append(results, fmt.Sprintf("new hook file %s is not executable", newHookPath))
  128. }
  129. }
  130. return results, nil
  131. }
  132. // SyncRepositoryHooks rewrites all repositories' pre-receive, update and post-receive hooks
  133. // to make sure the binary and custom conf path are up-to-date.
  134. func SyncRepositoryHooks(ctx context.Context) error {
  135. log.Trace("Doing: SyncRepositoryHooks")
  136. if err := models.Iterate(
  137. models.DefaultDBContext(),
  138. new(models.Repository),
  139. builder.Gt{"id": 0},
  140. func(idx int, bean interface{}) error {
  141. repo := bean.(*models.Repository)
  142. select {
  143. case <-ctx.Done():
  144. return models.ErrCancelledf("before sync repository hooks for %s", repo.FullName())
  145. default:
  146. }
  147. if err := createDelegateHooks(repo.RepoPath()); err != nil {
  148. return fmt.Errorf("SyncRepositoryHook: %v", err)
  149. }
  150. if repo.HasWiki() {
  151. if err := createDelegateHooks(repo.WikiPath()); err != nil {
  152. return fmt.Errorf("SyncRepositoryHook: %v", err)
  153. }
  154. }
  155. return nil
  156. },
  157. ); err != nil {
  158. return err
  159. }
  160. log.Trace("Finished: SyncRepositoryHooks")
  161. return nil
  162. }