Skip to content

Commit

Permalink
refactor: fix golangci-lint warnings
Browse files Browse the repository at this point in the history
  • Loading branch information
nikoheikkila committed May 3, 2024
1 parent 4267493 commit 0745769
Show file tree
Hide file tree
Showing 7 changed files with 94 additions and 98 deletions.
42 changes: 20 additions & 22 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,34 +29,32 @@ type Env struct {
}

// LoadConfig loads the file and parses it to struct
func LoadConfig(file string) *Config {
c := new(Config)
func LoadConfig(file string) (config *Config, err error) {
config = new(Config)

configFile, err := os.Open(file)
defer configFile.Close()
if err != nil {
log.Printf("OPEN FILE ERROR: %v\n", err.Error())
return c
return config, err
}

confJSONParser := json.NewDecoder(configFile)
confJSONParser.Decode(&c)

return c
}

// func LoadConfig(file string) *Config {
// c := new(Config)
defer func() {
closeErr := configFile.Close()
if closeErr != nil {
log.Printf("CLOSE FILE ERROR: %v\n", closeErr.Error())
if err == nil {
err = closeErr
}
}
}()

// configFile, err := os.Open(file)
// defer configFile.Close()
// if err != nil {
// log.Printf("OPEN FILE ERROR: %v\n", err.Error())
// return c
// }
confJSONParser := json.NewDecoder(configFile)
err = confJSONParser.Decode(&config)

// confJSONParser := json.NewDecoder(configFile)
// confJSONParser.Decode(&c)
if err != nil {
log.Printf("JSON DECODE ERROR: %v\n", err.Error())
return config, err
}

// return c
// }
return config, nil
}
18 changes: 15 additions & 3 deletions helpers.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package harvest

