/
hook_file.go
53 lines (47 loc) · 1.35 KB
/
hook_file.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package hook
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"github.com/go-git/go-git/v5/plumbing/object"
"gopkg.in/yaml.v3"
)
var (
// ConfigFilename Git hooks configuration filename to be parsed
ConfigFilename = ".githooks.yml"
// ErrFileNotFound File not found error
ErrFileNotFound = errors.New("configuration file .githooks.(yaml|yml) not found")
)
// LoadGitHooks load and return Configuration struct
func LoadGitHooks(filePath string) (*GitHooks, error) {
content, err := os.ReadFile(filepath.Clean(filePath))
if err != nil {
return nil, ErrFileNotFound
}
return LoadGitHooksFromRaw(string(content))
}
// ExtractConfigFile extract .githooks.yml file from Git bare repository
func ExtractConfigFile(ctx context.Context, commit *object.Commit) (gitHooks *GitHooks, err error) {
file, err := commit.File(ConfigFilename)
if err != nil {
return nil, ErrFileNotFound
}
content, err := file.Contents()
if err != nil {
return nil, err
}
return LoadGitHooksFromRaw(content)
}
// LoadGitHooksFromRaw load config file from raw data
func LoadGitHooksFromRaw(fileContent string) (*GitHooks, error) {
var hooks = &GitHooks{}
if err := yaml.Unmarshal([]byte(fileContent), hooks); err != nil {
return nil, fmt.Errorf("unable to decode into struct, %v", err)
}
if err := hooks.Validate(); err != nil {
return nil, err
}
return hooks, nil
}