diff --git a/golang/.golangci.yml b/golang/.golangci.yml new file mode 100644 index 0000000..7a54d17 --- /dev/null +++ b/golang/.golangci.yml @@ -0,0 +1,40 @@ +linters: + disable-all: true + enable: + - errcheck + - gosimple + - govet + - ineffassign + - staticcheck + - typecheck + - unused + - asciicheck + - bodyclose + - dogsled + - exhaustive + - gocognit + - goconst + - gofmt + - goheader + - goimports + - gosec + - misspell + - nakedret + - nestif + - noctx + - rowserrcheck + - sqlclosecheck + - unconvert + - unparam + - whitespace + +issues: + exclude: + - "composite literal uses unkeyed fields" + exclude-rules: + - path: _test\.go + linters: + - gosec + - noctx + - unparam + - bodyclose diff --git a/golang/README.md b/golang/README.md index 3f82ff1..0ef721d 100644 --- a/golang/README.md +++ b/golang/README.md @@ -2,4 +2,17 @@ A reimplementation of [wc](https://en.wikipedia.org/wiki/Wc_(Unix)) as based on [Coding Challenges / Build Your Own wc Tool](https://codingchallenges.fyi/challenges/challenge-wc). -`TODO: DOC TO BE WRITTEN` \ No newline at end of file +## Instructions + +1 - Build a binary by running `make build` which will save the binary in `bin/ccwc` + +2 - Running commands against a file: `bin/ccwc -c path/to/file` + +3 - Running commands against the standard input: `cat path/to/file | bin/ccwc -c` + +## Commands implemented + +- `-c` - The number of bytes in each input file is written to the standard output. +- `-l` - The number of lines in each input file is written to the standard output. +- `-m` - The number of characters in each input file is written to the standard output. +- `w` - The number of words in each input file is written to the standard output. diff --git a/golang/main.go b/golang/main.go index d8e9b02..693ae36 100644 --- a/golang/main.go +++ b/golang/main.go @@ -18,21 +18,29 @@ func main() { countCharactersCmd := flag.Bool("m", false, "ccwc -m path/to/file - Returns the number of characters in the file specified") flag.Parse() - fileName := os.Args[len(os.Args)-1] - - if strings.TrimSpace(fileName) == "" { - fmt.Println("A file must be specified. E.g.: ccwc -c path/to/file") - os.Exit(1) + var err error + var fileName string + var fileSource *os.File + + if len(os.Args) == 1 || len(os.Args) == 2 && (os.Args[1] == "-c" || os.Args[1] == "-l" || os.Args[1] == "-w" || os.Args[1] == "-m") { + fileSource = os.Stdin + } else { + fileName = os.Args[len(os.Args)-1] + fileSource, err = os.Open(fileName) + if err != nil { + fmt.Printf("error opening the file '%s': %v", fileName, err) + return + } } - f, err := os.Open(fileName) - if err != nil { - fmt.Printf("error opening the file '%s': %v", fileName, err) - return - } - defer func() { _ = f.Close() }() + defer func() { + closeErr := fileSource.Close() + if closeErr != nil { + fmt.Printf("error closing file or stdin: %v\n", closeErr) + } + }() - result, err := getStatsFromReader(f) + result, err := getStatsFromReader(fileSource) if err != nil { fmt.Println(err) os.Exit(1)