Skip to content

Commit

Permalink
refactor: maximize test coverage, improve -h output
Browse files Browse the repository at this point in the history
* refactor: flags

* refactor: process.File

* refactor: remove process.getLicense()

* refactor: files, fileHandler, tests

* refactor: consolidate everything into process pkg

* test: process.File + fix channel mgmt

* chore: make channel buffered for performance
  • Loading branch information
lluissm authored Mar 12, 2020
1 parent d3cbf3a commit 56d800c
Show file tree
Hide file tree
Showing 17 changed files with 837 additions and 348 deletions.
9 changes: 7 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
.PHONY: all clean build test test-e2e install cross-build cross-pack

all: build test
all: build test-e2e test

BIN_PATH = bin
VERSION = $(shell git describe --tags)
CMD = license-header-checker
BUILD_PATH = ./cmd/$(CMD)
LD_FLAGS = -ldflags="-X 'github.com/lsm-dev/license-header-checker/internal/config.version=${VERSION}'"
LD_FLAGS = -ldflags="-X 'main.version=${VERSION}'"

clean:
@echo "=> Cleaning project"
Expand All @@ -22,6 +22,11 @@ test:
@echo "=> Running unit tests"
@go test -cover ./...

test-cover:
@echo "=> Running unit tests and checking coverage"
@go test -coverprofile=coverage.out ./...
@go tool cover -html=coverage.out

