Skip to content

Commit

Permalink
Cosmetic changes (#44)
Browse files Browse the repository at this point in the history
* Cosmetic changes

* codecov config added

* Changelog updated
  • Loading branch information
tarampampam authored Apr 8, 2021
1 parent 503409a commit ddeec10
Show file tree
Hide file tree
Showing 20 changed files with 298 additions and 114 deletions.
26 changes: 26 additions & 0 deletions .codecov.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Docs: <https://docs.codecov.io/docs/commit-status>

coverage:
# coverage lower than 50 is red, higher than 90 green
range: 30..80

status:
project:
default:
# Choose a minimum coverage ratio that the commit must meet to be considered a success.
#
# `auto` will use the coverage from the base commit (pull request base or parent commit) coverage to compare
# against.
target: auto

# Allow the coverage to drop by X%, and posting a success status.
threshold: 5%

# Resulting status will pass no matter what the coverage is or what other settings are specified.
informational: true

patch:
default:
target: auto
threshold: 5%
informational: true
11 changes: 10 additions & 1 deletion .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,11 @@ on:
- master
tags-ignore:
- '**'
paths-ignore:
- '**.md'
pull_request:
paths-ignore:
- '**.md'

jobs:
golangci-lint:
Expand All @@ -19,7 +23,7 @@ jobs:
- name: Run linter
uses: golangci/golangci-lint-action@v2 # Action page: <https://github.com/golangci/golangci-lint-action>
with:
version: v1.33 # without patch version
version: v1.38 # without patch version
only-new-issues: false # show only new issues if it's a pull request

gitleaks:
Expand Down Expand Up @@ -54,6 +58,8 @@ jobs:

- name: Check out code
uses: actions/checkout@v2
with:
fetch-depth: 2 # Fixes codecov error 'Issue detecting commit SHA'

- name: Go modules Cache # Docs: <https://git.io/JfAKn#go---modules>
uses: actions/cache@v2
Expand Down Expand Up @@ -84,6 +90,9 @@ jobs:
matrix:
os: [linux, windows, darwin] # linux, freebsd, darwin, windows
arch: [amd64] # amd64, 386
include:
- os: linux
arch: 386
needs: [golangci-lint, go-test]
steps:
- name: Set up Go
Expand Down
17 changes: 1 addition & 16 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,6 @@ linters-settings:
locale: US
lll:
line-length: 120
maligned:
suggest-new: true
prealloc:
simple: true
range-loops: true
Expand All @@ -52,56 +50,42 @@ linters: # All available linters list: <https://golangci-lint.run/usage/linters/
- errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases
- errorlint # find code that will cause problems with the error wrapping scheme introduced in Go 1.13
- exhaustive # check exhaustiveness of enum switch statements
#- exhaustivestruct # Checks if all struct's fields are initialized
- exportloopref # checks for pointers to enclosing loop variables
- funlen # Tool for detection of long functions
#- gci # Gci control golang package import order and make it always deterministic
- gochecknoglobals # Checks that no globals are present in Go code
- gochecknoinits # Checks that no init functions are present in Go code
- gocognit # Computes and checks the cognitive complexity of functions
- goconst # Finds repeated strings that could be replaced by a constant
- gocritic # The most opinionated Go source code linter
- gocyclo # Computes and checks the cyclomatic complexity of functions
- godox # Tool for detection of FIXME, TODO and other comment keywords
#- goerr113 # Golang linter to check the errors handling expressions
- gofmt # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification
#- gofumpt # Gofumpt checks whether code was gofumpt-ed
#- goheader # Checks is file header matches to pattern
- goimports # Goimports does everything that gofmt does. Additionally it checks unused imports
- golint # Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes
- gomnd # An analyzer to detect magic numbers
#- gomodguard # Allow and block list linter for direct Go module dependencies
- goprintffuncname # Checks that printf-like functions are named with `f` at the end
- gosec # Inspects source code for security problems
- gosimple # Linter for Go source code that specializes in simplifying a code
- govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string
- ineffassign # Detects when assignments to existing variables are not used
- interfacer # Linter that suggests narrower interface types
- lll # Reports long lines
- maligned # Tool to detect Go structs that would take less memory if their fields were sorted
- misspell # Finds commonly misspelled English words in comments
- nakedret # Finds naked returns in functions greater than a specified function length
- nestif # Reports deeply nested if statements
- nlreturn # checks for a new line before return and branch statements to increase code clarity
- noctx # finds sending http request without context.Context
- nolintlint # Reports ill-formed or insufficient nolint directives
#- paralleltest # detects missing usage of t.Parallel() method in your Go test
- prealloc # Finds slice declarations that could potentially be preallocated
- rowserrcheck # Checks whether Err of rows is checked successfully
- scopelint # Scopelint checks for unpinned variables in go programs
#- sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed
- staticcheck # Staticcheck is a go vet on steroids, applying a ton of static analysis checks
- structcheck # Finds unused struct fields
- stylecheck # Stylecheck is a replacement for golint
#- testpackage # linter that makes you use a separate _test package
- tparallel # detects inappropriate usage of t.Parallel() method in your Go test codes
- typecheck # Like the front-end of a Go compiler, parses and type-checks Go code
- unconvert # Remove unnecessary type conversions
- unparam # Reports unused function parameters
- unused # Checks Go code for unused constants, variables, functions and types
- varcheck # Finds unused global variables and constants
- whitespace # Tool for detection of leading and trailing whitespace
#- wrapcheck # Checks that errors returned from external packages are wrapped
- wsl # Whitespace Linter - Forces you to use empty lines!

issues:
Expand All @@ -112,3 +96,4 @@ issues:
- funlen
- scopelint
- gocognit
- noctx
6 changes: 5 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog][keepachangelog] and this project adheres to [Semantic Versioning][semver].

