Skip to content

Commit

Permalink
Use errcheck to find unhandled errors (wtfutil#795)
Browse files Browse the repository at this point in the history
Signed-off-by: Chris Cummer <[email protected]>
  • Loading branch information
senorprogrammer authored Dec 17, 2019
1 parent 04ff03a commit cde904f
Show file tree
Hide file tree
Showing 44 changed files with 250 additions and 97 deletions.
25 changes: 25 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -68,16 +68,41 @@ install:

## lint: runs a number of code quality checks against the source code
lint:
# https://github.com/kisielk/errcheck
errcheck ./app
errcheck ./cfg
errcheck ./flags
errcheck ./help
errcheck ./logger
errcheck ./modules/...
errcheck ./utils
errcheck ./view
errcheck ./wtf
errcheck ./main.go

# https://golang.org/cmd/vet/
go vet ./app
go vet ./cfg
go vet ./flags
go vet ./help
go vet ./logger
go vet ./modules/...
go vet ./utils
go vet ./view
go vet ./wtf
go vet ./main.go

# https://staticcheck.io/docs/
staticcheck ./app
staticcheck ./cfg
staticcheck ./flags
staticcheck ./help
staticcheck ./logger
staticcheck ./modules/...
staticcheck ./utils
staticcheck ./view
staticcheck ./wtf
staticcheck ./main.go

## run: executes the locally-installed version
run: build
Expand Down
4 changes: 2 additions & 2 deletions cfg/copy.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func fcopy(src, dest string, info os.FileInfo) error {
if err != nil {
return err
}
defer f.Close()
defer func() { _ = f.Close() }()

if err = os.Chmod(f.Name(), info.Mode()); err != nil {
return err
Expand All @@ -44,7 +44,7 @@ func fcopy(src, dest string, info os.FileInfo) error {
if err != nil {
return err
}
defer s.Close()
defer func() { _ = f.Close() }()

_, err = io.Copy(f, s)
return err
Expand Down
8 changes: 4 additions & 4 deletions flags/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,14 @@ func (flags *Flags) ConfigFilePath() string {

// RenderIf displays special-case information based on the flags passed
// in, if any flags were passed in
func (flags *Flags) RenderIf(version string, config *config.Config) {
func (flags *Flags) RenderIf(version, date string, config *config.Config) {
if flags.HasModule() {
help.Display(flags.Module, config)
os.Exit(0)
}

if flags.HasVersion() {
fmt.Println(version)
fmt.Println(fmt.Sprintf("%s (%s)", version, date))
os.Exit(0)
}
}
Expand All @@ -59,7 +59,7 @@ func (flags *Flags) HasModule() bool {

// HasVersion returns TRUE if the version flag was passed in, FALSE if it was not
func (flags *Flags) HasVersion() bool {
return flags.Version == true
return flags.Version
}

// Parse parses the incoming flags
Expand All @@ -74,7 +74,7 @@ func (flags *Flags) Parse() {
// If we have a custom config, then we're done parsing parameters, we don't need to
// generate the default value
flags.hasCustom = (len(flags.Config) > 0)
if flags.hasCustom == true {
if flags.hasCustom {
return
}

Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ require (
github.com/xanzy/go-gitlab v0.22.2
github.com/zmb3/spotify v0.0.0-20191010212056-e12fb981aacb
github.com/zorkian/go-datadog-api v2.25.0+incompatible
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529 // indirect
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550 // indirect
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45
google.golang.org/api v0.14.0
gopkg.in/jarcoal/httpmock.v1 v1.0.0-20181110093347-3be5f16b70eb // indirect
Expand Down
5 changes: 3 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,7 @@ github.com/json-iterator/go v0.0.0-20180701071628-ab8a2e0c74be/go.mod h1:+SdeFBv
github.com/json-iterator/go v1.1.7 h1:KfgG9LzI+pYjr4xvmz/5H4FXjokeP+rlHLhv3iH62Fo=
github.com/json-iterator/go v1.1.7/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU=
github.com/kisielk/errcheck v1.2.0 h1:reN85Pxc5larApoH1keMBiu2GWtPqXQ1nc9gx+jOU+E=
github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
Expand Down Expand Up @@ -263,8 +264,8 @@ go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU=
golang.org/x/crypto v0.0.0-20181025213731-e84da0312774/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2 h1:VklqNMn3ovrHsnt90PveolxSbWFaJdECFbxSq0Mqo2M=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529 h1:iMGN4xG0cnqj3t+zOM8wUB0BiPKHEwSxEZCvzcbZuvk=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550 h1:ObdrDkeb4kJdCP557AjRjq69pTHfNouLtWZG7j9rPN8=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
Expand Down
6 changes: 5 additions & 1 deletion help/help.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@ func Display(moduleName string, cfg *config.Config) {
}

func helpFor(moduleName string, cfg *config.Config) string {
cfg.Set("wtf.mods."+moduleName+".enabled", true)
err := cfg.Set("wtf.mods."+moduleName+".enabled", true)
if err != nil {
return ""
}

widget := app.MakeWidget(nil, nil, moduleName, cfg)

// Since we are forcing enabled config, if no module
Expand Down
2 changes: 1 addition & 1 deletion logger/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ func Log(msg string) {
if err != nil {
log.Fatalf("error opening file: %v", err)
}
defer f.Close()
defer func() { _ = f.Close() }()

log.SetOutput(f)
log.Println(msg)
Expand Down
3 changes: 1 addition & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ import (
var tviewApp *tview.Application

var (
commit = "dev"
date = "dev"
version = "dev"
)
Expand Down Expand Up @@ -54,7 +53,7 @@ func main() {

// Load the configuration file
config := cfg.LoadWtfConfigFile(flags.ConfigFilePath())
flags.RenderIf(version, config)
flags.RenderIf(version, date, config)

if flags.Profile {
defer profile.Start(profile.MemProfile).Stop()
Expand Down
2 changes: 1 addition & 1 deletion modules/bamboohr/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ func Request(apiKey string, apiURL string) ([]byte, error) {
if err != nil {
return nil, err
}
defer resp.Body.Close()
defer func() { _ = resp.Body.Close() }()

data, err := ParseBody(resp)
if err != nil {
Expand Down
11 changes: 8 additions & 3 deletions modules/cmdrunner/widget.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ func (widget *Widget) Write(p []byte) (n int, err error) {
// Remove lines that exceed maxLines
lines := widget.countLines()
if lines > widget.settings.maxLines {
widget.drainLines(lines - widget.settings.maxLines)
err = widget.drainLines(lines - widget.settings.maxLines)
}

return n, err
Expand All @@ -93,10 +93,15 @@ func (widget *Widget) countLines() int {
}

// drainLines removed the first n lines from the buffer
func (widget *Widget) drainLines(n int) {
func (widget *Widget) drainLines(n int) error {
for i := 0; i < n; i++ {
widget.buffer.ReadBytes('\n')
_, err := widget.buffer.ReadBytes('\n')
if err != nil {
return err
}
}

return nil
}

func (widget *Widget) environment() []string {
Expand Down
8 changes: 6 additions & 2 deletions modules/cryptoexchanges/bittrex/display.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ func (widget *Widget) content() (string, string, bool) {
formatableText("Open Sell", "OpenSellOrders"),
)

strTemplate.Execute(writer, map[string]string{
err := strTemplate.Execute(writer, map[string]string{
"nameColor": widget.settings.colors.market.name,
"fieldColor": widget.settings.colors.market.field,
"valueColor": widget.settings.colors.market.value,
Expand All @@ -57,7 +57,11 @@ func (widget *Widget) content() (string, string, bool) {
"OpenSellOrders": marketCurrency.OpenSellOrders,
})

str += writer.String() + "\n"
if err != nil {
str = err.Error()
} else {
str += writer.String() + "\n"
}
}

}
Expand Down
12 changes: 9 additions & 3 deletions modules/cryptoexchanges/bittrex/widget.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,9 @@ func (widget *Widget) Refresh() {
func (widget *Widget) updateSummary() {
// In case if anything bad happened!
defer func() {
recover()
if r := recover(); r != nil {
fmt.Println("recovered in updateSummary()", r)
}
}()

client := &http.Client{
Expand Down Expand Up @@ -120,10 +122,14 @@ func (widget *Widget) updateSummary() {
errorText = ""
}

defer response.Body.Close()
defer func() { _ = response.Body.Close() }()
jsonResponse := summaryResponse{}
decoder := json.NewDecoder(response.Body)
decoder.Decode(&jsonResponse)
err = decoder.Decode(&jsonResponse)
if err != nil {
errorText = "Could not parse JSON!"
break
}

if !jsonResponse.Success {
ok = false
Expand Down
2 changes: 1 addition & 1 deletion modules/cryptoexchanges/blockfolio/widget.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ func MakeApiRequest(token string, method string) ([]byte, error) {
if err != nil {
return nil, err
}
defer resp.Body.Close()
defer func() { _ = resp.Body.Close() }()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
Expand Down
6 changes: 4 additions & 2 deletions modules/cryptoexchanges/cryptolive/price/widget.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,9 @@ func (widget *Widget) getToList(symbol string) []*toCurrency {

func (widget *Widget) updateCurrencies() {
defer func() {
recover()
if r := recover(); r != nil {
fmt.Println("recovered in updateSummary()", r)
}
}()
for _, fromCurrency := range widget.list.items {

Expand All @@ -121,7 +123,7 @@ func (widget *Widget) updateCurrencies() {
ok = true
}

defer response.Body.Close()
defer func() { _ = response.Body.Close() }()

_ = json.NewDecoder(response.Body).Decode(&jsonResponse)

Expand Down
4 changes: 3 additions & 1 deletion modules/cryptoexchanges/cryptolive/toplist/widget.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,9 @@ func (widget *Widget) Refresh(wg *sync.WaitGroup) {

func (widget *Widget) updateData() {
defer func() {
recover()
if r := recover(); r != nil {
fmt.Println("recovered in updateSummary()", r)
}
}()

client := &http.Client{
Expand Down
21 changes: 17 additions & 4 deletions modules/digitalocean/widget.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,10 @@ func (widget *Widget) dropletDestroy() {
return
}

widget.client.Droplets.Delete(context.Background(), currDroplet.ID)
_, err := widget.client.Droplets.Delete(context.Background(), currDroplet.ID)
if err != nil {
return
}

widget.dropletRemoveSelected()
widget.Refresh()
Expand All @@ -190,7 +193,11 @@ func (widget *Widget) dropletEnabledPrivateNetworking() {
return
}

widget.client.DropletActions.EnablePrivateNetworking(context.Background(), currDroplet.ID)
_, _, err := widget.client.DropletActions.EnablePrivateNetworking(context.Background(), currDroplet.ID)
if err != nil {
return
}

widget.Refresh()
}

Expand All @@ -210,7 +217,10 @@ func (widget *Widget) dropletRestart() {
return
}

widget.client.DropletActions.Reboot(context.Background(), currDroplet.ID)
_, _, err := widget.client.DropletActions.Reboot(context.Background(), currDroplet.ID)
if err != nil {
return
}
widget.Refresh()
}

Expand All @@ -221,7 +231,10 @@ func (widget *Widget) dropletShutDown() {
return
}

widget.client.DropletActions.Shutdown(context.Background(), currDroplet.ID)
_, _, err := widget.client.DropletActions.Shutdown(context.Background(), currDroplet.ID)
if err != nil {
return
}
widget.Refresh()
}

Expand Down
10 changes: 5 additions & 5 deletions modules/exchangerates/exchangerates.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,22 @@ func FetchExchangeRates(settings *Settings) (map[string]map[string]float64, erro
out := map[string]map[string]float64{}

for base, rates := range settings.rates {
res, err := http.Get(fmt.Sprintf("https://api.exchangeratesapi.io/latest?base=%s", base))
resp, err := http.Get(fmt.Sprintf("https://api.exchangeratesapi.io/latest?base=%s", base))
if err != nil {
return nil, err
}
defer res.Body.Close()
defer func() { _ = resp.Body.Close() }()

var resp Response
err = utils.ParseJSON(&resp, res.Body)
var data Response
err = utils.ParseJSON(&data, resp.Body)
if err != nil {
return nil, err
}

out[base] = map[string]float64{}

for _, currency := range rates {
rate, ok := resp.Rates[currency]
rate, ok := data.Rates[currency]
if ok {
out[base][currency] = rate
}
Expand Down
4 changes: 2 additions & 2 deletions modules/football/widget.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ func (widget *Widget) GetStandings(leagueId int) string {
if err != nil {
return fmt.Sprintf("Error fetching standings: %s", err.Error())
}
defer resp.Body.Close()
defer func() { _ = resp.Body.Close() }()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Sprintf("Error fetching standings: %s", err.Error())
Expand Down Expand Up @@ -141,7 +141,7 @@ func (widget *Widget) GetMatches(leagueId int) string {
if err != nil {
return fmt.Sprintf("Error fetching matches: %s", err.Error())
}
defer resp.Body.Close()
defer func() { _ = resp.Body.Close() }()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Sprintf("Error fetching matches: %s", err.Error())
Expand Down
Loading

0 comments on commit cde904f

Please sign in to comment.