forked from bigwhite/reviewdog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gitlab_push_commits_diff.go
83 lines (72 loc) · 2.47 KB
/
gitlab_push_commits_diff.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package gitlab
import (
"context"
"fmt"
"log"
"os/exec"
"github.com/xanzy/go-gitlab"
"github.com/mistwind/reviewdog"
"github.com/mistwind/reviewdog/service/serviceutil"
)
var _ reviewdog.DiffService = &PushCommitsDiff{}
// PushCommitsDiff is a diff service for GitLab Push Commits.
type PushCommitsDiff struct {
cli *gitlab.Client
sha string
beforeSHA string
projects string
// wd is working directory relative to root of repository.
wd string
}
// NewGitLabPushCommitsDiff returns a new PushCommitsDiff service.
// itLabPushCommitsDiff service needs git command in $PATH.
func NewGitLabPushCommitsDiff(cli *gitlab.Client, owner, repo string, sha string, beforeSHA string) (*PushCommitsDiff, error) {
workDir, err := serviceutil.GitRelWorkdir()
if err != nil {
return nil, fmt.Errorf("PushCommitsDiff needs 'git' command: %w", err)
}
return &PushCommitsDiff{
cli: cli,
sha: sha,
beforeSHA: beforeSHA,
projects: owner + "/" + repo,
wd: workDir,
}, nil
}
// NewGitLabPushCommitsDiffWithProjectID returns a new PushCommitsDiff service.
// itLabPushCommitsDiff service needs git command in $PATH.
func NewGitLabPushCommitsDiffWithProjectID(cli *gitlab.Client, projectID string, sha string, beforeSHA string) (*PushCommitsDiff, error) {
workDir, err := serviceutil.GitRelWorkdir()
if err != nil {
return nil, fmt.Errorf("PushCommitsDiff needs 'git' command: %w", err)
}
return &PushCommitsDiff{
cli: cli,
sha: sha,
beforeSHA: beforeSHA,
projects: projectID,
wd: workDir,
}, nil
}
// Diff returns a diff of PushCommits. It runs `git diff` locally instead of
// diff_url of GitLab Merge Request because diff of diff_url is not suited for
// comment API in a sense that diff of diff_url is equivalent to
// `git diff --no-renames`, we want diff which is equivalent to
// `git diff --find-renames`.
// git diff old new
func (g *PushCommitsDiff) Diff(ctx context.Context) ([]byte, error) {
b, err := g.gitDiff(ctx, g.beforeSHA, g.sha)
log.Printf("reviewdog: [gitlab-push-commit-report] PushCommitsDiff: %s\n", string(b))
return b, err
}
func (g *PushCommitsDiff) gitDiff(_ context.Context, baseSha, targetSha string) ([]byte, error) {
bytes, err := exec.Command("git", "diff", "--find-renames", baseSha, targetSha).Output()
if err != nil {
return nil, fmt.Errorf("failed to run git diff: %w", err)
}
return bytes, nil
}
// Strip returns 1 as a strip of git diff.
func (g *PushCommitsDiff) Strip() int {
return 1
}