Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: cli flags #3

Merged
merged 3 commits into from
Nov 30, 2021
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
27 changes: 27 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
name: release

on:
push:
tags: [ v* ]

jobs:
release:
runs-on: ubuntu-latest
steps:
- name: Set up Go
uses: actions/setup-go@v2
with:
go-version: 1.17

- name: Checkout code
uses: actions/checkout@v2
with:
fetch-depth: 0

- name: Run GoReleaser
uses: goreleaser/goreleaser-action@v2
with:
version: v1.0.0
args: release --rm-dist
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
9 changes: 9 additions & 0 deletions .goreleaser.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
builds:
- ldflags:
- -s -w -X main.appVersion={{.Version}}

release:
draft: true

changelog:
sort: asc
20 changes: 15 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
[![docs-img]][docs]
[![report-img]][report]
[![codecov-img]][codecov]
[![license-img]][license]
[![release-img]][release]

A dead simple CLI tool that prints the next semantic version based on the last tag of your git repository.

Expand All @@ -25,14 +27,18 @@ available commands:
print the next minor version
patch
print the next patch version
current
print the current version

available flags:
-debug
enable debug logs
-p string
shorthand for -prefix
-prefix string
consider only prefixed tags. also, will be used to print the result
consider only prefixed tags (also, will be used to print the result)
-v
shorthand for -verbose
-verbose
print additional information to stderr
-version
print the app version
```

[ci]: https://github.com/junk1tm/nextver/actions/workflows/go.yml
Expand All @@ -43,3 +49,7 @@ available flags:
[report-img]: https://goreportcard.com/badge/github.com/junk1tm/nextver
[codecov]: https://codecov.io/gh/junk1tm/nextver
[codecov-img]: https://codecov.io/gh/junk1tm/nextver/branch/main/graph/badge.svg
[license]: https://github.com/junk1tm/nextver/blob/main/LICENSE
[license-img]: https://img.shields.io/github/license/junk1tm/nextver
[release]: https://github.com/junk1tm/nextver/releases
[release-img]: https://img.shields.io/github/v/release/junk1tm/nextver
84 changes: 51 additions & 33 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,35 +15,38 @@ import (
"strings"
)

// available commands:
const (
majorCmd = "major"
minorCmd = "minor"
patchCmd = "patch"
currentCmd = "current"
)

// available flags:
var (
debug bool
prefix string
)
// appVersion is injected at build time.
var appVersion = "dev"

func main() {
var prefix string
flag.StringVar(&prefix, "p", "", "shorthand for -prefix")
flag.StringVar(&prefix, "prefix", "", "consider only prefixed tags (also, will be used to print the result)")

var verbose bool
flag.BoolVar(&verbose, "v", false, "\nshorthand for -verbose")
flag.BoolVar(&verbose, "verbose", false, "print additional information to stderr")

var version bool
flag.BoolVar(&version, "version", false, "print the app version")

flag.Usage = usage
flag.BoolVar(&debug, "debug", false, "enable debug logs")
flag.StringVar(&prefix, "prefix", "", "consider only prefixed tags. also, will be used to print the result")
flag.Parse()

if version {
fmt.Fprintf(os.Stderr, "%s version %s\n", os.Args[0], appVersion)
os.Exit(0)
}

log.SetFlags(0)
log.SetOutput(io.Discard)
log.SetPrefix(os.Args[0] + ": ")
if debug {
if verbose {
log.SetOutput(os.Stderr)
}

if err := run(); err != nil {
fmt.Fprintln(os.Stderr, err)
if err := run(prefix); err != nil {
fmt.Fprintf(os.Stderr, "%s: %s\n", os.Args[0], err)
if errors.As(err, new(usageError)) {
usage()
os.Exit(2)
Expand All @@ -52,6 +55,12 @@ func main() {
}
}

const (
majorCmd = "major"
minorCmd = "minor"
patchCmd = "patch"
)

func usage() {
fmt.Fprintf(os.Stderr, "usage: %s [flags] <command>\n", os.Args[0])

Expand All @@ -61,20 +70,12 @@ func usage() {
fmt.Fprintf(os.Stderr, " %s\n", cmd)
fmt.Fprintf(os.Stderr, "\tprint the next %s version\n", cmd)
}
fmt.Fprintf(os.Stderr, " %s\n", currentCmd)
fmt.Fprintf(os.Stderr, "\tprint the current version\n")

fmt.Fprintf(os.Stderr, "\navailable flags:\n")
flag.PrintDefaults()
}

// usageError is a wrapper for error to indicate the need for usage printing.
type usageError struct{ err error }

func (e usageError) Error() string { return e.err.Error() }
func (e usageError) Unwrap() error { return e.err }

func run() error {
func run(prefix string) error {
if flag.NArg() == 0 {
return usageError{errors.New("no command has been provided")}
}
Expand All @@ -87,24 +88,28 @@ func run() error {
printVersion = func(v version) { fmt.Print(prefix, v.nextMinor()) }
case patchCmd:
printVersion = func(v version) { fmt.Print(prefix, v.nextPatch()) }
case currentCmd:
printVersion = func(v version) { fmt.Print(prefix, v) }
default:
return usageError{fmt.Errorf("unknown command %q", cmd)}
}

ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()

var buf bytes.Buffer
var stdout, stderr bytes.Buffer
cmd := exec.CommandContext(ctx, "git", "tag", "--sort=-version:refname")
cmd.Stdout = &buf
cmd.Stdout = &stdout
cmd.Stderr = &stderr

if err := cmd.Run(); err != nil {
if stderr.Len() != 0 {
return fmt.Errorf("running %q: %s", "git tag", strings.TrimSpace(stderr.String()))
}
return fmt.Errorf("running %q: %w", "git tag", err)
}

scanner := bufio.NewScanner(&buf)
var current version

scanner := bufio.NewScanner(&stdout)
for scanner.Scan() {
line := scanner.Text()
if !strings.HasPrefix(line, prefix) {
Expand All @@ -119,12 +124,25 @@ func run() error {
continue
}

printVersion(v)
current = v
break
}
if err := scanner.Err(); err != nil {
return fmt.Errorf("reading %q output: %w", "git tag", err)
}

if current.isZero() {
return fmt.Errorf("no version in the form %q has been found", prefix+"x.y.z")
}

log.Printf("the current version is %q", prefix+current.String())
printVersion(current)

return nil
}

// usageError is a wrapper for error to indicate the need to print usage.
type usageError struct{ err error }

func (e usageError) Error() string { return e.err.Error() }
func (e usageError) Unwrap() error { return e.err }
17 changes: 9 additions & 8 deletions version.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ import (
)

var (
errWrongNumbersCount = errors.New("semver must have exactly 3 numbers")
errNegativeNumber = errors.New("all semver numbers must be non-negative")
errInvalidFormat = errors.New("semantic version must have exactly 3 numbers")
errNegativeNumber = errors.New("all semantic version numbers must be non-negative")
)

// version is a parsed semantic version.
Expand All @@ -26,10 +26,10 @@ type version struct {
func parseVersion(s string) (version, error) {
parts := strings.Split(s, ".")
if len(parts) != 3 {
return version{}, errWrongNumbersCount
return version{}, errInvalidFormat
}

var numbs []int
var numbers []int
for _, p := range parts {
n, err := strconv.Atoi(p)
if err != nil {
Expand All @@ -38,13 +38,13 @@ func parseVersion(s string) (version, error) {
if n < 0 {
return version{}, errNegativeNumber
}
numbs = append(numbs, n)
numbers = append(numbers, n)
}

return version{
major: numbs[0],
minor: numbs[1],
patch: numbs[2],
major: numbers[0],
minor: numbers[1],
patch: numbers[2],
}, nil
}

Expand All @@ -54,3 +54,4 @@ func (v version) String() string { return fmt.Sprintf(format, v.major, v.mino
func (v version) nextMajor() string { return fmt.Sprintf(format, v.major+1, 0, 0) }
func (v version) nextMinor() string { return fmt.Sprintf(format, v.major, v.minor+1, 0) }
func (v version) nextPatch() string { return fmt.Sprintf(format, v.major, v.minor, v.patch+1) }
func (v version) isZero() bool { return v.major == 0 && v.minor == 0 && v.patch == 0 }
13 changes: 8 additions & 5 deletions version_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,19 @@ import (

func Test_version(t *testing.T) {
v := version{1, 2, 3}
if v.isZero() {
t.Fatalf("want %v to be non-zero", v)
}

tests := []struct {
name string
method func() string
want string
}{
{name: "string", method: v.String, want: "1.2.3"},
{name: "next_major", method: v.nextMajor, want: "2.0.0"},
{name: "next_minor", method: v.nextMinor, want: "1.3.0"},
{name: "next_patch", method: v.nextPatch, want: "1.2.4"},
{name: "next major", method: v.nextMajor, want: "2.0.0"},
{name: "next minor", method: v.nextMinor, want: "1.3.0"},
{name: "next patch", method: v.nextPatch, want: "1.2.4"},
}

for _, tt := range tests {
Expand All @@ -39,8 +42,8 @@ func Test_parseVersion(t *testing.T) {
}{
{name: "valid version", input: "1.2.3", want: version{1, 2, 3}, err: nil},
{name: "prefixed version", input: "v1.2.3", want: version{}, err: strconv.ErrSyntax},
{name: "non numeric version", input: "x.y.z", want: version{}, err: strconv.ErrSyntax},
{name: "wrong numbers count", input: "1.2.3.4", want: version{}, err: errWrongNumbersCount},
{name: "non-numeric version", input: "x.y.z", want: version{}, err: strconv.ErrSyntax},
{name: "invalid format", input: "1.2.3.4", want: version{}, err: errInvalidFormat},
{name: "negative number", input: "-1.2.3", want: version{}, err: errNegativeNumber},
}

Expand Down