Skip to content

Commit

Permalink
[MAINT] initial work on linter setup (#16)
Browse files Browse the repository at this point in the history
* initial work on linter setup

* simple linter rules fixed
  • Loading branch information
enver-bisevac committed Sep 12, 2022
1 parent f58ceac commit ca8aa47
Show file tree
Hide file tree
Showing 31 changed files with 234 additions and 226 deletions.
4 changes: 2 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ tools: $(tools) ## Install tools required for the build
mocks: $(mocks)
@echo "Generating Test Mocks"

generate: $(mocks) wire_gen.go mocks/mock_client.go
generate: $(mocks) cli/server/wire_gen.go mocks/mock_client.go
@echo "Generating Code"

build: generate ## Build the gitness service binary
Expand Down Expand Up @@ -114,7 +114,7 @@ lint: tools generate # lint the golang code
# Some code generation can be slow, so we only run it if
# the source file has changed.
###########################################
wire_gen.go: cli/server/wire.go ## Update the wire dependency injection if wire.go has changed.
cli/server/wire_gen.go: cli/server/wire.go ## Update the wire dependency injection if wire.go has changed.
@echo "Updating wire_gen.go"
go generate ./cli/server/wire_gen.go

Expand Down
4 changes: 0 additions & 4 deletions cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
package cli

import (
"context"
"os"

"github.com/harness/gitness/cli/server"
Expand All @@ -17,9 +16,6 @@ import (
"gopkg.in/alecthomas/kingpin.v2"
)

// empty context
var nocontext = context.Background()

// application name
var application = "gitness"

Expand Down
5 changes: 4 additions & 1 deletion cli/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@ type command struct {

func (c *command) run(*kingpin.ParseContext) error {
// load environment variables from file.
godotenv.Load(c.envfile)
err := godotenv.Load(c.envfile)
if err != nil {
return err
}

// create the system configuration store by loading
// data from the environment.
Expand Down
4 changes: 3 additions & 1 deletion cli/users/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,9 @@ func (c *listCommand) run(*kingpin.ParseContext) error {
return enc.Encode(list)
}
for _, item := range list {
tmpl.Execute(os.Stdout, item)
if err = tmpl.Execute(os.Stdout, item); err != nil {
return err
}
}
return nil
}
Expand Down
4 changes: 2 additions & 2 deletions cli/util/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"encoding/json"
"errors"
"fmt"
"golang.org/x/term"
"io/ioutil"
"os"
"path/filepath"
Expand All @@ -20,7 +21,6 @@ import (
"github.com/harness/gitness/types"

"github.com/adrg/xdg"
"golang.org/x/crypto/ssh/terminal"
)

// Client returns a client that is configured from file.
Expand Down Expand Up @@ -72,7 +72,7 @@ func Username() string {
// Password returns the password from stdin.
func Password() string {
fmt.Print("Enter Password: ")
passwordb, _ := terminal.ReadPassword(int(syscall.Stdin))
passwordb, _ := term.ReadPassword(int(syscall.Stdin))
password := string(passwordb)

return strings.TrimSpace(password)
Expand Down
14 changes: 7 additions & 7 deletions client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"bytes"
"encoding/json"
"fmt"
"github.com/rs/zerolog/log"
"io"
"net/http"
"net/http/httputil"
Expand Down Expand Up @@ -150,11 +151,6 @@ func (c *HTTPClient) post(rawurl string, in, out interface{}) error {
return c.do(rawurl, "POST", in, out)
}

// helper function for making an http PUT request.
func (c *HTTPClient) put(rawurl string, in, out interface{}) error {
return c.do(rawurl, "PUT", in, out)
}

// helper function for making an http PATCH request.
func (c *HTTPClient) patch(rawurl string, in, out interface{}) error {
return c.do(rawurl, "PATCH", in, out)
Expand Down Expand Up @@ -199,7 +195,9 @@ func (c *HTTPClient) stream(rawurl, method string, in, out interface{}) (io.Read
buf = new(bytes.Buffer)
// if posting form data, encode the form values.
if form, ok := in.(*url.Values); ok {
io.WriteString(buf, form.Encode())
if _, err := io.WriteString(buf, form.Encode()); err != nil {
log.Err(err).Msg("in stream method")
}
} else {
if err := json.NewEncoder(buf).Encode(in); err != nil {
return nil, err
Expand Down Expand Up @@ -239,7 +237,9 @@ func (c *HTTPClient) stream(rawurl, method string, in, out interface{}) (io.Read
if resp.StatusCode > 299 {
defer resp.Body.Close()
err := new(remoteError)
json.NewDecoder(resp.Body).Decode(err)
if decodeErr := json.NewDecoder(resp.Body).Decode(err); decodeErr != nil {
return nil, decodeErr
}
return nil, err
}
return resp.Body, nil
Expand Down
4 changes: 3 additions & 1 deletion internal/api/handler/user/find_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@ func TestFind(t *testing.T) {
}

got, want := &types.User{}, mockUser
json.NewDecoder(w.Body).Decode(got)
if err := json.NewDecoder(w.Body).Decode(got); err != nil {
t.Error(err)
}
if diff := cmp.Diff(got, want); len(diff) != 0 {
t.Errorf(diff)
}
Expand Down
4 changes: 3 additions & 1 deletion internal/api/handler/user/token_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ func TestToken(t *testing.T) {
}

result := &types.Token{}
json.NewDecoder(w.Body).Decode(&result)
if err := json.NewDecoder(w.Body).Decode(&result); err != nil {
t.Error(err)
}

_, err := jwt.Parse(result.Value, func(token *jwt.Token) (interface{}, error) {
return []byte(mockUser.Salt), nil
Expand Down
22 changes: 15 additions & 7 deletions internal/api/handler/user/update_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ func TestUpdate(t *testing.T) {
users.EXPECT().Update(gomock.Any(), before)

in := new(bytes.Buffer)
json.NewEncoder(in).Encode(userInput)
_ = json.NewEncoder(in).Encode(userInput)
w := httptest.NewRecorder()
r := httptest.NewRequest("PATCH", "/api/v1/user", in)
r = r.WithContext(
Expand All @@ -81,7 +81,9 @@ func TestUpdate(t *testing.T) {
// Password hash is not exposecd to JSON
}
got, want := new(types.User), after
json.NewDecoder(w.Body).Decode(got)
if err := json.NewDecoder(w.Body).Decode(got); err != nil {
t.Error(err)
}
if diff := cmp.Diff(got, want); len(diff) != 0 {
t.Errorf(diff)
}
Expand All @@ -108,7 +110,7 @@ func TestUpdate_HashError(t *testing.T) {
}

in := new(bytes.Buffer)
json.NewEncoder(in).Encode(userInput)
_ = json.NewEncoder(in).Encode(userInput)
w := httptest.NewRecorder()
r := httptest.NewRequest("PATCH", "/api/v1/user", in)
r = r.WithContext(
Expand All @@ -121,7 +123,9 @@ func TestUpdate_HashError(t *testing.T) {
}

got := new(render.Error)
json.NewDecoder(w.Body).Decode(got)
if err := json.NewDecoder(w.Body).Decode(got); err != nil {
t.Error(err)
}
if diff := cmp.Diff(got.Message, render.ErrInternal.Message); len(diff) != 0 {
t.Errorf(diff)
}
Expand Down Expand Up @@ -152,7 +156,9 @@ func TestUpdate_BadRequest(t *testing.T) {
}

got := new(render.Error)
json.NewDecoder(w.Body).Decode(got)
if err := json.NewDecoder(w.Body).Decode(got); err != nil {
t.Error(err)
}
if diff := cmp.Diff(got.Message, "Invalid request body: EOF."); len(diff) != 0 {
t.Errorf(diff)
}
Expand All @@ -176,7 +182,7 @@ func TestUpdate_ServerError(t *testing.T) {
users.EXPECT().Update(gomock.Any(), user).Return(render.ErrNotFound)

in := new(bytes.Buffer)
json.NewEncoder(in).Encode(userInput)
_ = json.NewEncoder(in).Encode(userInput)
w := httptest.NewRecorder()
r := httptest.NewRequest("PATCH", "/api/v1/user", in)
r = r.WithContext(
Expand All @@ -189,7 +195,9 @@ func TestUpdate_ServerError(t *testing.T) {
}

got, want := new(render.Error), render.ErrInternal
json.NewDecoder(w.Body).Decode(got)
if err := json.NewDecoder(w.Body).Decode(got); err != nil {
t.Error(err)
}
if diff := cmp.Diff(got, want); len(diff) != 0 {
t.Errorf(diff)
}
Expand Down
22 changes: 11 additions & 11 deletions internal/api/openapi/account.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,19 +32,19 @@ func buildAccount(reflector *openapi3.Reflector) {
onLogin := openapi3.Operation{}
onLogin.WithTags("account")
onLogin.WithMapOfAnything(map[string]interface{}{"operationId": "onLogin"})
reflector.SetRequest(&onLogin, new(loginRequest), http.MethodPost)
reflector.SetJSONResponse(&onLogin, new(types.Token), http.StatusOK)
reflector.SetJSONResponse(&onLogin, new(render.Error), http.StatusBadRequest)
reflector.SetJSONResponse(&onLogin, new(render.Error), http.StatusInternalServerError)
reflector.SetJSONResponse(&onLogin, new(render.Error), http.StatusNotFound)
reflector.Spec.AddOperation(http.MethodPost, "/login", onLogin)
_ = reflector.SetRequest(&onLogin, new(loginRequest), http.MethodPost)
_ = reflector.SetJSONResponse(&onLogin, new(types.Token), http.StatusOK)
_ = reflector.SetJSONResponse(&onLogin, new(render.Error), http.StatusBadRequest)
_ = reflector.SetJSONResponse(&onLogin, new(render.Error), http.StatusInternalServerError)
_ = reflector.SetJSONResponse(&onLogin, new(render.Error), http.StatusNotFound)
_ = reflector.Spec.AddOperation(http.MethodPost, "/login", onLogin)

onRegister := openapi3.Operation{}
onRegister.WithTags("account")
onRegister.WithMapOfAnything(map[string]interface{}{"operationId": "onRegister"})
reflector.SetRequest(&onRegister, new(registerRequest), http.MethodPost)
reflector.SetJSONResponse(&onRegister, new(types.Token), http.StatusOK)
reflector.SetJSONResponse(&onRegister, new(render.Error), http.StatusInternalServerError)
reflector.SetJSONResponse(&onRegister, new(render.Error), http.StatusBadRequest)
reflector.Spec.AddOperation(http.MethodPost, "/register", onRegister)
_ = reflector.SetRequest(&onRegister, new(registerRequest), http.MethodPost)
_ = reflector.SetJSONResponse(&onRegister, new(types.Token), http.StatusOK)
_ = reflector.SetJSONResponse(&onRegister, new(render.Error), http.StatusInternalServerError)
_ = reflector.SetJSONResponse(&onRegister, new(render.Error), http.StatusBadRequest)
_ = reflector.Spec.AddOperation(http.MethodPost, "/register", onRegister)
}
74 changes: 36 additions & 38 deletions internal/api/openapi/openapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,6 @@
package openapi

import (
"bytes"
"net/http"
"strings"

"github.com/harness/gitness/version"

"github.com/swaggest/openapi-go/openapi3"
Expand All @@ -29,37 +25,38 @@ type (
Size int `query:"per_page" default:"100"`
}

// base response for pagination
paginationResponse struct {
Total int `header:"x-total"`
Pagelen int `header:"x-total-pages"`
Page int `header:"x-page"`
Size int `header:"x-per-page"`
Next int `header:"x-next"`
Prev int `header:"x-prev"`
Link []string `header:"Link"`
}
// TODO: base response for pagination
//paginationResponse struct {
// Total int `header:"x-total"`
// Pagelen int `header:"x-total-pages"`
// Page int `header:"x-page"`
// Size int `header:"x-per-page"`
// Next int `header:"x-next"`
// Prev int `header:"x-prev"`
// Link []string `header:"Link"`
//}
)

// Handler returns an http.HandlerFunc that writes the openapi v3
// specification file to the http.Response body.
func Handler() http.HandlerFunc {
spec := Generate()
yaml, _ := spec.MarshalYAML()
json, _ := spec.MarshalJSON()

yaml = normalize(yaml)
json = normalize(json)

return func(w http.ResponseWriter, r *http.Request) {
switch {
case strings.HasSuffix(r.URL.Path, ".json"):
w.Write(json)
default:
w.Write(yaml)
}
}
}
// TODO: unused function
//func Handler() http.HandlerFunc {
// spec := Generate()
// yaml, _ := spec.MarshalYAML()
// json, _ := spec.MarshalJSON()
//
// yaml = normalize(yaml)
// json = normalize(json)
//
// return func(w http.ResponseWriter, r *http.Request) {
// switch {
// case strings.HasSuffix(r.URL.Path, ".json"):
// w.Write(json)
// default:
// w.Write(yaml)
// }
// }
//}

// Generate is a helper function that constructs the
// openapi specification object, which can be marshaled
Expand Down Expand Up @@ -108,10 +105,11 @@ func Generate() *openapi3.Spec {

// helper function normalizes the output to ensure
// automatically-generated names are more user friendly.
func normalize(data []byte) []byte {
data = bytes.ReplaceAll(data, []byte("Types"), []byte(""))
data = bytes.ReplaceAll(data, []byte("Openapi"), []byte(""))
data = bytes.ReplaceAll(data, []byte("FormData"), []byte(""))
data = bytes.ReplaceAll(data, []byte("RenderError"), []byte("Error"))
return data
}
// TODO: unused function
//func normalize(data []byte) []byte {
// data = bytes.ReplaceAll(data, []byte("Types"), []byte(""))
// data = bytes.ReplaceAll(data, []byte("Openapi"), []byte(""))
// data = bytes.ReplaceAll(data, []byte("FormData"), []byte(""))
// data = bytes.ReplaceAll(data, []byte("RenderError"), []byte("Error"))
// return data
//}
32 changes: 16 additions & 16 deletions internal/api/openapi/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,32 +25,32 @@ func buildUser(reflector *openapi3.Reflector) {
opFind := openapi3.Operation{}
opFind.WithTags("user")
opFind.WithMapOfAnything(map[string]interface{}{"operationId": "getUser"})
reflector.SetRequest(&opFind, nil, http.MethodGet)
reflector.SetJSONResponse(&opFind, new(types.User), http.StatusOK)
reflector.SetJSONResponse(&opFind, new(render.Error), http.StatusInternalServerError)
reflector.Spec.AddOperation(http.MethodGet, "/user", opFind)
_ = reflector.SetRequest(&opFind, nil, http.MethodGet)
_ = reflector.SetJSONResponse(&opFind, new(types.User), http.StatusOK)
_ = reflector.SetJSONResponse(&opFind, new(render.Error), http.StatusInternalServerError)
_ = reflector.Spec.AddOperation(http.MethodGet, "/user", opFind)

opUpdate := openapi3.Operation{}
opUpdate.WithTags("user")
opUpdate.WithMapOfAnything(map[string]interface{}{"operationId": "updateUser"})
reflector.SetRequest(&opUpdate, new(types.UserInput), http.MethodPatch)
reflector.SetJSONResponse(&opUpdate, new(types.User), http.StatusOK)
reflector.SetJSONResponse(&opUpdate, new(render.Error), http.StatusInternalServerError)
reflector.Spec.AddOperation(http.MethodPatch, "/user", opUpdate)
_ = reflector.SetRequest(&opUpdate, new(types.UserInput), http.MethodPatch)
_ = reflector.SetJSONResponse(&opUpdate, new(types.User), http.StatusOK)
_ = reflector.SetJSONResponse(&opUpdate, new(render.Error), http.StatusInternalServerError)
_ = reflector.Spec.AddOperation(http.MethodPatch, "/user", opUpdate)

opToken := openapi3.Operation{}
opToken.WithTags("user")
opToken.WithMapOfAnything(map[string]interface{}{"operationId": "createToken"})
reflector.SetRequest(&opToken, new(types.Token), http.MethodPost)
reflector.SetJSONResponse(&opToken, new(types.User), http.StatusOK)
reflector.SetJSONResponse(&opToken, new(render.Error), http.StatusInternalServerError)
reflector.Spec.AddOperation(http.MethodPost, "/user/token", opToken)
_ = reflector.SetRequest(&opToken, new(types.Token), http.MethodPost)
_ = reflector.SetJSONResponse(&opToken, new(types.User), http.StatusOK)
_ = reflector.SetJSONResponse(&opToken, new(render.Error), http.StatusInternalServerError)
_ = reflector.Spec.AddOperation(http.MethodPost, "/user/token", opToken)

opCurrent := openapi3.Operation{}
opCurrent.WithTags("user")
opCurrent.WithMapOfAnything(map[string]interface{}{"operationId": "getCurrentUser"})
reflector.SetRequest(&opFind, new(baseRequest), http.MethodGet)
reflector.SetJSONResponse(&opCurrent, new(currentUserResponse), http.StatusOK)
reflector.SetJSONResponse(&opCurrent, new(render.Error), http.StatusInternalServerError)
reflector.Spec.AddOperation(http.MethodGet, "/api/user/currentUser", opCurrent)
_ = reflector.SetRequest(&opFind, new(baseRequest), http.MethodGet)
_ = reflector.SetJSONResponse(&opCurrent, new(currentUserResponse), http.StatusOK)
_ = reflector.SetJSONResponse(&opCurrent, new(render.Error), http.StatusInternalServerError)
_ = reflector.Spec.AddOperation(http.MethodGet, "/api/user/currentUser", opCurrent)
}
Loading

0 comments on commit ca8aa47

Please sign in to comment.