test-e2e: build
@echo "=> Executing end to end tests"
@cd test && bash test.sh ../$(BIN_PATH)/$(CMD)
Expand Down
9 changes: 7 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,17 @@ To **cross-compile** (generate the binaries for Linux, Windows and macOS all at
```bash
$ make cross-build
```
To run **unit** tests:
To run **unit tests**:

```bash
$ make test
```
To run **end-to-end** tests:
To see **unit test coverage**:

```bash
$ make test-cover
```
To run **end-to-end tests**:

```bash
$ make test-e2e
Expand Down
20 changes: 14 additions & 6 deletions cmd/license-header-checker/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,26 @@ package main

import (
"fmt"
"log"
"os"

"github.com/lsm-dev/license-header-checker/internal/config"
"github.com/lsm-dev/license-header-checker/internal/process"
)

var version string = "development"

func main() {
options := config.ParseOptions()
stats, err := process.Files(options)
options, err := parseOptions(os.Args)
if err != nil {
log.Fatal(err.Error())
}
if options.ShowVersion {
fmt.Printf("version: %s\n", version)
os.Exit(0)
}
stats, err := process.Files(options.Process)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
log.Fatal(err.Error())
}
printStats(stats, options)
printStats(options.Verbose, stats, options.Process)
}
106 changes: 106 additions & 0 deletions cmd/license-header-checker/options.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
/* MIT License
Copyright (c) 2020 Lluis Sanchez
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

package main

import (
"errors"
"flag"
"fmt"
"strings"

"github.com/lsm-dev/license-header-checker/internal/process"
)

// Options are the process.Options parsed from command line flags/args
type Options struct {
ShowVersion bool
Verbose bool
Process *process.Options
}

// parseOptions returns the parsed Options from command line flags/args
func parseOptions(osArgs []string) (*Options, error) {

flagSet := flag.NewFlagSet("lhc", flag.ExitOnError)
flagSet.Usage = func() {
fmt.Fprintf(flag.CommandLine.Output(), "\033[1;4mSYNOPSIS\033[0m\n\n")
fmt.Fprintf(flag.CommandLine.Output(), "license-header-checker [-a] [-r] [-v] [-i path1,...] license-header-path src-path extensions...\n\n")
fmt.Fprintf(flag.CommandLine.Output(), "\033[1;4mOPTIONS\033[0m\n\n")
flagSet.PrintDefaults()
fmt.Fprintf(flag.CommandLine.Output(), "\033[1;4mEXAMPLE\033[0m\n\n")
fmt.Fprintf(flag.CommandLine.Output(), "license-header-checker -a -r -v -i folder,ignore/path license-header-path project-src-path extension1 extension2\n\n")
}

addFlag := flagSet.Bool("a", false, "Add the target license in case the file does not have any.")
replaceFlag := flagSet.Bool("r", false, "Replace the existing license by the target one in case they are different.")
ignorePathsFlag := flagSet.String("i", "", "A comma separated list of the folders, files and/or paths that should be ignored. Does not support wildcards.")
verboseFlag := flagSet.Bool("v", false, "Be verbose during execution printing options, files being processed, execution time, ...")
showVersionFlag := flagSet.Bool("version", false, "Display version number")

flagSet.Parse(osArgs[1:])

args := flagSet.Args()

if *showVersionFlag {
return &Options{
true,
false,
nil,
}, nil
}

if len(args) < 3 {
return nil, errors.New("Missing arguments, please see documentation")
}

licensePath := args[0]
path := args[1]

extensions := []string{}
for _, e := range args[2:] {
extensions = append(extensions, "."+e)
}

ignorePaths := []string{}
for _, p := range strings.Split(*ignorePathsFlag, ",") {
if len(p) > 0 {
ignorePaths = append(ignorePaths, p)
}
}

processOptions := &process.Options{
Add: *addFlag,
Replace: *replaceFlag,
Path: path,
LicensePath: licensePath,
Extensions: extensions,
IgnorePaths: ignorePaths,
}

return &Options{
*showVersionFlag,
*verboseFlag,
processOptions,
}, nil
}
125 changes: 125 additions & 0 deletions cmd/license-header-checker/options_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
/* MIT License
Copyright (c) 2020 Lluis Sanchez
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

package main

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestErrorIfMissingArgs(t *testing.T) {
args := []string{"license-header-checker"}
_, err := parseOptions(args)
assert.NotNil(t, err)

args = []string{"license-header-checker", "license-path"}
_, err = parseOptions(args)
assert.NotNil(t, err)

args = []string{"license-header-checker", "license-path", "source-path"}
_, err = parseOptions(args)
assert.NotNil(t, err)

args = []string{"license-header-checker", "license-path", "source-path", "js"}
_, err = parseOptions(args)
assert.Nil(t, err)
}

func TestVersion(t *testing.T) {
args := []string{"license-header-checker", "-version", "license-path", "source-path", "js"}
options, _ := parseOptions(args)
assert.True(t, options.ShowVersion)

args = []string{"license-header-checker", "license-path", "source-path", "js"}
options, _ = parseOptions(args)
assert.False(t, options.ShowVersion)
}

func TestAdd(t *testing.T) {
args := []string{"license-header-checker", "-a", "license-path", "source-path", "js"}
options, _ := parseOptions(args)
assert.True(t, options.Process.Add)

args = []string{"license-header-checker", "license-path", "source-path", "js"}
options, _ = parseOptions(args)
assert.False(t, options.Process.Add)
}

func TestReplace(t *testing.T) {
args := []string{"license-header-checker", "-r", "license-path", "source-path", "js"}
options, _ := parseOptions(args)
assert.True(t, options.Process.Replace)

args = []string{"license-header-checker", "license-path", "source-path", "js"}
options, _ = parseOptions(args)
assert.False(t, options.Process.Replace)
}

func TestVerbose(t *testing.T) {
args := []string{"license-header-checker", "-v", "license-path", "source-path", "js"}
options, _ := parseOptions(args)
assert.True(t, options.Verbose)

args = []string{"license-header-checker", "license-path", "source-path", "js"}
options, _ = parseOptions(args)
assert.False(t, options.Verbose)
}

func TestPath(t *testing.T) {
args := []string{"license-header-checker", "license-path", "source-path", "js", "ts"}
options, _ := parseOptions(args)
assert.True(t, options.Process.Path == "source-path")
}

func TestLicensePath(t *testing.T) {
args := []string{"license-header-checker", "license-path", "source-path", "js", "ts"}
options, _ := parseOptions(args)
assert.True(t, options.Process.LicensePath == "license-path")
}

func TestExtensions(t *testing.T) {
args := []string{"license-header-checker", "license-path", "source-path", "js", "ts"}
options, _ := parseOptions(args)
assert.True(t, len(options.Process.Extensions) == 2)
assert.True(t, options.Process.Extensions[0] == ".js")
assert.True(t, options.Process.Extensions[1] == ".ts")

args = []string{"license-header-checker", "license-path", "source-path", "cpp"}
options, _ = parseOptions(args)
assert.True(t, len(options.Process.Extensions) == 1)
assert.True(t, options.Process.Extensions[0] == ".cpp")
}

func TestIgnorePaths(t *testing.T) {
args := []string{"license-header-checker", "-i", "node_modules,client/assets", "license-path", "source-path", "js"}
options, _ := parseOptions(args)
assert.True(t, len(options.Process.IgnorePaths) == 2)
assert.True(t, options.Process.IgnorePaths[0] == "node_modules")
assert.True(t, options.Process.IgnorePaths[1] == "client/assets")

args = []string{"license-header-checker", "license-path", "source-path", "js"}
options, _ = parseOptions(args)
assert.True(t, len(options.Process.IgnorePaths) == 0)
}
20 changes: 8 additions & 12 deletions cmd/license-header-checker/print.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ import (
"fmt"

"github.com/gookit/color"
"github.com/lsm-dev/license-header-checker/internal/config"
"github.com/lsm-dev/license-header-checker/internal/process"
)

Expand All @@ -39,7 +38,7 @@ var (
)

// printStats prints the options, files processed and aggregate data
func printStats(stats *process.Stats, options *config.Options) {
func printStats(verbose bool, stats *process.Stats, options *process.Options) {
var licensesOk, licensesAdded, licensesReplaced, skippedAdds, skippedReplaces, errors []string

for _, op := range stats.Operations {
Expand All @@ -60,9 +59,9 @@ func printStats(stats *process.Stats, options *config.Options) {
}
}

if options.Verbose {
printFiles(licensesOk, licensesReplaced, licensesAdded, skippedReplaces, skippedAdds, errors)
printOptions(options)
if verbose {
printProcessedFiles(licensesOk, licensesReplaced, licensesAdded, skippedReplaces, skippedAdds, errors)
printProcessOptions(options)
printTotals(len(licensesOk), len(licensesReplaced), len(licensesAdded), len(skippedReplaces), len(skippedAdds), len(errors), int(stats.ElapsedMs))
} else {
fmt.Printf("%s licenses ok, %s licenses replaced, %s licenses added\n", okRender(fmt.Sprintf("%d", len(licensesOk))), warningRender(fmt.Sprintf("%d", len(licensesReplaced))), errorRender(fmt.Sprintf("%d", len(licensesAdded))))
Expand All @@ -71,8 +70,8 @@ func printStats(stats *process.Stats, options *config.Options) {
printWarnings(len(skippedReplaces), len(skippedAdds), len(errors))
}

// printFiles prints the the output of each file grouped by result type
func printFiles(licensesOk, licensesReplaced, licensesAdded, skippedReplaces, skippedAdds, errors []string) {
// printProcessedFiles prints the the output of each file grouped by result type
func printProcessedFiles(licensesOk, licensesReplaced, licensesAdded, skippedReplaces, skippedAdds, errors []string) {
fmt.Printf("files:\n")
if len(licensesOk) > 0 {
fmt.Printf(" license_ok:\n")
Expand Down Expand Up @@ -112,8 +111,8 @@ func printFiles(licensesOk, licensesReplaced, licensesAdded, skippedReplaces, sk
}
}

// printOptions prints the options that were supplied to the cli app
func printOptions(options *config.Options) {
// printProcessOptions prints the options that were supplied to the cli app
func printProcessOptions(options *process.Options) {
fmt.Printf("options:\n")
fmt.Printf(" project_path: %s\n", infoRender(fmt.Sprintf("%s", options.Path)))
if len(options.IgnorePaths) > 0 {
Expand All @@ -133,9 +132,6 @@ func printOptions(options *config.Options) {
if options.Replace {
fmt.Printf(" - %s\n", infoRender("replace"))
}
if options.Verbose {
fmt.Printf(" - %s\n", infoRender("verbose"))
}
fmt.Printf(" license_header: %s\n", infoRender(fmt.Sprintf("%s", options.LicensePath)))
}

Expand Down
Loading

0 comments on commit 56d800c

Please sign in to comment.