import (
"io/ioutil"
"io"
"net/http"
"net/url"

Expand Down Expand Up @@ -33,8 +33,20 @@ func (h *Harvest) getURL(method string, url string) ([]byte, error) {
req.Header.Set("Content-Type", "application/json")

resp, err := Client.Do(req)
body, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
if err != nil {
return nil, err
}

body, err := io.ReadAll(resp.Body)

defer func() {
closeErr := resp.Body.Close()
if closeErr != nil {
if err == nil {
err = closeErr
}
}
}()

return body, err
}
Expand Down
3 changes: 1 addition & 2 deletions hours.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,9 +115,8 @@ func IsWorkday(date time.Time) bool { // Should this be placed in helpers.go?

// Filter is generic function to filter Entries
func (e *TimeEntries) Filter(f func(structs.Entries) bool) (ret []structs.Entries) {
// var r []structs.Entries
for _, v := range e.Entries {
if f(v) == true {
if f(v) {
ret = append(ret, v)
}
}
Expand Down
44 changes: 20 additions & 24 deletions hours_test.go
Original file line number Diff line number Diff line change
@@ -1,32 +1,33 @@
package harvest

import (
"log"
"os"
"testing"

"encoding/json"
"io/ioutil"
"time"
)

var (
testDataFile = "test/test_timeEntries.json"
entries = []float64{7.5, 5.5, 9.5, 6.5, 1, 7.5, 5.5, 4, 7.5, 2.5, 2, 3, 0.5, 1, 1, 2, 1.5, 1.5, 7.5, 2, 7.5}
)

func TestDailyHours(t *testing.T) {
var expect float64
var timeEntries TimeEntries
expect = 7.5

// var c config.Config
// h := Init(&c)
body, err := ioutil.ReadFile(testDataFile)
body, err := os.ReadFile(testDataFile)
if err != nil {
log.Fatalf("[ERROR] %v", err)
t.Errorf("[ERROR] %v", err)
}

var timeEntries TimeEntries
json.Unmarshal(body, &timeEntries)
err = json.Unmarshal(body, &timeEntries)
if err != nil {
t.Errorf("[ERROR] %v", err)
}

date, _ := time.Parse("2006-01-02", "2019-04-15")
result := timeEntries.DailyHours(date)
Expand All @@ -52,15 +53,13 @@ func TestDailyTotals(t *testing.T) {
expectSaldo = 0.0
expectOvertime = -2.0

// var c config.Config
// h := Init(&c)
body, _ := ioutil.ReadFile(testDataFile)
// if err != nil {
// log.Fatalf(err.Error)
// }
body, _ := os.ReadFile(testDataFile)

var timeEntries TimeEntries
json.Unmarshal(body, &timeEntries)
err := json.Unmarshal(body, &timeEntries)
if err != nil {
t.Errorf("[ERROR] %v", err)
}

date, _ := time.Parse("2006-01-02", "2019-04-16")
resultHours, resultSaldo, resultOvertime := timeEntries.DailyTotals(date)
Expand All @@ -84,24 +83,21 @@ func TestDailyTotals(t *testing.T) {

func TestTotalHours(t *testing.T) {
var expect float64
// weekOne := []string{"2019-04-15", "2019-04-21"}
// weekTwo := []string{"2019-04-22", "2019-04-28"}
var timeEntries TimeEntries
expectWeekOne := 47.0
expectWeekTwo := 39.5
expect = expectWeekOne + expectWeekTwo

// var c config.Config
// h := Init(&c)

body, err := ioutil.ReadFile(testDataFile)
body, err := os.ReadFile(testDataFile)
if err != nil {
log.Fatalf("[ERROR] Could not read test data.\n[ERROR] %v", err)
t.Errorf("[ERROR] Could not read test data.\n[ERROR] %v", err)
}

var timeEntries TimeEntries
json.Unmarshal(body, &timeEntries)
err = json.Unmarshal(body, &timeEntries)
if err != nil {
t.Errorf("[ERROR] Could not unmarshal test data.\n[ERROR] %v", err)
}

// date, _ := time.Parse("2006-01-02", "2019-02-28")
result := timeEntries.TotalHours()
if result != expect {
t.Errorf("TotalHours: expecting %v, got %v!", expect, result)
Expand Down
13 changes: 0 additions & 13 deletions structs/structs.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,16 +88,3 @@ type dailyHours struct {
Date time.Time
DailyHours float64
}

type selectedEntries struct {
selection []Entries
}

type userAccount struct {
ID int64 `json:"id"`
Email string `json:"email"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
IsActive bool `json:"is_active"`
IsAdmin bool `json:"is_admin"`
}
24 changes: 15 additions & 9 deletions time_entries.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
package harvest

import (
// "fmt"
"log"

"encoding/json"
"log"
"time"

// "github.com/google/go-querystring/query"
"github.com/polarsquad/harvest/structs"
)

Expand All @@ -19,6 +16,8 @@ import (
// to: time.Time with format "2006-01-02"
// u: User, specifies which users TimeEntries are fetched.
func (h *Harvest) GetEntries(from time.Time, to time.Time, u *User) *TimeEntries {
var times TimeEntries

// Let's build the URL with parameters.
params := GetTimeEntriesParams{
UserID: int64(u.ID),
Expand All @@ -34,8 +33,11 @@ func (h *Harvest) GetEntries(from time.Time, to time.Time, u *User) *TimeEntries
log.Fatalln(err.Error())
}

var times TimeEntries
json.Unmarshal(body, &times)
err = json.Unmarshal(body, &times)
if err != nil {
log.Fatalln(err.Error())
}

log.Printf("TotalEntries: %v, Pages: %v\n", times.TotalEntries, times.TotalPages)

// IF: returned entries have Next link, then we fetch the additional pages
Expand All @@ -44,18 +46,22 @@ func (h *Harvest) GetEntries(from time.Time, to time.Time, u *User) *TimeEntries
// time.Sleep(1 * time.Second) // This might be needed, if Harvest API starts throttling
entries := h.getAllEntries(times.Links)
times.Entries = append(times.Entries, entries...)

}

return &times
}

// func (h *Harvest) getAllEntries(l structs.Links, entries *[]structs.Entries, i int) Entries {
func (h *Harvest) getAllEntries(l structs.Links) Entries {
var times TimeEntries
// getURL to fetch additional Entries from Links.Next URL
body, _ := h.getURL("GET", l.Next)
var times TimeEntries
json.Unmarshal(body, &times)

err := json.Unmarshal(body, &times)
if err != nil {
log.Fatalln(err.Error())
}

if times.Links.Next != "" {
// IF Next URL still available, let's call getAllEntries() again.
entries := h.getAllEntries(times.Links)
Expand Down
48 changes: 23 additions & 25 deletions user.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,14 @@ package harvest
import (
"encoding/json"
"fmt"
"io/ioutil"
"io"
"log"
"net/http"
// "github.com/polarsquad/harvest/structs"
)

// GetUser Fetches the information of the logged in user
func (h *Harvest) GetUser() (*User, error) {

url := "https://api.harvestapp.com/v2/users/me"
// url := "https://api.harvestapp.com/v2/company"
Client := &http.Client{}

req, _ := http.NewRequest("GET", url, nil)
Expand All @@ -23,29 +20,27 @@ func (h *Harvest) GetUser() (*User, error) {

resp, err := Client.Do(req)
if err != nil {
return nil, fmt.Errorf("Couldn't fetch user API: %v", err)
return nil, fmt.Errorf("couldn't fetch user API: %v", err)
}
body, _ := ioutil.ReadAll(resp.Body)
// if err != nil {
// return nil, fmt.Errorf("Can't read body: %v", err)
// }

defer resp.Body.Close()

// body, err := getURL("GET", url)
// if err != nil {
// os.Exit(1)
// }
body, _ := io.ReadAll(resp.Body)

defer func() {
closeErr := resp.Body.Close()
if closeErr != nil {
log.Printf("CLOSE RESPONSE ERROR: %v\n", closeErr.Error())
if err == nil {
err = closeErr
}
}
}()

// var jsonResponse map[string]interface{}
// var user structs.User
var user User

// json.Unmarshal(body, &jsonResponse)
json.Unmarshal(body, &user)
err = json.Unmarshal(body, &user)
if err != nil {
return nil, fmt.Errorf("couldn't unmarshal user: %v", err)
}

// prettyJson, _ := json.MarshalIndent(user, "", " ")
// fmt.Println(string(prettyJson))
if !user.IsActive {
log.Fatalf("User not active!")
}
Expand All @@ -56,15 +51,19 @@ func (h *Harvest) GetUser() (*User, error) {
// GetUserByEmail is ...
func (h *Harvest) GetUserByEmail(email string) (*User, error) {
var user User
var usersList Users

body, err := h.getURL("GET", usersURL)
if err != nil {
log.Fatalf("[ERROR] Could not get users.")
return &user, err
}

var usersList Users
json.Unmarshal(body, &usersList)
err = json.Unmarshal(body, &usersList)
if err != nil {
log.Fatalf("[ERROR] Could not unmarshal users.")
return &user, err
}

for _, v := range usersList.Users {
if v.Email == email {
Expand All @@ -74,5 +73,4 @@ func (h *Harvest) GetUserByEmail(email string) (*User, error) {
}

return &user, fmt.Errorf("could not found user")

}

0 comments on commit 0745769

Please sign in to comment.