Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
FROM golang:1.27.0 AS binary
FROM golang:1.27.2 AS binary

WORKDIR /go/src/github.com/jwilder/dockerize
COPY *.go go.* /go/src/github.com/jwilder/dockerize/
Expand Down
3 changes: 1 addition & 2 deletions e2e/e2e_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,7 @@ func TestExitCodePassthrough(t *testing.T) {
if err == nil {
t.Fatalf("expected non-zero exit")
}
var exitErr *exec.ExitError
if errors.As(err, &exitErr) {
if exitErr, ok := errors.AsType[*exec.ExitError](err); ok {
if exitErr.ExitCode() != tt.exitCode {
t.Fatalf("expected exit code %d, got %d", tt.exitCode, exitErr.ExitCode())
}
Expand Down
10 changes: 3 additions & 7 deletions exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,7 @@ func runCmd(ctx context.Context, cancel context.CancelFunc, cmd string, args ...
signal.Notify(sigs, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM)
waitDone := make(chan struct{})

wg.Add(1)
go func() {
defer wg.Done()

wg.Go(func() {
select {
case sig := <-sigs:
log.Printf("Received signal: %s\n", sig)
Expand All @@ -42,7 +39,7 @@ func runCmd(ctx context.Context, cancel context.CancelFunc, cmd string, args ...
case <-ctx.Done():
// exit when context is done
}
}()
})

err = process.Wait()
close(waitDone)
Expand All @@ -53,8 +50,7 @@ func runCmd(ctx context.Context, cancel context.CancelFunc, cmd string, args ...
} else {
log.Printf("Command exited with error: %s\n", err)

var exitErr *exec.ExitError
if errors.As(err, &exitErr) {
if exitErr, ok := errors.AsType[*exec.ExitError](err); ok {
if status, ok := exitErr.Sys().(syscall.WaitStatus); ok {
os.Exit(status.ExitStatus())
}
Expand Down
15 changes: 13 additions & 2 deletions exec_error_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"errors"
"fmt"
"os/exec"
"syscall"
"testing"
Expand All @@ -13,8 +14,7 @@ func extractExitCode(err error) int {
return 0
}

var exitErr *exec.ExitError
if errors.As(err, &exitErr) {
if exitErr, ok := errors.AsType[*exec.ExitError](err); ok {
if status, ok := exitErr.Sys().(syscall.WaitStatus); ok {
return status.ExitStatus()
}
Expand All @@ -37,6 +37,17 @@ func TestExtractExitCode_FromExitError(t *testing.T) {
}
}

func TestExtractExitCode_FromWrappedExitError(t *testing.T) {
cmd := exec.Command("sh", "-c", "exit 3")
exitErr := cmd.Run()

err := fmt.Errorf("run: %w", exitErr)
code := extractExitCode(err)
if code != 3 {
t.Fatalf("expected exit code 3, got %d", code)
}
}

func TestExtractExitCode_FromGenericError(t *testing.T) {
err := errors.New("some generic error")

Expand Down
18 changes: 6 additions & 12 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,9 +138,7 @@ func waitForDependencies() {
}

func waitForFile(u url.URL) {
wg.Add(1)
go func() {
defer wg.Done()
wg.Go(func() {
ticker := time.NewTicker(waitRetryInterval)
defer ticker.Stop()
var err error
Expand All @@ -158,17 +156,15 @@ func waitForFile(u url.URL) {
log.Printf("Problem with check file %s exist: %v. Sleeping %s\n", u.String(), err.Error(), waitRetryInterval)
}
}
}()
})
}

func waitForHTTP(u url.URL) {
wg.Add(1)
go func() {
wg.Go(func() {
client := &http.Client{
Timeout: waitTimeoutFlag,
}

defer wg.Done()
for {
req, err := http.NewRequest("GET", u.String(), nil)
if err != nil {
Expand All @@ -195,13 +191,11 @@ func waitForHTTP(u url.URL) {
time.Sleep(waitRetryInterval)
}
}
}()
})
}

func waitForSocket(scheme, addr string, timeout time.Duration) {
wg.Add(1)
go func() {
defer wg.Done()
wg.Go(func() {
for {
conn, err := dialTimeout(scheme, addr, timeout)
if err != nil {
Expand All @@ -214,7 +208,7 @@ func waitForSocket(scheme, addr string, timeout time.Duration) {
return
}
}
}()
})
}

func usage() {
Expand Down
31 changes: 31 additions & 0 deletions main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -408,6 +408,37 @@ func TestWaitForSocketConnectsToTCPServer(t *testing.T) {
assert.Contains(t, logs.String(), "Connected to tcp://"+ln.Addr().String())
}

func TestWaitForFileReturnsWhenFileCreatedAfterDelay(t *testing.T) {
readyFile := filepath.Join(t.TempDir(), "ready.txt")

oldRetry := waitRetryInterval
wg = sync.WaitGroup{}
waitRetryInterval = 10 * time.Millisecond
defer func() {
wg = sync.WaitGroup{}
waitRetryInterval = oldRetry
}()

go func() {
time.Sleep(200 * time.Millisecond)
_ = os.WriteFile(readyFile, []byte("ready"), 0o644)
}()

waitForFile(url.URL{Scheme: "file", Path: readyFile})

done := make(chan struct{})
go func() {
wg.Wait()
close(done)
}()

select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatal("timed out waiting for file to be created")
}
}

func TestWaitForDependenciesWaitsForFileAndHTTP(t *testing.T) {
tmpDir := t.TempDir()
readyFile := filepath.Join(tmpDir, "ready.txt")
Expand Down
15 changes: 10 additions & 5 deletions template.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"log"
"maps"
"net/url"
"os"
"path/filepath"
Expand Down Expand Up @@ -126,7 +127,9 @@ func loop(args ...int) (<-chan int, error) {
return c, nil
}

func generateFile(templatePath, destPath string) bool {
// templateFuncMap returns sprig's functions with dockerize's own functions
// merged over them, so a dockerize function wins when both define the same name.
func templateFuncMap() template.FuncMap {
templateMap := template.FuncMap{
"contains": contains,
"exists": exists,
Expand All @@ -144,10 +147,12 @@ func generateFile(templatePath, destPath string) bool {
}

combinedFuncMap := sprig.TxtFuncMap()
for k, v := range templateMap {
combinedFuncMap[k] = v
}
tmpl := template.New(filepath.Base(templatePath)).Funcs(combinedFuncMap)
maps.Copy(combinedFuncMap, templateMap)
return combinedFuncMap
}

func generateFile(templatePath, destPath string) bool {
tmpl := template.New(filepath.Base(templatePath)).Funcs(templateFuncMap())

if len(delims) > 0 {
tmpl = tmpl.Delims(delims[0], delims[1])
Expand Down
31 changes: 31 additions & 0 deletions template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package main
import (
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
"syscall"
"testing"
Expand Down Expand Up @@ -319,3 +321,32 @@ func TestGenerateFileWritesFullContentAndKeepsMode(t *testing.T) {
}
}
}

func TestTemplateFuncMapDockerizeOverridesSprig(t *testing.T) {
merged := templateFuncMap()

dockerizeFuncs := map[string]any{
"contains": contains,
"exists": exists,
"split": strings.Split,
"replace": strings.Replace,
"default": defaultValue,
"parseUrl": parseUrl,
"atoi": strconv.Atoi,
"add": add,
"isTrue": isTrue,
"lower": strings.ToLower,
"upper": strings.ToUpper,
"jsonQuery": jsonQuery,
"loop": loop,
}
for name, fn := range dockerizeFuncs {
got, ok := merged[name]
if !ok {
t.Fatalf("%s missing from merged func map", name)
}
if reflect.ValueOf(got).Pointer() != reflect.ValueOf(fn).Pointer() {
t.Errorf("%s: merged map does not hold dockerize's function", name)
}
}
}
102 changes: 102 additions & 0 deletions toolchain_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
package main

import (
"os"
"regexp"
"strings"
"testing"
)

var (
goModToolchainRe = regexp.MustCompile(`(?m)^\s*toolchain\s+go(\S+)`)
goModGoRe = regexp.MustCompile(`(?m)^\s*go\s+(\S+)`)
dockerfileGoRe = regexp.MustCompile(`(?im)^\s*FROM\s+golang:([^\s-]+)`)
)

// goModVersion returns the toolchain directive from go.mod content if present,
// otherwise the go directive.
func goModVersion(content string) (string, bool) {
if m := goModToolchainRe.FindStringSubmatch(content); m != nil {
return m[1], true
}
if m := goModGoRe.FindStringSubmatch(content); m != nil {
return m[1], true
}
return "", false
}

// dockerfileGoVersion returns the version part of the first golang image tag
// in the Dockerfile content, dropping any suffix such as "-alpine".
func dockerfileGoVersion(content string) (string, bool) {
if m := dockerfileGoRe.FindStringSubmatch(content); m != nil {
return m[1], true
}
return "", false
}

func TestDockerfileGoVersionMatchesGoMod(t *testing.T) {
goMod, err := os.ReadFile("go.mod")
if err != nil {
t.Fatalf("reading go.mod: %v", err)
}
dockerfile, err := os.ReadFile("Dockerfile")
if err != nil {
t.Fatalf("reading Dockerfile: %v", err)
}

modVersion, ok := goModVersion(string(goMod))
if !ok {
t.Fatal("no go or toolchain directive found in go.mod")
}
imageVersion, ok := dockerfileGoVersion(string(dockerfile))
if !ok {
t.Fatal("no FROM golang:<tag> line found in Dockerfile")
}
if modVersion != imageVersion {
t.Errorf("Dockerfile uses golang:%s but go.mod requires %s", imageVersion, modVersion)
}
}

func TestGoModVersion(t *testing.T) {
tests := []struct {
name string
content string
want string
wantOK bool
}{
{"go directive", "module x\n\ngo 1.27.2\n", "1.27.2", true},
{"toolchain overrides go", "module x\n\ngo 1.27.0\ntoolchain go1.27.2\n", "1.27.2", true},
{"no directive", "module x\n", "", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, ok := goModVersion(tt.content)
if ok != tt.wantOK || got != tt.want {
t.Errorf("goModVersion() = %q, %v; want %q, %v", got, ok, tt.want, tt.wantOK)
}
})
}
}

func TestDockerfileGoVersion(t *testing.T) {
tests := []struct {
name string
content string
want string
wantOK bool
}{
{"plain tag", "FROM golang:1.27.2 AS binary\n", "1.27.2", true},
{"alpine suffix", "FROM golang:1.27.2-alpine AS binary\n", "1.27.2", true},
{"lowercase keyword", "from golang:1.27.2\n", "1.27.2", true},
{"no golang image", "FROM gcr.io/distroless/static:nonroot\n", "", false},
{"golang mentioned mid-line", "# uses golang:1.27.2\n", "", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, ok := dockerfileGoVersion(strings.TrimSpace(tt.content))
if ok != tt.wantOK || got != tt.want {
t.Errorf("dockerfileGoVersion() = %q, %v; want %q, %v", got, ok, tt.want, tt.wantOK)
}
})
}
}
Loading