123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- package git
- import (
- "errors"
- "io/ioutil"
- "os"
- "path"
- "strings"
- )
- var (
-
- HookDir = "hooks"
- HookSampleDir = HookDir
-
- HookNames = []string{
- "pre-receive",
- "update",
- "post-receive",
- }
- )
- var (
- ErrNotValidHook = errors.New("not a valid Git hook")
- )
- func IsValidHookName(name string) bool {
- for _, hn := range HookNames {
- if hn == name {
- return true
- }
- }
- return false
- }
- type Hook struct {
- name string
- IsActive bool
- Content string
- Sample string
- path string
- }
- func GetHook(repoPath, name string) (*Hook, error) {
- if !IsValidHookName(name) {
- return nil, ErrNotValidHook
- }
- h := &Hook{
- name: name,
- path: path.Join(repoPath, HookDir, name),
- }
- if isFile(h.path) {
- data, err := ioutil.ReadFile(h.path)
- if err != nil {
- return nil, err
- }
- h.IsActive = true
- h.Content = string(data)
- return h, nil
- }
-
- samplePath := path.Join(repoPath, HookSampleDir, h.name) + ".sample"
- if isFile(samplePath) {
- data, err := ioutil.ReadFile(samplePath)
- if err != nil {
- return nil, err
- }
- h.Sample = string(data)
- }
- return h, nil
- }
- func (h *Hook) Name() string {
- return h.name
- }
- func (h *Hook) Update() error {
- if len(strings.TrimSpace(h.Content)) == 0 {
- if isExist(h.path) {
- return os.Remove(h.path)
- }
- return nil
- }
- os.MkdirAll(path.Dir(h.path), os.ModePerm)
- return ioutil.WriteFile(h.path, []byte(strings.Replace(h.Content, "\r", "", -1)), os.ModePerm)
- }
- func ListHooks(repoPath string) (_ []*Hook, err error) {
- if !isDir(path.Join(repoPath, "hooks")) {
- return nil, errors.New("hooks path does not exist")
- }
- hooks := make([]*Hook, len(HookNames))
- for i, name := range HookNames {
- hooks[i], err = GetHook(repoPath, name)
- if err != nil {
- return nil, err
- }
- }
- return hooks, nil
- }
|