## UNRELEASED
## v3.3.0

### Added

- Global flag `--debug`

### Changed

Expand Down
33 changes: 14 additions & 19 deletions cmd/tinifier/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,31 +5,26 @@ import (
"os"
"path/filepath"

"github.com/fatih/color"
"github.com/tarampampam/tinifier/v3/internal/pkg/cli"

"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)

func main() {
var atomicLogLevel, logEncoderConfig = zap.NewAtomicLevel(), zap.NewDevelopmentEncoderConfig()

logEncoderConfig.EncodeLevel = zapcore.LowercaseColorLevelEncoder
logEncoderConfig.EncodeTime = zapcore.TimeEncoderOfLayout("15:04:05")

logger := zap.New(zapcore.NewCore(
zapcore.NewConsoleEncoder(logEncoderConfig),
zapcore.Lock(os.Stdout),
atomicLogLevel,
))
// exitFn is a function for application exiting.
var exitFn = os.Exit //nolint:gochecknoglobals

defer func() {
_ = logger.Sync()
}()
// main CLI application entrypoint.
func main() { exitFn(run()) }

var cmd = cli.NewCommand(logger, &atomicLogLevel, filepath.Base(os.Args[0]))
// run this CLI application.
// Exit codes documentation: <https://tldp.org/LDP/abs/html/exitcodes.html>
func run() int {
cmd := cli.NewCommand(filepath.Base(os.Args[0]))

if err := cmd.Execute(); err != nil {
logger.Fatal(err.Error()) // `os.Exit(1)` here
_, _ = color.New(color.FgHiRed, color.Bold).Fprintln(os.Stderr, err.Error())

return 1
}

return 0
}
45 changes: 15 additions & 30 deletions cmd/tinifier/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,53 +4,38 @@ import (
"os"
"testing"

"bou.ke/monkey"
"github.com/kami-zh/go-capturer"
"github.com/stretchr/testify/assert"
)

func Test_Main(t *testing.T) {
origFlags := make([]string, 0)
origFlags = append(origFlags, os.Args...)

defer func() { os.Args = origFlags }()

os.Args = []string{"", "--help"}
exitFn = func(code int) { assert.Equal(t, 0, code) }

output := capturer.CaptureStdout(func() {
main()
})
output := capturer.CaptureStdout(main)

assert.Contains(t, output, "Usage:")
assert.Contains(t, output, "Available Commands:")
assert.Contains(t, output, "Flags:")
}

func Test_MainWrongCommand(t *testing.T) {
origFlags := make([]string, 0)
origFlags = append(origFlags, os.Args...)

defer func() { os.Args = origFlags }()

var (
osExitGuard *monkey.PatchGuard
exitCode int = 666
)
func Test_MainWithoutCommands(t *testing.T) {
os.Args = []string{""}
exitFn = func(code int) { assert.Equal(t, 0, code) }

osExitGuard = monkey.Patch(os.Exit, func(code int) {
osExitGuard.Unpatch()
defer osExitGuard.Restore()
output := capturer.CaptureStdout(main)

exitCode = code
})
assert.Contains(t, output, "Usage:")
assert.Contains(t, output, "Available Commands:")
assert.Contains(t, output, "Flags:")
}

os.Args = []string{"", "foo bar"}
func Test_MainUnknownSubcommand(t *testing.T) {
os.Args = []string{"", "foobar"}
exitFn = func(code int) { assert.Equal(t, 1, code) }

output := capturer.CaptureStdout(func() {
main()
})
output := capturer.CaptureStderr(main)

assert.Contains(t, output, "unknown command")
assert.Contains(t, output, "foo bar")
assert.Equal(t, 1, exitCode)
assert.Contains(t, output, "foobar")
}
2 changes: 1 addition & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ services:
- tmp-data:/tmp:cached

golint:
image: golangci/golangci-lint:v1.33-alpine # Image page: <https://hub.docker.com/r/golangci/golangci-lint>
image: golangci/golangci-lint:v1.39-alpine # Image page: <https://hub.docker.com/r/golangci/golangci-lint>
volumes:
- .:/src:ro
working_dir: /src
Expand Down
3 changes: 2 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
module github.com/tarampampam/tinifier/v3

go 1.15
go 1.16

require (
bou.ke/monkey v1.0.2
github.com/dustin/go-humanize v1.0.0
github.com/fatih/color v1.7.0
github.com/kami-zh/go-capturer v0.0.0-20171211120116-e492ea43421d
github.com/olekukonko/tablewriter v0.0.5
github.com/pkg/errors v0.9.1
Expand Down
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZm
github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no=
github.com/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo=
github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
github.com/fatih/color v1.7.0 h1:DkWD4oS2D8LGGgTQ6IvwJJXSL5Vp2ffcQg58nFV38Ys=
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
Expand Down Expand Up @@ -113,7 +114,9 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
github.com/mattn/go-colorable v0.0.9 h1:UVL0vNpWh04HeJXV0KLcaT7r06gOH2l4OW6ddYRUIY4=
github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
github.com/mattn/go-isatty v0.0.3 h1:ns/ykhmWi7G9O+8a448SecJU3nSMBXJfqQkl0upE1jI=
github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/mattn/go-runewidth v0.0.9 h1:Lm995f3rfxdpd6TSmuVCHVb/QhupuXlYr8sCI/QdE+0=
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
Expand Down Expand Up @@ -253,6 +256,7 @@ golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0 h1:HyfiK1WMnHj5FXFXatD+Qs1A/xC2Run6RzeW1SyHxpc=
golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
Expand Down
17 changes: 7 additions & 10 deletions internal/pkg/cli/compress/command.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,15 @@ import (
"sync/atomic"
"time"

"github.com/spf13/cobra"
"github.com/tarampampam/tinifier/v3/internal/pkg/breaker"
"github.com/tarampampam/tinifier/v3/internal/pkg/env"
"github.com/tarampampam/tinifier/v3/internal/pkg/files"
"github.com/tarampampam/tinifier/v3/internal/pkg/keys"
"github.com/tarampampam/tinifier/v3/internal/pkg/pool"

"github.com/spf13/cobra"
"go.uber.org/zap"
)

const (
apiKeyEnvName = "TINYPNG_API_KEY"
apiKeyMinLength uint8 = 8
)

// NewCommand creates `compress` command.
func NewCommand(log *zap.Logger) *cobra.Command { //nolint:funlen
var (
Expand All @@ -51,13 +46,15 @@ func NewCommand(log *zap.Logger) *cobra.Command { //nolint:funlen
}

if len(apiKeys) == 0 {
if envAPIKey, exists := os.LookupEnv(apiKeyEnvName); exists {
if envAPIKey, exists := env.TinyPngAPIKey.Lookup(); exists {
apiKeys = append(apiKeys, envAPIKey)
} else {
return errors.New("API key was not provided")
}
}

const apiKeyMinLength uint8 = 8

for i := 0; i < len(apiKeys); i++ {
if uint8(len(apiKeys[i])) <= apiKeyMinLength {
return fmt.Errorf("API key (%s) is too short", apiKeys[i])
Expand Down Expand Up @@ -99,7 +96,7 @@ func NewCommand(log *zap.Logger) *cobra.Command { //nolint:funlen
[]string{}, // default
fmt.Sprintf(
"TinyPNG API key <https://tinypng.com/dashboard/api> (multiple keys are allowed) [$%s]",
apiKeyEnvName,
env.TinyPngAPIKey.String(),
),
)

Expand Down Expand Up @@ -176,7 +173,7 @@ func execute( //nolint:funlen
p := pool.NewPool(ctx, newWorker(
log,
&keeper,
5, //nolint:gomnd
5,
time.Millisecond*700, //nolint:gomnd
))

Expand Down
2 changes: 1 addition & 1 deletion internal/pkg/cli/compress/file_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func newFileInfo(path string) (*fileInfo, error) {

buf := make([]byte, 32) // 32 bytes are enough for images

if _, err := io.ReadFull(file, buf); err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, io.ErrUnexpectedEOF) {
if _, err = io.ReadFull(file, buf); err != nil && !errors.Is(err, io.EOF) && !errors.Is(err, io.ErrUnexpectedEOF) {
return nil, err
}

Expand Down
Loading

0 comments on commit ddeec10

Please sign in to comment.