Skip to content

Commit

Permalink
Support -v flag to print version
Browse files Browse the repository at this point in the history
If binary is called with -v, --v, -version, --version flags, or with a
single "version" argument, print line with program version to stdout and
exit with 0 code.

Closes #12
  • Loading branch information
artyom committed Dec 19, 2019
1 parent 49f0319 commit bacc614
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
4 changes: 3 additions & 1 deletion .github/workflows/docker.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,9 @@ jobs:
steps:
- uses: actions/checkout@v1
- name: Build image
run: docker build . --tag image
run: |
echo ${GITHUB_REF##*/} | tee ci-version.txt
docker build . --tag image
- name: Log into registry
run: echo "${{ secrets.GITHUB_TOKEN }}" | docker login docker.pkg.github.com -u ${GITHUB_ACTOR} --password-stdin
- name: Push image
Expand Down
6 changes: 5 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ ENV GOPROXY=https://proxy.golang.org CGO_ENABLED=0
COPY go.mod go.sum ./
RUN go mod download
COPY . ./
RUN go build -ldflags='-s -w' -o bitmapist-server && upx --lzma bitmapist-server
RUN test -s ci-version.txt && \
go build -ldflags='-s -w' -o bitmapist-server \
-ldflags="-X=main.explicitVersion=$(cat ci-version.txt)" || \
go build -ldflags='-s -w' -o bitmapist-server \
&& upx --lzma bitmapist-server

FROM scratch
COPY --from=builder /app/bitmapist-server .
Expand Down
18 changes: 18 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@ package main

import (
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"os/signal"
"path/filepath"
"runtime/debug"
"syscall"
"time"

Expand All @@ -16,6 +18,8 @@ import (
"github.com/artyom/red"
)

var explicitVersion string // to be set by CI with -ldflags="-X=main.explicitVersion=v1.2.3"

func main() {
args := struct {
Addr string `flag:"addr,address to listen"`
Expand All @@ -27,7 +31,21 @@ func main() {
File: "bitmapist.db",
}
autoflags.Define(&args)
var versionOnly bool
flag.BoolVar(&versionOnly, "v", versionOnly, "print version and exit")
flag.BoolVar(&versionOnly, "version", versionOnly, "print version and exit")
flag.Parse()
if versionOnly || (len(os.Args) == 2 && os.Args[1] == "version") {
v := "unknown"
if explicitVersion != "" {
v = explicitVersion
} else if bi, ok := debug.ReadBuildInfo(); ok {
v = bi.Main.Version
}
fmt.Printf("bitmapist-server %s\n", v)
return
}

log := log.New(os.Stderr, "", log.LstdFlags)

log.Println("loading data from", args.File)
Expand Down

0 comments on commit bacc614

Please sign in to comment.