diff --git a/cmd/drone-docker/main.go b/cmd/drone-docker/main.go index 3a1247f..a7462b2 100644 --- a/cmd/drone-docker/main.go +++ b/cmd/drone-docker/main.go @@ -192,6 +192,11 @@ func main() { Usage: "docker email", EnvVar: "PLUGIN_EMAIL,DOCKER_EMAIL", }, + cli.StringFlag{ + Name: "repo.branch", + Usage: "repository default branch", + EnvVar: "DRONE_REPO_BRANCH", + }, } if err := app.Run(os.Args); err != nil { @@ -240,10 +245,19 @@ func run(c *cli.Context) error { } if c.Bool("tags.auto") { - plugin.Build.Tags = docker.DefaultTagSuffix( + if docker.UseDefaultTag( // return true if tag event or default branch c.String("commit.ref"), - c.String("tags.suffix"), - ) + c.String("repo.branch"), + ) { + plugin.Build.Tags = docker.DefaultTagSuffix( + c.String("commit.ref"), + c.String("tags.suffix"), + ) + } else { + logrus.Printf("skipping automated docker build for %s", c.String("commit.ref")) + + return nil + } } return plugin.Exec() diff --git a/docker.go b/docker.go index e7ca7e0..30faeeb 100644 --- a/docker.go +++ b/docker.go @@ -60,6 +60,24 @@ type ( } ) +func stripHeadPrefix(ref string) string { + ref = strings.TrimPrefix(ref, "refs/heads/") + return ref +} + +// UseDefaultTag for keep only default branch for latest tag +func UseDefaultTag(ref, defaultBranch string) bool { + if strings.HasPrefix(ref, "refs/tags/") { + return true + } + + if stripHeadPrefix(ref) == defaultBranch { + return true + } + + return false +} + // Exec executes the plugin step func (p Plugin) Exec() error { // start the Docker daemon server diff --git a/docker_test.go b/docker_test.go new file mode 100644 index 0000000..7781593 --- /dev/null +++ b/docker_test.go @@ -0,0 +1,67 @@ +package docker + +import "testing" + +func Test_stripHeadPrefix(t *testing.T) { + type args struct { + ref string + } + tests := []struct { + args args + want string + }{ + { + args: args{ + ref: "refs/heads/master", + }, + want: "master", + }, + } + for _, tt := range tests { + if got := stripHeadPrefix(tt.args.ref); got != tt.want { + t.Errorf("stripHeadPrefix() = %v, want %v", got, tt.want) + } + } +} + +func TestUseDefaultTag(t *testing.T) { + type args struct { + ref string + defaultBranch string + } + tests := []struct { + name string + args args + want bool + }{ + { + name: "latest tag for default branch", + args: args{ + ref: "refs/heads/master", + defaultBranch: "master", + }, + want: true, + }, + { + name: "build from tags", + args: args{ + ref: "refs/tags/v1.0.0", + defaultBranch: "master", + }, + want: true, + }, + { + name: "skip build for not default branch", + args: args{ + ref: "refs/heads/develop", + defaultBranch: "master", + }, + want: false, + }, + } + for _, tt := range tests { + if got := UseDefaultTag(tt.args.ref, tt.args.defaultBranch); got != tt.want { + t.Errorf("%q. UseDefaultTag() = %v, want %v", tt.name, got, tt.want) + } + } +}