forked from adamm/autogits
Compare commits
34 Commits
generate
...
submodulem
Author | SHA256 | Date | |
---|---|---|---|
b6bb7f9968 | |||
e2abbfcc63 | |||
f6cb35acca | |||
f4386c3d12 | |||
f8594af8c6 | |||
b8ef69a5a7 | |||
c980b9f84d | |||
4651440457 | |||
7d58882ed8 | |||
e90ba95869 | |||
1015e79026 | |||
833cb8b430 | |||
a882ae283f | |||
305e90b254 | |||
c80683182d | |||
51cd4da97b | |||
cf71fe49d6 | |||
85a9a81804 | |||
72b979b587 | |||
bb4350519b | |||
62658e23a7 | |||
6a1f92af12 | |||
24ed21ce7d | |||
46a187a60e | |||
e0c7ea44ea | |||
f013180c4b | |||
b96b784b38 | |||
6864e95404 | |||
0ba4652595 | |||
8d0047649a | |||
2f180c264e | |||
7b87c4fd73 | |||
7d2233dd4a | |||
c30ae5750b |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1,3 +1,4 @@
|
|||||||
|
mock
|
||||||
node_modules
|
node_modules
|
||||||
*.obscpio
|
*.obscpio
|
||||||
autogits-tmp.tar.zst
|
autogits-tmp.tar.zst
|
||||||
|
@@ -30,6 +30,11 @@ BuildRequires: go
|
|||||||
Git Workflow tooling and utilities enabling automated handing of OBS projects
|
Git Workflow tooling and utilities enabling automated handing of OBS projects
|
||||||
as git repositories
|
as git repositories
|
||||||
|
|
||||||
|
%package -n hujson
|
||||||
|
Summary: HuJSON to JSON parser
|
||||||
|
|
||||||
|
%description -n hujson
|
||||||
|
HuJSON to JSON parser, using stdin -> stdout pipe
|
||||||
|
|
||||||
%package -n gitea-events-rabbitmq-publisher
|
%package -n gitea-events-rabbitmq-publisher
|
||||||
Summary: Publishes Gitea webhook data via RabbitMQ
|
Summary: Publishes Gitea webhook data via RabbitMQ
|
||||||
@@ -88,6 +93,9 @@ Keeps ProjectGit PR in-sync with a PackageGit PR
|
|||||||
cp -r /home/abuild/rpmbuild/SOURCES/* ./
|
cp -r /home/abuild/rpmbuild/SOURCES/* ./
|
||||||
|
|
||||||
%build
|
%build
|
||||||
|
go build \
|
||||||
|
-C hujson \
|
||||||
|
-buildmode=pie
|
||||||
go build \
|
go build \
|
||||||
-C gitea-events-rabbitmq-publisher \
|
-C gitea-events-rabbitmq-publisher \
|
||||||
-buildmode=pie
|
-buildmode=pie
|
||||||
@@ -112,9 +120,11 @@ install -D -m0755 gitea-events-rabbitmq-publisher/gitea-events-rabbitmq-publishe
|
|||||||
install -D -m0644 systemd/gitea-events-rabbitmq-publisher.service %{buildroot}%{_unitdir}/gitea-events-rabbitmq-publisher.service
|
install -D -m0644 systemd/gitea-events-rabbitmq-publisher.service %{buildroot}%{_unitdir}/gitea-events-rabbitmq-publisher.service
|
||||||
install -D -m0755 group-review/group-review %{buildroot}%{_bindir}/group-review
|
install -D -m0755 group-review/group-review %{buildroot}%{_bindir}/group-review
|
||||||
install -D -m0755 obs-staging-bot/obs-staging-bot %{buildroot}%{_bindir}/obs-staging-bot
|
install -D -m0755 obs-staging-bot/obs-staging-bot %{buildroot}%{_bindir}/obs-staging-bot
|
||||||
|
install -D -m0644 systemd/obs-staging-bot.service %{buildroot}%{_unitdir}/obs-staging-bot.service
|
||||||
install -D -m0755 obs-status-service/obs-status-service %{buildroot}%{_bindir}/obs-status-service
|
install -D -m0755 obs-status-service/obs-status-service %{buildroot}%{_bindir}/obs-status-service
|
||||||
install -D -m0755 workflow-direct/workflow-direct %{buildroot}%{_bindir}/workflow-direct
|
install -D -m0755 workflow-direct/workflow-direct %{buildroot}%{_bindir}/workflow-direct
|
||||||
install -D -m0755 workflow-pr/workflow-pr %{buildroot}%{_bindir}/workflow-pr
|
install -D -m0755 workflow-pr/workflow-pr %{buildroot}%{_bindir}/workflow-pr
|
||||||
|
install -D -m0755 hujson/hujson %{buildroot}%{_bindir}/hujson
|
||||||
|
|
||||||
%pre -n gitea-events-rabbitmq-publisher
|
%pre -n gitea-events-rabbitmq-publisher
|
||||||
%service_add_pre gitea-events-rabbitmq-publisher.service
|
%service_add_pre gitea-events-rabbitmq-publisher.service
|
||||||
@@ -128,6 +138,18 @@ install -D -m0755 workflow-pr/workflow-pr
|
|||||||
%postun -n gitea-events-rabbitmq-publisher
|
%postun -n gitea-events-rabbitmq-publisher
|
||||||
%service_del_postun gitea-events-rabbitmq-publisher.service
|
%service_del_postun gitea-events-rabbitmq-publisher.service
|
||||||
|
|
||||||
|
%pre -n obs-staging-bot
|
||||||
|
%service_add_pre obs-staging-bot.service
|
||||||
|
|
||||||
|
%post -n obs-staging-bot
|
||||||
|
%service_add_post obs-staging-bot.service
|
||||||
|
|
||||||
|
%preun -n obs-staging-bot
|
||||||
|
%service_del_preun obs-staging-bot.service
|
||||||
|
|
||||||
|
%postun -n obs-staging-bot
|
||||||
|
%service_del_postun obs-staging-bot.service
|
||||||
|
|
||||||
%files -n gitea-events-rabbitmq-publisher
|
%files -n gitea-events-rabbitmq-publisher
|
||||||
%license COPYING
|
%license COPYING
|
||||||
%doc gitea-events-rabbitmq-publisher/README.md
|
%doc gitea-events-rabbitmq-publisher/README.md
|
||||||
@@ -144,10 +166,15 @@ install -D -m0755 workflow-pr/workflow-pr
|
|||||||
%doc group-review/README.md
|
%doc group-review/README.md
|
||||||
%{_bindir}/group-review
|
%{_bindir}/group-review
|
||||||
|
|
||||||
|
%files -n hujson
|
||||||
|
%license COPYING
|
||||||
|
%{_bindir}/hujson
|
||||||
|
|
||||||
%files -n obs-staging-bot
|
%files -n obs-staging-bot
|
||||||
%license COPYING
|
%license COPYING
|
||||||
%doc obs-staging-bot/README.md
|
%doc obs-staging-bot/README.md
|
||||||
%{_bindir}/obs-staging-bot
|
%{_bindir}/obs-staging-bot
|
||||||
|
%{_unitdir}/obs-staging-bot.service
|
||||||
|
|
||||||
%files -n obs-status-service
|
%files -n obs-status-service
|
||||||
%license COPYING
|
%license COPYING
|
||||||
|
@@ -39,7 +39,7 @@ func parsePrLine(line string) (BasicPR, error) {
|
|||||||
repo := strings.SplitN(org[1], "!", 2)
|
repo := strings.SplitN(org[1], "!", 2)
|
||||||
ret.Repo = repo[0]
|
ret.Repo = repo[0]
|
||||||
if len(repo) != 2 {
|
if len(repo) != 2 {
|
||||||
repo := strings.SplitN(org[1], "#", 2)
|
repo = strings.SplitN(org[1], "#", 2)
|
||||||
ret.Repo = repo[0]
|
ret.Repo = repo[0]
|
||||||
}
|
}
|
||||||
if len(repo) != 2 {
|
if len(repo) != 2 {
|
||||||
|
@@ -34,7 +34,7 @@ func TestAssociatedPRScanner(t *testing.T) {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
"Multiple PRs",
|
"Multiple PRs",
|
||||||
"Some header of the issue\n\nFollowed by some description\nPR: test/foo#4\n\nPR: test/goo#5\n",
|
"Some header of the issue\n\nFollowed by some description\nPR: test/foo#4\n\nPR: test/goo!5\n",
|
||||||
[]common.BasicPR{
|
[]common.BasicPR{
|
||||||
{Org: "test", Repo: "foo", Num: 4},
|
{Org: "test", Repo: "foo", Num: 4},
|
||||||
{Org: "test", Repo: "goo", Num: 5},
|
{Org: "test", Repo: "goo", Num: 5},
|
||||||
@@ -107,7 +107,7 @@ func TestAppendingPRsToDescription(t *testing.T) {
|
|||||||
[]common.BasicPR{
|
[]common.BasicPR{
|
||||||
{Org: "a", Repo: "b", Num: 100},
|
{Org: "a", Repo: "b", Num: 100},
|
||||||
},
|
},
|
||||||
"something\n\nPR: a/b#100",
|
"something\n\nPR: a/b!100",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"Append multiple PR to end of description",
|
"Append multiple PR to end of description",
|
||||||
@@ -119,7 +119,7 @@ func TestAppendingPRsToDescription(t *testing.T) {
|
|||||||
{Org: "b", Repo: "b", Num: 100},
|
{Org: "b", Repo: "b", Num: 100},
|
||||||
{Org: "c", Repo: "b", Num: 100},
|
{Org: "c", Repo: "b", Num: 100},
|
||||||
},
|
},
|
||||||
"something\n\nPR: a1/b#100\nPR: a1/c#100\nPR: a1/c#101\nPR: b/b#100\nPR: c/b#100",
|
"something\n\nPR: a1/b!100\nPR: a1/c!100\nPR: a1/c!101\nPR: b/b!100\nPR: c/b!100",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"Append multiple sorted PR to end of description and remove dups",
|
"Append multiple sorted PR to end of description and remove dups",
|
||||||
@@ -133,7 +133,7 @@ func TestAppendingPRsToDescription(t *testing.T) {
|
|||||||
{Org: "a1", Repo: "c", Num: 101},
|
{Org: "a1", Repo: "c", Num: 101},
|
||||||
{Org: "a1", Repo: "b", Num: 100},
|
{Org: "a1", Repo: "b", Num: 100},
|
||||||
},
|
},
|
||||||
"something\n\nPR: a1/b#100\nPR: a1/c#100\nPR: a1/c#101\nPR: b/b#100\nPR: c/b#100",
|
"something\n\nPR: a1/b!100\nPR: a1/c!100\nPR: a1/c!101\nPR: b/b!100\nPR: c/b!100",
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -62,6 +62,7 @@ type AutogitConfig struct {
|
|||||||
Committers []string // group in addition to Reviewers and Maintainers that can order the bot around, mostly as helper for factory-maintainers
|
Committers []string // group in addition to Reviewers and Maintainers that can order the bot around, mostly as helper for factory-maintainers
|
||||||
Subdirs []string // list of directories to sort submodules into. Needed b/c _manifest cannot list non-existent directories
|
Subdirs []string // list of directories to sort submodules into. Needed b/c _manifest cannot list non-existent directories
|
||||||
|
|
||||||
|
NoProjectGitPR bool // do not automatically create project git PRs, just assign reviewers and assume somethign else creates the ProjectGit PR
|
||||||
ManualMergeOnly bool // only merge with "Merge OK" comment by Project Maintainers and/or Package Maintainers and/or reviewers
|
ManualMergeOnly bool // only merge with "Merge OK" comment by Project Maintainers and/or Package Maintainers and/or reviewers
|
||||||
ManualMergeProject bool // require merge of ProjectGit PRs with "Merge OK" by ProjectMaintainers and/or reviewers
|
ManualMergeProject bool // require merge of ProjectGit PRs with "Merge OK" by ProjectMaintainers and/or reviewers
|
||||||
}
|
}
|
||||||
|
@@ -109,6 +109,7 @@ func TestConfigWorkflowParser(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// FIXME: should test ReadWorkflowConfig as it will always set prjgit completely
|
||||||
func TestProjectGitParser(t *testing.T) {
|
func TestProjectGitParser(t *testing.T) {
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name string
|
name string
|
||||||
@@ -119,7 +120,7 @@ func TestProjectGitParser(t *testing.T) {
|
|||||||
}{
|
}{
|
||||||
{
|
{
|
||||||
name: "repo only",
|
name: "repo only",
|
||||||
prjgit: "repo.git",
|
prjgit: "repo.git#master",
|
||||||
org: "org",
|
org: "org",
|
||||||
branch: "br",
|
branch: "br",
|
||||||
res: [3]string{"org", "repo.git", "master"},
|
res: [3]string{"org", "repo.git", "master"},
|
||||||
@@ -127,12 +128,13 @@ func TestProjectGitParser(t *testing.T) {
|
|||||||
{
|
{
|
||||||
name: "default",
|
name: "default",
|
||||||
org: "org",
|
org: "org",
|
||||||
|
prjgit: "org/_ObsPrj#master",
|
||||||
res: [3]string{"org", common.DefaultGitPrj, "master"},
|
res: [3]string{"org", common.DefaultGitPrj, "master"},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "repo with branch",
|
name: "repo with branch",
|
||||||
org: "org2",
|
org: "org2",
|
||||||
prjgit: "repo.git#somebranch",
|
prjgit: "org2/repo.git#somebranch",
|
||||||
res: [3]string{"org2", "repo.git", "somebranch"},
|
res: [3]string{"org2", "repo.git", "somebranch"},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -149,25 +151,25 @@ func TestProjectGitParser(t *testing.T) {
|
|||||||
{
|
{
|
||||||
name: "repo org and empty branch",
|
name: "repo org and empty branch",
|
||||||
org: "org3",
|
org: "org3",
|
||||||
prjgit: "oorg/foo.bar#",
|
prjgit: "oorg/foo.bar#master",
|
||||||
res: [3]string{"oorg", "foo.bar", "master"},
|
res: [3]string{"oorg", "foo.bar", "master"},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "only branch defined",
|
name: "only branch defined",
|
||||||
org: "org3",
|
org: "org3",
|
||||||
prjgit: "#mybranch",
|
prjgit: "org3/_ObsPrj#mybranch",
|
||||||
res: [3]string{"org3", "_ObsPrj", "mybranch"},
|
res: [3]string{"org3", "_ObsPrj", "mybranch"},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "only org and branch defined",
|
name: "only org and branch defined",
|
||||||
org: "org3",
|
org: "org3",
|
||||||
prjgit: "org1/#mybranch",
|
prjgit: "org1/_ObsPrj#mybranch",
|
||||||
res: [3]string{"org1", "_ObsPrj", "mybranch"},
|
res: [3]string{"org1", "_ObsPrj", "mybranch"},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "empty org and repo",
|
name: "empty org and repo",
|
||||||
org: "org3",
|
org: "org3",
|
||||||
prjgit: "/repo#",
|
prjgit: "org3/repo#master",
|
||||||
res: [3]string{"org3", "repo", "master"},
|
res: [3]string{"org3", "repo", "master"},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
296
common/git_parser.go
Normal file
296
common/git_parser.go
Normal file
@@ -0,0 +1,296 @@
|
|||||||
|
package common
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
GitStatus_Untracked = 0
|
||||||
|
GitStatus_Modified = 1
|
||||||
|
GitStatus_Ignored = 2
|
||||||
|
GitStatus_Unmerged = 3 // States[0..3] -- Stage1, Stage2, Stage3 of merge objects
|
||||||
|
GitStatus_Renamed = 4 // orig name in States[0]
|
||||||
|
)
|
||||||
|
|
||||||
|
type GitStatusData struct {
|
||||||
|
Path string
|
||||||
|
Status int
|
||||||
|
States [3]string
|
||||||
|
|
||||||
|
/*
|
||||||
|
<sub> A 4 character field describing the submodule state.
|
||||||
|
"N..." when the entry is not a submodule.
|
||||||
|
"S<c><m><u>" when the entry is a submodule.
|
||||||
|
<c> is "C" if the commit changed; otherwise ".".
|
||||||
|
<m> is "M" if it has tracked changes; otherwise ".".
|
||||||
|
<u> is "U" if there are untracked changes; otherwise ".".
|
||||||
|
*/
|
||||||
|
SubmoduleChanges string
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseGit_HexString(data io.ByteReader) (string, error) {
|
||||||
|
str := make([]byte, 0, 32)
|
||||||
|
for {
|
||||||
|
c, err := data.ReadByte()
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
switch {
|
||||||
|
case c == 0 || c == ' ':
|
||||||
|
return string(str), nil
|
||||||
|
case c >= 'a' && c <= 'f':
|
||||||
|
case c >= 'A' && c <= 'F':
|
||||||
|
case c >= '0' && c <= '9':
|
||||||
|
default:
|
||||||
|
return "", errors.New("Invalid character in hex string:" + string(c))
|
||||||
|
}
|
||||||
|
str = append(str, c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
func parseGit_String(data io.ByteReader) (string, error) {
|
||||||
|
str := make([]byte, 0, 100)
|
||||||
|
for {
|
||||||
|
c, err := data.ReadByte()
|
||||||
|
if err != nil {
|
||||||
|
return "", errors.New("Unexpected EOF. Expected NUL string term")
|
||||||
|
}
|
||||||
|
if c == 0 || c == ' ' {
|
||||||
|
return string(str), nil
|
||||||
|
}
|
||||||
|
str = append(str, c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseGit_StringWithSpace(data io.ByteReader) (string, error) {
|
||||||
|
str := make([]byte, 0, 100)
|
||||||
|
for {
|
||||||
|
c, err := data.ReadByte()
|
||||||
|
if err != nil {
|
||||||
|
return "", errors.New("Unexpected EOF. Expected NUL string term")
|
||||||
|
}
|
||||||
|
if c == 0 {
|
||||||
|
return string(str), nil
|
||||||
|
}
|
||||||
|
str = append(str, c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func skipGitStatusEntry(data io.ByteReader, skipSpaceLen int) error {
|
||||||
|
for skipSpaceLen > 0 {
|
||||||
|
c, err := data.ReadByte()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if c == ' ' {
|
||||||
|
skipSpaceLen--
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseSingleStatusEntry(data io.ByteReader) (*GitStatusData, error) {
|
||||||
|
ret := GitStatusData{}
|
||||||
|
statusType, err := data.ReadByte()
|
||||||
|
if err != nil {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
switch statusType {
|
||||||
|
case '1':
|
||||||
|
var err error
|
||||||
|
if err = skipGitStatusEntry(data, 8); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
ret.Status = GitStatus_Modified
|
||||||
|
ret.Path, err = parseGit_StringWithSpace(data)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
case '2':
|
||||||
|
var err error
|
||||||
|
if err = skipGitStatusEntry(data, 9); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
ret.Status = GitStatus_Renamed
|
||||||
|
ret.Path, err = parseGit_StringWithSpace(data)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
ret.States[0], err = parseGit_StringWithSpace(data)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
case '?':
|
||||||
|
var err error
|
||||||
|
if err = skipGitStatusEntry(data, 1); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
ret.Status = GitStatus_Untracked
|
||||||
|
ret.Path, err = parseGit_StringWithSpace(data)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
case '!':
|
||||||
|
var err error
|
||||||
|
if err = skipGitStatusEntry(data, 1); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
ret.Status = GitStatus_Ignored
|
||||||
|
ret.Path, err = parseGit_StringWithSpace(data)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
case 'u':
|
||||||
|
var err error
|
||||||
|
if err = skipGitStatusEntry(data, 2); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if ret.SubmoduleChanges, err = parseGit_String(data); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err = skipGitStatusEntry(data, 4); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if ret.States[0], err = parseGit_HexString(data); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if ret.States[1], err = parseGit_HexString(data); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if ret.States[2], err = parseGit_HexString(data); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
ret.Status = GitStatus_Unmerged
|
||||||
|
ret.Path, err = parseGit_StringWithSpace(data)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return nil, errors.New("Invalid status type" + string(statusType))
|
||||||
|
}
|
||||||
|
return &ret, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseGitStatusData(data io.ByteReader) (Data, error) {
|
||||||
|
ret := make([]GitStatusData, 0, 10)
|
||||||
|
for {
|
||||||
|
data, err := parseSingleStatusEntry(data)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
} else if data == nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
ret = append(ret, *data)
|
||||||
|
}
|
||||||
|
return ret, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
type Data interface{}
|
||||||
|
|
||||||
|
type CommitStatus int
|
||||||
|
|
||||||
|
const (
|
||||||
|
Add CommitStatus = iota
|
||||||
|
Rm
|
||||||
|
Copy
|
||||||
|
Modify
|
||||||
|
Rename
|
||||||
|
TypeChange
|
||||||
|
Unmerged
|
||||||
|
Unknown
|
||||||
|
)
|
||||||
|
|
||||||
|
type GitDiffRawData struct {
|
||||||
|
SrcMode, DstMode string
|
||||||
|
SrcCommit, DstCommit string
|
||||||
|
Status CommitStatus
|
||||||
|
Src, Dst string
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseGit_DiffIndexStatus(data io.ByteReader, d *GitDiffRawData) error {
|
||||||
|
b, err := data.ReadByte()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
switch b {
|
||||||
|
case 'A':
|
||||||
|
d.Status = Add
|
||||||
|
case 'C':
|
||||||
|
d.Status = Copy
|
||||||
|
case 'D':
|
||||||
|
d.Status = Rm
|
||||||
|
case 'M':
|
||||||
|
d.Status = Modify
|
||||||
|
case 'R':
|
||||||
|
d.Status = Rename
|
||||||
|
case 'T':
|
||||||
|
d.Status = TypeChange
|
||||||
|
case 'U':
|
||||||
|
d.Status = Unmerged
|
||||||
|
case 'X':
|
||||||
|
return fmt.Errorf("Unexpected unknown change type. This is a git bug")
|
||||||
|
}
|
||||||
|
_, err = parseGit_StringWithSpace(data)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseSingleGitDiffIndexRawData(data io.ByteReader) (*GitDiffRawData, error) {
|
||||||
|
var ret GitDiffRawData
|
||||||
|
|
||||||
|
b, err := data.ReadByte()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if b != ':' {
|
||||||
|
return nil, fmt.Errorf("Expected ':' but got '%s'", string(b))
|
||||||
|
}
|
||||||
|
|
||||||
|
if ret.SrcMode, err = parseGit_String(data); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if ret.DstMode, err = parseGit_String(data); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if ret.Src, err = parseGit_String(data); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if ret.Dst, err = parseGit_String(data); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err = parseGit_DiffIndexStatus(data, &ret); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
ret.Dst = ret.Src
|
||||||
|
switch ret.Status {
|
||||||
|
case Copy, Rename:
|
||||||
|
if ret.Src, err = parseGit_StringWithSpace(data); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return &ret, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseGitDiffIndexRawData(data io.ByteReader) (Data, error) {
|
||||||
|
ret := make([]GitDiffRawData, 0, 10)
|
||||||
|
for {
|
||||||
|
data, err := parseSingleGitDiffIndexRawData(data)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
} else if data == nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
ret = append(ret, *data)
|
||||||
|
}
|
||||||
|
return ret, nil
|
||||||
|
}
|
@@ -19,9 +19,7 @@ package common
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
|
||||||
"bytes"
|
"bytes"
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"os"
|
"os"
|
||||||
@@ -40,6 +38,10 @@ type GitSubmoduleLister interface {
|
|||||||
GitSubmoduleCommitId(cwd, packageName, commitId string) (subCommitId string, valid bool)
|
GitSubmoduleCommitId(cwd, packageName, commitId string) (subCommitId string, valid bool)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type GitSubmoduleFileConflictResolver interface {
|
||||||
|
GitResolveSubmoduleFileConflict(cwd string) error
|
||||||
|
}
|
||||||
|
|
||||||
type GitStatusLister interface {
|
type GitStatusLister interface {
|
||||||
GitStatus(cwd string) ([]GitStatusData, error)
|
GitStatus(cwd string) ([]GitStatusData, error)
|
||||||
}
|
}
|
||||||
@@ -67,8 +69,10 @@ type Git interface {
|
|||||||
GitExecOrPanic(cwd string, params ...string)
|
GitExecOrPanic(cwd string, params ...string)
|
||||||
GitExec(cwd string, params ...string) error
|
GitExec(cwd string, params ...string) error
|
||||||
GitExecWithOutput(cwd string, params ...string) (string, error)
|
GitExecWithOutput(cwd string, params ...string) (string, error)
|
||||||
|
GitExecQuietOrPanic(cwd string, params ...string)
|
||||||
|
|
||||||
GitDiffLister
|
GitDiffLister
|
||||||
|
GitSubmoduleFileConflictResolver
|
||||||
}
|
}
|
||||||
|
|
||||||
type GitHandlerImpl struct {
|
type GitHandlerImpl struct {
|
||||||
@@ -77,6 +81,7 @@ type GitHandlerImpl struct {
|
|||||||
GitEmail string
|
GitEmail string
|
||||||
|
|
||||||
lock *sync.Mutex
|
lock *sync.Mutex
|
||||||
|
quiet bool
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *GitHandlerImpl) GetPath() string {
|
func (s *GitHandlerImpl) GetPath() string {
|
||||||
@@ -211,7 +216,7 @@ func (e *GitHandlerImpl) GitClone(repo, branch, remoteUrl string) (string, error
|
|||||||
return "", fmt.Errorf("Cannot parse remote URL: %w", err)
|
return "", fmt.Errorf("Cannot parse remote URL: %w", err)
|
||||||
}
|
}
|
||||||
remoteBranch := "HEAD"
|
remoteBranch := "HEAD"
|
||||||
if len(branch) == 0 && remoteUrlComp != nil {
|
if len(branch) == 0 && remoteUrlComp != nil && remoteUrlComp.Commit != "HEAD" {
|
||||||
branch = remoteUrlComp.Commit
|
branch = remoteUrlComp.Commit
|
||||||
remoteBranch = branch
|
remoteBranch = branch
|
||||||
} else if len(branch) > 0 {
|
} else if len(branch) > 0 {
|
||||||
@@ -240,12 +245,12 @@ func (e *GitHandlerImpl) GitClone(repo, branch, remoteUrl string) (string, error
|
|||||||
|
|
||||||
// check if we have submodule to deinit
|
// check if we have submodule to deinit
|
||||||
if list, _ := e.GitSubmoduleList(repo, "HEAD"); len(list) > 0 {
|
if list, _ := e.GitSubmoduleList(repo, "HEAD"); len(list) > 0 {
|
||||||
e.GitExecOrPanic(repo, "submodule", "deinit", "--all", "--force")
|
e.GitExecQuietOrPanic(repo, "submodule", "deinit", "--all", "--force")
|
||||||
}
|
}
|
||||||
|
|
||||||
e.GitExecOrPanic(repo, "fetch", "--prune", remoteName, remoteBranch)
|
e.GitExecOrPanic(repo, "fetch", "--prune", remoteName, remoteBranch)
|
||||||
}
|
}
|
||||||
|
/*
|
||||||
refsBytes, err := os.ReadFile(path.Join(e.GitPath, repo, ".git/refs/remotes", remoteName, "HEAD"))
|
refsBytes, err := os.ReadFile(path.Join(e.GitPath, repo, ".git/refs/remotes", remoteName, "HEAD"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
LogError("Cannot read HEAD of remote", remoteName)
|
LogError("Cannot read HEAD of remote", remoteName)
|
||||||
@@ -264,7 +269,7 @@ func (e *GitHandlerImpl) GitClone(repo, branch, remoteUrl string) (string, error
|
|||||||
LogDebug("remoteRef", remoteRef)
|
LogDebug("remoteRef", remoteRef)
|
||||||
LogDebug("branch", branch)
|
LogDebug("branch", branch)
|
||||||
}
|
}
|
||||||
|
*/
|
||||||
args := []string{"fetch", "--prune", remoteName, branch}
|
args := []string{"fetch", "--prune", remoteName, branch}
|
||||||
if strings.TrimSpace(e.GitExecWithOutputOrPanic(repo, "rev-parse", "--is-shallow-repository")) == "true" {
|
if strings.TrimSpace(e.GitExecWithOutputOrPanic(repo, "rev-parse", "--is-shallow-repository")) == "true" {
|
||||||
args = slices.Insert(args, 1, "--unshallow")
|
args = slices.Insert(args, 1, "--unshallow")
|
||||||
@@ -274,7 +279,7 @@ func (e *GitHandlerImpl) GitClone(repo, branch, remoteUrl string) (string, error
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (e *GitHandlerImpl) GitBranchHead(gitDir, branchName string) (string, error) {
|
func (e *GitHandlerImpl) GitBranchHead(gitDir, branchName string) (string, error) {
|
||||||
id, err := e.GitExecWithOutput(gitDir, "show-ref", "--branches", "--hash", branchName)
|
id, err := e.GitExecWithOutput(gitDir, "show-ref", "--heads", "--hash", branchName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", fmt.Errorf("Can't find default branch: %s", branchName)
|
return "", fmt.Errorf("Can't find default branch: %s", branchName)
|
||||||
}
|
}
|
||||||
@@ -361,7 +366,9 @@ func (e *GitHandlerImpl) GitExecWithOutput(cwd string, params ...string) (string
|
|||||||
|
|
||||||
LogDebug("git execute @", cwd, ":", cmd.Args)
|
LogDebug("git execute @", cwd, ":", cmd.Args)
|
||||||
out, err := cmd.CombinedOutput()
|
out, err := cmd.CombinedOutput()
|
||||||
|
if !e.quiet {
|
||||||
LogDebug(string(out))
|
LogDebug(string(out))
|
||||||
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
LogError("git", cmd.Args, " error:", err)
|
LogError("git", cmd.Args, " error:", err)
|
||||||
return "", fmt.Errorf("error executing: git %#v \n%s\n err: %w", cmd.Args, out, err)
|
return "", fmt.Errorf("error executing: git %#v \n%s\n err: %w", cmd.Args, out, err)
|
||||||
@@ -370,6 +377,13 @@ func (e *GitHandlerImpl) GitExecWithOutput(cwd string, params ...string) (string
|
|||||||
return string(out), nil
|
return string(out), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (e *GitHandlerImpl) GitExecQuietOrPanic(cwd string, params ...string) {
|
||||||
|
e.quiet = true
|
||||||
|
e.GitExecOrPanic(cwd, params...)
|
||||||
|
e.quiet = false
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
type ChanIO struct {
|
type ChanIO struct {
|
||||||
ch chan byte
|
ch chan byte
|
||||||
}
|
}
|
||||||
@@ -912,193 +926,10 @@ func (e *GitHandlerImpl) GitSubmoduleCommitId(cwd, packageName, commitId string)
|
|||||||
return subCommitId, len(subCommitId) > 0
|
return subCommitId, len(subCommitId) > 0
|
||||||
}
|
}
|
||||||
|
|
||||||
const (
|
func (e *GitHandlerImpl) GitExecWithDataParse(cwd string, dataprocessor func(io.ByteReader) (Data, error), gitcmd string, args ...string) (Data, error) {
|
||||||
GitStatus_Untracked = 0
|
LogDebug("getting", gitcmd)
|
||||||
GitStatus_Modified = 1
|
args = append([]string{gitcmd}, args...)
|
||||||
GitStatus_Ignored = 2
|
cmd := exec.Command("/usr/bin/git", args...)
|
||||||
GitStatus_Unmerged = 3 // States[0..3] -- Stage1, Stage2, Stage3 of merge objects
|
|
||||||
GitStatus_Renamed = 4 // orig name in States[0]
|
|
||||||
)
|
|
||||||
|
|
||||||
type GitStatusData struct {
|
|
||||||
Path string
|
|
||||||
Status int
|
|
||||||
States [3]string
|
|
||||||
|
|
||||||
/*
|
|
||||||
<sub> A 4 character field describing the submodule state.
|
|
||||||
"N..." when the entry is not a submodule.
|
|
||||||
"S<c><m><u>" when the entry is a submodule.
|
|
||||||
<c> is "C" if the commit changed; otherwise ".".
|
|
||||||
<m> is "M" if it has tracked changes; otherwise ".".
|
|
||||||
<u> is "U" if there are untracked changes; otherwise ".".
|
|
||||||
*/
|
|
||||||
SubmoduleChanges string
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseGitStatusHexString(data io.ByteReader) (string, error) {
|
|
||||||
str := make([]byte, 0, 32)
|
|
||||||
for {
|
|
||||||
c, err := data.ReadByte()
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
switch {
|
|
||||||
case c == 0 || c == ' ':
|
|
||||||
return string(str), nil
|
|
||||||
case c >= 'a' && c <= 'f':
|
|
||||||
case c >= 'A' && c <= 'F':
|
|
||||||
case c >= '0' && c <= '9':
|
|
||||||
default:
|
|
||||||
return "", errors.New("Invalid character in hex string:" + string(c))
|
|
||||||
}
|
|
||||||
str = append(str, c)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
func parseGitStatusString(data io.ByteReader) (string, error) {
|
|
||||||
str := make([]byte, 0, 100)
|
|
||||||
for {
|
|
||||||
c, err := data.ReadByte()
|
|
||||||
if err != nil {
|
|
||||||
return "", errors.New("Unexpected EOF. Expected NUL string term")
|
|
||||||
}
|
|
||||||
if c == 0 || c == ' ' {
|
|
||||||
return string(str), nil
|
|
||||||
}
|
|
||||||
str = append(str, c)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseGitStatusStringWithSpace(data io.ByteReader) (string, error) {
|
|
||||||
str := make([]byte, 0, 100)
|
|
||||||
for {
|
|
||||||
c, err := data.ReadByte()
|
|
||||||
if err != nil {
|
|
||||||
return "", errors.New("Unexpected EOF. Expected NUL string term")
|
|
||||||
}
|
|
||||||
if c == 0 {
|
|
||||||
return string(str), nil
|
|
||||||
}
|
|
||||||
str = append(str, c)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func skipGitStatusEntry(data io.ByteReader, skipSpaceLen int) error {
|
|
||||||
for skipSpaceLen > 0 {
|
|
||||||
c, err := data.ReadByte()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if c == ' ' {
|
|
||||||
skipSpaceLen--
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseSingleStatusEntry(data io.ByteReader) (*GitStatusData, error) {
|
|
||||||
ret := GitStatusData{}
|
|
||||||
statusType, err := data.ReadByte()
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
switch statusType {
|
|
||||||
case '1':
|
|
||||||
var err error
|
|
||||||
if err = skipGitStatusEntry(data, 8); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
ret.Status = GitStatus_Modified
|
|
||||||
ret.Path, err = parseGitStatusStringWithSpace(data)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
case '2':
|
|
||||||
var err error
|
|
||||||
if err = skipGitStatusEntry(data, 9); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
ret.Status = GitStatus_Renamed
|
|
||||||
ret.Path, err = parseGitStatusStringWithSpace(data)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
ret.States[0], err = parseGitStatusStringWithSpace(data)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
case '?':
|
|
||||||
var err error
|
|
||||||
if err = skipGitStatusEntry(data, 1); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
ret.Status = GitStatus_Untracked
|
|
||||||
ret.Path, err = parseGitStatusStringWithSpace(data)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
case '!':
|
|
||||||
var err error
|
|
||||||
if err = skipGitStatusEntry(data, 1); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
ret.Status = GitStatus_Ignored
|
|
||||||
ret.Path, err = parseGitStatusStringWithSpace(data)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
case 'u':
|
|
||||||
var err error
|
|
||||||
if err = skipGitStatusEntry(data, 2); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if ret.SubmoduleChanges, err = parseGitStatusString(data); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if err = skipGitStatusEntry(data, 4); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if ret.States[0], err = parseGitStatusHexString(data); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if ret.States[1], err = parseGitStatusHexString(data); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
if ret.States[2], err = parseGitStatusHexString(data); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
ret.Status = GitStatus_Unmerged
|
|
||||||
ret.Path, err = parseGitStatusStringWithSpace(data)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
return nil, errors.New("Invalid status type" + string(statusType))
|
|
||||||
}
|
|
||||||
return &ret, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseGitStatusData(data io.ByteReader) ([]GitStatusData, error) {
|
|
||||||
ret := make([]GitStatusData, 0, 10)
|
|
||||||
for {
|
|
||||||
data, err := parseSingleStatusEntry(data)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
} else if data == nil {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
|
|
||||||
ret = append(ret, *data)
|
|
||||||
}
|
|
||||||
return ret, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e *GitHandlerImpl) GitStatus(cwd string) (ret []GitStatusData, err error) {
|
|
||||||
LogDebug("getting git-status()")
|
|
||||||
|
|
||||||
cmd := exec.Command("/usr/bin/git", "status", "--porcelain=2", "-z")
|
|
||||||
cmd.Env = []string{
|
cmd.Env = []string{
|
||||||
"GIT_CEILING_DIRECTORIES=" + e.GitPath,
|
"GIT_CEILING_DIRECTORIES=" + e.GitPath,
|
||||||
"GIT_LFS_SKIP_SMUDGE=1",
|
"GIT_LFS_SKIP_SMUDGE=1",
|
||||||
@@ -1115,7 +946,12 @@ func (e *GitHandlerImpl) GitStatus(cwd string) (ret []GitStatusData, err error)
|
|||||||
LogError("Error running command", cmd.Args, err)
|
LogError("Error running command", cmd.Args, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return parseGitStatusData(bufio.NewReader(bytes.NewReader(out)))
|
return dataprocessor(bytes.NewReader(out))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *GitHandlerImpl) GitStatus(cwd string) (ret []GitStatusData, err error) {
|
||||||
|
data, err := e.GitExecWithDataParse(cwd, parseGitStatusData, "status", "--porcelain=2", "-z")
|
||||||
|
return data.([]GitStatusData), err
|
||||||
}
|
}
|
||||||
|
|
||||||
func (e *GitHandlerImpl) GitDiff(cwd, base, head string) (string, error) {
|
func (e *GitHandlerImpl) GitDiff(cwd, base, head string) (string, error) {
|
||||||
@@ -1140,3 +976,94 @@ func (e *GitHandlerImpl) GitDiff(cwd, base, head string) (string, error) {
|
|||||||
|
|
||||||
return string(out), nil
|
return string(out), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (e *GitHandlerImpl) GitDiffIndex(cwd, commit string) ([]GitDiffRawData, error) {
|
||||||
|
data, err := e.GitExecWithDataParse("diff-index", parseGitDiffIndexRawData, cwd, "diff-index", "-z", "--raw", "--full-index", "--submodule=short", "HEAD")
|
||||||
|
return data.([]GitDiffRawData), err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (git *GitHandlerImpl) GitResolveSubmoduleFileConflict(cwd string) error {
|
||||||
|
status, err := git.GitStatus(cwd)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Status failed: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// we can only resolve conflicts with .gitmodules
|
||||||
|
for _, s := range status {
|
||||||
|
if s.Status == GitStatus_Unmerged {
|
||||||
|
if s.Path != ".gitmodules" {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
submodules, err := git.GitSubmoduleList(cwd, "HEAD")
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Failed to fetch submodules during merge resolution: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// We need to adjust the `submodules` list by the pending changes to the index
|
||||||
|
|
||||||
|
s1, err := git.GitExecWithOutput(cwd, "cat-file", "blob", s.States[0])
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Failed fetching data during .gitmodules merge resoulution: %w", err)
|
||||||
|
}
|
||||||
|
s2, err := git.GitExecWithOutput(cwd, "cat-file", "blob", s.States[1])
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Failed fetching data during .gitmodules merge resoulution: %w", err)
|
||||||
|
}
|
||||||
|
s3, err := git.GitExecWithOutput(cwd, "cat-file", "blob", s.States[2])
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Failed fetching data during .gitmodules merge resoulution: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
subs1, err := ParseSubmodulesFile(strings.NewReader(s1))
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Failed parsing submodule file [%s] in merge: %w", s.States[0], err)
|
||||||
|
}
|
||||||
|
subs2, err := ParseSubmodulesFile(strings.NewReader(s2))
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Failed parsing submodule file [%s] in merge: %w", s.States[0], err)
|
||||||
|
}
|
||||||
|
subs3, err := ParseSubmodulesFile(strings.NewReader(s3))
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Failed parsing submodule file [%s] in merge: %w", s.States[0], err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for r := range submodules {
|
||||||
|
LogError(r)
|
||||||
|
}
|
||||||
|
|
||||||
|
// merge from subs3 (target), subs1 (orig), subs2 (2-nd base that is missing from target base)
|
||||||
|
// this will update submodules
|
||||||
|
mergedSubs := slices.Concat(subs1, subs2, subs3)
|
||||||
|
|
||||||
|
var filteredSubs []Submodule = make([]Submodule, 0, max(len(subs1), len(subs2), len(subs3)))
|
||||||
|
nextSub:
|
||||||
|
for subName := range submodules {
|
||||||
|
|
||||||
|
for i := range mergedSubs {
|
||||||
|
if path.Base(mergedSubs[i].Path) == subName {
|
||||||
|
filteredSubs = append(filteredSubs, mergedSubs[i])
|
||||||
|
continue nextSub
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fmt.Errorf("Cannot find submodule for path: %s", subName)
|
||||||
|
}
|
||||||
|
|
||||||
|
out, err := os.Create(path.Join(git.GetPath(), cwd, ".gitmodules"))
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Can't open .gitmodules for writing: %w", err)
|
||||||
|
}
|
||||||
|
if err = WriteSubmodules(filteredSubs, out); err != nil {
|
||||||
|
return fmt.Errorf("Can't write .gitmodules: %w", err)
|
||||||
|
}
|
||||||
|
if out.Close(); err != nil {
|
||||||
|
return fmt.Errorf("Can't close .gitmodules: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
git.GitExecOrPanic(cwd, "add", ".gitmodules")
|
||||||
|
git.GitExecOrPanic(cwd, "-c", "core.editor=true", "merge", "--continue")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
@@ -24,6 +24,7 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
"path"
|
"path"
|
||||||
|
"runtime/debug"
|
||||||
"slices"
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -93,6 +94,93 @@ func TestGitClone(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestSubmoduleConflictResolution(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
checkout, merge string
|
||||||
|
result string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "adding two submodules",
|
||||||
|
checkout: "base_add_b1",
|
||||||
|
merge: "base_add_b2",
|
||||||
|
result: `[submodule "pkgA"]
|
||||||
|
path = pkgA
|
||||||
|
url = ../pkgA
|
||||||
|
[submodule "pkgB"]
|
||||||
|
path = pkgB
|
||||||
|
url = ../pkgB
|
||||||
|
[submodule "pkgC"]
|
||||||
|
path = pkgC
|
||||||
|
url = ../pkgC
|
||||||
|
[submodule "pkgB1"]
|
||||||
|
path = pkgB1
|
||||||
|
url = ../pkgB1
|
||||||
|
[submodule "pkgB2"]
|
||||||
|
path = pkgB2
|
||||||
|
url = ../pkgB2
|
||||||
|
`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
d, err := os.MkdirTemp(os.TempDir(), "submoduletests")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
cwd, err := os.Getwd()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
cmd := exec.Command(cwd + "/test_repo_setup.sh")
|
||||||
|
cmd.Dir = d
|
||||||
|
_, err = cmd.Output()
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
gh, err := AllocateGitWorkTree(d, "test", "foo@example.com")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
success := true
|
||||||
|
noErrorOrFail := func(t *testing.T, err error) {
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(string(debug.Stack()), err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _, test := range tests {
|
||||||
|
success = t.Run(test.name, func(t *testing.T) {
|
||||||
|
git, err := gh.ReadExistingPath("prjgit")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
noErrorOrFail(t, git.GitExec("", "checkout", "-B", "test", "main"))
|
||||||
|
noErrorOrFail(t, git.GitExec("", "merge", "base_add_b1"))
|
||||||
|
err = git.GitExec("", "merge", "base_add_b2")
|
||||||
|
if err == nil {
|
||||||
|
t.Fatal("expected a conflict")
|
||||||
|
}
|
||||||
|
err = git.GitResolveSubmoduleFileConflict("")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
data, err := os.ReadFile(git.GetPath() + "/.gitmodules")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal("Cannot read .gitmodules.", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if string(data) != test.result {
|
||||||
|
t.Error("Expected", test.result, "but have", string(data))
|
||||||
|
}
|
||||||
|
}) && success
|
||||||
|
}
|
||||||
|
|
||||||
|
if success {
|
||||||
|
os.RemoveAll(d)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func TestGitMsgParsing(t *testing.T) {
|
func TestGitMsgParsing(t *testing.T) {
|
||||||
t.Run("tree message with size 56", func(t *testing.T) {
|
t.Run("tree message with size 56", func(t *testing.T) {
|
||||||
const hdr = "f40888ea4515fe2e8eea617a16f5f50a45f652d894de3ad181d58de3aafb8f98 tree 56\x00"
|
const hdr = "f40888ea4515fe2e8eea617a16f5f50a45f652d894de3ad181d58de3aafb8f98 tree 56\x00"
|
||||||
|
@@ -63,6 +63,10 @@ func SetLoggingLevel(ll LogLevel) {
|
|||||||
logLevel = ll
|
logLevel = ll
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func GetLoggingLevel() LogLevel {
|
||||||
|
return logLevel
|
||||||
|
}
|
||||||
|
|
||||||
func SetLoggingLevelFromString(ll string) error {
|
func SetLoggingLevelFromString(ll string) error {
|
||||||
switch ll {
|
switch ll {
|
||||||
case "info":
|
case "info":
|
||||||
|
@@ -1,120 +0,0 @@
|
|||||||
// Code generated by MockGen. DO NOT EDIT.
|
|
||||||
// Source: config.go
|
|
||||||
//
|
|
||||||
// Generated by this command:
|
|
||||||
//
|
|
||||||
// mockgen -source=config.go -destination=mock/config.go -typed
|
|
||||||
//
|
|
||||||
|
|
||||||
// Package mock_common is a generated GoMock package.
|
|
||||||
package mock_common
|
|
||||||
|
|
||||||
import (
|
|
||||||
reflect "reflect"
|
|
||||||
|
|
||||||
gomock "go.uber.org/mock/gomock"
|
|
||||||
models "src.opensuse.org/autogits/common/gitea-generated/models"
|
|
||||||
)
|
|
||||||
|
|
||||||
// MockGiteaFileContentAndRepoFetcher is a mock of GiteaFileContentAndRepoFetcher interface.
|
|
||||||
type MockGiteaFileContentAndRepoFetcher struct {
|
|
||||||
ctrl *gomock.Controller
|
|
||||||
recorder *MockGiteaFileContentAndRepoFetcherMockRecorder
|
|
||||||
isgomock struct{}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MockGiteaFileContentAndRepoFetcherMockRecorder is the mock recorder for MockGiteaFileContentAndRepoFetcher.
|
|
||||||
type MockGiteaFileContentAndRepoFetcherMockRecorder struct {
|
|
||||||
mock *MockGiteaFileContentAndRepoFetcher
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewMockGiteaFileContentAndRepoFetcher creates a new mock instance.
|
|
||||||
func NewMockGiteaFileContentAndRepoFetcher(ctrl *gomock.Controller) *MockGiteaFileContentAndRepoFetcher {
|
|
||||||
mock := &MockGiteaFileContentAndRepoFetcher{ctrl: ctrl}
|
|
||||||
mock.recorder = &MockGiteaFileContentAndRepoFetcherMockRecorder{mock}
|
|
||||||
return mock
|
|
||||||
}
|
|
||||||
|
|
||||||
// EXPECT returns an object that allows the caller to indicate expected use.
|
|
||||||
func (m *MockGiteaFileContentAndRepoFetcher) EXPECT() *MockGiteaFileContentAndRepoFetcherMockRecorder {
|
|
||||||
return m.recorder
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetRepository mocks base method.
|
|
||||||
func (m *MockGiteaFileContentAndRepoFetcher) GetRepository(org, repo string) (*models.Repository, error) {
|
|
||||||
m.ctrl.T.Helper()
|
|
||||||
ret := m.ctrl.Call(m, "GetRepository", org, repo)
|
|
||||||
ret0, _ := ret[0].(*models.Repository)
|
|
||||||
ret1, _ := ret[1].(error)
|
|
||||||
return ret0, ret1
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetRepository indicates an expected call of GetRepository.
|
|
||||||
func (mr *MockGiteaFileContentAndRepoFetcherMockRecorder) GetRepository(org, repo any) *MockGiteaFileContentAndRepoFetcherGetRepositoryCall {
|
|
||||||
mr.mock.ctrl.T.Helper()
|
|
||||||
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRepository", reflect.TypeOf((*MockGiteaFileContentAndRepoFetcher)(nil).GetRepository), org, repo)
|
|
||||||
return &MockGiteaFileContentAndRepoFetcherGetRepositoryCall{Call: call}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MockGiteaFileContentAndRepoFetcherGetRepositoryCall wrap *gomock.Call
|
|
||||||
type MockGiteaFileContentAndRepoFetcherGetRepositoryCall struct {
|
|
||||||
*gomock.Call
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return rewrite *gomock.Call.Return
|
|
||||||
func (c *MockGiteaFileContentAndRepoFetcherGetRepositoryCall) Return(arg0 *models.Repository, arg1 error) *MockGiteaFileContentAndRepoFetcherGetRepositoryCall {
|
|
||||||
c.Call = c.Call.Return(arg0, arg1)
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// Do rewrite *gomock.Call.Do
|
|
||||||
func (c *MockGiteaFileContentAndRepoFetcherGetRepositoryCall) Do(f func(string, string) (*models.Repository, error)) *MockGiteaFileContentAndRepoFetcherGetRepositoryCall {
|
|
||||||
c.Call = c.Call.Do(f)
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// DoAndReturn rewrite *gomock.Call.DoAndReturn
|
|
||||||
func (c *MockGiteaFileContentAndRepoFetcherGetRepositoryCall) DoAndReturn(f func(string, string) (*models.Repository, error)) *MockGiteaFileContentAndRepoFetcherGetRepositoryCall {
|
|
||||||
c.Call = c.Call.DoAndReturn(f)
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetRepositoryFileContent mocks base method.
|
|
||||||
func (m *MockGiteaFileContentAndRepoFetcher) GetRepositoryFileContent(org, repo, hash, path string) ([]byte, string, error) {
|
|
||||||
m.ctrl.T.Helper()
|
|
||||||
ret := m.ctrl.Call(m, "GetRepositoryFileContent", org, repo, hash, path)
|
|
||||||
ret0, _ := ret[0].([]byte)
|
|
||||||
ret1, _ := ret[1].(string)
|
|
||||||
ret2, _ := ret[2].(error)
|
|
||||||
return ret0, ret1, ret2
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetRepositoryFileContent indicates an expected call of GetRepositoryFileContent.
|
|
||||||
func (mr *MockGiteaFileContentAndRepoFetcherMockRecorder) GetRepositoryFileContent(org, repo, hash, path any) *MockGiteaFileContentAndRepoFetcherGetRepositoryFileContentCall {
|
|
||||||
mr.mock.ctrl.T.Helper()
|
|
||||||
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetRepositoryFileContent", reflect.TypeOf((*MockGiteaFileContentAndRepoFetcher)(nil).GetRepositoryFileContent), org, repo, hash, path)
|
|
||||||
return &MockGiteaFileContentAndRepoFetcherGetRepositoryFileContentCall{Call: call}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MockGiteaFileContentAndRepoFetcherGetRepositoryFileContentCall wrap *gomock.Call
|
|
||||||
type MockGiteaFileContentAndRepoFetcherGetRepositoryFileContentCall struct {
|
|
||||||
*gomock.Call
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return rewrite *gomock.Call.Return
|
|
||||||
func (c *MockGiteaFileContentAndRepoFetcherGetRepositoryFileContentCall) Return(arg0 []byte, arg1 string, arg2 error) *MockGiteaFileContentAndRepoFetcherGetRepositoryFileContentCall {
|
|
||||||
c.Call = c.Call.Return(arg0, arg1, arg2)
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// Do rewrite *gomock.Call.Do
|
|
||||||
func (c *MockGiteaFileContentAndRepoFetcherGetRepositoryFileContentCall) Do(f func(string, string, string, string) ([]byte, string, error)) *MockGiteaFileContentAndRepoFetcherGetRepositoryFileContentCall {
|
|
||||||
c.Call = c.Call.Do(f)
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// DoAndReturn rewrite *gomock.Call.DoAndReturn
|
|
||||||
func (c *MockGiteaFileContentAndRepoFetcherGetRepositoryFileContentCall) DoAndReturn(f func(string, string, string, string) ([]byte, string, error)) *MockGiteaFileContentAndRepoFetcherGetRepositoryFileContentCall {
|
|
||||||
c.Call = c.Call.DoAndReturn(f)
|
|
||||||
return c
|
|
||||||
}
|
|
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,155 +0,0 @@
|
|||||||
// Code generated by MockGen. DO NOT EDIT.
|
|
||||||
// Source: maintainership.go
|
|
||||||
//
|
|
||||||
// Generated by this command:
|
|
||||||
//
|
|
||||||
// mockgen -source=maintainership.go -destination=mock/maintainership.go -typed
|
|
||||||
//
|
|
||||||
|
|
||||||
// Package mock_common is a generated GoMock package.
|
|
||||||
package mock_common
|
|
||||||
|
|
||||||
import (
|
|
||||||
reflect "reflect"
|
|
||||||
|
|
||||||
gomock "go.uber.org/mock/gomock"
|
|
||||||
models "src.opensuse.org/autogits/common/gitea-generated/models"
|
|
||||||
)
|
|
||||||
|
|
||||||
// MockMaintainershipData is a mock of MaintainershipData interface.
|
|
||||||
type MockMaintainershipData struct {
|
|
||||||
ctrl *gomock.Controller
|
|
||||||
recorder *MockMaintainershipDataMockRecorder
|
|
||||||
isgomock struct{}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MockMaintainershipDataMockRecorder is the mock recorder for MockMaintainershipData.
|
|
||||||
type MockMaintainershipDataMockRecorder struct {
|
|
||||||
mock *MockMaintainershipData
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewMockMaintainershipData creates a new mock instance.
|
|
||||||
func NewMockMaintainershipData(ctrl *gomock.Controller) *MockMaintainershipData {
|
|
||||||
mock := &MockMaintainershipData{ctrl: ctrl}
|
|
||||||
mock.recorder = &MockMaintainershipDataMockRecorder{mock}
|
|
||||||
return mock
|
|
||||||
}
|
|
||||||
|
|
||||||
// EXPECT returns an object that allows the caller to indicate expected use.
|
|
||||||
func (m *MockMaintainershipData) EXPECT() *MockMaintainershipDataMockRecorder {
|
|
||||||
return m.recorder
|
|
||||||
}
|
|
||||||
|
|
||||||
// IsApproved mocks base method.
|
|
||||||
func (m *MockMaintainershipData) IsApproved(pkg string, reviews []*models.PullReview, submitter string) bool {
|
|
||||||
m.ctrl.T.Helper()
|
|
||||||
ret := m.ctrl.Call(m, "IsApproved", pkg, reviews, submitter)
|
|
||||||
ret0, _ := ret[0].(bool)
|
|
||||||
return ret0
|
|
||||||
}
|
|
||||||
|
|
||||||
// IsApproved indicates an expected call of IsApproved.
|
|
||||||
func (mr *MockMaintainershipDataMockRecorder) IsApproved(pkg, reviews, submitter any) *MockMaintainershipDataIsApprovedCall {
|
|
||||||
mr.mock.ctrl.T.Helper()
|
|
||||||
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsApproved", reflect.TypeOf((*MockMaintainershipData)(nil).IsApproved), pkg, reviews, submitter)
|
|
||||||
return &MockMaintainershipDataIsApprovedCall{Call: call}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MockMaintainershipDataIsApprovedCall wrap *gomock.Call
|
|
||||||
type MockMaintainershipDataIsApprovedCall struct {
|
|
||||||
*gomock.Call
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return rewrite *gomock.Call.Return
|
|
||||||
func (c *MockMaintainershipDataIsApprovedCall) Return(arg0 bool) *MockMaintainershipDataIsApprovedCall {
|
|
||||||
c.Call = c.Call.Return(arg0)
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// Do rewrite *gomock.Call.Do
|
|
||||||
func (c *MockMaintainershipDataIsApprovedCall) Do(f func(string, []*models.PullReview, string) bool) *MockMaintainershipDataIsApprovedCall {
|
|
||||||
c.Call = c.Call.Do(f)
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// DoAndReturn rewrite *gomock.Call.DoAndReturn
|
|
||||||
func (c *MockMaintainershipDataIsApprovedCall) DoAndReturn(f func(string, []*models.PullReview, string) bool) *MockMaintainershipDataIsApprovedCall {
|
|
||||||
c.Call = c.Call.DoAndReturn(f)
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListPackageMaintainers mocks base method.
|
|
||||||
func (m *MockMaintainershipData) ListPackageMaintainers(pkg string) []string {
|
|
||||||
m.ctrl.T.Helper()
|
|
||||||
ret := m.ctrl.Call(m, "ListPackageMaintainers", pkg)
|
|
||||||
ret0, _ := ret[0].([]string)
|
|
||||||
return ret0
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListPackageMaintainers indicates an expected call of ListPackageMaintainers.
|
|
||||||
func (mr *MockMaintainershipDataMockRecorder) ListPackageMaintainers(pkg any) *MockMaintainershipDataListPackageMaintainersCall {
|
|
||||||
mr.mock.ctrl.T.Helper()
|
|
||||||
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListPackageMaintainers", reflect.TypeOf((*MockMaintainershipData)(nil).ListPackageMaintainers), pkg)
|
|
||||||
return &MockMaintainershipDataListPackageMaintainersCall{Call: call}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MockMaintainershipDataListPackageMaintainersCall wrap *gomock.Call
|
|
||||||
type MockMaintainershipDataListPackageMaintainersCall struct {
|
|
||||||
*gomock.Call
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return rewrite *gomock.Call.Return
|
|
||||||
func (c *MockMaintainershipDataListPackageMaintainersCall) Return(arg0 []string) *MockMaintainershipDataListPackageMaintainersCall {
|
|
||||||
c.Call = c.Call.Return(arg0)
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// Do rewrite *gomock.Call.Do
|
|
||||||
func (c *MockMaintainershipDataListPackageMaintainersCall) Do(f func(string) []string) *MockMaintainershipDataListPackageMaintainersCall {
|
|
||||||
c.Call = c.Call.Do(f)
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// DoAndReturn rewrite *gomock.Call.DoAndReturn
|
|
||||||
func (c *MockMaintainershipDataListPackageMaintainersCall) DoAndReturn(f func(string) []string) *MockMaintainershipDataListPackageMaintainersCall {
|
|
||||||
c.Call = c.Call.DoAndReturn(f)
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListProjectMaintainers mocks base method.
|
|
||||||
func (m *MockMaintainershipData) ListProjectMaintainers() []string {
|
|
||||||
m.ctrl.T.Helper()
|
|
||||||
ret := m.ctrl.Call(m, "ListProjectMaintainers")
|
|
||||||
ret0, _ := ret[0].([]string)
|
|
||||||
return ret0
|
|
||||||
}
|
|
||||||
|
|
||||||
// ListProjectMaintainers indicates an expected call of ListProjectMaintainers.
|
|
||||||
func (mr *MockMaintainershipDataMockRecorder) ListProjectMaintainers() *MockMaintainershipDataListProjectMaintainersCall {
|
|
||||||
mr.mock.ctrl.T.Helper()
|
|
||||||
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListProjectMaintainers", reflect.TypeOf((*MockMaintainershipData)(nil).ListProjectMaintainers))
|
|
||||||
return &MockMaintainershipDataListProjectMaintainersCall{Call: call}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MockMaintainershipDataListProjectMaintainersCall wrap *gomock.Call
|
|
||||||
type MockMaintainershipDataListProjectMaintainersCall struct {
|
|
||||||
*gomock.Call
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return rewrite *gomock.Call.Return
|
|
||||||
func (c *MockMaintainershipDataListProjectMaintainersCall) Return(arg0 []string) *MockMaintainershipDataListProjectMaintainersCall {
|
|
||||||
c.Call = c.Call.Return(arg0)
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// Do rewrite *gomock.Call.Do
|
|
||||||
func (c *MockMaintainershipDataListProjectMaintainersCall) Do(f func() []string) *MockMaintainershipDataListProjectMaintainersCall {
|
|
||||||
c.Call = c.Call.Do(f)
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// DoAndReturn rewrite *gomock.Call.DoAndReturn
|
|
||||||
func (c *MockMaintainershipDataListProjectMaintainersCall) DoAndReturn(f func() []string) *MockMaintainershipDataListProjectMaintainersCall {
|
|
||||||
c.Call = c.Call.DoAndReturn(f)
|
|
||||||
return c
|
|
||||||
}
|
|
@@ -1,85 +0,0 @@
|
|||||||
// Code generated by MockGen. DO NOT EDIT.
|
|
||||||
// Source: obs_utils.go
|
|
||||||
//
|
|
||||||
// Generated by this command:
|
|
||||||
//
|
|
||||||
// mockgen -source=obs_utils.go -destination=mock/obs_utils.go -typed
|
|
||||||
//
|
|
||||||
|
|
||||||
// Package mock_common is a generated GoMock package.
|
|
||||||
package mock_common
|
|
||||||
|
|
||||||
import (
|
|
||||||
reflect "reflect"
|
|
||||||
|
|
||||||
gomock "go.uber.org/mock/gomock"
|
|
||||||
common "src.opensuse.org/autogits/common"
|
|
||||||
)
|
|
||||||
|
|
||||||
// MockObsStatusFetcherWithState is a mock of ObsStatusFetcherWithState interface.
|
|
||||||
type MockObsStatusFetcherWithState struct {
|
|
||||||
ctrl *gomock.Controller
|
|
||||||
recorder *MockObsStatusFetcherWithStateMockRecorder
|
|
||||||
isgomock struct{}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MockObsStatusFetcherWithStateMockRecorder is the mock recorder for MockObsStatusFetcherWithState.
|
|
||||||
type MockObsStatusFetcherWithStateMockRecorder struct {
|
|
||||||
mock *MockObsStatusFetcherWithState
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewMockObsStatusFetcherWithState creates a new mock instance.
|
|
||||||
func NewMockObsStatusFetcherWithState(ctrl *gomock.Controller) *MockObsStatusFetcherWithState {
|
|
||||||
mock := &MockObsStatusFetcherWithState{ctrl: ctrl}
|
|
||||||
mock.recorder = &MockObsStatusFetcherWithStateMockRecorder{mock}
|
|
||||||
return mock
|
|
||||||
}
|
|
||||||
|
|
||||||
// EXPECT returns an object that allows the caller to indicate expected use.
|
|
||||||
func (m *MockObsStatusFetcherWithState) EXPECT() *MockObsStatusFetcherWithStateMockRecorder {
|
|
||||||
return m.recorder
|
|
||||||
}
|
|
||||||
|
|
||||||
// BuildStatusWithState mocks base method.
|
|
||||||
func (m *MockObsStatusFetcherWithState) BuildStatusWithState(project string, opts *common.BuildResultOptions, packages ...string) (*common.BuildResultList, error) {
|
|
||||||
m.ctrl.T.Helper()
|
|
||||||
varargs := []any{project, opts}
|
|
||||||
for _, a := range packages {
|
|
||||||
varargs = append(varargs, a)
|
|
||||||
}
|
|
||||||
ret := m.ctrl.Call(m, "BuildStatusWithState", varargs...)
|
|
||||||
ret0, _ := ret[0].(*common.BuildResultList)
|
|
||||||
ret1, _ := ret[1].(error)
|
|
||||||
return ret0, ret1
|
|
||||||
}
|
|
||||||
|
|
||||||
// BuildStatusWithState indicates an expected call of BuildStatusWithState.
|
|
||||||
func (mr *MockObsStatusFetcherWithStateMockRecorder) BuildStatusWithState(project, opts any, packages ...any) *MockObsStatusFetcherWithStateBuildStatusWithStateCall {
|
|
||||||
mr.mock.ctrl.T.Helper()
|
|
||||||
varargs := append([]any{project, opts}, packages...)
|
|
||||||
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BuildStatusWithState", reflect.TypeOf((*MockObsStatusFetcherWithState)(nil).BuildStatusWithState), varargs...)
|
|
||||||
return &MockObsStatusFetcherWithStateBuildStatusWithStateCall{Call: call}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MockObsStatusFetcherWithStateBuildStatusWithStateCall wrap *gomock.Call
|
|
||||||
type MockObsStatusFetcherWithStateBuildStatusWithStateCall struct {
|
|
||||||
*gomock.Call
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return rewrite *gomock.Call.Return
|
|
||||||
func (c *MockObsStatusFetcherWithStateBuildStatusWithStateCall) Return(arg0 *common.BuildResultList, arg1 error) *MockObsStatusFetcherWithStateBuildStatusWithStateCall {
|
|
||||||
c.Call = c.Call.Return(arg0, arg1)
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// Do rewrite *gomock.Call.Do
|
|
||||||
func (c *MockObsStatusFetcherWithStateBuildStatusWithStateCall) Do(f func(string, *common.BuildResultOptions, ...string) (*common.BuildResultList, error)) *MockObsStatusFetcherWithStateBuildStatusWithStateCall {
|
|
||||||
c.Call = c.Call.Do(f)
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// DoAndReturn rewrite *gomock.Call.DoAndReturn
|
|
||||||
func (c *MockObsStatusFetcherWithStateBuildStatusWithStateCall) DoAndReturn(f func(string, *common.BuildResultOptions, ...string) (*common.BuildResultList, error)) *MockObsStatusFetcherWithStateBuildStatusWithStateCall {
|
|
||||||
c.Call = c.Call.DoAndReturn(f)
|
|
||||||
return c
|
|
||||||
}
|
|
103
common/pr.go
103
common/pr.go
@@ -4,8 +4,6 @@ import (
|
|||||||
"bufio"
|
"bufio"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
|
||||||
"path"
|
|
||||||
"slices"
|
"slices"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
@@ -63,7 +61,6 @@ func readPRData(gitea GiteaPRFetcher, pr *models.PullRequest, currentSet []*PRIn
|
|||||||
var Timeline_RefIssueNotFound error = errors.New("RefIssue not found on the timeline")
|
var Timeline_RefIssueNotFound error = errors.New("RefIssue not found on the timeline")
|
||||||
|
|
||||||
func LastPrjGitRefOnTimeline(gitea GiteaPRTimelineFetcher, org, repo string, num int64, prjGitOrg, prjGitRepo string) (*models.PullRequest, error) {
|
func LastPrjGitRefOnTimeline(gitea GiteaPRTimelineFetcher, org, repo string, num int64, prjGitOrg, prjGitRepo string) (*models.PullRequest, error) {
|
||||||
prRefLine := fmt.Sprintf(PrPattern, org, repo, num)
|
|
||||||
timeline, err := gitea.GetTimeline(org, repo, num)
|
timeline, err := gitea.GetTimeline(org, repo, num)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
LogError("Failed to fetch timeline for", org, repo, "#", num, err)
|
LogError("Failed to fetch timeline for", org, repo, "#", num, err)
|
||||||
@@ -79,9 +76,9 @@ func LastPrjGitRefOnTimeline(gitea GiteaPRTimelineFetcher, org, repo string, num
|
|||||||
issue.Repository.Owner == prjGitOrg &&
|
issue.Repository.Owner == prjGitOrg &&
|
||||||
issue.Repository.Name == prjGitRepo {
|
issue.Repository.Name == prjGitRepo {
|
||||||
|
|
||||||
lines := SplitLines(item.RefIssue.Body)
|
_, prs := ExtractDescriptionAndPRs(bufio.NewScanner(strings.NewReader(item.RefIssue.Body)))
|
||||||
for _, line := range lines {
|
for _, pr := range prs {
|
||||||
if strings.TrimSpace(line) == prRefLine {
|
if pr.Org == org && pr.Repo == repo && pr.Num == num {
|
||||||
LogDebug("Found PrjGit PR in Timeline:", issue.Index)
|
LogDebug("Found PrjGit PR in Timeline:", issue.Index)
|
||||||
|
|
||||||
// found prjgit PR in timeline. Return it
|
// found prjgit PR in timeline. Return it
|
||||||
@@ -282,6 +279,12 @@ func (rs *PRSet) AssignReviewers(gitea GiteaReviewFetcherAndRequester, maintaine
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (rs *PRSet) RemoveClosedPRs() {
|
||||||
|
rs.PRs = slices.DeleteFunc(rs.PRs, func(pr *PRInfo) bool {
|
||||||
|
return pr.PR.State != "open"
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
func (rs *PRSet) IsApproved(gitea GiteaPRChecker, maintainers MaintainershipData) bool {
|
func (rs *PRSet) IsApproved(gitea GiteaPRChecker, maintainers MaintainershipData) bool {
|
||||||
configReviewers := ParseReviewers(rs.Config.Reviewers)
|
configReviewers := ParseReviewers(rs.Config.Reviewers)
|
||||||
|
|
||||||
@@ -380,7 +383,8 @@ func (rs *PRSet) Merge(gitea GiteaReviewUnrequester, git Git) error {
|
|||||||
}
|
}
|
||||||
prjgit := prjgit_info.PR
|
prjgit := prjgit_info.PR
|
||||||
|
|
||||||
remote, err := git.GitClone(DefaultGitPrj, rs.Config.Branch, prjgit.Base.Repo.SSHURL)
|
_, _, prjgitBranch := rs.Config.GetPrjGit()
|
||||||
|
remote, err := git.GitClone(DefaultGitPrj, prjgitBranch, prjgit.Base.Repo.SSHURL)
|
||||||
PanicOnError(err)
|
PanicOnError(err)
|
||||||
git.GitExecOrPanic(DefaultGitPrj, "fetch", remote, prjgit.Head.Sha)
|
git.GitExecOrPanic(DefaultGitPrj, "fetch", remote, prjgit.Head.Sha)
|
||||||
|
|
||||||
@@ -401,79 +405,8 @@ func (rs *PRSet) Merge(gitea GiteaReviewUnrequester, git Git) error {
|
|||||||
|
|
||||||
err = git.GitExec(DefaultGitPrj, "merge", "--no-ff", "-m", msg, prjgit.Head.Sha)
|
err = git.GitExec(DefaultGitPrj, "merge", "--no-ff", "-m", msg, prjgit.Head.Sha)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
status, statusErr := git.GitStatus(DefaultGitPrj)
|
if resolveError := git.GitResolveSubmoduleFileConflict(DefaultGitPrj); resolveError != nil {
|
||||||
if statusErr != nil {
|
return fmt.Errorf("Merge failed. (%w): %w", err, resolveError)
|
||||||
return fmt.Errorf("Failed to merge: %w . Status also failed: %w", err, statusErr)
|
|
||||||
}
|
|
||||||
|
|
||||||
// we can only resolve conflicts with .gitmodules
|
|
||||||
for _, s := range status {
|
|
||||||
if s.Status == GitStatus_Unmerged {
|
|
||||||
if s.Path != ".gitmodules" {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
submodules, err := git.GitSubmoduleList(DefaultGitPrj, "MERGE_HEAD")
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("Failed to fetch submodules during merge resolution: %w", err)
|
|
||||||
}
|
|
||||||
s1, err := git.GitExecWithOutput(DefaultGitPrj, "cat-file", "blob", s.States[0])
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("Failed fetching data during .gitmodules merge resoulution: %w", err)
|
|
||||||
}
|
|
||||||
s2, err := git.GitExecWithOutput(DefaultGitPrj, "cat-file", "blob", s.States[1])
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("Failed fetching data during .gitmodules merge resoulution: %w", err)
|
|
||||||
}
|
|
||||||
s3, err := git.GitExecWithOutput(DefaultGitPrj, "cat-file", "blob", s.States[2])
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("Failed fetching data during .gitmodules merge resoulution: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
subs1, err := ParseSubmodulesFile(strings.NewReader(s1))
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("Failed parsing submodule file [%s] in merge: %w", s.States[0], err)
|
|
||||||
}
|
|
||||||
subs2, err := ParseSubmodulesFile(strings.NewReader(s2))
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("Failed parsing submodule file [%s] in merge: %w", s.States[0], err)
|
|
||||||
}
|
|
||||||
subs3, err := ParseSubmodulesFile(strings.NewReader(s3))
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("Failed parsing submodule file [%s] in merge: %w", s.States[0], err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// merge from subs3 (target), subs1 (orig), subs2 (2-nd base that is missing from target base)
|
|
||||||
// this will update submodules
|
|
||||||
mergedSubs := slices.Concat(subs1, subs2, subs3)
|
|
||||||
|
|
||||||
var filteredSubs []Submodule = make([]Submodule, 0, max(len(subs1), len(subs2), len(subs3)))
|
|
||||||
nextSub:
|
|
||||||
for subName := range submodules {
|
|
||||||
|
|
||||||
for i := range mergedSubs {
|
|
||||||
if path.Base(mergedSubs[i].Path) == subName {
|
|
||||||
filteredSubs = append(filteredSubs, mergedSubs[i])
|
|
||||||
continue nextSub
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return fmt.Errorf("Cannot find submodule for path: %s", subName)
|
|
||||||
}
|
|
||||||
|
|
||||||
out, err := os.Create(path.Join(git.GetPath(), DefaultGitPrj, ".gitmodules"))
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("Can't open .gitmodules for writing: %w", err)
|
|
||||||
}
|
|
||||||
if err = WriteSubmodules(filteredSubs, out); err != nil {
|
|
||||||
return fmt.Errorf("Can't write .gitmodules: %w", err)
|
|
||||||
}
|
|
||||||
if out.Close(); err != nil {
|
|
||||||
return fmt.Errorf("Can't close .gitmodules: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
git.GitExecOrPanic(DefaultGitPrj, "add", ".gitmodules")
|
|
||||||
git.GitExecOrPanic(DefaultGitPrj, "-c", "core.editor=true", "merge", "--continue")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -499,7 +432,15 @@ func (rs *PRSet) Merge(gitea GiteaReviewUnrequester, git Git) error {
|
|||||||
if rs.IsPrjGitPR(prinfo.PR) {
|
if rs.IsPrjGitPR(prinfo.PR) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
prinfo.RemoteName, err = git.GitClone(repo.Name, rs.Config.Branch, repo.SSHURL)
|
br := rs.Config.Branch
|
||||||
|
if len(br) == 0 {
|
||||||
|
// if branch is unspecified, take it from the PR as it
|
||||||
|
// matches default branch already
|
||||||
|
br = prinfo.PR.Base.Name
|
||||||
|
} else if br != prinfo.PR.Base.Name {
|
||||||
|
panic(prinfo.PR.Base.Name + " is expected to match " + br)
|
||||||
|
}
|
||||||
|
prinfo.RemoteName, err = git.GitClone(repo.Name, br, repo.SSHURL)
|
||||||
PanicOnError(err)
|
PanicOnError(err)
|
||||||
git.GitExecOrPanic(repo.Name, "fetch", prinfo.RemoteName, head.Sha)
|
git.GitExecOrPanic(repo.Name, "fetch", prinfo.RemoteName, head.Sha)
|
||||||
git.GitExecOrPanic(repo.Name, "merge", "--ff", head.Sha)
|
git.GitExecOrPanic(repo.Name, "merge", "--ff", head.Sha)
|
||||||
|
@@ -15,8 +15,9 @@ import (
|
|||||||
"src.opensuse.org/autogits/common/gitea-generated/models"
|
"src.opensuse.org/autogits/common/gitea-generated/models"
|
||||||
mock_common "src.opensuse.org/autogits/common/mock"
|
mock_common "src.opensuse.org/autogits/common/mock"
|
||||||
)
|
)
|
||||||
|
|
||||||
/*
|
/*
|
||||||
func TestCockpit(t *testing.T) {
|
func TestCockpit(t *testing.T) {
|
||||||
common.SetLoggingLevel(common.LogLevelDebug)
|
common.SetLoggingLevel(common.LogLevelDebug)
|
||||||
gitea := common.AllocateGiteaTransport("https://src.opensuse.org")
|
gitea := common.AllocateGiteaTransport("https://src.opensuse.org")
|
||||||
tl, err := gitea.GetTimeline("cockpit", "cockpit", 29)
|
tl, err := gitea.GetTimeline("cockpit", "cockpit", 29)
|
||||||
@@ -30,7 +31,7 @@ func TestCockpit(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
t.Error(r)
|
t.Error(r)
|
||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
func reviewsToTimeline(reviews []*models.PullReview) []*models.TimelineComment {
|
func reviewsToTimeline(reviews []*models.PullReview) []*models.TimelineComment {
|
||||||
timeline := make([]*models.TimelineComment, len(reviews))
|
timeline := make([]*models.TimelineComment, len(reviews))
|
||||||
@@ -48,11 +49,13 @@ func reviewsToTimeline(reviews []*models.PullReview) []*models.TimelineComment {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestPR(t *testing.T) {
|
func TestPR(t *testing.T) {
|
||||||
|
return
|
||||||
|
|
||||||
baseConfig := common.AutogitConfig{
|
baseConfig := common.AutogitConfig{
|
||||||
Reviewers: []string{"+super1", "*super2", "m1", "-m2"},
|
Reviewers: []string{"+super1", "*super2", "m1", "-m2"},
|
||||||
Branch: "branch",
|
Branch: "branch",
|
||||||
Organization: "foo",
|
Organization: "foo",
|
||||||
GitProjectName: "barPrj",
|
GitProjectName: "foo/barPrj#master",
|
||||||
}
|
}
|
||||||
|
|
||||||
type prdata struct {
|
type prdata struct {
|
||||||
@@ -638,7 +641,7 @@ func TestPRAssignReviewers(t *testing.T) {
|
|||||||
{
|
{
|
||||||
name: "No reviewers",
|
name: "No reviewers",
|
||||||
config: common.AutogitConfig{
|
config: common.AutogitConfig{
|
||||||
GitProjectName: "repo",
|
GitProjectName: "prg/repo#main",
|
||||||
Organization: "org",
|
Organization: "org",
|
||||||
Branch: "main",
|
Branch: "main",
|
||||||
Reviewers: []string{},
|
Reviewers: []string{},
|
||||||
@@ -648,7 +651,7 @@ func TestPRAssignReviewers(t *testing.T) {
|
|||||||
{
|
{
|
||||||
name: "One project reviewer only",
|
name: "One project reviewer only",
|
||||||
config: common.AutogitConfig{
|
config: common.AutogitConfig{
|
||||||
GitProjectName: "repo",
|
GitProjectName: "prg/repo#main",
|
||||||
Organization: "org",
|
Organization: "org",
|
||||||
Branch: "main",
|
Branch: "main",
|
||||||
Reviewers: []string{"-user1"},
|
Reviewers: []string{"-user1"},
|
||||||
@@ -658,7 +661,7 @@ func TestPRAssignReviewers(t *testing.T) {
|
|||||||
{
|
{
|
||||||
name: "One project reviewer and one pkg reviewer only",
|
name: "One project reviewer and one pkg reviewer only",
|
||||||
config: common.AutogitConfig{
|
config: common.AutogitConfig{
|
||||||
GitProjectName: "repo",
|
GitProjectName: "prg/repo#main",
|
||||||
Organization: "org",
|
Organization: "org",
|
||||||
Branch: "main",
|
Branch: "main",
|
||||||
Reviewers: []string{"-user1", "user2"},
|
Reviewers: []string{"-user1", "user2"},
|
||||||
@@ -668,7 +671,7 @@ func TestPRAssignReviewers(t *testing.T) {
|
|||||||
{
|
{
|
||||||
name: "No need to get reviews of submitter",
|
name: "No need to get reviews of submitter",
|
||||||
config: common.AutogitConfig{
|
config: common.AutogitConfig{
|
||||||
GitProjectName: "repo",
|
GitProjectName: "prg/repo#main",
|
||||||
Organization: "org",
|
Organization: "org",
|
||||||
Branch: "main",
|
Branch: "main",
|
||||||
Reviewers: []string{"-user1", "submitter"},
|
Reviewers: []string{"-user1", "submitter"},
|
||||||
@@ -678,7 +681,7 @@ func TestPRAssignReviewers(t *testing.T) {
|
|||||||
{
|
{
|
||||||
name: "Reviews are done",
|
name: "Reviews are done",
|
||||||
config: common.AutogitConfig{
|
config: common.AutogitConfig{
|
||||||
GitProjectName: "repo",
|
GitProjectName: "prg/repo#main",
|
||||||
Organization: "org",
|
Organization: "org",
|
||||||
Branch: "main",
|
Branch: "main",
|
||||||
Reviewers: []string{"-user1", "user2"},
|
Reviewers: []string{"-user1", "user2"},
|
||||||
@@ -712,7 +715,7 @@ func TestPRAssignReviewers(t *testing.T) {
|
|||||||
{
|
{
|
||||||
name: "Stale review is not done, re-request it",
|
name: "Stale review is not done, re-request it",
|
||||||
config: common.AutogitConfig{
|
config: common.AutogitConfig{
|
||||||
GitProjectName: "repo",
|
GitProjectName: "org/repo#main",
|
||||||
Organization: "org",
|
Organization: "org",
|
||||||
Branch: "main",
|
Branch: "main",
|
||||||
Reviewers: []string{"-user1", "user2"},
|
Reviewers: []string{"-user1", "user2"},
|
||||||
@@ -744,7 +747,7 @@ func TestPRAssignReviewers(t *testing.T) {
|
|||||||
{
|
{
|
||||||
name: "Stale optional review is not done, re-request it",
|
name: "Stale optional review is not done, re-request it",
|
||||||
config: common.AutogitConfig{
|
config: common.AutogitConfig{
|
||||||
GitProjectName: "repo",
|
GitProjectName: "prg/repo#main",
|
||||||
Organization: "org",
|
Organization: "org",
|
||||||
Branch: "main",
|
Branch: "main",
|
||||||
Reviewers: []string{"-user1", "user2", "~bot"},
|
Reviewers: []string{"-user1", "user2", "~bot"},
|
||||||
@@ -852,7 +855,7 @@ func TestPRAssignReviewers(t *testing.T) {
|
|||||||
{
|
{
|
||||||
name: "PrjMaintainers in prjgit review when not part of pkg set",
|
name: "PrjMaintainers in prjgit review when not part of pkg set",
|
||||||
config: common.AutogitConfig{
|
config: common.AutogitConfig{
|
||||||
GitProjectName: "repo",
|
GitProjectName: "org/repo#main",
|
||||||
Organization: "org",
|
Organization: "org",
|
||||||
Branch: "main",
|
Branch: "main",
|
||||||
Reviewers: []string{},
|
Reviewers: []string{},
|
||||||
@@ -923,7 +926,7 @@ func TestPRMerge(t *testing.T) {
|
|||||||
|
|
||||||
config := &common.AutogitConfig{
|
config := &common.AutogitConfig{
|
||||||
Organization: "org",
|
Organization: "org",
|
||||||
GitProjectName: "prj",
|
GitProjectName: "org/prj#master",
|
||||||
}
|
}
|
||||||
|
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
@@ -937,6 +940,7 @@ func TestPRMerge(t *testing.T) {
|
|||||||
pr: &models.PullRequest{
|
pr: &models.PullRequest{
|
||||||
Base: &models.PRBranchInfo{
|
Base: &models.PRBranchInfo{
|
||||||
Sha: "e8b0de43d757c96a9d2c7101f4bff404e322f53a1fa4041fb85d646110c38ad4", // "base_add_b1"
|
Sha: "e8b0de43d757c96a9d2c7101f4bff404e322f53a1fa4041fb85d646110c38ad4", // "base_add_b1"
|
||||||
|
Name: "master",
|
||||||
Repo: &models.Repository{
|
Repo: &models.Repository{
|
||||||
Name: "prj",
|
Name: "prj",
|
||||||
Owner: &models.User{
|
Owner: &models.User{
|
||||||
@@ -957,6 +961,7 @@ func TestPRMerge(t *testing.T) {
|
|||||||
pr: &models.PullRequest{
|
pr: &models.PullRequest{
|
||||||
Base: &models.PRBranchInfo{
|
Base: &models.PRBranchInfo{
|
||||||
Sha: "4fbd1026b2d7462ebe9229a49100c11f1ad6555520a21ba515122d8bc41328a8",
|
Sha: "4fbd1026b2d7462ebe9229a49100c11f1ad6555520a21ba515122d8bc41328a8",
|
||||||
|
Name: "master",
|
||||||
Repo: &models.Repository{
|
Repo: &models.Repository{
|
||||||
Name: "prj",
|
Name: "prj",
|
||||||
Owner: &models.User{
|
Owner: &models.User{
|
||||||
@@ -976,6 +981,7 @@ func TestPRMerge(t *testing.T) {
|
|||||||
t.Run(test.name, func(t *testing.T) {
|
t.Run(test.name, func(t *testing.T) {
|
||||||
ctl := gomock.NewController(t)
|
ctl := gomock.NewController(t)
|
||||||
mock := mock_common.NewMockGiteaPRTimelineFetcher(ctl)
|
mock := mock_common.NewMockGiteaPRTimelineFetcher(ctl)
|
||||||
|
|
||||||
reviewUnrequestMock := mock_common.NewMockGiteaReviewUnrequester(ctl)
|
reviewUnrequestMock := mock_common.NewMockGiteaReviewUnrequester(ctl)
|
||||||
|
|
||||||
reviewUnrequestMock.EXPECT().UnrequestReview(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil)
|
reviewUnrequestMock.EXPECT().UnrequestReview(gomock.Any(), gomock.Any(), gomock.Any(), gomock.Any()).Return(nil)
|
||||||
|
@@ -164,7 +164,7 @@ func (l *RabbitConnection) ConnectAndProcessRabbitMQ(ch chan<- RabbitMessage) {
|
|||||||
for {
|
for {
|
||||||
err := l.ProcessRabbitMQ(ch)
|
err := l.ProcessRabbitMQ(ch)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
LogError("Error in RabbitMQ connection. %#v", err)
|
LogError("Error in RabbitMQ connection:", err)
|
||||||
LogInfo("Reconnecting in 2 seconds...")
|
LogInfo("Reconnecting in 2 seconds...")
|
||||||
time.Sleep(2 * time.Second)
|
time.Sleep(2 * time.Second)
|
||||||
}
|
}
|
||||||
|
@@ -99,12 +99,12 @@ func (gitea *RabbitMQGiteaEventsProcessor) ProcessRabbitMessage(msg RabbitMessag
|
|||||||
req, err := ParseRequestJSON(reqType, msg.Body)
|
req, err := ParseRequestJSON(reqType, msg.Body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
LogError("Error parsing request JSON:", err)
|
LogError("Error parsing request JSON:", err)
|
||||||
return nil
|
|
||||||
} else {
|
} else {
|
||||||
LogDebug("processing req", req.Type)
|
LogDebug("processing req", req.Type)
|
||||||
// h.Request = req
|
// h.Request = req
|
||||||
ProcessEvent(handler, req)
|
ProcessEvent(handler, req)
|
||||||
}
|
}
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
4
go.mod
4
go.mod
@@ -10,8 +10,10 @@ require (
|
|||||||
github.com/go-openapi/validate v0.24.0
|
github.com/go-openapi/validate v0.24.0
|
||||||
github.com/opentracing/opentracing-go v1.2.0
|
github.com/opentracing/opentracing-go v1.2.0
|
||||||
github.com/rabbitmq/amqp091-go v1.10.0
|
github.com/rabbitmq/amqp091-go v1.10.0
|
||||||
|
github.com/redis/go-redis/v9 v9.11.0
|
||||||
github.com/tailscale/hujson v0.0.0-20250226034555-ec1d1c113d33
|
github.com/tailscale/hujson v0.0.0-20250226034555-ec1d1c113d33
|
||||||
go.uber.org/mock v0.5.0
|
go.uber.org/mock v0.5.0
|
||||||
|
gopkg.in/yaml.v3 v3.0.1
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
@@ -30,11 +32,9 @@ require (
|
|||||||
github.com/mailru/easyjson v0.7.7 // indirect
|
github.com/mailru/easyjson v0.7.7 // indirect
|
||||||
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
||||||
github.com/oklog/ulid v1.3.1 // indirect
|
github.com/oklog/ulid v1.3.1 // indirect
|
||||||
github.com/redis/go-redis/v9 v9.11.0 // indirect
|
|
||||||
go.mongodb.org/mongo-driver v1.14.0 // indirect
|
go.mongodb.org/mongo-driver v1.14.0 // indirect
|
||||||
go.opentelemetry.io/otel v1.24.0 // indirect
|
go.opentelemetry.io/otel v1.24.0 // indirect
|
||||||
go.opentelemetry.io/otel/metric v1.24.0 // indirect
|
go.opentelemetry.io/otel/metric v1.24.0 // indirect
|
||||||
go.opentelemetry.io/otel/trace v1.24.0 // indirect
|
go.opentelemetry.io/otel/trace v1.24.0 // indirect
|
||||||
golang.org/x/sync v0.7.0 // indirect
|
golang.org/x/sync v0.7.0 // indirect
|
||||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
|
||||||
)
|
)
|
||||||
|
4
go.sum
4
go.sum
@@ -1,5 +1,9 @@
|
|||||||
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so=
|
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 h1:DklsrG3dyBCFEj5IhUbnKptjxatkF07cF2ak3yi77so=
|
||||||
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw=
|
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2/go.mod h1:WaHUgvxTVq04UNunO+XhnAqY/wQc+bxr74GqbsZ/Jqw=
|
||||||
|
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||||
|
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
||||||
|
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||||
|
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
||||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
@@ -125,6 +125,16 @@ func FindAcceptableReviewInTimeline(user string, timeline []*models.TimelineComm
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func FindOurLastReviewInTimeline(timeline []*models.TimelineComment) *models.TimelineComment {
|
||||||
|
for _, t := range timeline {
|
||||||
|
if t.Type == common.TimelineCommentType_Review && t.User.UserName == groupName && t.Created == t.Updated {
|
||||||
|
return t
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
func UnrequestReviews(gitea common.Gitea, org, repo string, id int64, users []string) {
|
func UnrequestReviews(gitea common.Gitea, org, repo string, id int64, users []string) {
|
||||||
if err := gitea.UnrequestReview(org, repo, id, users...); err != nil {
|
if err := gitea.UnrequestReview(org, repo, id, users...); err != nil {
|
||||||
common.LogError("Can't remove reviewrs after a review:", err)
|
common.LogError("Can't remove reviewrs after a review:", err)
|
||||||
@@ -164,6 +174,22 @@ func ProcessNotifications(notification *models.NotificationThread, gitea common.
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err := ProcessPR(pr); err == nil && !common.IsDryRun {
|
||||||
|
if err := gitea.SetNotificationRead(notification.ID); err != nil {
|
||||||
|
common.LogDebug(" Cannot set notification as read", err)
|
||||||
|
}
|
||||||
|
} else if err != nil && err != ReviewNotFinished {
|
||||||
|
common.LogError(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var ReviewNotFinished = fmt.Errorf("Review is not finished")
|
||||||
|
|
||||||
|
func ProcessPR(pr *models.PullRequest) error {
|
||||||
|
org := pr.Base.Repo.Owner.UserName
|
||||||
|
repo := pr.Base.Repo.Name
|
||||||
|
id := pr.Index
|
||||||
|
|
||||||
found := false
|
found := false
|
||||||
for _, reviewer := range pr.RequestedReviewers {
|
for _, reviewer := range pr.RequestedReviewers {
|
||||||
if reviewer != nil && reviewer.UserName == groupName {
|
if reviewer != nil && reviewer.UserName == groupName {
|
||||||
@@ -173,42 +199,32 @@ func ProcessNotifications(notification *models.NotificationThread, gitea common.
|
|||||||
}
|
}
|
||||||
if !found {
|
if !found {
|
||||||
common.LogInfo(" review is not requested for", groupName)
|
common.LogInfo(" review is not requested for", groupName)
|
||||||
if !common.IsDryRun {
|
return nil
|
||||||
gitea.SetNotificationRead(notification.ID)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
config := configs.GetPrjGitConfig(org, repo, pr.Base.Name)
|
config := configs.GetPrjGitConfig(org, repo, pr.Base.Name)
|
||||||
if config == nil {
|
if config == nil {
|
||||||
common.LogError("Cannot find config for:", fmt.Sprintf("%s/%s!%s", org, repo, pr.Base.Name))
|
return fmt.Errorf("Cannot find config for: %s", pr.URL)
|
||||||
return
|
|
||||||
}
|
}
|
||||||
if pr.State == "closed" {
|
if pr.State == "closed" {
|
||||||
// dismiss the review
|
// dismiss the review
|
||||||
common.LogInfo(" -- closed request, so nothing to review")
|
common.LogInfo(" -- closed request, so nothing to review")
|
||||||
if !common.IsDryRun {
|
return nil
|
||||||
gitea.SetNotificationRead(notification.ID)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
reviews, err := gitea.GetPullRequestReviews(org, repo, id)
|
reviews, err := gitea.GetPullRequestReviews(org, repo, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
common.LogInfo(" ** No reviews associated with request:", subject.URL, "Error:", err)
|
return fmt.Errorf("Failed to fetch reviews for: %v: %w", pr.URL, err)
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
timeline, err := common.FetchTimelineSinceReviewRequestOrPush(gitea, groupName, pr.Head.Sha, org, repo, id)
|
timeline, err := common.FetchTimelineSinceReviewRequestOrPush(gitea, groupName, pr.Head.Sha, org, repo, id)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
common.LogError(err)
|
return fmt.Errorf("Failed to fetch timeline to review. %w", err)
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
groupConfig, err := config.GetReviewGroup(groupName)
|
groupConfig, err := config.GetReviewGroup(groupName)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
common.LogError(err)
|
return fmt.Errorf("Failed to fetch review group. %w", err)
|
||||||
return
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// submitter cannot be reviewer
|
// submitter cannot be reviewer
|
||||||
@@ -220,27 +236,31 @@ func ProcessNotifications(notification *models.NotificationThread, gitea common.
|
|||||||
if review := FindAcceptableReviewInTimeline(reviewer, timeline, reviews); review != nil {
|
if review := FindAcceptableReviewInTimeline(reviewer, timeline, reviews); review != nil {
|
||||||
if ReviewAccepted(review.Body) {
|
if ReviewAccepted(review.Body) {
|
||||||
if !common.IsDryRun {
|
if !common.IsDryRun {
|
||||||
gitea.AddReviewComment(pr, common.ReviewStateApproved, "Signed off by: "+reviewer)
|
text := reviewer + " approved a review on behalf of " + groupName
|
||||||
UnrequestReviews(gitea, org, repo, id, requestReviewers)
|
if review := FindOurLastReviewInTimeline(timeline); review == nil || review.Body != text {
|
||||||
if !common.IsDryRun {
|
_, err := gitea.AddReviewComment(pr, common.ReviewStateApproved, text)
|
||||||
if err := gitea.SetNotificationRead(notification.ID); err != nil {
|
if err != nil {
|
||||||
common.LogDebug(" Cannot set notification as read", err)
|
common.LogError(" -> failed to write approval comment", err)
|
||||||
}
|
}
|
||||||
|
UnrequestReviews(gitea, org, repo, id, requestReviewers)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
common.LogInfo(" -> approved by", reviewer)
|
common.LogInfo(" -> approved by", reviewer)
|
||||||
common.LogInfo(" review at", review.Created)
|
common.LogInfo(" review at", review.Created)
|
||||||
return
|
return nil
|
||||||
} else if ReviewRejected(review.Body) {
|
} else if ReviewRejected(review.Body) {
|
||||||
if !common.IsDryRun {
|
if !common.IsDryRun {
|
||||||
gitea.AddReviewComment(pr, common.ReviewStateRequestChanges, "Changes requested. See review by: "+reviewer)
|
text := reviewer + " requested changes on behalf of " + groupName + ". See " + review.HTMLURL
|
||||||
|
if review := FindOurLastReviewInTimeline(timeline); review == nil || review.Body != text {
|
||||||
|
_, err := gitea.AddReviewComment(pr, common.ReviewStateRequestChanges, "Changes requested. See review by: "+reviewer)
|
||||||
|
if err != nil {
|
||||||
|
common.LogError(" -> failed to write rejecting comment", err)
|
||||||
|
}
|
||||||
UnrequestReviews(gitea, org, repo, id, requestReviewers)
|
UnrequestReviews(gitea, org, repo, id, requestReviewers)
|
||||||
if err := gitea.SetNotificationRead(notification.ID); err != nil {
|
|
||||||
common.LogDebug(" Cannot set notification as read", err)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
common.LogInfo(" -> declined by", reviewer)
|
common.LogInfo(" -> declined by", reviewer)
|
||||||
return
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -270,15 +290,22 @@ func ProcessNotifications(notification *models.NotificationThread, gitea common.
|
|||||||
}
|
}
|
||||||
|
|
||||||
if !found_help_comment && !common.IsDryRun {
|
if !found_help_comment && !common.IsDryRun {
|
||||||
helpComment := fmt.Sprintln("Review by", groupName, "represents a group of reviewers:", strings.Join(requestReviewers, ", "), ". To review as part of this group, create a comment with contents @"+groupName+": LGTM on a separate line to accept a review. To request changes, write @"+groupName+": followed by reason for rejection. Do not use reviews to review as a group. Editing a comment invalidates that comment.")
|
helpComment := fmt.Sprintln("Review by", groupName, "represents a group of reviewers:", strings.Join(requestReviewers, ", "), ".\n\n"+
|
||||||
|
"Do **not** use standard review interface to review on behalf of the group.\n"+
|
||||||
|
"To accept the review on behalf of the group, create the following comment: `@"+groupName+": approve`.\n"+
|
||||||
|
"To request changes on behalf of the group, create the following comment: `@"+groupName+": decline` followed with lines justifying the decision.\n"+
|
||||||
|
"Future edits of the comments are ignored, a new comment is required to change the review state.")
|
||||||
if slices.Contains(groupConfig.Reviewers, pr.User.UserName) {
|
if slices.Contains(groupConfig.Reviewers, pr.User.UserName) {
|
||||||
helpComment = helpComment + "\n\n" + fmt.Sprintln("Submitter is member of this review group, hence they are excluded from being one of the reviewers here")
|
helpComment = helpComment + "\n\n" +
|
||||||
|
"Submitter is member of this review group, hence they are excluded from being one of the reviewers here"
|
||||||
}
|
}
|
||||||
gitea.AddComment(pr, helpComment)
|
gitea.AddComment(pr, helpComment)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return ReviewNotFinished
|
||||||
}
|
}
|
||||||
|
|
||||||
func PeriodReviewCheck(gitea common.Gitea) {
|
func PeriodReviewCheck() {
|
||||||
notifications, err := gitea.GetNotifications(common.GiteaNotificationType_Pull, nil)
|
notifications, err := gitea.GetNotifications(common.GiteaNotificationType_Pull, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
common.LogError(" Error fetching unread notifications: %w", err)
|
common.LogError(" Error fetching unread notifications: %w", err)
|
||||||
@@ -287,14 +314,15 @@ func PeriodReviewCheck(gitea common.Gitea) {
|
|||||||
|
|
||||||
for _, notification := range notifications {
|
for _, notification := range notifications {
|
||||||
ProcessNotifications(notification, gitea)
|
ProcessNotifications(notification, gitea)
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var gitea common.Gitea
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
giteaUrl := flag.String("gitea-url", "https://src.opensuse.org", "Gitea instance used for reviews")
|
giteaUrl := flag.String("gitea-url", "https://src.opensuse.org", "Gitea instance used for reviews")
|
||||||
rabbitMqHost := flag.String("rabbit-url", "amqps://rabbit.opensuse.org", "RabbitMQ instance where Gitea webhook notifications are sent")
|
rabbitMqHost := flag.String("rabbit-url", "amqps://rabbit.opensuse.org", "RabbitMQ instance where Gitea webhook notifications are sent")
|
||||||
interval := flag.Int64("interval", 5, "Notification polling interval in minutes (min 1 min)")
|
interval := flag.Int64("interval", 10, "Notification polling interval in minutes (min 1 min)")
|
||||||
configFile := flag.String("config", "", "PrjGit listing config file")
|
configFile := flag.String("config", "", "PrjGit listing config file")
|
||||||
logging := flag.String("logging", "info", "Logging level: [none, error, info, debug]")
|
logging := flag.String("logging", "info", "Logging level: [none, error, info, debug]")
|
||||||
flag.BoolVar(&common.IsDryRun, "dry", false, "Dry run, no effect. For debugging")
|
flag.BoolVar(&common.IsDryRun, "dry", false, "Dry run, no effect. For debugging")
|
||||||
@@ -331,7 +359,7 @@ func main() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
gitea := common.AllocateGiteaTransport(*giteaUrl)
|
gitea = common.AllocateGiteaTransport(*giteaUrl)
|
||||||
configs, err = common.ResolveWorkflowConfigs(gitea, configData)
|
configs, err = common.ResolveWorkflowConfigs(gitea, configData)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
common.LogError("Cannot parse workflow configs:", err)
|
common.LogError("Cannot parse workflow configs:", err)
|
||||||
@@ -375,10 +403,13 @@ func main() {
|
|||||||
config_modified: make(chan *common.AutogitConfig),
|
config_modified: make(chan *common.AutogitConfig),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
process_issue_pr := IssueCommentProcessor{}
|
||||||
|
|
||||||
configUpdates := &common.RabbitMQGiteaEventsProcessor{
|
configUpdates := &common.RabbitMQGiteaEventsProcessor{
|
||||||
Orgs: []string{},
|
Orgs: []string{},
|
||||||
Handlers: map[string]common.RequestProcessor{
|
Handlers: map[string]common.RequestProcessor{
|
||||||
common.RequestType_Push: &config_update,
|
common.RequestType_Push: &config_update,
|
||||||
|
common.RequestType_IssueComment: &process_issue_pr,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
configUpdates.Connection().RabbitURL = u
|
configUpdates.Connection().RabbitURL = u
|
||||||
@@ -415,7 +446,7 @@ func main() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
PeriodReviewCheck(gitea)
|
PeriodReviewCheck()
|
||||||
time.Sleep(time.Duration(*interval * int64(time.Minute)))
|
time.Sleep(time.Duration(*interval * int64(time.Minute)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@@ -7,6 +7,25 @@ import (
|
|||||||
"src.opensuse.org/autogits/common"
|
"src.opensuse.org/autogits/common"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type IssueCommentProcessor struct{}
|
||||||
|
|
||||||
|
func (s *IssueCommentProcessor) ProcessFunc(req *common.Request) error {
|
||||||
|
if req.Type != common.RequestType_IssueComment {
|
||||||
|
return fmt.Errorf("Unhandled, ignored request type: %s", req.Type)
|
||||||
|
}
|
||||||
|
|
||||||
|
data := req.Data.(*common.IssueCommentWebhookEvent)
|
||||||
|
org := data.Repository.Owner.Username
|
||||||
|
repo := data.Repository.Name
|
||||||
|
index := int64(data.Issue.Number)
|
||||||
|
|
||||||
|
pr, err := gitea.GetPullRequest(org, repo, index)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("Failed to fetch PullRequest from event: %s/%s!%d Error: %w", org, repo, index, err)
|
||||||
|
}
|
||||||
|
return ProcessPR(pr)
|
||||||
|
}
|
||||||
|
|
||||||
type ConfigUpdatePush struct {
|
type ConfigUpdatePush struct {
|
||||||
config_modified chan *common.AutogitConfig
|
config_modified chan *common.AutogitConfig
|
||||||
}
|
}
|
||||||
|
27
hujson/main.go
Normal file
27
hujson/main.go
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
|
||||||
|
"github.com/tailscale/hujson"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
data, err := io.ReadAll(os.Stdin)
|
||||||
|
if err != nil {
|
||||||
|
log.Println(err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
json, err := hujson.Standardize(data)
|
||||||
|
if err != nil {
|
||||||
|
log.Println(err)
|
||||||
|
os.Exit(2)
|
||||||
|
}
|
||||||
|
_, err = os.Stdout.Write(json)
|
||||||
|
if err != nil {
|
||||||
|
log.Print(err)
|
||||||
|
os.Exit(3)
|
||||||
|
}
|
||||||
|
}
|
@@ -263,7 +263,7 @@ func ProcessRepoBuildStatus(results, ref []*common.PackageBuildStatus) (status B
|
|||||||
return BuildStatusSummarySuccess, SomeSuccess
|
return BuildStatusSummarySuccess, SomeSuccess
|
||||||
}
|
}
|
||||||
|
|
||||||
func GenerateObsPrjMeta(git common.Git, gitea common.Gitea, pr *models.PullRequest, stagingPrj, buildPrj string) (*common.ProjectMeta, error) {
|
func GenerateObsPrjMeta(git common.Git, gitea common.Gitea, pr *models.PullRequest, stagingPrj, buildPrj string, stagingMasterPrj string) (*common.ProjectMeta, error) {
|
||||||
common.LogDebug("repo content fetching ...")
|
common.LogDebug("repo content fetching ...")
|
||||||
err := FetchPrGit(git, pr)
|
err := FetchPrGit(git, pr)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -289,7 +289,15 @@ func GenerateObsPrjMeta(git common.Git, gitea common.Gitea, pr *models.PullReque
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
meta, err := ObsClient.GetProjectMeta(buildPrj)
|
common.LogDebug("Trying first staging master project: ", stagingMasterPrj)
|
||||||
|
meta, err := ObsClient.GetProjectMeta(stagingMasterPrj)
|
||||||
|
if err == nil {
|
||||||
|
// success, so we use that staging master project as our build project
|
||||||
|
buildPrj = stagingMasterPrj
|
||||||
|
} else {
|
||||||
|
common.LogInfo("error fetching project meta for ", stagingMasterPrj, ". Fall Back to ", buildPrj)
|
||||||
|
meta, err = ObsClient.GetProjectMeta(buildPrj)
|
||||||
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
common.LogError("error fetching project meta for", buildPrj, ". Err:", err)
|
common.LogError("error fetching project meta for", buildPrj, ". Err:", err)
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -414,7 +422,8 @@ func StartOrUpdateBuild(config *common.StagingConfig, git common.Git, gitea comm
|
|||||||
var state RequestModification = RequestModificationSourceChanged
|
var state RequestModification = RequestModificationSourceChanged
|
||||||
if meta == nil {
|
if meta == nil {
|
||||||
// new build
|
// new build
|
||||||
meta, err = GenerateObsPrjMeta(git, gitea, pr, obsPrProject, config.ObsProject)
|
common.LogDebug(" Staging master:", config.StagingProject)
|
||||||
|
meta, err = GenerateObsPrjMeta(git, gitea, pr, obsPrProject, config.ObsProject, config.StagingProject)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return RequestModificationNoChange, err
|
return RequestModificationNoChange, err
|
||||||
}
|
}
|
||||||
@@ -428,6 +437,8 @@ func StartOrUpdateBuild(config *common.StagingConfig, git common.Git, gitea comm
|
|||||||
} else {
|
} else {
|
||||||
err = ObsClient.SetProjectMeta(meta)
|
err = ObsClient.SetProjectMeta(meta)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
x, _ := xml.MarshalIndent(meta, "", " ")
|
||||||
|
common.LogDebug(" meta:", string(x))
|
||||||
common.LogError("cannot create meta project:", err)
|
common.LogError("cannot create meta project:", err)
|
||||||
return RequestModificationNoChange, err
|
return RequestModificationNoChange, err
|
||||||
}
|
}
|
||||||
@@ -584,7 +595,7 @@ func CleanupPullNotification(gitea common.Gitea, thread *models.NotificationThre
|
|||||||
}
|
}
|
||||||
|
|
||||||
if !pr.HasMerged && time.Since(time.Time(pr.Closed)) < time.Duration(config.CleanupDelay)*time.Hour {
|
if !pr.HasMerged && time.Since(time.Time(pr.Closed)) < time.Duration(config.CleanupDelay)*time.Hour {
|
||||||
common.LogInfo("Cooldown period for cleanup of", thread.URL)
|
common.LogInfo("Cooldown period for cleanup of", thread.Subject.HTMLURL)
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -805,7 +816,12 @@ func ProcessPullRequest(gitea common.Gitea, org, repo string, id int64) (bool, e
|
|||||||
if !rebuild_all {
|
if !rebuild_all {
|
||||||
common.LogInfo("No package changes detected. Ignoring")
|
common.LogInfo("No package changes detected. Ignoring")
|
||||||
if !IsDryRun {
|
if !IsDryRun {
|
||||||
_, err = gitea.AddReviewComment(pr, common.ReviewStateComment, "No package changes. Not rebuilding project by default")
|
_, err := gitea.AddReviewComment(pr, common.ReviewStateApproved, "No package changes, not rebuilding project by default, accepting change")
|
||||||
|
if err != nil {
|
||||||
|
common.LogError(err)
|
||||||
|
} else {
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return true, err
|
return true, err
|
||||||
}
|
}
|
||||||
|
@@ -191,15 +191,24 @@ func main() {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var rescanRepoError error
|
||||||
go func() {
|
go func() {
|
||||||
for {
|
for {
|
||||||
if err := RescanRepositories(); err != nil {
|
if rescanRepoError = RescanRepositories(); rescanRepoError != nil {
|
||||||
common.LogError("Failed to rescan repositories.", err)
|
common.LogError("Failed to rescan repositories.", err)
|
||||||
}
|
}
|
||||||
time.Sleep(time.Minute * 5)
|
time.Sleep(time.Minute * 5)
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
|
http.HandleFunc("GET /", func(res http.ResponseWriter, req *http.Request) {
|
||||||
|
if rescanRepoError != nil {
|
||||||
|
res.WriteHeader(500)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
res.WriteHeader(404)
|
||||||
|
res.Write([]byte("404 page not found\n"))
|
||||||
|
})
|
||||||
http.HandleFunc("GET /status/{Project}", func(res http.ResponseWriter, req *http.Request) {
|
http.HandleFunc("GET /status/{Project}", func(res http.ResponseWriter, req *http.Request) {
|
||||||
obsPrj := req.PathValue("Project")
|
obsPrj := req.PathValue("Project")
|
||||||
common.LogInfo(" request: GET /status/" + obsPrj)
|
common.LogInfo(" request: GET /status/" + obsPrj)
|
||||||
|
16
systemd/obs-staging-bot.service
Normal file
16
systemd/obs-staging-bot.service
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Staging bot for project git PRs in OBS
|
||||||
|
After=network-online.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=exec
|
||||||
|
ExecStart=/usr/bin/obs-staging-bot
|
||||||
|
EnvironmentFile=-/etc/sysconfig/obs-staging-bot.env
|
||||||
|
DynamicUser=yes
|
||||||
|
NoNewPrivileges=yes
|
||||||
|
ProtectSystem=strict
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
|
||||||
|
|
4
test/main.go
Normal file
4
test/main.go
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
// exists only to import this for go.modules
|
||||||
|
import "go.uber.org/mock/mockgen/model"
|
12
vendor/go.uber.org/mock/AUTHORS
generated
vendored
12
vendor/go.uber.org/mock/AUTHORS
generated
vendored
@@ -1,12 +0,0 @@
|
|||||||
# This is the official list of GoMock authors for copyright purposes.
|
|
||||||
# This file is distinct from the CONTRIBUTORS files.
|
|
||||||
# See the latter for an explanation.
|
|
||||||
|
|
||||||
# Names should be added to this file as
|
|
||||||
# Name or Organization <email address>
|
|
||||||
# The email address is not required for organizations.
|
|
||||||
|
|
||||||
# Please keep the list sorted.
|
|
||||||
|
|
||||||
Alex Reece <awreece@gmail.com>
|
|
||||||
Google Inc.
|
|
202
vendor/go.uber.org/mock/LICENSE
generated
vendored
202
vendor/go.uber.org/mock/LICENSE
generated
vendored
@@ -1,202 +0,0 @@
|
|||||||
|
|
||||||
Apache License
|
|
||||||
Version 2.0, January 2004
|
|
||||||
http://www.apache.org/licenses/
|
|
||||||
|
|
||||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
||||||
|
|
||||||
1. Definitions.
|
|
||||||
|
|
||||||
"License" shall mean the terms and conditions for use, reproduction,
|
|
||||||
and distribution as defined by Sections 1 through 9 of this document.
|
|
||||||
|
|
||||||
"Licensor" shall mean the copyright owner or entity authorized by
|
|
||||||
the copyright owner that is granting the License.
|
|
||||||
|
|
||||||
"Legal Entity" shall mean the union of the acting entity and all
|
|
||||||
other entities that control, are controlled by, or are under common
|
|
||||||
control with that entity. For the purposes of this definition,
|
|
||||||
"control" means (i) the power, direct or indirect, to cause the
|
|
||||||
direction or management of such entity, whether by contract or
|
|
||||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
||||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
||||||
|
|
||||||
"You" (or "Your") shall mean an individual or Legal Entity
|
|
||||||
exercising permissions granted by this License.
|
|
||||||
|
|
||||||
"Source" form shall mean the preferred form for making modifications,
|
|
||||||
including but not limited to software source code, documentation
|
|
||||||
source, and configuration files.
|
|
||||||
|
|
||||||
"Object" form shall mean any form resulting from mechanical
|
|
||||||
transformation or translation of a Source form, including but
|
|
||||||
not limited to compiled object code, generated documentation,
|
|
||||||
and conversions to other media types.
|
|
||||||
|
|
||||||
"Work" shall mean the work of authorship, whether in Source or
|
|
||||||
Object form, made available under the License, as indicated by a
|
|
||||||
copyright notice that is included in or attached to the work
|
|
||||||
(an example is provided in the Appendix below).
|
|
||||||
|
|
||||||
"Derivative Works" shall mean any work, whether in Source or Object
|
|
||||||
form, that is based on (or derived from) the Work and for which the
|
|
||||||
editorial revisions, annotations, elaborations, or other modifications
|
|
||||||
represent, as a whole, an original work of authorship. For the purposes
|
|
||||||
of this License, Derivative Works shall not include works that remain
|
|
||||||
separable from, or merely link (or bind by name) to the interfaces of,
|
|
||||||
the Work and Derivative Works thereof.
|
|
||||||
|
|
||||||
"Contribution" shall mean any work of authorship, including
|
|
||||||
the original version of the Work and any modifications or additions
|
|
||||||
to that Work or Derivative Works thereof, that is intentionally
|
|
||||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
||||||
or by an individual or Legal Entity authorized to submit on behalf of
|
|
||||||
the copyright owner. For the purposes of this definition, "submitted"
|
|
||||||
means any form of electronic, verbal, or written communication sent
|
|
||||||
to the Licensor or its representatives, including but not limited to
|
|
||||||
communication on electronic mailing lists, source code control systems,
|
|
||||||
and issue tracking systems that are managed by, or on behalf of, the
|
|
||||||
Licensor for the purpose of discussing and improving the Work, but
|
|
||||||
excluding communication that is conspicuously marked or otherwise
|
|
||||||
designated in writing by the copyright owner as "Not a Contribution."
|
|
||||||
|
|
||||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
||||||
on behalf of whom a Contribution has been received by Licensor and
|
|
||||||
subsequently incorporated within the Work.
|
|
||||||
|
|
||||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
||||||
this License, each Contributor hereby grants to You a perpetual,
|
|
||||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
||||||
copyright license to reproduce, prepare Derivative Works of,
|
|
||||||
publicly display, publicly perform, sublicense, and distribute the
|
|
||||||
Work and such Derivative Works in Source or Object form.
|
|
||||||
|
|
||||||
3. Grant of Patent License. Subject to the terms and conditions of
|
|
||||||
this License, each Contributor hereby grants to You a perpetual,
|
|
||||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
||||||
(except as stated in this section) patent license to make, have made,
|
|
||||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
||||||
where such license applies only to those patent claims licensable
|
|
||||||
by such Contributor that are necessarily infringed by their
|
|
||||||
Contribution(s) alone or by combination of their Contribution(s)
|
|
||||||
with the Work to which such Contribution(s) was submitted. If You
|
|
||||||
institute patent litigation against any entity (including a
|
|
||||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
||||||
or a Contribution incorporated within the Work constitutes direct
|
|
||||||
or contributory patent infringement, then any patent licenses
|
|
||||||
granted to You under this License for that Work shall terminate
|
|
||||||
as of the date such litigation is filed.
|
|
||||||
|
|
||||||
4. Redistribution. You may reproduce and distribute copies of the
|
|
||||||
Work or Derivative Works thereof in any medium, with or without
|
|
||||||
modifications, and in Source or Object form, provided that You
|
|
||||||
meet the following conditions:
|
|
||||||
|
|
||||||
(a) You must give any other recipients of the Work or
|
|
||||||
Derivative Works a copy of this License; and
|
|
||||||
|
|
||||||
(b) You must cause any modified files to carry prominent notices
|
|
||||||
stating that You changed the files; and
|
|
||||||
|
|
||||||
(c) You must retain, in the Source form of any Derivative Works
|
|
||||||
that You distribute, all copyright, patent, trademark, and
|
|
||||||
attribution notices from the Source form of the Work,
|
|
||||||
excluding those notices that do not pertain to any part of
|
|
||||||
the Derivative Works; and
|
|
||||||
|
|
||||||
(d) If the Work includes a "NOTICE" text file as part of its
|
|
||||||
distribution, then any Derivative Works that You distribute must
|
|
||||||
include a readable copy of the attribution notices contained
|
|
||||||
within such NOTICE file, excluding those notices that do not
|
|
||||||
pertain to any part of the Derivative Works, in at least one
|
|
||||||
of the following places: within a NOTICE text file distributed
|
|
||||||
as part of the Derivative Works; within the Source form or
|
|
||||||
documentation, if provided along with the Derivative Works; or,
|
|
||||||
within a display generated by the Derivative Works, if and
|
|
||||||
wherever such third-party notices normally appear. The contents
|
|
||||||
of the NOTICE file are for informational purposes only and
|
|
||||||
do not modify the License. You may add Your own attribution
|
|
||||||
notices within Derivative Works that You distribute, alongside
|
|
||||||
or as an addendum to the NOTICE text from the Work, provided
|
|
||||||
that such additional attribution notices cannot be construed
|
|
||||||
as modifying the License.
|
|
||||||
|
|
||||||
You may add Your own copyright statement to Your modifications and
|
|
||||||
may provide additional or different license terms and conditions
|
|
||||||
for use, reproduction, or distribution of Your modifications, or
|
|
||||||
for any such Derivative Works as a whole, provided Your use,
|
|
||||||
reproduction, and distribution of the Work otherwise complies with
|
|
||||||
the conditions stated in this License.
|
|
||||||
|
|
||||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
||||||
any Contribution intentionally submitted for inclusion in the Work
|
|
||||||
by You to the Licensor shall be under the terms and conditions of
|
|
||||||
this License, without any additional terms or conditions.
|
|
||||||
Notwithstanding the above, nothing herein shall supersede or modify
|
|
||||||
the terms of any separate license agreement you may have executed
|
|
||||||
with Licensor regarding such Contributions.
|
|
||||||
|
|
||||||
6. Trademarks. This License does not grant permission to use the trade
|
|
||||||
names, trademarks, service marks, or product names of the Licensor,
|
|
||||||
except as required for reasonable and customary use in describing the
|
|
||||||
origin of the Work and reproducing the content of the NOTICE file.
|
|
||||||
|
|
||||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
||||||
agreed to in writing, Licensor provides the Work (and each
|
|
||||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
||||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
||||||
implied, including, without limitation, any warranties or conditions
|
|
||||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
||||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
||||||
appropriateness of using or redistributing the Work and assume any
|
|
||||||
risks associated with Your exercise of permissions under this License.
|
|
||||||
|
|
||||||
8. Limitation of Liability. In no event and under no legal theory,
|
|
||||||
whether in tort (including negligence), contract, or otherwise,
|
|
||||||
unless required by applicable law (such as deliberate and grossly
|
|
||||||
negligent acts) or agreed to in writing, shall any Contributor be
|
|
||||||
liable to You for damages, including any direct, indirect, special,
|
|
||||||
incidental, or consequential damages of any character arising as a
|
|
||||||
result of this License or out of the use or inability to use the
|
|
||||||
Work (including but not limited to damages for loss of goodwill,
|
|
||||||
work stoppage, computer failure or malfunction, or any and all
|
|
||||||
other commercial damages or losses), even if such Contributor
|
|
||||||
has been advised of the possibility of such damages.
|
|
||||||
|
|
||||||
9. Accepting Warranty or Additional Liability. While redistributing
|
|
||||||
the Work or Derivative Works thereof, You may choose to offer,
|
|
||||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
||||||
or other liability obligations and/or rights consistent with this
|
|
||||||
License. However, in accepting such obligations, You may act only
|
|
||||||
on Your own behalf and on Your sole responsibility, not on behalf
|
|
||||||
of any other Contributor, and only if You agree to indemnify,
|
|
||||||
defend, and hold each Contributor harmless for any liability
|
|
||||||
incurred by, or claims asserted against, such Contributor by reason
|
|
||||||
of your accepting any such warranty or additional liability.
|
|
||||||
|
|
||||||
END OF TERMS AND CONDITIONS
|
|
||||||
|
|
||||||
APPENDIX: How to apply the Apache License to your work.
|
|
||||||
|
|
||||||
To apply the Apache License to your work, attach the following
|
|
||||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
||||||
replaced with your own identifying information. (Don't include
|
|
||||||
the brackets!) The text should be enclosed in the appropriate
|
|
||||||
comment syntax for the file format. We also recommend that a
|
|
||||||
file or class name and description of purpose be included on the
|
|
||||||
same "printed page" as the copyright notice for easier
|
|
||||||
identification within third-party archives.
|
|
||||||
|
|
||||||
Copyright [yyyy] [name of copyright owner]
|
|
||||||
|
|
||||||
Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
you may not use this file except in compliance with the License.
|
|
||||||
You may obtain a copy of the License at
|
|
||||||
|
|
||||||
http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
|
|
||||||
Unless required by applicable law or agreed to in writing, software
|
|
||||||
distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
See the License for the specific language governing permissions and
|
|
||||||
limitations under the License.
|
|
506
vendor/go.uber.org/mock/gomock/call.go
generated
vendored
506
vendor/go.uber.org/mock/gomock/call.go
generated
vendored
@@ -1,506 +0,0 @@
|
|||||||
// Copyright 2010 Google Inc.
|
|
||||||
//
|
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
// you may not use this file except in compliance with the License.
|
|
||||||
// You may obtain a copy of the License at
|
|
||||||
//
|
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
//
|
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
// See the License for the specific language governing permissions and
|
|
||||||
// limitations under the License.
|
|
||||||
|
|
||||||
package gomock
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"reflect"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
// Call represents an expected call to a mock.
|
|
||||||
type Call struct {
|
|
||||||
t TestHelper // for triggering test failures on invalid call setup
|
|
||||||
|
|
||||||
receiver any // the receiver of the method call
|
|
||||||
method string // the name of the method
|
|
||||||
methodType reflect.Type // the type of the method
|
|
||||||
args []Matcher // the args
|
|
||||||
origin string // file and line number of call setup
|
|
||||||
|
|
||||||
preReqs []*Call // prerequisite calls
|
|
||||||
|
|
||||||
// Expectations
|
|
||||||
minCalls, maxCalls int
|
|
||||||
|
|
||||||
numCalls int // actual number made
|
|
||||||
|
|
||||||
// actions are called when this Call is called. Each action gets the args and
|
|
||||||
// can set the return values by returning a non-nil slice. Actions run in the
|
|
||||||
// order they are created.
|
|
||||||
actions []func([]any) []any
|
|
||||||
}
|
|
||||||
|
|
||||||
// newCall creates a *Call. It requires the method type in order to support
|
|
||||||
// unexported methods.
|
|
||||||
func newCall(t TestHelper, receiver any, method string, methodType reflect.Type, args ...any) *Call {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
// TODO: check arity, types.
|
|
||||||
mArgs := make([]Matcher, len(args))
|
|
||||||
for i, arg := range args {
|
|
||||||
if m, ok := arg.(Matcher); ok {
|
|
||||||
mArgs[i] = m
|
|
||||||
} else if arg == nil {
|
|
||||||
// Handle nil specially so that passing a nil interface value
|
|
||||||
// will match the typed nils of concrete args.
|
|
||||||
mArgs[i] = Nil()
|
|
||||||
} else {
|
|
||||||
mArgs[i] = Eq(arg)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// callerInfo's skip should be updated if the number of calls between the user's test
|
|
||||||
// and this line changes, i.e. this code is wrapped in another anonymous function.
|
|
||||||
// 0 is us, 1 is RecordCallWithMethodType(), 2 is the generated recorder, and 3 is the user's test.
|
|
||||||
origin := callerInfo(3)
|
|
||||||
actions := []func([]any) []any{func([]any) []any {
|
|
||||||
// Synthesize the zero value for each of the return args' types.
|
|
||||||
rets := make([]any, methodType.NumOut())
|
|
||||||
for i := 0; i < methodType.NumOut(); i++ {
|
|
||||||
rets[i] = reflect.Zero(methodType.Out(i)).Interface()
|
|
||||||
}
|
|
||||||
return rets
|
|
||||||
}}
|
|
||||||
return &Call{
|
|
||||||
t: t, receiver: receiver, method: method, methodType: methodType,
|
|
||||||
args: mArgs, origin: origin, minCalls: 1, maxCalls: 1, actions: actions,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// AnyTimes allows the expectation to be called 0 or more times
|
|
||||||
func (c *Call) AnyTimes() *Call {
|
|
||||||
c.minCalls, c.maxCalls = 0, 1e8 // close enough to infinity
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// MinTimes requires the call to occur at least n times. If AnyTimes or MaxTimes have not been called or if MaxTimes
|
|
||||||
// was previously called with 1, MinTimes also sets the maximum number of calls to infinity.
|
|
||||||
func (c *Call) MinTimes(n int) *Call {
|
|
||||||
c.minCalls = n
|
|
||||||
if c.maxCalls == 1 {
|
|
||||||
c.maxCalls = 1e8
|
|
||||||
}
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// MaxTimes limits the number of calls to n times. If AnyTimes or MinTimes have not been called or if MinTimes was
|
|
||||||
// previously called with 1, MaxTimes also sets the minimum number of calls to 0.
|
|
||||||
func (c *Call) MaxTimes(n int) *Call {
|
|
||||||
c.maxCalls = n
|
|
||||||
if c.minCalls == 1 {
|
|
||||||
c.minCalls = 0
|
|
||||||
}
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// DoAndReturn declares the action to run when the call is matched.
|
|
||||||
// The return values from this function are returned by the mocked function.
|
|
||||||
// It takes an any argument to support n-arity functions.
|
|
||||||
// The anonymous function must match the function signature mocked method.
|
|
||||||
func (c *Call) DoAndReturn(f any) *Call {
|
|
||||||
// TODO: Check arity and types here, rather than dying badly elsewhere.
|
|
||||||
v := reflect.ValueOf(f)
|
|
||||||
|
|
||||||
c.addAction(func(args []any) []any {
|
|
||||||
c.t.Helper()
|
|
||||||
ft := v.Type()
|
|
||||||
if c.methodType.NumIn() != ft.NumIn() {
|
|
||||||
if ft.IsVariadic() {
|
|
||||||
c.t.Fatalf("wrong number of arguments in DoAndReturn func for %T.%v The function signature must match the mocked method, a variadic function cannot be used.",
|
|
||||||
c.receiver, c.method)
|
|
||||||
} else {
|
|
||||||
c.t.Fatalf("wrong number of arguments in DoAndReturn func for %T.%v: got %d, want %d [%s]",
|
|
||||||
c.receiver, c.method, ft.NumIn(), c.methodType.NumIn(), c.origin)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
vArgs := make([]reflect.Value, len(args))
|
|
||||||
for i := 0; i < len(args); i++ {
|
|
||||||
if args[i] != nil {
|
|
||||||
vArgs[i] = reflect.ValueOf(args[i])
|
|
||||||
} else {
|
|
||||||
// Use the zero value for the arg.
|
|
||||||
vArgs[i] = reflect.Zero(ft.In(i))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
vRets := v.Call(vArgs)
|
|
||||||
rets := make([]any, len(vRets))
|
|
||||||
for i, ret := range vRets {
|
|
||||||
rets[i] = ret.Interface()
|
|
||||||
}
|
|
||||||
return rets
|
|
||||||
})
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// Do declares the action to run when the call is matched. The function's
|
|
||||||
// return values are ignored to retain backward compatibility. To use the
|
|
||||||
// return values call DoAndReturn.
|
|
||||||
// It takes an any argument to support n-arity functions.
|
|
||||||
// The anonymous function must match the function signature mocked method.
|
|
||||||
func (c *Call) Do(f any) *Call {
|
|
||||||
// TODO: Check arity and types here, rather than dying badly elsewhere.
|
|
||||||
v := reflect.ValueOf(f)
|
|
||||||
|
|
||||||
c.addAction(func(args []any) []any {
|
|
||||||
c.t.Helper()
|
|
||||||
ft := v.Type()
|
|
||||||
if c.methodType.NumIn() != ft.NumIn() {
|
|
||||||
if ft.IsVariadic() {
|
|
||||||
c.t.Fatalf("wrong number of arguments in Do func for %T.%v The function signature must match the mocked method, a variadic function cannot be used.",
|
|
||||||
c.receiver, c.method)
|
|
||||||
} else {
|
|
||||||
c.t.Fatalf("wrong number of arguments in Do func for %T.%v: got %d, want %d [%s]",
|
|
||||||
c.receiver, c.method, ft.NumIn(), c.methodType.NumIn(), c.origin)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
vArgs := make([]reflect.Value, len(args))
|
|
||||||
for i := 0; i < len(args); i++ {
|
|
||||||
if args[i] != nil {
|
|
||||||
vArgs[i] = reflect.ValueOf(args[i])
|
|
||||||
} else {
|
|
||||||
// Use the zero value for the arg.
|
|
||||||
vArgs[i] = reflect.Zero(ft.In(i))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
v.Call(vArgs)
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return declares the values to be returned by the mocked function call.
|
|
||||||
func (c *Call) Return(rets ...any) *Call {
|
|
||||||
c.t.Helper()
|
|
||||||
|
|
||||||
mt := c.methodType
|
|
||||||
if len(rets) != mt.NumOut() {
|
|
||||||
c.t.Fatalf("wrong number of arguments to Return for %T.%v: got %d, want %d [%s]",
|
|
||||||
c.receiver, c.method, len(rets), mt.NumOut(), c.origin)
|
|
||||||
}
|
|
||||||
for i, ret := range rets {
|
|
||||||
if got, want := reflect.TypeOf(ret), mt.Out(i); got == want {
|
|
||||||
// Identical types; nothing to do.
|
|
||||||
} else if got == nil {
|
|
||||||
// Nil needs special handling.
|
|
||||||
switch want.Kind() {
|
|
||||||
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
|
|
||||||
// ok
|
|
||||||
default:
|
|
||||||
c.t.Fatalf("argument %d to Return for %T.%v is nil, but %v is not nillable [%s]",
|
|
||||||
i, c.receiver, c.method, want, c.origin)
|
|
||||||
}
|
|
||||||
} else if got.AssignableTo(want) {
|
|
||||||
// Assignable type relation. Make the assignment now so that the generated code
|
|
||||||
// can return the values with a type assertion.
|
|
||||||
v := reflect.New(want).Elem()
|
|
||||||
v.Set(reflect.ValueOf(ret))
|
|
||||||
rets[i] = v.Interface()
|
|
||||||
} else {
|
|
||||||
c.t.Fatalf("wrong type of argument %d to Return for %T.%v: %v is not assignable to %v [%s]",
|
|
||||||
i, c.receiver, c.method, got, want, c.origin)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
c.addAction(func([]any) []any {
|
|
||||||
return rets
|
|
||||||
})
|
|
||||||
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// Times declares the exact number of times a function call is expected to be executed.
|
|
||||||
func (c *Call) Times(n int) *Call {
|
|
||||||
c.minCalls, c.maxCalls = n, n
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// SetArg declares an action that will set the nth argument's value,
|
|
||||||
// indirected through a pointer. Or, in the case of a slice and map, SetArg
|
|
||||||
// will copy value's elements/key-value pairs into the nth argument.
|
|
||||||
func (c *Call) SetArg(n int, value any) *Call {
|
|
||||||
c.t.Helper()
|
|
||||||
|
|
||||||
mt := c.methodType
|
|
||||||
// TODO: This will break on variadic methods.
|
|
||||||
// We will need to check those at invocation time.
|
|
||||||
if n < 0 || n >= mt.NumIn() {
|
|
||||||
c.t.Fatalf("SetArg(%d, ...) called for a method with %d args [%s]",
|
|
||||||
n, mt.NumIn(), c.origin)
|
|
||||||
}
|
|
||||||
// Permit setting argument through an interface.
|
|
||||||
// In the interface case, we don't (nay, can't) check the type here.
|
|
||||||
at := mt.In(n)
|
|
||||||
switch at.Kind() {
|
|
||||||
case reflect.Ptr:
|
|
||||||
dt := at.Elem()
|
|
||||||
if vt := reflect.TypeOf(value); !vt.AssignableTo(dt) {
|
|
||||||
c.t.Fatalf("SetArg(%d, ...) argument is a %v, not assignable to %v [%s]",
|
|
||||||
n, vt, dt, c.origin)
|
|
||||||
}
|
|
||||||
case reflect.Interface, reflect.Slice, reflect.Map:
|
|
||||||
// nothing to do
|
|
||||||
default:
|
|
||||||
c.t.Fatalf("SetArg(%d, ...) referring to argument of non-pointer non-interface non-slice non-map type %v [%s]",
|
|
||||||
n, at, c.origin)
|
|
||||||
}
|
|
||||||
|
|
||||||
c.addAction(func(args []any) []any {
|
|
||||||
v := reflect.ValueOf(value)
|
|
||||||
switch reflect.TypeOf(args[n]).Kind() {
|
|
||||||
case reflect.Slice:
|
|
||||||
setSlice(args[n], v)
|
|
||||||
case reflect.Map:
|
|
||||||
setMap(args[n], v)
|
|
||||||
default:
|
|
||||||
reflect.ValueOf(args[n]).Elem().Set(v)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
})
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// isPreReq returns true if other is a direct or indirect prerequisite to c.
|
|
||||||
func (c *Call) isPreReq(other *Call) bool {
|
|
||||||
for _, preReq := range c.preReqs {
|
|
||||||
if other == preReq || preReq.isPreReq(other) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// After declares that the call may only match after preReq has been exhausted.
|
|
||||||
func (c *Call) After(preReq *Call) *Call {
|
|
||||||
c.t.Helper()
|
|
||||||
|
|
||||||
if c == preReq {
|
|
||||||
c.t.Fatalf("A call isn't allowed to be its own prerequisite")
|
|
||||||
}
|
|
||||||
if preReq.isPreReq(c) {
|
|
||||||
c.t.Fatalf("Loop in call order: %v is a prerequisite to %v (possibly indirectly).", c, preReq)
|
|
||||||
}
|
|
||||||
|
|
||||||
c.preReqs = append(c.preReqs, preReq)
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// Returns true if the minimum number of calls have been made.
|
|
||||||
func (c *Call) satisfied() bool {
|
|
||||||
return c.numCalls >= c.minCalls
|
|
||||||
}
|
|
||||||
|
|
||||||
// Returns true if the maximum number of calls have been made.
|
|
||||||
func (c *Call) exhausted() bool {
|
|
||||||
return c.numCalls >= c.maxCalls
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Call) String() string {
|
|
||||||
args := make([]string, len(c.args))
|
|
||||||
for i, arg := range c.args {
|
|
||||||
args[i] = arg.String()
|
|
||||||
}
|
|
||||||
arguments := strings.Join(args, ", ")
|
|
||||||
return fmt.Sprintf("%T.%v(%s) %s", c.receiver, c.method, arguments, c.origin)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Tests if the given call matches the expected call.
|
|
||||||
// If yes, returns nil. If no, returns error with message explaining why it does not match.
|
|
||||||
func (c *Call) matches(args []any) error {
|
|
||||||
if !c.methodType.IsVariadic() {
|
|
||||||
if len(args) != len(c.args) {
|
|
||||||
return fmt.Errorf("expected call at %s has the wrong number of arguments. Got: %d, want: %d",
|
|
||||||
c.origin, len(args), len(c.args))
|
|
||||||
}
|
|
||||||
|
|
||||||
for i, m := range c.args {
|
|
||||||
if !m.Matches(args[i]) {
|
|
||||||
return fmt.Errorf(
|
|
||||||
"expected call at %s doesn't match the argument at index %d.\nGot: %v\nWant: %v",
|
|
||||||
c.origin, i, formatGottenArg(m, args[i]), m,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if len(c.args) < c.methodType.NumIn()-1 {
|
|
||||||
return fmt.Errorf("expected call at %s has the wrong number of matchers. Got: %d, want: %d",
|
|
||||||
c.origin, len(c.args), c.methodType.NumIn()-1)
|
|
||||||
}
|
|
||||||
if len(c.args) != c.methodType.NumIn() && len(args) != len(c.args) {
|
|
||||||
return fmt.Errorf("expected call at %s has the wrong number of arguments. Got: %d, want: %d",
|
|
||||||
c.origin, len(args), len(c.args))
|
|
||||||
}
|
|
||||||
if len(args) < len(c.args)-1 {
|
|
||||||
return fmt.Errorf("expected call at %s has the wrong number of arguments. Got: %d, want: greater than or equal to %d",
|
|
||||||
c.origin, len(args), len(c.args)-1)
|
|
||||||
}
|
|
||||||
|
|
||||||
for i, m := range c.args {
|
|
||||||
if i < c.methodType.NumIn()-1 {
|
|
||||||
// Non-variadic args
|
|
||||||
if !m.Matches(args[i]) {
|
|
||||||
return fmt.Errorf("expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v",
|
|
||||||
c.origin, strconv.Itoa(i), formatGottenArg(m, args[i]), m)
|
|
||||||
}
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
// The last arg has a possibility of a variadic argument, so let it branch
|
|
||||||
|
|
||||||
// sample: Foo(a int, b int, c ...int)
|
|
||||||
if i < len(c.args) && i < len(args) {
|
|
||||||
if m.Matches(args[i]) {
|
|
||||||
// Got Foo(a, b, c) want Foo(matcherA, matcherB, gomock.Any())
|
|
||||||
// Got Foo(a, b, c) want Foo(matcherA, matcherB, someSliceMatcher)
|
|
||||||
// Got Foo(a, b, c) want Foo(matcherA, matcherB, matcherC)
|
|
||||||
// Got Foo(a, b) want Foo(matcherA, matcherB)
|
|
||||||
// Got Foo(a, b, c, d) want Foo(matcherA, matcherB, matcherC, matcherD)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// The number of actual args don't match the number of matchers,
|
|
||||||
// or the last matcher is a slice and the last arg is not.
|
|
||||||
// If this function still matches it is because the last matcher
|
|
||||||
// matches all the remaining arguments or the lack of any.
|
|
||||||
// Convert the remaining arguments, if any, into a slice of the
|
|
||||||
// expected type.
|
|
||||||
vArgsType := c.methodType.In(c.methodType.NumIn() - 1)
|
|
||||||
vArgs := reflect.MakeSlice(vArgsType, 0, len(args)-i)
|
|
||||||
for _, arg := range args[i:] {
|
|
||||||
vArgs = reflect.Append(vArgs, reflect.ValueOf(arg))
|
|
||||||
}
|
|
||||||
if m.Matches(vArgs.Interface()) {
|
|
||||||
// Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, gomock.Any())
|
|
||||||
// Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, someSliceMatcher)
|
|
||||||
// Got Foo(a, b) want Foo(matcherA, matcherB, gomock.Any())
|
|
||||||
// Got Foo(a, b) want Foo(matcherA, matcherB, someEmptySliceMatcher)
|
|
||||||
break
|
|
||||||
}
|
|
||||||
// Wrong number of matchers or not match. Fail.
|
|
||||||
// Got Foo(a, b) want Foo(matcherA, matcherB, matcherC, matcherD)
|
|
||||||
// Got Foo(a, b, c) want Foo(matcherA, matcherB, matcherC, matcherD)
|
|
||||||
// Got Foo(a, b, c, d) want Foo(matcherA, matcherB, matcherC, matcherD, matcherE)
|
|
||||||
// Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, matcherC, matcherD)
|
|
||||||
// Got Foo(a, b, c) want Foo(matcherA, matcherB)
|
|
||||||
|
|
||||||
return fmt.Errorf("expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v",
|
|
||||||
c.origin, strconv.Itoa(i), formatGottenArg(m, args[i:]), c.args[i])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check that all prerequisite calls have been satisfied.
|
|
||||||
for _, preReqCall := range c.preReqs {
|
|
||||||
if !preReqCall.satisfied() {
|
|
||||||
return fmt.Errorf("expected call at %s doesn't have a prerequisite call satisfied:\n%v\nshould be called before:\n%v",
|
|
||||||
c.origin, preReqCall, c)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check that the call is not exhausted.
|
|
||||||
if c.exhausted() {
|
|
||||||
return fmt.Errorf("expected call at %s has already been called the max number of times", c.origin)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// dropPrereqs tells the expected Call to not re-check prerequisite calls any
|
|
||||||
// longer, and to return its current set.
|
|
||||||
func (c *Call) dropPrereqs() (preReqs []*Call) {
|
|
||||||
preReqs = c.preReqs
|
|
||||||
c.preReqs = nil
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Call) call() []func([]any) []any {
|
|
||||||
c.numCalls++
|
|
||||||
return c.actions
|
|
||||||
}
|
|
||||||
|
|
||||||
// InOrder declares that the given calls should occur in order.
|
|
||||||
// It panics if the type of any of the arguments isn't *Call or a generated
|
|
||||||
// mock with an embedded *Call.
|
|
||||||
func InOrder(args ...any) {
|
|
||||||
calls := make([]*Call, 0, len(args))
|
|
||||||
for i := 0; i < len(args); i++ {
|
|
||||||
if call := getCall(args[i]); call != nil {
|
|
||||||
calls = append(calls, call)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
panic(fmt.Sprintf(
|
|
||||||
"invalid argument at position %d of type %T, InOrder expects *gomock.Call or generated mock types with an embedded *gomock.Call",
|
|
||||||
i,
|
|
||||||
args[i],
|
|
||||||
))
|
|
||||||
}
|
|
||||||
for i := 1; i < len(calls); i++ {
|
|
||||||
calls[i].After(calls[i-1])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// getCall checks if the parameter is a *Call or a generated struct
|
|
||||||
// that wraps a *Call and returns the *Call pointer - if neither, it returns nil.
|
|
||||||
func getCall(arg any) *Call {
|
|
||||||
if call, ok := arg.(*Call); ok {
|
|
||||||
return call
|
|
||||||
}
|
|
||||||
t := reflect.ValueOf(arg)
|
|
||||||
if t.Kind() != reflect.Ptr && t.Kind() != reflect.Interface {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
t = t.Elem()
|
|
||||||
for i := 0; i < t.NumField(); i++ {
|
|
||||||
f := t.Field(i)
|
|
||||||
if !f.CanInterface() {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if call, ok := f.Interface().(*Call); ok {
|
|
||||||
return call
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func setSlice(arg any, v reflect.Value) {
|
|
||||||
va := reflect.ValueOf(arg)
|
|
||||||
for i := 0; i < v.Len(); i++ {
|
|
||||||
va.Index(i).Set(v.Index(i))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func setMap(arg any, v reflect.Value) {
|
|
||||||
va := reflect.ValueOf(arg)
|
|
||||||
for _, e := range va.MapKeys() {
|
|
||||||
va.SetMapIndex(e, reflect.Value{})
|
|
||||||
}
|
|
||||||
for _, e := range v.MapKeys() {
|
|
||||||
va.SetMapIndex(e, v.MapIndex(e))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Call) addAction(action func([]any) []any) {
|
|
||||||
c.actions = append(c.actions, action)
|
|
||||||
}
|
|
||||||
|
|
||||||
func formatGottenArg(m Matcher, arg any) string {
|
|
||||||
got := fmt.Sprintf("%v (%T)", arg, arg)
|
|
||||||
if gs, ok := m.(GotFormatter); ok {
|
|
||||||
got = gs.Got(arg)
|
|
||||||
}
|
|
||||||
return got
|
|
||||||
}
|
|
164
vendor/go.uber.org/mock/gomock/callset.go
generated
vendored
164
vendor/go.uber.org/mock/gomock/callset.go
generated
vendored
@@ -1,164 +0,0 @@
|
|||||||
// Copyright 2011 Google Inc.
|
|
||||||
//
|
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
// you may not use this file except in compliance with the License.
|
|
||||||
// You may obtain a copy of the License at
|
|
||||||
//
|
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
//
|
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
// See the License for the specific language governing permissions and
|
|
||||||
// limitations under the License.
|
|
||||||
|
|
||||||
package gomock
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"errors"
|
|
||||||
"fmt"
|
|
||||||
"sync"
|
|
||||||
)
|
|
||||||
|
|
||||||
// callSet represents a set of expected calls, indexed by receiver and method
|
|
||||||
// name.
|
|
||||||
type callSet struct {
|
|
||||||
// Calls that are still expected.
|
|
||||||
expected map[callSetKey][]*Call
|
|
||||||
expectedMu *sync.Mutex
|
|
||||||
// Calls that have been exhausted.
|
|
||||||
exhausted map[callSetKey][]*Call
|
|
||||||
// when set to true, existing call expectations are overridden when new call expectations are made
|
|
||||||
allowOverride bool
|
|
||||||
}
|
|
||||||
|
|
||||||
// callSetKey is the key in the maps in callSet
|
|
||||||
type callSetKey struct {
|
|
||||||
receiver any
|
|
||||||
fname string
|
|
||||||
}
|
|
||||||
|
|
||||||
func newCallSet() *callSet {
|
|
||||||
return &callSet{
|
|
||||||
expected: make(map[callSetKey][]*Call),
|
|
||||||
expectedMu: &sync.Mutex{},
|
|
||||||
exhausted: make(map[callSetKey][]*Call),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func newOverridableCallSet() *callSet {
|
|
||||||
return &callSet{
|
|
||||||
expected: make(map[callSetKey][]*Call),
|
|
||||||
expectedMu: &sync.Mutex{},
|
|
||||||
exhausted: make(map[callSetKey][]*Call),
|
|
||||||
allowOverride: true,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add adds a new expected call.
|
|
||||||
func (cs callSet) Add(call *Call) {
|
|
||||||
key := callSetKey{call.receiver, call.method}
|
|
||||||
|
|
||||||
cs.expectedMu.Lock()
|
|
||||||
defer cs.expectedMu.Unlock()
|
|
||||||
|
|
||||||
m := cs.expected
|
|
||||||
if call.exhausted() {
|
|
||||||
m = cs.exhausted
|
|
||||||
}
|
|
||||||
if cs.allowOverride {
|
|
||||||
m[key] = make([]*Call, 0)
|
|
||||||
}
|
|
||||||
|
|
||||||
m[key] = append(m[key], call)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Remove removes an expected call.
|
|
||||||
func (cs callSet) Remove(call *Call) {
|
|
||||||
key := callSetKey{call.receiver, call.method}
|
|
||||||
|
|
||||||
cs.expectedMu.Lock()
|
|
||||||
defer cs.expectedMu.Unlock()
|
|
||||||
|
|
||||||
calls := cs.expected[key]
|
|
||||||
for i, c := range calls {
|
|
||||||
if c == call {
|
|
||||||
// maintain order for remaining calls
|
|
||||||
cs.expected[key] = append(calls[:i], calls[i+1:]...)
|
|
||||||
cs.exhausted[key] = append(cs.exhausted[key], call)
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// FindMatch searches for a matching call. Returns error with explanation message if no call matched.
|
|
||||||
func (cs callSet) FindMatch(receiver any, method string, args []any) (*Call, error) {
|
|
||||||
key := callSetKey{receiver, method}
|
|
||||||
|
|
||||||
cs.expectedMu.Lock()
|
|
||||||
defer cs.expectedMu.Unlock()
|
|
||||||
|
|
||||||
// Search through the expected calls.
|
|
||||||
expected := cs.expected[key]
|
|
||||||
var callsErrors bytes.Buffer
|
|
||||||
for _, call := range expected {
|
|
||||||
err := call.matches(args)
|
|
||||||
if err != nil {
|
|
||||||
_, _ = fmt.Fprintf(&callsErrors, "\n%v", err)
|
|
||||||
} else {
|
|
||||||
return call, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// If we haven't found a match then search through the exhausted calls so we
|
|
||||||
// get useful error messages.
|
|
||||||
exhausted := cs.exhausted[key]
|
|
||||||
for _, call := range exhausted {
|
|
||||||
if err := call.matches(args); err != nil {
|
|
||||||
_, _ = fmt.Fprintf(&callsErrors, "\n%v", err)
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
_, _ = fmt.Fprintf(
|
|
||||||
&callsErrors, "all expected calls for method %q have been exhausted", method,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
if len(expected)+len(exhausted) == 0 {
|
|
||||||
_, _ = fmt.Fprintf(&callsErrors, "there are no expected calls of the method %q for that receiver", method)
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil, errors.New(callsErrors.String())
|
|
||||||
}
|
|
||||||
|
|
||||||
// Failures returns the calls that are not satisfied.
|
|
||||||
func (cs callSet) Failures() []*Call {
|
|
||||||
cs.expectedMu.Lock()
|
|
||||||
defer cs.expectedMu.Unlock()
|
|
||||||
|
|
||||||
failures := make([]*Call, 0, len(cs.expected))
|
|
||||||
for _, calls := range cs.expected {
|
|
||||||
for _, call := range calls {
|
|
||||||
if !call.satisfied() {
|
|
||||||
failures = append(failures, call)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return failures
|
|
||||||
}
|
|
||||||
|
|
||||||
// Satisfied returns true in case all expected calls in this callSet are satisfied.
|
|
||||||
func (cs callSet) Satisfied() bool {
|
|
||||||
cs.expectedMu.Lock()
|
|
||||||
defer cs.expectedMu.Unlock()
|
|
||||||
|
|
||||||
for _, calls := range cs.expected {
|
|
||||||
for _, call := range calls {
|
|
||||||
if !call.satisfied() {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return true
|
|
||||||
}
|
|
326
vendor/go.uber.org/mock/gomock/controller.go
generated
vendored
326
vendor/go.uber.org/mock/gomock/controller.go
generated
vendored
@@ -1,326 +0,0 @@
|
|||||||
// Copyright 2010 Google Inc.
|
|
||||||
//
|
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
// you may not use this file except in compliance with the License.
|
|
||||||
// You may obtain a copy of the License at
|
|
||||||
//
|
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
//
|
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
// See the License for the specific language governing permissions and
|
|
||||||
// limitations under the License.
|
|
||||||
|
|
||||||
package gomock
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"fmt"
|
|
||||||
"reflect"
|
|
||||||
"runtime"
|
|
||||||
"sync"
|
|
||||||
)
|
|
||||||
|
|
||||||
// A TestReporter is something that can be used to report test failures. It
|
|
||||||
// is satisfied by the standard library's *testing.T.
|
|
||||||
type TestReporter interface {
|
|
||||||
Errorf(format string, args ...any)
|
|
||||||
Fatalf(format string, args ...any)
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestHelper is a TestReporter that has the Helper method. It is satisfied
|
|
||||||
// by the standard library's *testing.T.
|
|
||||||
type TestHelper interface {
|
|
||||||
TestReporter
|
|
||||||
Helper()
|
|
||||||
}
|
|
||||||
|
|
||||||
// cleanuper is used to check if TestHelper also has the `Cleanup` method. A
|
|
||||||
// common pattern is to pass in a `*testing.T` to
|
|
||||||
// `NewController(t TestReporter)`. In Go 1.14+, `*testing.T` has a cleanup
|
|
||||||
// method. This can be utilized to call `Finish()` so the caller of this library
|
|
||||||
// does not have to.
|
|
||||||
type cleanuper interface {
|
|
||||||
Cleanup(func())
|
|
||||||
}
|
|
||||||
|
|
||||||
// A Controller represents the top-level control of a mock ecosystem. It
|
|
||||||
// defines the scope and lifetime of mock objects, as well as their
|
|
||||||
// expectations. It is safe to call Controller's methods from multiple
|
|
||||||
// goroutines. Each test should create a new Controller.
|
|
||||||
//
|
|
||||||
// func TestFoo(t *testing.T) {
|
|
||||||
// ctrl := gomock.NewController(t)
|
|
||||||
// // ..
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// func TestBar(t *testing.T) {
|
|
||||||
// t.Run("Sub-Test-1", st) {
|
|
||||||
// ctrl := gomock.NewController(st)
|
|
||||||
// // ..
|
|
||||||
// })
|
|
||||||
// t.Run("Sub-Test-2", st) {
|
|
||||||
// ctrl := gomock.NewController(st)
|
|
||||||
// // ..
|
|
||||||
// })
|
|
||||||
// })
|
|
||||||
type Controller struct {
|
|
||||||
// T should only be called within a generated mock. It is not intended to
|
|
||||||
// be used in user code and may be changed in future versions. T is the
|
|
||||||
// TestReporter passed in when creating the Controller via NewController.
|
|
||||||
// If the TestReporter does not implement a TestHelper it will be wrapped
|
|
||||||
// with a nopTestHelper.
|
|
||||||
T TestHelper
|
|
||||||
mu sync.Mutex
|
|
||||||
expectedCalls *callSet
|
|
||||||
finished bool
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewController returns a new Controller. It is the preferred way to create a Controller.
|
|
||||||
//
|
|
||||||
// Passing [*testing.T] registers cleanup function to automatically call [Controller.Finish]
|
|
||||||
// when the test and all its subtests complete.
|
|
||||||
func NewController(t TestReporter, opts ...ControllerOption) *Controller {
|
|
||||||
h, ok := t.(TestHelper)
|
|
||||||
if !ok {
|
|
||||||
h = &nopTestHelper{t}
|
|
||||||
}
|
|
||||||
ctrl := &Controller{
|
|
||||||
T: h,
|
|
||||||
expectedCalls: newCallSet(),
|
|
||||||
}
|
|
||||||
for _, opt := range opts {
|
|
||||||
opt.apply(ctrl)
|
|
||||||
}
|
|
||||||
if c, ok := isCleanuper(ctrl.T); ok {
|
|
||||||
c.Cleanup(func() {
|
|
||||||
ctrl.T.Helper()
|
|
||||||
ctrl.finish(true, nil)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
return ctrl
|
|
||||||
}
|
|
||||||
|
|
||||||
// ControllerOption configures how a Controller should behave.
|
|
||||||
type ControllerOption interface {
|
|
||||||
apply(*Controller)
|
|
||||||
}
|
|
||||||
|
|
||||||
type overridableExpectationsOption struct{}
|
|
||||||
|
|
||||||
// WithOverridableExpectations allows for overridable call expectations
|
|
||||||
// i.e., subsequent call expectations override existing call expectations
|
|
||||||
func WithOverridableExpectations() overridableExpectationsOption {
|
|
||||||
return overridableExpectationsOption{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (o overridableExpectationsOption) apply(ctrl *Controller) {
|
|
||||||
ctrl.expectedCalls = newOverridableCallSet()
|
|
||||||
}
|
|
||||||
|
|
||||||
type cancelReporter struct {
|
|
||||||
t TestHelper
|
|
||||||
cancel func()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *cancelReporter) Errorf(format string, args ...any) {
|
|
||||||
r.t.Errorf(format, args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *cancelReporter) Fatalf(format string, args ...any) {
|
|
||||||
defer r.cancel()
|
|
||||||
r.t.Fatalf(format, args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *cancelReporter) Helper() {
|
|
||||||
r.t.Helper()
|
|
||||||
}
|
|
||||||
|
|
||||||
// WithContext returns a new Controller and a Context, which is cancelled on any
|
|
||||||
// fatal failure.
|
|
||||||
func WithContext(ctx context.Context, t TestReporter) (*Controller, context.Context) {
|
|
||||||
h, ok := t.(TestHelper)
|
|
||||||
if !ok {
|
|
||||||
h = &nopTestHelper{t: t}
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx, cancel := context.WithCancel(ctx)
|
|
||||||
return NewController(&cancelReporter{t: h, cancel: cancel}), ctx
|
|
||||||
}
|
|
||||||
|
|
||||||
type nopTestHelper struct {
|
|
||||||
t TestReporter
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *nopTestHelper) Errorf(format string, args ...any) {
|
|
||||||
h.t.Errorf(format, args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *nopTestHelper) Fatalf(format string, args ...any) {
|
|
||||||
h.t.Fatalf(format, args...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h nopTestHelper) Helper() {}
|
|
||||||
|
|
||||||
// RecordCall is called by a mock. It should not be called by user code.
|
|
||||||
func (ctrl *Controller) RecordCall(receiver any, method string, args ...any) *Call {
|
|
||||||
ctrl.T.Helper()
|
|
||||||
|
|
||||||
recv := reflect.ValueOf(receiver)
|
|
||||||
for i := 0; i < recv.Type().NumMethod(); i++ {
|
|
||||||
if recv.Type().Method(i).Name == method {
|
|
||||||
return ctrl.RecordCallWithMethodType(receiver, method, recv.Method(i).Type(), args...)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ctrl.T.Fatalf("gomock: failed finding method %s on %T", method, receiver)
|
|
||||||
panic("unreachable")
|
|
||||||
}
|
|
||||||
|
|
||||||
// RecordCallWithMethodType is called by a mock. It should not be called by user code.
|
|
||||||
func (ctrl *Controller) RecordCallWithMethodType(receiver any, method string, methodType reflect.Type, args ...any) *Call {
|
|
||||||
ctrl.T.Helper()
|
|
||||||
|
|
||||||
call := newCall(ctrl.T, receiver, method, methodType, args...)
|
|
||||||
|
|
||||||
ctrl.mu.Lock()
|
|
||||||
defer ctrl.mu.Unlock()
|
|
||||||
ctrl.expectedCalls.Add(call)
|
|
||||||
|
|
||||||
return call
|
|
||||||
}
|
|
||||||
|
|
||||||
// Call is called by a mock. It should not be called by user code.
|
|
||||||
func (ctrl *Controller) Call(receiver any, method string, args ...any) []any {
|
|
||||||
ctrl.T.Helper()
|
|
||||||
|
|
||||||
// Nest this code so we can use defer to make sure the lock is released.
|
|
||||||
actions := func() []func([]any) []any {
|
|
||||||
ctrl.T.Helper()
|
|
||||||
ctrl.mu.Lock()
|
|
||||||
defer ctrl.mu.Unlock()
|
|
||||||
|
|
||||||
expected, err := ctrl.expectedCalls.FindMatch(receiver, method, args)
|
|
||||||
if err != nil {
|
|
||||||
// callerInfo's skip should be updated if the number of calls between the user's test
|
|
||||||
// and this line changes, i.e. this code is wrapped in another anonymous function.
|
|
||||||
// 0 is us, 1 is controller.Call(), 2 is the generated mock, and 3 is the user's test.
|
|
||||||
origin := callerInfo(3)
|
|
||||||
stringArgs := make([]string, len(args))
|
|
||||||
for i, arg := range args {
|
|
||||||
stringArgs[i] = getString(arg)
|
|
||||||
}
|
|
||||||
ctrl.T.Fatalf("Unexpected call to %T.%v(%v) at %s because: %s", receiver, method, stringArgs, origin, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Two things happen here:
|
|
||||||
// * the matching call no longer needs to check prerequisite calls,
|
|
||||||
// * and the prerequisite calls are no longer expected, so remove them.
|
|
||||||
preReqCalls := expected.dropPrereqs()
|
|
||||||
for _, preReqCall := range preReqCalls {
|
|
||||||
ctrl.expectedCalls.Remove(preReqCall)
|
|
||||||
}
|
|
||||||
|
|
||||||
actions := expected.call()
|
|
||||||
if expected.exhausted() {
|
|
||||||
ctrl.expectedCalls.Remove(expected)
|
|
||||||
}
|
|
||||||
return actions
|
|
||||||
}()
|
|
||||||
|
|
||||||
var rets []any
|
|
||||||
for _, action := range actions {
|
|
||||||
if r := action(args); r != nil {
|
|
||||||
rets = r
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return rets
|
|
||||||
}
|
|
||||||
|
|
||||||
// Finish checks to see if all the methods that were expected to be called were called.
|
|
||||||
// It is not idempotent and therefore can only be invoked once.
|
|
||||||
//
|
|
||||||
// Note: If you pass a *testing.T into [NewController], you no longer
|
|
||||||
// need to call ctrl.Finish() in your test methods.
|
|
||||||
func (ctrl *Controller) Finish() {
|
|
||||||
// If we're currently panicking, probably because this is a deferred call.
|
|
||||||
// This must be recovered in the deferred function.
|
|
||||||
err := recover()
|
|
||||||
ctrl.finish(false, err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Satisfied returns whether all expected calls bound to this Controller have been satisfied.
|
|
||||||
// Calling Finish is then guaranteed to not fail due to missing calls.
|
|
||||||
func (ctrl *Controller) Satisfied() bool {
|
|
||||||
ctrl.mu.Lock()
|
|
||||||
defer ctrl.mu.Unlock()
|
|
||||||
return ctrl.expectedCalls.Satisfied()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ctrl *Controller) finish(cleanup bool, panicErr any) {
|
|
||||||
ctrl.T.Helper()
|
|
||||||
|
|
||||||
ctrl.mu.Lock()
|
|
||||||
defer ctrl.mu.Unlock()
|
|
||||||
|
|
||||||
if ctrl.finished {
|
|
||||||
if _, ok := isCleanuper(ctrl.T); !ok {
|
|
||||||
ctrl.T.Fatalf("Controller.Finish was called more than once. It has to be called exactly once.")
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ctrl.finished = true
|
|
||||||
|
|
||||||
// Short-circuit, pass through the panic.
|
|
||||||
if panicErr != nil {
|
|
||||||
panic(panicErr)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check that all remaining expected calls are satisfied.
|
|
||||||
failures := ctrl.expectedCalls.Failures()
|
|
||||||
for _, call := range failures {
|
|
||||||
ctrl.T.Errorf("missing call(s) to %v", call)
|
|
||||||
}
|
|
||||||
if len(failures) != 0 {
|
|
||||||
if !cleanup {
|
|
||||||
ctrl.T.Fatalf("aborting test due to missing call(s)")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
ctrl.T.Errorf("aborting test due to missing call(s)")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// callerInfo returns the file:line of the call site. skip is the number
|
|
||||||
// of stack frames to skip when reporting. 0 is callerInfo's call site.
|
|
||||||
func callerInfo(skip int) string {
|
|
||||||
if _, file, line, ok := runtime.Caller(skip + 1); ok {
|
|
||||||
return fmt.Sprintf("%s:%d", file, line)
|
|
||||||
}
|
|
||||||
return "unknown file"
|
|
||||||
}
|
|
||||||
|
|
||||||
// isCleanuper checks it if t's base TestReporter has a Cleanup method.
|
|
||||||
func isCleanuper(t TestReporter) (cleanuper, bool) {
|
|
||||||
tr := unwrapTestReporter(t)
|
|
||||||
c, ok := tr.(cleanuper)
|
|
||||||
return c, ok
|
|
||||||
}
|
|
||||||
|
|
||||||
// unwrapTestReporter unwraps TestReporter to the base implementation.
|
|
||||||
func unwrapTestReporter(t TestReporter) TestReporter {
|
|
||||||
tr := t
|
|
||||||
switch nt := t.(type) {
|
|
||||||
case *cancelReporter:
|
|
||||||
tr = nt.t
|
|
||||||
if h, check := tr.(*nopTestHelper); check {
|
|
||||||
tr = h.t
|
|
||||||
}
|
|
||||||
case *nopTestHelper:
|
|
||||||
tr = nt.t
|
|
||||||
default:
|
|
||||||
// not wrapped
|
|
||||||
}
|
|
||||||
return tr
|
|
||||||
}
|
|
60
vendor/go.uber.org/mock/gomock/doc.go
generated
vendored
60
vendor/go.uber.org/mock/gomock/doc.go
generated
vendored
@@ -1,60 +0,0 @@
|
|||||||
// Copyright 2022 Google LLC
|
|
||||||
//
|
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
// you may not use this file except in compliance with the License.
|
|
||||||
// You may obtain a copy of the License at
|
|
||||||
//
|
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
//
|
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
// See the License for the specific language governing permissions and
|
|
||||||
// limitations under the License.
|
|
||||||
|
|
||||||
// Package gomock is a mock framework for Go.
|
|
||||||
//
|
|
||||||
// Standard usage:
|
|
||||||
//
|
|
||||||
// (1) Define an interface that you wish to mock.
|
|
||||||
// type MyInterface interface {
|
|
||||||
// SomeMethod(x int64, y string)
|
|
||||||
// }
|
|
||||||
// (2) Use mockgen to generate a mock from the interface.
|
|
||||||
// (3) Use the mock in a test:
|
|
||||||
// func TestMyThing(t *testing.T) {
|
|
||||||
// mockCtrl := gomock.NewController(t)
|
|
||||||
// mockObj := something.NewMockMyInterface(mockCtrl)
|
|
||||||
// mockObj.EXPECT().SomeMethod(4, "blah")
|
|
||||||
// // pass mockObj to a real object and play with it.
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// By default, expected calls are not enforced to run in any particular order.
|
|
||||||
// Call order dependency can be enforced by use of InOrder and/or Call.After.
|
|
||||||
// Call.After can create more varied call order dependencies, but InOrder is
|
|
||||||
// often more convenient.
|
|
||||||
//
|
|
||||||
// The following examples create equivalent call order dependencies.
|
|
||||||
//
|
|
||||||
// Example of using Call.After to chain expected call order:
|
|
||||||
//
|
|
||||||
// firstCall := mockObj.EXPECT().SomeMethod(1, "first")
|
|
||||||
// secondCall := mockObj.EXPECT().SomeMethod(2, "second").After(firstCall)
|
|
||||||
// mockObj.EXPECT().SomeMethod(3, "third").After(secondCall)
|
|
||||||
//
|
|
||||||
// Example of using InOrder to declare expected call order:
|
|
||||||
//
|
|
||||||
// gomock.InOrder(
|
|
||||||
// mockObj.EXPECT().SomeMethod(1, "first"),
|
|
||||||
// mockObj.EXPECT().SomeMethod(2, "second"),
|
|
||||||
// mockObj.EXPECT().SomeMethod(3, "third"),
|
|
||||||
// )
|
|
||||||
//
|
|
||||||
// The standard TestReporter most users will pass to `NewController` is a
|
|
||||||
// `*testing.T` from the context of the test. Note that this will use the
|
|
||||||
// standard `t.Error` and `t.Fatal` methods to report what happened in the test.
|
|
||||||
// In some cases this can leave your testing package in a weird state if global
|
|
||||||
// state is used since `t.Fatal` is like calling panic in the middle of a
|
|
||||||
// function. In these cases it is recommended that you pass in your own
|
|
||||||
// `TestReporter`.
|
|
||||||
package gomock
|
|
447
vendor/go.uber.org/mock/gomock/matchers.go
generated
vendored
447
vendor/go.uber.org/mock/gomock/matchers.go
generated
vendored
@@ -1,447 +0,0 @@
|
|||||||
// Copyright 2010 Google Inc.
|
|
||||||
//
|
|
||||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
||||||
// you may not use this file except in compliance with the License.
|
|
||||||
// You may obtain a copy of the License at
|
|
||||||
//
|
|
||||||
// http://www.apache.org/licenses/LICENSE-2.0
|
|
||||||
//
|
|
||||||
// Unless required by applicable law or agreed to in writing, software
|
|
||||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
||||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
||||||
// See the License for the specific language governing permissions and
|
|
||||||
// limitations under the License.
|
|
||||||
|
|
||||||
package gomock
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"reflect"
|
|
||||||
"regexp"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
// A Matcher is a representation of a class of values.
|
|
||||||
// It is used to represent the valid or expected arguments to a mocked method.
|
|
||||||
type Matcher interface {
|
|
||||||
// Matches returns whether x is a match.
|
|
||||||
Matches(x any) bool
|
|
||||||
|
|
||||||
// String describes what the matcher matches.
|
|
||||||
String() string
|
|
||||||
}
|
|
||||||
|
|
||||||
// WantFormatter modifies the given Matcher's String() method to the given
|
|
||||||
// Stringer. This allows for control on how the "Want" is formatted when
|
|
||||||
// printing .
|
|
||||||
func WantFormatter(s fmt.Stringer, m Matcher) Matcher {
|
|
||||||
type matcher interface {
|
|
||||||
Matches(x any) bool
|
|
||||||
}
|
|
||||||
|
|
||||||
return struct {
|
|
||||||
matcher
|
|
||||||
fmt.Stringer
|
|
||||||
}{
|
|
||||||
matcher: m,
|
|
||||||
Stringer: s,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// StringerFunc type is an adapter to allow the use of ordinary functions as
|
|
||||||
// a Stringer. If f is a function with the appropriate signature,
|
|
||||||
// StringerFunc(f) is a Stringer that calls f.
|
|
||||||
type StringerFunc func() string
|
|
||||||
|
|
||||||
// String implements fmt.Stringer.
|
|
||||||
func (f StringerFunc) String() string {
|
|
||||||
return f()
|
|
||||||
}
|
|
||||||
|
|
||||||
// GotFormatter is used to better print failure messages. If a matcher
|
|
||||||
// implements GotFormatter, it will use the result from Got when printing
|
|
||||||
// the failure message.
|
|
||||||
type GotFormatter interface {
|
|
||||||
// Got is invoked with the received value. The result is used when
|
|
||||||
// printing the failure message.
|
|
||||||
Got(got any) string
|
|
||||||
}
|
|
||||||
|
|
||||||
// GotFormatterFunc type is an adapter to allow the use of ordinary
|
|
||||||
// functions as a GotFormatter. If f is a function with the appropriate
|
|
||||||
// signature, GotFormatterFunc(f) is a GotFormatter that calls f.
|
|
||||||
type GotFormatterFunc func(got any) string
|
|
||||||
|
|
||||||
// Got implements GotFormatter.
|
|
||||||
func (f GotFormatterFunc) Got(got any) string {
|
|
||||||
return f(got)
|
|
||||||
}
|
|
||||||
|
|
||||||
// GotFormatterAdapter attaches a GotFormatter to a Matcher.
|
|
||||||
func GotFormatterAdapter(s GotFormatter, m Matcher) Matcher {
|
|
||||||
return struct {
|
|
||||||
GotFormatter
|
|
||||||
Matcher
|
|
||||||
}{
|
|
||||||
GotFormatter: s,
|
|
||||||
Matcher: m,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type anyMatcher struct{}
|
|
||||||
|
|
||||||
func (anyMatcher) Matches(any) bool {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (anyMatcher) String() string {
|
|
||||||
return "is anything"
|
|
||||||
}
|
|
||||||
|
|
||||||
type condMatcher[T any] struct {
|
|
||||||
fn func(x T) bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c condMatcher[T]) Matches(x any) bool {
|
|
||||||
typed, ok := x.(T)
|
|
||||||
if !ok {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return c.fn(typed)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c condMatcher[T]) String() string {
|
|
||||||
return "adheres to a custom condition"
|
|
||||||
}
|
|
||||||
|
|
||||||
type eqMatcher struct {
|
|
||||||
x any
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e eqMatcher) Matches(x any) bool {
|
|
||||||
// In case, some value is nil
|
|
||||||
if e.x == nil || x == nil {
|
|
||||||
return reflect.DeepEqual(e.x, x)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if types assignable and convert them to common type
|
|
||||||
x1Val := reflect.ValueOf(e.x)
|
|
||||||
x2Val := reflect.ValueOf(x)
|
|
||||||
|
|
||||||
if x1Val.Type().AssignableTo(x2Val.Type()) {
|
|
||||||
x1ValConverted := x1Val.Convert(x2Val.Type())
|
|
||||||
return reflect.DeepEqual(x1ValConverted.Interface(), x2Val.Interface())
|
|
||||||
}
|
|
||||||
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e eqMatcher) String() string {
|
|
||||||
return fmt.Sprintf("is equal to %s (%T)", getString(e.x), e.x)
|
|
||||||
}
|
|
||||||
|
|
||||||
type nilMatcher struct{}
|
|
||||||
|
|
||||||
func (nilMatcher) Matches(x any) bool {
|
|
||||||
if x == nil {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
v := reflect.ValueOf(x)
|
|
||||||
switch v.Kind() {
|
|
||||||
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map,
|
|
||||||
reflect.Ptr, reflect.Slice:
|
|
||||||
return v.IsNil()
|
|
||||||
}
|
|
||||||
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (nilMatcher) String() string {
|
|
||||||
return "is nil"
|
|
||||||
}
|
|
||||||
|
|
||||||
type notMatcher struct {
|
|
||||||
m Matcher
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n notMatcher) Matches(x any) bool {
|
|
||||||
return !n.m.Matches(x)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (n notMatcher) String() string {
|
|
||||||
return "not(" + n.m.String() + ")"
|
|
||||||
}
|
|
||||||
|
|
||||||
type regexMatcher struct {
|
|
||||||
regex *regexp.Regexp
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m regexMatcher) Matches(x any) bool {
|
|
||||||
switch t := x.(type) {
|
|
||||||
case string:
|
|
||||||
return m.regex.MatchString(t)
|
|
||||||
case []byte:
|
|
||||||
return m.regex.Match(t)
|
|
||||||
default:
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m regexMatcher) String() string {
|
|
||||||
return "matches regex " + m.regex.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
type assignableToTypeOfMatcher struct {
|
|
||||||
targetType reflect.Type
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m assignableToTypeOfMatcher) Matches(x any) bool {
|
|
||||||
return reflect.TypeOf(x).AssignableTo(m.targetType)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m assignableToTypeOfMatcher) String() string {
|
|
||||||
return "is assignable to " + m.targetType.Name()
|
|
||||||
}
|
|
||||||
|
|
||||||
type anyOfMatcher struct {
|
|
||||||
matchers []Matcher
|
|
||||||
}
|
|
||||||
|
|
||||||
func (am anyOfMatcher) Matches(x any) bool {
|
|
||||||
for _, m := range am.matchers {
|
|
||||||
if m.Matches(x) {
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
func (am anyOfMatcher) String() string {
|
|
||||||
ss := make([]string, 0, len(am.matchers))
|
|
||||||
for _, matcher := range am.matchers {
|
|
||||||
ss = append(ss, matcher.String())
|
|
||||||
}
|
|
||||||
return strings.Join(ss, " | ")
|
|
||||||
}
|
|
||||||
|
|
||||||
type allMatcher struct {
|
|
||||||
matchers []Matcher
|
|
||||||
}
|
|
||||||
|
|
||||||
func (am allMatcher) Matches(x any) bool {
|
|
||||||
for _, m := range am.matchers {
|
|
||||||
if !m.Matches(x) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
func (am allMatcher) String() string {
|
|
||||||
ss := make([]string, 0, len(am.matchers))
|
|
||||||
for _, matcher := range am.matchers {
|
|
||||||
ss = append(ss, matcher.String())
|
|
||||||
}
|
|
||||||
return strings.Join(ss, "; ")
|
|
||||||
}
|
|
||||||
|
|
||||||
type lenMatcher struct {
|
|
||||||
i int
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m lenMatcher) Matches(x any) bool {
|
|
||||||
v := reflect.ValueOf(x)
|
|
||||||
switch v.Kind() {
|
|
||||||
case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice, reflect.String:
|
|
||||||
return v.Len() == m.i
|
|
||||||
default:
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m lenMatcher) String() string {
|
|
||||||
return fmt.Sprintf("has length %d", m.i)
|
|
||||||
}
|
|
||||||
|
|
||||||
type inAnyOrderMatcher struct {
|
|
||||||
x any
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m inAnyOrderMatcher) Matches(x any) bool {
|
|
||||||
given, ok := m.prepareValue(x)
|
|
||||||
if !ok {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
wanted, ok := m.prepareValue(m.x)
|
|
||||||
if !ok {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
if given.Len() != wanted.Len() {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
usedFromGiven := make([]bool, given.Len())
|
|
||||||
foundFromWanted := make([]bool, wanted.Len())
|
|
||||||
for i := 0; i < wanted.Len(); i++ {
|
|
||||||
wantedMatcher := Eq(wanted.Index(i).Interface())
|
|
||||||
for j := 0; j < given.Len(); j++ {
|
|
||||||
if usedFromGiven[j] {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if wantedMatcher.Matches(given.Index(j).Interface()) {
|
|
||||||
foundFromWanted[i] = true
|
|
||||||
usedFromGiven[j] = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
missingFromWanted := 0
|
|
||||||
for _, found := range foundFromWanted {
|
|
||||||
if !found {
|
|
||||||
missingFromWanted++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
extraInGiven := 0
|
|
||||||
for _, used := range usedFromGiven {
|
|
||||||
if !used {
|
|
||||||
extraInGiven++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return extraInGiven == 0 && missingFromWanted == 0
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m inAnyOrderMatcher) prepareValue(x any) (reflect.Value, bool) {
|
|
||||||
xValue := reflect.ValueOf(x)
|
|
||||||
switch xValue.Kind() {
|
|
||||||
case reflect.Slice, reflect.Array:
|
|
||||||
return xValue, true
|
|
||||||
default:
|
|
||||||
return reflect.Value{}, false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m inAnyOrderMatcher) String() string {
|
|
||||||
return fmt.Sprintf("has the same elements as %v", m.x)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Constructors
|
|
||||||
|
|
||||||
// All returns a composite Matcher that returns true if and only all of the
|
|
||||||
// matchers return true.
|
|
||||||
func All(ms ...Matcher) Matcher { return allMatcher{ms} }
|
|
||||||
|
|
||||||
// Any returns a matcher that always matches.
|
|
||||||
func Any() Matcher { return anyMatcher{} }
|
|
||||||
|
|
||||||
// Cond returns a matcher that matches when the given function returns true
|
|
||||||
// after passing it the parameter to the mock function.
|
|
||||||
// This is particularly useful in case you want to match over a field of a custom struct, or dynamic logic.
|
|
||||||
//
|
|
||||||
// Example usage:
|
|
||||||
//
|
|
||||||
// Cond(func(x int){return x == 1}).Matches(1) // returns true
|
|
||||||
// Cond(func(x int){return x == 2}).Matches(1) // returns false
|
|
||||||
func Cond[T any](fn func(x T) bool) Matcher { return condMatcher[T]{fn} }
|
|
||||||
|
|
||||||
// AnyOf returns a composite Matcher that returns true if at least one of the
|
|
||||||
// matchers returns true.
|
|
||||||
//
|
|
||||||
// Example usage:
|
|
||||||
//
|
|
||||||
// AnyOf(1, 2, 3).Matches(2) // returns true
|
|
||||||
// AnyOf(1, 2, 3).Matches(10) // returns false
|
|
||||||
// AnyOf(Nil(), Len(2)).Matches(nil) // returns true
|
|
||||||
// AnyOf(Nil(), Len(2)).Matches("hi") // returns true
|
|
||||||
// AnyOf(Nil(), Len(2)).Matches("hello") // returns false
|
|
||||||
func AnyOf(xs ...any) Matcher {
|
|
||||||
ms := make([]Matcher, 0, len(xs))
|
|
||||||
for _, x := range xs {
|
|
||||||
if m, ok := x.(Matcher); ok {
|
|
||||||
ms = append(ms, m)
|
|
||||||
} else {
|
|
||||||
ms = append(ms, Eq(x))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return anyOfMatcher{ms}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Eq returns a matcher that matches on equality.
|
|
||||||
//
|
|
||||||
// Example usage:
|
|
||||||
//
|
|
||||||
// Eq(5).Matches(5) // returns true
|
|
||||||
// Eq(5).Matches(4) // returns false
|
|
||||||
func Eq(x any) Matcher { return eqMatcher{x} }
|
|
||||||
|
|
||||||
// Len returns a matcher that matches on length. This matcher returns false if
|
|
||||||
// is compared to a type that is not an array, chan, map, slice, or string.
|
|
||||||
func Len(i int) Matcher {
|
|
||||||
return lenMatcher{i}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Nil returns a matcher that matches if the received value is nil.
|
|
||||||
//
|
|
||||||
// Example usage:
|
|
||||||
//
|
|
||||||
// var x *bytes.Buffer
|
|
||||||
// Nil().Matches(x) // returns true
|
|
||||||
// x = &bytes.Buffer{}
|
|
||||||
// Nil().Matches(x) // returns false
|
|
||||||
func Nil() Matcher { return nilMatcher{} }
|
|
||||||
|
|
||||||
// Not reverses the results of its given child matcher.
|
|
||||||
//
|
|
||||||
// Example usage:
|
|
||||||
//
|
|
||||||
// Not(Eq(5)).Matches(4) // returns true
|
|
||||||
// Not(Eq(5)).Matches(5) // returns false
|
|
||||||
func Not(x any) Matcher {
|
|
||||||
if m, ok := x.(Matcher); ok {
|
|
||||||
return notMatcher{m}
|
|
||||||
}
|
|
||||||
return notMatcher{Eq(x)}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Regex checks whether parameter matches the associated regex.
|
|
||||||
//
|
|
||||||
// Example usage:
|
|
||||||
//
|
|
||||||
// Regex("[0-9]{2}:[0-9]{2}").Matches("23:02") // returns true
|
|
||||||
// Regex("[0-9]{2}:[0-9]{2}").Matches([]byte{'2', '3', ':', '0', '2'}) // returns true
|
|
||||||
// Regex("[0-9]{2}:[0-9]{2}").Matches("hello world") // returns false
|
|
||||||
// Regex("[0-9]{2}").Matches(21) // returns false as it's not a valid type
|
|
||||||
func Regex(regexStr string) Matcher {
|
|
||||||
return regexMatcher{regex: regexp.MustCompile(regexStr)}
|
|
||||||
}
|
|
||||||
|
|
||||||
// AssignableToTypeOf is a Matcher that matches if the parameter to the mock
|
|
||||||
// function is assignable to the type of the parameter to this function.
|
|
||||||
//
|
|
||||||
// Example usage:
|
|
||||||
//
|
|
||||||
// var s fmt.Stringer = &bytes.Buffer{}
|
|
||||||
// AssignableToTypeOf(s).Matches(time.Second) // returns true
|
|
||||||
// AssignableToTypeOf(s).Matches(99) // returns false
|
|
||||||
//
|
|
||||||
// var ctx = reflect.TypeOf((*context.Context)(nil)).Elem()
|
|
||||||
// AssignableToTypeOf(ctx).Matches(context.Background()) // returns true
|
|
||||||
func AssignableToTypeOf(x any) Matcher {
|
|
||||||
if xt, ok := x.(reflect.Type); ok {
|
|
||||||
return assignableToTypeOfMatcher{xt}
|
|
||||||
}
|
|
||||||
return assignableToTypeOfMatcher{reflect.TypeOf(x)}
|
|
||||||
}
|
|
||||||
|
|
||||||
// InAnyOrder is a Matcher that returns true for collections of the same elements ignoring the order.
|
|
||||||
//
|
|
||||||
// Example usage:
|
|
||||||
//
|
|
||||||
// InAnyOrder([]int{1, 2, 3}).Matches([]int{1, 3, 2}) // returns true
|
|
||||||
// InAnyOrder([]int{1, 2, 3}).Matches([]int{1, 2}) // returns false
|
|
||||||
func InAnyOrder(x any) Matcher {
|
|
||||||
return inAnyOrderMatcher{x}
|
|
||||||
}
|
|
36
vendor/go.uber.org/mock/gomock/string.go
generated
vendored
36
vendor/go.uber.org/mock/gomock/string.go
generated
vendored
@@ -1,36 +0,0 @@
|
|||||||
package gomock
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"reflect"
|
|
||||||
)
|
|
||||||
|
|
||||||
// getString is a safe way to convert a value to a string for printing results
|
|
||||||
// If the value is a a mock, getString avoids calling the mocked String() method,
|
|
||||||
// which avoids potential deadlocks
|
|
||||||
func getString(x any) string {
|
|
||||||
if isGeneratedMock(x) {
|
|
||||||
return fmt.Sprintf("%T", x)
|
|
||||||
}
|
|
||||||
if s, ok := x.(fmt.Stringer); ok {
|
|
||||||
return s.String()
|
|
||||||
}
|
|
||||||
return fmt.Sprintf("%v", x)
|
|
||||||
}
|
|
||||||
|
|
||||||
// isGeneratedMock checks if the given type has a "isgomock" field,
|
|
||||||
// indicating it is a generated mock.
|
|
||||||
func isGeneratedMock(x any) bool {
|
|
||||||
typ := reflect.TypeOf(x)
|
|
||||||
if typ == nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
if typ.Kind() == reflect.Ptr {
|
|
||||||
typ = typ.Elem()
|
|
||||||
}
|
|
||||||
if typ.Kind() != reflect.Struct {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
_, isgomock := typ.FieldByName("isgomock")
|
|
||||||
return isgomock
|
|
||||||
}
|
|
1
vendor/modules.txt
vendored
1
vendor/modules.txt
vendored
@@ -132,6 +132,7 @@ go.opentelemetry.io/otel/trace/embedded
|
|||||||
# go.uber.org/mock v0.5.0
|
# go.uber.org/mock v0.5.0
|
||||||
## explicit; go 1.22
|
## explicit; go 1.22
|
||||||
go.uber.org/mock/gomock
|
go.uber.org/mock/gomock
|
||||||
|
go.uber.org/mock/mockgen/model
|
||||||
# golang.org/x/sync v0.7.0
|
# golang.org/x/sync v0.7.0
|
||||||
## explicit; go 1.18
|
## explicit; go 1.18
|
||||||
golang.org/x/sync/errgroup
|
golang.org/x/sync/errgroup
|
||||||
|
@@ -33,6 +33,7 @@ JSON
|
|||||||
* _ManualMergeOnly_: (true, false) only merge if "merge ok" comment/review by package or project maintainers or reviewers
|
* _ManualMergeOnly_: (true, false) only merge if "merge ok" comment/review by package or project maintainers or reviewers
|
||||||
* _ManualMergeProject_: (true, false) only merge if "merge ok" by project maintainers or reviewers
|
* _ManualMergeProject_: (true, false) only merge if "merge ok" by project maintainers or reviewers
|
||||||
* _ReviewRequired_: (true, false) ignores that submitter is a maintainer and require a review from other maintainer IFF available
|
* _ReviewRequired_: (true, false) ignores that submitter is a maintainer and require a review from other maintainer IFF available
|
||||||
|
* _NoProjectGitPR_: (true, false) do not create PrjGit PRs, but still process reviews, etc.
|
||||||
|
|
||||||
NOTE: `-rm`, `-removed`, `-deleted` are all removed suffixes used to indicate current branch is a placeholder for previously existing package. These branches will be ignored by the bot, and if default, the package will be removed and will not be added to the project.
|
NOTE: `-rm`, `-removed`, `-deleted` are all removed suffixes used to indicate current branch is a placeholder for previously existing package. These branches will be ignored by the bot, and if default, the package will be removed and will not be added to the project.
|
||||||
example:
|
example:
|
||||||
|
@@ -1,10 +0,0 @@
|
|||||||
// Code generated by MockGen. DO NOT EDIT.
|
|
||||||
// Source: pr_processor.go
|
|
||||||
//
|
|
||||||
// Generated by this command:
|
|
||||||
//
|
|
||||||
// mockgen -source=pr_processor.go -destination=mock/pr_processor.go -typed
|
|
||||||
//
|
|
||||||
|
|
||||||
// Package mock_main is a generated GoMock package.
|
|
||||||
package mock_main
|
|
@@ -1,157 +0,0 @@
|
|||||||
// Code generated by MockGen. DO NOT EDIT.
|
|
||||||
// Source: state_checker.go
|
|
||||||
//
|
|
||||||
// Generated by this command:
|
|
||||||
//
|
|
||||||
// mockgen -source=state_checker.go -destination=../mock/state_checker.go -typed -package mock_main
|
|
||||||
//
|
|
||||||
|
|
||||||
// Package mock_main is a generated GoMock package.
|
|
||||||
package mock_main
|
|
||||||
|
|
||||||
import (
|
|
||||||
reflect "reflect"
|
|
||||||
|
|
||||||
gomock "go.uber.org/mock/gomock"
|
|
||||||
common "src.opensuse.org/autogits/common"
|
|
||||||
interfaces "src.opensuse.org/autogits/workflow-pr/interfaces"
|
|
||||||
)
|
|
||||||
|
|
||||||
// MockStateChecker is a mock of StateChecker interface.
|
|
||||||
type MockStateChecker struct {
|
|
||||||
ctrl *gomock.Controller
|
|
||||||
recorder *MockStateCheckerMockRecorder
|
|
||||||
isgomock struct{}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MockStateCheckerMockRecorder is the mock recorder for MockStateChecker.
|
|
||||||
type MockStateCheckerMockRecorder struct {
|
|
||||||
mock *MockStateChecker
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewMockStateChecker creates a new mock instance.
|
|
||||||
func NewMockStateChecker(ctrl *gomock.Controller) *MockStateChecker {
|
|
||||||
mock := &MockStateChecker{ctrl: ctrl}
|
|
||||||
mock.recorder = &MockStateCheckerMockRecorder{mock}
|
|
||||||
return mock
|
|
||||||
}
|
|
||||||
|
|
||||||
// EXPECT returns an object that allows the caller to indicate expected use.
|
|
||||||
func (m *MockStateChecker) EXPECT() *MockStateCheckerMockRecorder {
|
|
||||||
return m.recorder
|
|
||||||
}
|
|
||||||
|
|
||||||
// CheckRepos mocks base method.
|
|
||||||
func (m *MockStateChecker) CheckRepos() error {
|
|
||||||
m.ctrl.T.Helper()
|
|
||||||
ret := m.ctrl.Call(m, "CheckRepos")
|
|
||||||
ret0, _ := ret[0].(error)
|
|
||||||
return ret0
|
|
||||||
}
|
|
||||||
|
|
||||||
// CheckRepos indicates an expected call of CheckRepos.
|
|
||||||
func (mr *MockStateCheckerMockRecorder) CheckRepos() *MockStateCheckerCheckReposCall {
|
|
||||||
mr.mock.ctrl.T.Helper()
|
|
||||||
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CheckRepos", reflect.TypeOf((*MockStateChecker)(nil).CheckRepos))
|
|
||||||
return &MockStateCheckerCheckReposCall{Call: call}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MockStateCheckerCheckReposCall wrap *gomock.Call
|
|
||||||
type MockStateCheckerCheckReposCall struct {
|
|
||||||
*gomock.Call
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return rewrite *gomock.Call.Return
|
|
||||||
func (c *MockStateCheckerCheckReposCall) Return(arg0 error) *MockStateCheckerCheckReposCall {
|
|
||||||
c.Call = c.Call.Return(arg0)
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// Do rewrite *gomock.Call.Do
|
|
||||||
func (c *MockStateCheckerCheckReposCall) Do(f func() error) *MockStateCheckerCheckReposCall {
|
|
||||||
c.Call = c.Call.Do(f)
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// DoAndReturn rewrite *gomock.Call.DoAndReturn
|
|
||||||
func (c *MockStateCheckerCheckReposCall) DoAndReturn(f func() error) *MockStateCheckerCheckReposCall {
|
|
||||||
c.Call = c.Call.DoAndReturn(f)
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// ConsistencyCheckProcess mocks base method.
|
|
||||||
func (m *MockStateChecker) ConsistencyCheckProcess() error {
|
|
||||||
m.ctrl.T.Helper()
|
|
||||||
ret := m.ctrl.Call(m, "ConsistencyCheckProcess")
|
|
||||||
ret0, _ := ret[0].(error)
|
|
||||||
return ret0
|
|
||||||
}
|
|
||||||
|
|
||||||
// ConsistencyCheckProcess indicates an expected call of ConsistencyCheckProcess.
|
|
||||||
func (mr *MockStateCheckerMockRecorder) ConsistencyCheckProcess() *MockStateCheckerConsistencyCheckProcessCall {
|
|
||||||
mr.mock.ctrl.T.Helper()
|
|
||||||
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ConsistencyCheckProcess", reflect.TypeOf((*MockStateChecker)(nil).ConsistencyCheckProcess))
|
|
||||||
return &MockStateCheckerConsistencyCheckProcessCall{Call: call}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MockStateCheckerConsistencyCheckProcessCall wrap *gomock.Call
|
|
||||||
type MockStateCheckerConsistencyCheckProcessCall struct {
|
|
||||||
*gomock.Call
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return rewrite *gomock.Call.Return
|
|
||||||
func (c *MockStateCheckerConsistencyCheckProcessCall) Return(arg0 error) *MockStateCheckerConsistencyCheckProcessCall {
|
|
||||||
c.Call = c.Call.Return(arg0)
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// Do rewrite *gomock.Call.Do
|
|
||||||
func (c *MockStateCheckerConsistencyCheckProcessCall) Do(f func() error) *MockStateCheckerConsistencyCheckProcessCall {
|
|
||||||
c.Call = c.Call.Do(f)
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// DoAndReturn rewrite *gomock.Call.DoAndReturn
|
|
||||||
func (c *MockStateCheckerConsistencyCheckProcessCall) DoAndReturn(f func() error) *MockStateCheckerConsistencyCheckProcessCall {
|
|
||||||
c.Call = c.Call.DoAndReturn(f)
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// VerifyProjectState mocks base method.
|
|
||||||
func (m *MockStateChecker) VerifyProjectState(configs *common.AutogitConfig) ([]*interfaces.PRToProcess, error) {
|
|
||||||
m.ctrl.T.Helper()
|
|
||||||
ret := m.ctrl.Call(m, "VerifyProjectState", configs)
|
|
||||||
ret0, _ := ret[0].([]*interfaces.PRToProcess)
|
|
||||||
ret1, _ := ret[1].(error)
|
|
||||||
return ret0, ret1
|
|
||||||
}
|
|
||||||
|
|
||||||
// VerifyProjectState indicates an expected call of VerifyProjectState.
|
|
||||||
func (mr *MockStateCheckerMockRecorder) VerifyProjectState(configs any) *MockStateCheckerVerifyProjectStateCall {
|
|
||||||
mr.mock.ctrl.T.Helper()
|
|
||||||
call := mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "VerifyProjectState", reflect.TypeOf((*MockStateChecker)(nil).VerifyProjectState), configs)
|
|
||||||
return &MockStateCheckerVerifyProjectStateCall{Call: call}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MockStateCheckerVerifyProjectStateCall wrap *gomock.Call
|
|
||||||
type MockStateCheckerVerifyProjectStateCall struct {
|
|
||||||
*gomock.Call
|
|
||||||
}
|
|
||||||
|
|
||||||
// Return rewrite *gomock.Call.Return
|
|
||||||
func (c *MockStateCheckerVerifyProjectStateCall) Return(arg0 []*interfaces.PRToProcess, arg1 error) *MockStateCheckerVerifyProjectStateCall {
|
|
||||||
c.Call = c.Call.Return(arg0, arg1)
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// Do rewrite *gomock.Call.Do
|
|
||||||
func (c *MockStateCheckerVerifyProjectStateCall) Do(f func(*common.AutogitConfig) ([]*interfaces.PRToProcess, error)) *MockStateCheckerVerifyProjectStateCall {
|
|
||||||
c.Call = c.Call.Do(f)
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// DoAndReturn rewrite *gomock.Call.DoAndReturn
|
|
||||||
func (c *MockStateCheckerVerifyProjectStateCall) DoAndReturn(f func(*common.AutogitConfig) ([]*interfaces.PRToProcess, error)) *MockStateCheckerVerifyProjectStateCall {
|
|
||||||
c.Call = c.Call.DoAndReturn(f)
|
|
||||||
return c
|
|
||||||
}
|
|
@@ -3,6 +3,7 @@ package main
|
|||||||
//go:generate mockgen -source=pr_processor.go -destination=mock/pr_processor.go -typed
|
//go:generate mockgen -source=pr_processor.go -destination=mock/pr_processor.go -typed
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"path"
|
"path"
|
||||||
"runtime/debug"
|
"runtime/debug"
|
||||||
@@ -27,6 +28,10 @@ func PrjGitDescription(prset *common.PRSet) (title string, desc string) {
|
|||||||
if prset.IsPrjGitPR(pr.PR) {
|
if prset.IsPrjGitPR(pr.PR) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
if pr.PR.State != "open" {
|
||||||
|
// remove PRs that are not open from description
|
||||||
|
continue
|
||||||
|
}
|
||||||
org, repo, idx := pr.PRComponents()
|
org, repo, idx := pr.PRComponents()
|
||||||
|
|
||||||
title_refs = append(title_refs, repo)
|
title_refs = append(title_refs, repo)
|
||||||
@@ -69,7 +74,7 @@ func updateSubmoduleInPR(submodule, headSha string, git common.Git) {
|
|||||||
// as long as we can update to newer one later, we are still OK
|
// as long as we can update to newer one later, we are still OK
|
||||||
git.GitExec(common.DefaultGitPrj, "submodule", "update", "--init", "--checkout", "--depth", "1", submodule)
|
git.GitExec(common.DefaultGitPrj, "submodule", "update", "--init", "--checkout", "--depth", "1", submodule)
|
||||||
common.PanicOnError(git.GitExec(path.Join(common.DefaultGitPrj, submodule), "fetch", "--depth", "1", "origin", headSha))
|
common.PanicOnError(git.GitExec(path.Join(common.DefaultGitPrj, submodule), "fetch", "--depth", "1", "origin", headSha))
|
||||||
common.PanicOnError(git.GitExec(path.Join(common.DefaultGitPrj, submodule), "checkout", headSha))
|
common.PanicOnError(git.GitExec(path.Join(common.DefaultGitPrj, submodule), "checkout", "-f", headSha))
|
||||||
}
|
}
|
||||||
|
|
||||||
type PRProcessor struct {
|
type PRProcessor struct {
|
||||||
@@ -99,7 +104,10 @@ func AllocatePRProcessor(req *models.PullRequest, configs common.AutogitConfigs)
|
|||||||
return nil, fmt.Errorf("Cannot find config for PR")
|
return nil, fmt.Errorf("Cannot find config for PR")
|
||||||
}
|
}
|
||||||
|
|
||||||
common.LogDebug("found config", config)
|
if common.GetLoggingLevel() >= common.LogLevelDebug {
|
||||||
|
cjson, _ := json.Marshal(config)
|
||||||
|
common.LogDebug("found config:", string(cjson))
|
||||||
|
}
|
||||||
if config == nil {
|
if config == nil {
|
||||||
common.LogError("Cannot find config for branch '%s'", req.Base.Ref)
|
common.LogError("Cannot find config for branch '%s'", req.Base.Ref)
|
||||||
return nil, fmt.Errorf("Cannot find config for branch '%s'", req.Base.Ref)
|
return nil, fmt.Errorf("Cannot find config for branch '%s'", req.Base.Ref)
|
||||||
@@ -158,10 +166,10 @@ func (pr *PRProcessor) SetSubmodulesToMatchPRSet(prset *common.PRSet) error {
|
|||||||
submodule_found = true
|
submodule_found = true
|
||||||
if id != prHead {
|
if id != prHead {
|
||||||
ref := fmt.Sprintf(common.PrPattern, org, repo, idx)
|
ref := fmt.Sprintf(common.PrPattern, org, repo, idx)
|
||||||
commitMsg := fmt.Sprintln("auto-created for", repo, "\n\nThis commit was autocreated by", GitAuthor, "referencing\n", ref)
|
commitMsg := fmt.Sprintln("auto-created for", repo, "\n\nThis commit was autocreated by", GitAuthor, "\n\nreferencing PRs:\n", ref)
|
||||||
|
|
||||||
if revert {
|
if revert {
|
||||||
commitMsg = fmt.Sprintln("auto-created for", repo, "\n\nThis commit was autocreated by", GitAuthor, "removing\n", ref)
|
commitMsg = fmt.Sprintln("auto-created for", repo, "\n\nThis commit was autocreated by", GitAuthor, "\n\nremoving PRs:\n", ref)
|
||||||
}
|
}
|
||||||
|
|
||||||
updateSubmoduleInPR(submodulePath, prHead, git)
|
updateSubmoduleInPR(submodulePath, prHead, git)
|
||||||
@@ -170,6 +178,8 @@ func (pr *PRProcessor) SetSubmodulesToMatchPRSet(prset *common.PRSet) error {
|
|||||||
common.LogDebug("submodule", repo, " hash:", id, " -> ", prHead)
|
common.LogDebug("submodule", repo, " hash:", id, " -> ", prHead)
|
||||||
common.PanicOnError(err)
|
common.PanicOnError(err)
|
||||||
common.PanicOnError(git.GitExec(common.DefaultGitPrj, "commit", "-a", "-m", commitMsg))
|
common.PanicOnError(git.GitExec(common.DefaultGitPrj, "commit", "-a", "-m", commitMsg))
|
||||||
|
|
||||||
|
pr.PR.Head.Sha = id // update the prset
|
||||||
}
|
}
|
||||||
submodule_found = true
|
submodule_found = true
|
||||||
break
|
break
|
||||||
@@ -209,7 +219,7 @@ func (pr *PRProcessor) CreatePRjGitPR(prjGitPRbranch string, prset *common.PRSet
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
if !common.IsDryRun {
|
if !common.IsDryRun && !pr.config.NoProjectGitPR {
|
||||||
if headCommit != newHeadCommit {
|
if headCommit != newHeadCommit {
|
||||||
common.PanicOnError(git.GitExec(common.DefaultGitPrj, "push", RemoteName, "+HEAD:"+prjGitPRbranch))
|
common.PanicOnError(git.GitExec(common.DefaultGitPrj, "push", RemoteName, "+HEAD:"+prjGitPRbranch))
|
||||||
}
|
}
|
||||||
@@ -247,7 +257,7 @@ func (pr *PRProcessor) RebaseAndSkipSubmoduleCommits(prset *common.PRSet, branch
|
|||||||
for _, s := range statuses {
|
for _, s := range statuses {
|
||||||
if s.SubmoduleChanges != "S..." {
|
if s.SubmoduleChanges != "S..." {
|
||||||
git.GitExecOrPanic(common.DefaultGitPrj, "rebase", "--abort")
|
git.GitExecOrPanic(common.DefaultGitPrj, "rebase", "--abort")
|
||||||
return fmt.Errorf("Unexpected conflict in rebase. %s", s)
|
return fmt.Errorf("Unexpected conflict in rebase. %v", s)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
conflict = git.GitExec(common.DefaultGitPrj, "rebase", "--skip")
|
conflict = git.GitExec(common.DefaultGitPrj, "rebase", "--skip")
|
||||||
@@ -265,6 +275,12 @@ func (pr *PRProcessor) UpdatePrjGitPR(prset *common.PRSet) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
git := pr.git
|
git := pr.git
|
||||||
|
if len(prset.PRs) == 1 {
|
||||||
|
git.GitExecOrPanic(common.DefaultGitPrj, "fetch", PrjGitPR.RemoteName, PrjGitPR.PR.Head.Sha)
|
||||||
|
common.LogDebug("Only project git in PR. Nothing to update.")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
PrjGit := PrjGitPR.PR.Base.Repo
|
PrjGit := PrjGitPR.PR.Base.Repo
|
||||||
prjGitPRbranch := PrjGitPR.PR.Head.Name
|
prjGitPRbranch := PrjGitPR.PR.Head.Name
|
||||||
if strings.Contains(prjGitPRbranch, "/") {
|
if strings.Contains(prjGitPRbranch, "/") {
|
||||||
@@ -300,6 +316,12 @@ func (pr *PRProcessor) UpdatePrjGitPR(prset *common.PRSet) error {
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
PrjGitTitle, PrjGitBody := PrjGitDescription(prset)
|
||||||
|
if PrjGitPR.PR.Title != PrjGitTitle || PrjGitPR.PR.Body != PrjGitBody {
|
||||||
|
common.LogDebug("New title:", PrjGitTitle)
|
||||||
|
common.LogDebug(PrjGitBody)
|
||||||
|
}
|
||||||
|
|
||||||
if !common.IsDryRun {
|
if !common.IsDryRun {
|
||||||
if headCommit != newHeadCommit {
|
if headCommit != newHeadCommit {
|
||||||
params := []string{"push", PrjGitPR.RemoteName, "+HEAD:" + prjGitPRbranch}
|
params := []string{"push", PrjGitPR.RemoteName, "+HEAD:" + prjGitPRbranch}
|
||||||
@@ -310,7 +332,6 @@ func (pr *PRProcessor) UpdatePrjGitPR(prset *common.PRSet) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// update PR
|
// update PR
|
||||||
PrjGitTitle, PrjGitBody := PrjGitDescription(prset)
|
|
||||||
if PrjGitPR.PR.Body != PrjGitBody || PrjGitPR.PR.Title != PrjGitTitle {
|
if PrjGitPR.PR.Body != PrjGitBody || PrjGitPR.PR.Title != PrjGitTitle {
|
||||||
Gitea.UpdatePullRequest(PrjGit.Owner.UserName, PrjGit.Name, PrjGitPR.PR.Index, &models.EditPullRequestOption{
|
Gitea.UpdatePullRequest(PrjGit.Owner.UserName, PrjGit.Name, PrjGitPR.PR.Index, &models.EditPullRequestOption{
|
||||||
RemoveDeadline: true,
|
RemoveDeadline: true,
|
||||||
@@ -319,6 +340,9 @@ func (pr *PRProcessor) UpdatePrjGitPR(prset *common.PRSet) error {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// remove closed PRs from prset
|
||||||
|
prset.RemoveClosedPRs()
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -344,7 +368,7 @@ func (pr *PRProcessor) Process(req *models.PullRequest) error {
|
|||||||
prjGitPRbranch := prGitBranchNameForPR(prRepo, prNo)
|
prjGitPRbranch := prGitBranchNameForPR(prRepo, prNo)
|
||||||
prjGitPR, err := prset.GetPrjGitPR()
|
prjGitPR, err := prset.GetPrjGitPR()
|
||||||
if err == common.PRSet_PrjGitMissing {
|
if err == common.PRSet_PrjGitMissing {
|
||||||
common.LogDebug("Missing PrjGit. Need to create one...")
|
common.LogDebug("Missing PrjGit. Need to create one under branch", prjGitPRbranch)
|
||||||
|
|
||||||
if err = pr.CreatePRjGitPR(prjGitPRbranch, prset); err != nil {
|
if err = pr.CreatePRjGitPR(prjGitPRbranch, prset); err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -421,7 +445,11 @@ func (pr *PRProcessor) Process(req *models.PullRequest) error {
|
|||||||
|
|
||||||
if prjGitPR == nil {
|
if prjGitPR == nil {
|
||||||
prjGitPR, err = prset.GetPrjGitPR()
|
prjGitPR, err = prset.GetPrjGitPR()
|
||||||
if err != nil {
|
if err == common.PRSet_PrjGitMissing && config.NoProjectGitPR {
|
||||||
|
// we could be waiting for other tooling to create the
|
||||||
|
// project git PR. In meantime, we can assign some
|
||||||
|
// reviewers here.
|
||||||
|
} else if err != nil {
|
||||||
common.LogError("Error fetching PrjGitPR:", err)
|
common.LogError("Error fetching PrjGitPR:", err)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -433,11 +461,12 @@ func (pr *PRProcessor) Process(req *models.PullRequest) error {
|
|||||||
// reset anything that changed that is not part of the prset
|
// reset anything that changed that is not part of the prset
|
||||||
// package removals/additions are *not* counted here
|
// package removals/additions are *not* counted here
|
||||||
org, repo, branch := config.GetPrjGit()
|
org, repo, branch := config.GetPrjGit()
|
||||||
if pr, err := prset.GetPrjGitPR(); err == nil {
|
// TODO: this is broken...
|
||||||
|
if pr, err := prset.GetPrjGitPR(); err == nil && false {
|
||||||
common.LogDebug("Submodule parse begin")
|
common.LogDebug("Submodule parse begin")
|
||||||
orig_subs, err := git.GitSubmoduleList(common.DefaultGitPrj, pr.PR.MergeBase)
|
orig_subs, err := git.GitSubmoduleList(common.DefaultGitPrj, pr.PR.MergeBase)
|
||||||
common.PanicOnError(err)
|
common.PanicOnError(err)
|
||||||
new_subs, err := git.GitSubmoduleList(common.DefaultGitPrj, pr.PR.Head.Sha)
|
new_subs, err := git.GitSubmoduleList(common.DefaultGitPrj, "HEAD")
|
||||||
common.PanicOnError(err)
|
common.PanicOnError(err)
|
||||||
common.LogDebug("Submodule parse done")
|
common.LogDebug("Submodule parse done")
|
||||||
|
|
||||||
@@ -445,6 +474,7 @@ func (pr *PRProcessor) Process(req *models.PullRequest) error {
|
|||||||
updateSubmoduleInPR(submodule, sha, git)
|
updateSubmoduleInPR(submodule, sha, git)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
common.LogDebug("Checking we only change linked commits")
|
||||||
for path, commit := range new_subs {
|
for path, commit := range new_subs {
|
||||||
if old, ok := orig_subs[path]; ok && old != commit {
|
if old, ok := orig_subs[path]; ok && old != commit {
|
||||||
found := false
|
found := false
|
||||||
@@ -452,6 +482,8 @@ func (pr *PRProcessor) Process(req *models.PullRequest) error {
|
|||||||
if pr.PR.Base.Repo.Name == path && commit == pr.PR.Head.Sha {
|
if pr.PR.Base.Repo.Name == path && commit == pr.PR.Head.Sha {
|
||||||
found = true
|
found = true
|
||||||
break
|
break
|
||||||
|
} else if pr.PR.Base.Repo.Name == path {
|
||||||
|
common.LogError(path, "-- commits not match", commit, pr.PR.Head.Sha)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if !found {
|
if !found {
|
||||||
@@ -461,24 +493,29 @@ func (pr *PRProcessor) Process(req *models.PullRequest) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
stats, err := git.GitStatus(common.DefaultGitPrj)
|
stats, err := git.GitStatus(common.DefaultGitPrj)
|
||||||
|
common.LogDebug("Check Done", len(stats), "changes")
|
||||||
common.PanicOnError(err)
|
common.PanicOnError(err)
|
||||||
if len(stats) > 0 {
|
if len(stats) > 0 {
|
||||||
git.GitExecOrPanic(common.DefaultGitPrj, "commit", "-a", "-m", "Sync submodule updates with PR-set")
|
git.GitExecOrPanic(common.DefaultGitPrj, "commit", "-a", "-m", "Sync submodule updates with PR-set")
|
||||||
git.GitExecOrPanic(common.DefaultGitPrj, "submodule", "deinit", "--all", "--force")
|
git.GitExecQuietOrPanic(common.DefaultGitPrj, "submodule", "deinit", "--all", "--force")
|
||||||
if !common.IsDryRun {
|
if !common.IsDryRun {
|
||||||
git.GitExecOrPanic(common.DefaultGitPrj, "push")
|
git.GitExecOrPanic(common.DefaultGitPrj, "push")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if prjGitPR != nil {
|
||||||
common.LogDebug(" num of reviewers:", len(prjGitPR.PR.RequestedReviewers))
|
common.LogDebug(" num of reviewers:", len(prjGitPR.PR.RequestedReviewers))
|
||||||
|
} else {
|
||||||
|
common.LogInfo("* No prjgit")
|
||||||
|
}
|
||||||
maintainers, err := common.FetchProjectMaintainershipData(Gitea, org, repo, branch)
|
maintainers, err := common.FetchProjectMaintainershipData(Gitea, org, repo, branch)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
// handle case where PrjGit PR is only one left and there are no changes, then we can just close the PR
|
// handle case where PrjGit PR is only one left and there are no changes, then we can just close the PR
|
||||||
if len(prset.PRs) == 1 && prset.PRs[0] == prjGitPR && prjGitPR.PR.User.UserName == prset.BotUser {
|
if len(prset.PRs) == 1 && prjGitPR != nil && prset.PRs[0] == prjGitPR && prjGitPR.PR.User.UserName == prset.BotUser {
|
||||||
common.LogDebug(" --> checking if superflous PR")
|
common.LogDebug(" --> checking if superflous PR")
|
||||||
diff, err := git.GitDiff(common.DefaultGitPrj, prjGitPR.PR.MergeBase, prjGitPR.PR.Head.Sha)
|
diff, err := git.GitDiff(common.DefaultGitPrj, prjGitPR.PR.MergeBase, prjGitPR.PR.Head.Sha)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -500,7 +537,6 @@ func (pr *PRProcessor) Process(req *models.PullRequest) error {
|
|||||||
common.LogDebug(" --> NOT superflous PR")
|
common.LogDebug(" --> NOT superflous PR")
|
||||||
}
|
}
|
||||||
|
|
||||||
prset.AssignReviewers(Gitea, maintainers)
|
|
||||||
for _, pr := range prset.PRs {
|
for _, pr := range prset.PRs {
|
||||||
if err := verifyRepositoryConfiguration(pr.PR.Base.Repo); err != nil {
|
if err := verifyRepositoryConfiguration(pr.PR.Base.Repo); err != nil {
|
||||||
common.LogError("Cannot set manual merge... aborting processing")
|
common.LogError("Cannot set manual merge... aborting processing")
|
||||||
@@ -515,8 +551,9 @@ func (pr *PRProcessor) Process(req *models.PullRequest) error {
|
|||||||
if err = prset.Merge(Gitea, git); err != nil {
|
if err = prset.Merge(Gitea, git); err != nil {
|
||||||
common.LogError("merge error:", err)
|
common.LogError("merge error:", err)
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
prset.AssignReviewers(Gitea, maintainers)
|
||||||
}
|
}
|
||||||
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user