diff --git a/.travis.yml b/.travis.yml index c6647c0..468b105 100644 --- a/.travis.yml +++ b/.travis.yml @@ -9,6 +9,9 @@ env: - PACKAGE_TYPE=deb - PACKAGE_TYPE=rpm +install: + - go get -u golang.org/x/lint/golint + script: make test before_install: diff --git a/Makefile b/Makefile index 92072a9..267971f 100644 --- a/Makefile +++ b/Makefile @@ -7,7 +7,7 @@ DATADIR := ./data CI_COMMIT ?= dev GIT_COMMIT := $(shell git rev-parse --short HEAD || echo $(CI_COMMIT)) VERSION ?= $(shell cat ./VERSION) -FLAGS := "-X main.GitCommit=$(GIT_COMMIT) -X main.Version=$(VERSION)" +FLAGS := "-X main.gitCommit=$(GIT_COMMIT) -X main.version=$(VERSION)" DISTRIBUTIONS := ubuntu debian rhel centos opensuse sles amzn PACKAGE_TYPE := deb rpm @@ -43,7 +43,7 @@ clean: ## cleans up the repository /bin/rm -rf $(DATADIR) /bin/rm -rf ./.state -test: vet ## runs unit tests +test: lint vet ## runs unit tests go test -v ./... format: ## formats the code @@ -52,6 +52,9 @@ format: ## formats the code vet: ## examines the go code with `go vet` go vet ./... +lint: ## lint the source code + golint -set_exit_status $(shell go list ./...) + up: $(addprefix up/,$(DISTRIBUTIONS)) ## start agents for all distributions up/%: build ## starts the agent for a specific distribution mkdir -p .state diff --git a/client.go b/client.go index f608fa2..89dad9a 100644 --- a/client.go +++ b/client.go @@ -9,54 +9,59 @@ import ( "strings" "time" - "github.com/tactycal/agent/packageLookup" + "github.com/tactycal/agent/packagelookup" ) const ( - DefaultClientTimeout = time.Second * 3 - ErrorCodeExpiredToken = "TOKEN_EXPIRED" - ErrorCodeInvalidToken = "TOKEN_INVALID" + defaultClientTimeout = time.Second * 3 + errorCodeExpiredToken = "TOKEN_EXPIRED" + errorCodeInvalidToken = "TOKEN_INVALID" apiVersionPrefix = "v2" ) -type Client struct { +// List of errors +var ( + ErrInvalidToken = fmt.Errorf("token was reported as invalid (perhaps the host was deleted), new host ID will be assigned to this machine") +) + +type client struct { token string host *Host uri string - proxyUrl *url.URL - state *State + proxyURL *url.URL + state *state timeout time.Duration } -type SendPackagesRequestBody struct { +type sendPackagesRequestBody struct { *Host - Package []*packageLookup.Package `json:"packages"` + Package []*packagelookup.Package `json:"packages"` } -type ResponseErrorCode struct { +type responseErrorCode struct { Error string `json:"error"` } -type Token struct { +type token struct { Token string `json:"token"` } -func NewClient(cfg *Config, host *Host, state *State, timeout time.Duration) *Client { +func newClient(cfg *config, host *Host, state *state, timeout time.Duration) *client { // copy labels from config to host host.Labels = cfg.Labels // compose the client - return &Client{ + return &client{ token: cfg.Token, host: host, - uri: cfg.Uri, - proxyUrl: cfg.Proxy, + uri: cfg.URI, + proxyURL: cfg.Proxy, state: state, timeout: timeout, } } -func (c *Client) Authenticate() (string, error) { +func (c *client) Authenticate() (string, error) { // create a request rsp, err := c.apiRequest("POST", "/agent/auth", fmt.Sprintf("Token %s", c.token), &c.host) if err != nil { @@ -72,7 +77,7 @@ func (c *Client) Authenticate() (string, error) { } // decode the response - var rspData Token + var rspData token decoder := json.NewDecoder(rsp.Body) err = decoder.Decode(&rspData) if err != nil { @@ -82,13 +87,13 @@ func (c *Client) Authenticate() (string, error) { return rspData.Token, nil } -func (c *Client) SendPackageList(packages []*packageLookup.Package) error { +func (c *client) SendPackageList(packages []*packagelookup.Package) error { token, err := c.getToken() if err != nil { return err } - body := &SendPackagesRequestBody{ + body := &sendPackagesRequestBody{ Host: c.host, Package: packages, } @@ -117,20 +122,20 @@ func (c *Client) SendPackageList(packages []*packageLookup.Package) error { // handle invalid or expired token response if rsp.StatusCode == http.StatusUnauthorized { // check error code - errCode := &ResponseErrorCode{} + errCode := &responseErrorCode{} if err := json.NewDecoder(rsp.Body).Decode(errCode); err != nil { return err } - if errCode.Error == ErrorCodeInvalidToken { + if errCode.Error == errorCodeInvalidToken { if err := c.state.Reset(); err != nil { return err } - return fmt.Errorf("Token was reported as invalid. Perhaps the host was deleted. New host ID will be assigned to this machine.") + return ErrInvalidToken } // renew a token - if errCode.Error == ErrorCodeExpiredToken { + if errCode.Error == errorCodeExpiredToken { err := c.renewToken(token) if err == nil { err = fmt.Errorf("Token was reported as expired. It has been renewed") @@ -142,7 +147,7 @@ func (c *Client) SendPackageList(packages []*packageLookup.Package) error { return fmt.Errorf("API returned status code %d, expected 204", rsp.StatusCode) } -func (c *Client) getToken() (string, error) { +func (c *client) getToken() (string, error) { // try to read token from state token, err := c.state.GetToken() if err == nil && token != "" { @@ -164,9 +169,9 @@ func (c *Client) getToken() (string, error) { return token, nil } -func (c *Client) renewToken(token string) error { +func (c *client) renewToken(accessToken string) error { // create a request - rsp, err := c.apiRequest("POST", "/agent/renew", fmt.Sprintf("Token %s", c.token), &Token{token}) + rsp, err := c.apiRequest("POST", "/agent/renew", fmt.Sprintf("Token %s", c.token), &token{accessToken}) if err != nil { return err } @@ -176,14 +181,14 @@ func (c *Client) renewToken(token string) error { if rsp.StatusCode == 401 { c.state.Reset() - return fmt.Errorf("Token was reported as invalid. Perhaps the host was deleted. New host ID will be assigned to this machine.") + return ErrInvalidToken } if rsp.StatusCode != 200 { return fmt.Errorf("Token could not be renewed") } - var rspData Token + var rspData token decoder := json.NewDecoder(rsp.Body) err = decoder.Decode(&rspData) if err != nil { @@ -196,7 +201,7 @@ func (c *Client) renewToken(token string) error { return err } -func (c *Client) apiRequest(method, endpoint, authorization string, input interface{}) (*http.Response, error) { +func (c *client) apiRequest(method, endpoint, authorization string, input interface{}) (*http.Response, error) { // encode body body := bytes.NewBuffer(nil) if input != nil { @@ -223,7 +228,7 @@ func (c *Client) apiRequest(method, endpoint, authorization string, input interf // execute the request client := &http.Client{ Transport: &http.Transport{ - Proxy: http.ProxyURL(c.proxyUrl), + Proxy: http.ProxyURL(c.proxyURL), }, Timeout: c.timeout, } diff --git a/client_test.go b/client_test.go index bfd5259..3a6474f 100644 --- a/client_test.go +++ b/client_test.go @@ -11,7 +11,7 @@ import ( "strings" "testing" - "github.com/tactycal/agent/packageLookup" + "github.com/tactycal/agent/packagelookup" ) func TestAuthenticate_Ok(t *testing.T) { @@ -34,12 +34,12 @@ func TestAuthenticate_Ok(t *testing.T) { initLogging(false) - client := &Client{ + c := &client{ uri: ts.URL, token: "token", } - result, err := client.Authenticate() + result, err := c.Authenticate() if err != nil { t.Errorf("An error was not expected; got \"%s\"", err.Error()) } @@ -62,9 +62,9 @@ func TestAuthenticate_StatusUnauthorized(t *testing.T) { initLogging(false) - client := &Client{uri: ts.URL} + c := &client{uri: ts.URL} - _, err := client.Authenticate() + _, err := c.Authenticate() if err == nil { t.Error("Expected err to not be nil") @@ -86,19 +86,19 @@ func TestAuthenticate_CloseConn(t *testing.T) { initLogging(false) - client := &Client{uri: ts.URL} + c := &client{uri: ts.URL} - _, err := client.Authenticate() + _, err := c.Authenticate() if err == nil { t.Errorf("An error was expected") } } func TestSendPackageList_Ok(t *testing.T) { - expectedReqBody := &SendPackagesRequestBody{ + expectedReqBody := &sendPackagesRequestBody{ Host: &Host{Fqdn: "Fqdn"}, - Package: []*packageLookup.Package{ - &packageLookup.Package{ + Package: []*packagelookup.Package{ + &packagelookup.Package{ Name: "Package", }, }, @@ -108,11 +108,11 @@ func TestSendPackageList_Ok(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Header.Get("Authorization") != "JWT token" { w.WriteHeader(http.StatusUnauthorized) - json.NewEncoder(w).Encode(&ResponseErrorCode{ErrorCodeInvalidToken}) + json.NewEncoder(w).Encode(&responseErrorCode{errorCodeInvalidToken}) return } - reqBody := &SendPackagesRequestBody{} + reqBody := &sendPackagesRequestBody{} err := json.NewDecoder(r.Body).Decode(reqBody) if err != nil { http.Error(w, "", http.StatusInternalServerError) @@ -136,29 +136,29 @@ func TestSendPackageList_Ok(t *testing.T) { defer os.Remove(tmpFile.Name()) // get a state - state := NewState(tmpFile.Name()) + state := newState(tmpFile.Name()) // setup a client - client := &Client{ + c := &client{ state: state, uri: ts.URL, host: expectedReqBody.Host, } - err := client.SendPackageList(expectedReqBody.Package) + err := c.SendPackageList(expectedReqBody.Package) if err != nil { t.Errorf("An error was not expected; got \"%s\"", err.Error()) } } func TestSendPackageList_InvalidToken(t *testing.T) { - expectedErr := "Token was reported as invalid. Perhaps the host was deleted. New host ID will be assigned to this machine." + expectedErr := ErrInvalidToken.Error() // setup a mock server ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Header.Get("Authorization") != "JWT token" { w.WriteHeader(http.StatusUnauthorized) - json.NewEncoder(w).Encode(&ResponseErrorCode{ErrorCodeInvalidToken}) + json.NewEncoder(w).Encode(&responseErrorCode{errorCodeInvalidToken}) return } })) @@ -172,15 +172,15 @@ func TestSendPackageList_InvalidToken(t *testing.T) { defer os.Remove(tmpFile.Name()) // get a state - state := NewState(tmpFile.Name()) + state := newState(tmpFile.Name()) // setup a client - client := &Client{ + c := &client{ state: state, uri: ts.URL, } - err := client.SendPackageList([]*packageLookup.Package{}) + err := c.SendPackageList([]*packagelookup.Package{}) if err == nil { t.Error("Expected err to not be nil") @@ -197,28 +197,28 @@ func TestSendPackageList_ExpiredToken(t *testing.T) { // setup a mock server ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - reqUrl := r.URL.Path + reqURL := r.URL.Path // 0.1 packages will be submitted with expired token - if strings.HasSuffix(reqUrl, "/submit") && r.Header.Get("Authorization") == "JWT expired_token" { + if strings.HasSuffix(reqURL, "/submit") && r.Header.Get("Authorization") == "JWT expired_token" { w.WriteHeader(http.StatusUnauthorized) - json.NewEncoder(w).Encode(&ResponseErrorCode{ErrorCodeExpiredToken}) + json.NewEncoder(w).Encode(&responseErrorCode{errorCodeExpiredToken}) return } // 0.2 a renew process is expected - if strings.HasSuffix(reqUrl, "/renew") && r.Header.Get("Authorization") == "Token token" { - var token Token - json.NewDecoder(r.Body).Decode(&token) - if token.Token != "expired_token" { + if strings.HasSuffix(reqURL, "/renew") && r.Header.Get("Authorization") == "Token token" { + var tkn token + json.NewDecoder(r.Body).Decode(&tkn) + if tkn.Token != "expired_token" { w.WriteHeader(http.StatusBadRequest) return } w.WriteHeader(http.StatusOK) // return a new token - token.Token = expectedNewToken - json.NewEncoder(w).Encode(token) + tkn.Token = expectedNewToken + json.NewEncoder(w).Encode(tkn) return } @@ -235,16 +235,16 @@ func TestSendPackageList_ExpiredToken(t *testing.T) { defer os.Remove(tmpFile.Name()) // get a state - state := NewState(tmpFile.Name()) + state := newState(tmpFile.Name()) // setup a client - client := &Client{ + c := &client{ state: state, uri: ts.URL, token: "token", } - err := client.SendPackageList([]*packageLookup.Package{}) + err := c.SendPackageList([]*packagelookup.Package{}) if err == nil { t.Error("Expected err to not be nil") diff --git a/config.go b/config.go index 5b9b714..1f86528 100644 --- a/config.go +++ b/config.go @@ -9,24 +9,24 @@ import ( "strings" "time" - "github.com/tactycal/agent/stubUtils" + "github.com/tactycal/agent/stubutils" ) const ( - DefaultConfigurationFile = "/etc/tactycal/agent.conf" - DefaultApiUri = "https://api.tactycal.com" + defaultConfigurationFile = "/etc/tactycal/agent.conf" + defaultAPIURI = "https://api.tactycal.com" ) -type Config struct { +type config struct { Token string - Uri string + URI string Proxy *url.URL Labels []string StatePath string ClientTimeout time.Duration } -func NewConfig(file, statePath string, clientTimeout time.Duration) (*Config, error) { +func newConfig(file, statePath string, clientTimeout time.Duration) (*config, error) { cfg, err := readConfigurationFromFile(file) if err != nil { return nil, errors.New("configuration: " + err.Error()) @@ -34,7 +34,7 @@ func NewConfig(file, statePath string, clientTimeout time.Duration) (*Config, er // set defaults if cfg["uri"] == "" { - cfg["uri"] = DefaultApiUri + cfg["uri"] = defaultAPIURI } else { // trim trailing slashes cfg["uri"] = strings.TrimRight(cfg["uri"], "/") @@ -51,7 +51,7 @@ func NewConfig(file, statePath string, clientTimeout time.Duration) (*Config, er // check token is set if cfg["token"] == "" { - return nil, errors.New("configuration: No token provided.") + return nil, errors.New("configuration: No token provided") } // set client timeout @@ -70,19 +70,19 @@ func NewConfig(file, statePath string, clientTimeout time.Duration) (*Config, er } // finally! :) - config := &Config{ + c := &config{ Token: cfg["token"], - Uri: cfg["uri"], + URI: cfg["uri"], Proxy: urlProxy, Labels: cleanSplit(cfg["labels"]), ClientTimeout: timeout, StatePath: cfg["state"], } - return config, nil + return c, nil } func readConfigurationFromFile(file string) (map[string]string, error) { - data, err := stubUtils.ReadFile(file) + data, err := stubutils.ReadFile(file) if err != nil { return nil, err } @@ -114,16 +114,16 @@ func cleanSplit(str string) []string { // check if we need to substitute any of the values if arr[key][:1] == `$` { - arr[key] = Getenv(arr[key][1:], arr[key][1:]) + arr[key] = getenv(arr[key][1:], arr[key][1:]) } } return arr } -// Retuns value of environment variable `name`. If env. variable is empty the +// getenv returns value of environment variable `name`. If env. variable is empty, // defaultValue is returned. -func Getenv(name, defaultValue string) string { +func getenv(name, defaultValue string) string { if v := os.Getenv(name); v != "" { return v } diff --git a/config_test.go b/config_test.go index f64fa5f..ecdfe4e 100644 --- a/config_test.go +++ b/config_test.go @@ -9,21 +9,21 @@ import ( "testing" "time" - "github.com/tactycal/agent/stubUtils" + "github.com/tactycal/agent/stubutils" ) func TestNewConfig_Valid(t *testing.T) { fixtures := []struct { title string data []byte - expected *Config + expected *config }{ { title: "minimal config", data: []byte(`token=TOKEN`), - expected: &Config{ + expected: &config{ Token: "TOKEN", - Uri: "https://api.tactycal.com", + URI: "https://api.tactycal.com", Labels: []string{}, StatePath: "/default/path", ClientTimeout: time.Second, @@ -36,9 +36,9 @@ func TestNewConfig_Valid(t *testing.T) { labels=$PATH,label timeout=10s state=/path/to/state`), - expected: &Config{ + expected: &config{ Token: "TOKEN", - Uri: "API_URL", + URI: "API_URL", Labels: []string{os.Getenv("PATH"), "label"}, ClientTimeout: time.Second * 10, StatePath: "/path/to/state", @@ -48,11 +48,11 @@ func TestNewConfig_Valid(t *testing.T) { for _, fixture := range fixtures { t.Run(fixture.title, func(t *testing.T) { - s := stubUtils.NewStubs(t, &stubUtils.ReadFileStub{Path: "path", Output: fixture.data}) + s := stubutils.NewStubs(t, &stubutils.ReadFileStub{Path: "path", Output: fixture.data}) defer s.Close() // parse - c, err := NewConfig("path", "/default/path", time.Second) + c, err := newConfig("path", "/default/path", time.Second) if err != nil { t.Error("Error should be nil; got", err) @@ -92,15 +92,15 @@ func TestNewConfig_Errors(t *testing.T) { for _, fixture := range fixtures { t.Run(fixture.title, func(t *testing.T) { // // create a temp file - s := stubUtils.NewStubs(t) + s := stubutils.NewStubs(t) if bytes.Equal(fixture.data, []byte("missing")) { - s.Add(&stubUtils.ReadFileStub{Err: stubUtils.OhNoErr}) + s.Add(&stubutils.ReadFileStub{Err: stubutils.ErrOhNo}) } else { - s.Add(&stubUtils.ReadFileStub{Output: fixture.data}) + s.Add(&stubutils.ReadFileStub{Output: fixture.data}) } // parse - c, err := NewConfig("path", "/default/path", time.Second) + c, err := newConfig("path", "/default/path", time.Second) if c != nil { t.Errorf("Expected Config to be nil; got %+v", c) @@ -117,7 +117,7 @@ func TestNewConfig_Errors(t *testing.T) { } } -func mustParseUrl(rawUrl string) *url.URL { - parsed, _ := url.Parse(rawUrl) +func mustParseURL(rawURL string) *url.URL { + parsed, _ := url.Parse(rawURL) return parsed } diff --git a/host.go b/host.go index 3c56c77..54c9eec 100644 --- a/host.go +++ b/host.go @@ -1,7 +1,8 @@ package main -import "github.com/tactycal/agent/osDiscovery" +import "github.com/tactycal/agent/osdiscovery" +// Host holds information about a single host type Host struct { Fqdn string `json:"fqdn"` Distribution string `json:"distribution"` @@ -11,9 +12,9 @@ type Host struct { Labels []string `json:"labels"` } -func GetHostInfo() (*Host, error) { +func getHostInfo() (*Host, error) { - osInfo, err := osDiscovery.Get() + osInfo, err := osdiscovery.Get() if err != nil { return nil, err } diff --git a/host_test.go b/host_test.go index b7c196c..d042419 100644 --- a/host_test.go +++ b/host_test.go @@ -4,15 +4,15 @@ import ( "reflect" "testing" - "github.com/tactycal/agent/stubUtils" + "github.com/tactycal/agent/stubutils" ) func TestGetHostInfo(t *testing.T) { - s := stubUtils.NewStubs(t, - &stubUtils.ReadFileStub{Path: "/etc/os-release", Output: []byte("ID=ubuntu\nID_LIKE=debian\nVERSION_ID=\"14.04\"")}, - &stubUtils.CmdStub{Cmd: "uname", Args: []string{"-m"}, Output: []byte("ARCH")}, - &stubUtils.CmdStub{Cmd: "uname", Args: []string{"-r"}, Output: []byte("KERN")}, - &stubUtils.CmdStub{Cmd: "hostname", Args: []string{"-f"}, Output: []byte("FQDN")}, + s := stubutils.NewStubs(t, + &stubutils.ReadFileStub{Path: "/etc/os-release", Output: []byte("ID=ubuntu\nID_LIKE=debian\nVERSION_ID=\"14.04\"")}, + &stubutils.CmdStub{Cmd: "uname", Args: []string{"-m"}, Output: []byte("ARCH")}, + &stubutils.CmdStub{Cmd: "uname", Args: []string{"-r"}, Output: []byte("KERN")}, + &stubutils.CmdStub{Cmd: "hostname", Args: []string{"-f"}, Output: []byte("FQDN")}, ) defer s.Close() expected := &Host{ @@ -23,15 +23,15 @@ func TestGetHostInfo(t *testing.T) { Kernel: "KERN", } - host, _ := GetHostInfo() + host, _ := getHostInfo() if !reflect.DeepEqual(host, expected) { t.Errorf("Host\n%+v\ndoesn't match expected\n%+v\n", host, expected) } - s.Add(&stubUtils.ReadFileStub{Path: "/etc/os-release", Output: []byte("ID=ubuntu\nID_LIKE=debian\nVERSION_ID=\"14.04\"")}, - &stubUtils.CmdStub{Cmd: "uname", Args: []string{"-m"}, Err: stubUtils.OhNoErr}) + s.Add(&stubutils.ReadFileStub{Path: "/etc/os-release", Output: []byte("ID=ubuntu\nID_LIKE=debian\nVERSION_ID=\"14.04\"")}, + &stubutils.CmdStub{Cmd: "uname", Args: []string{"-m"}, Err: stubutils.ErrOhNo}) - _, err := GetHostInfo() + _, err := getHostInfo() if err == nil { t.Error("An error was expected") } diff --git a/local.go b/local.go index bfeefad..b840efe 100644 --- a/local.go +++ b/local.go @@ -3,21 +3,21 @@ package main import ( "encoding/json" - "github.com/tactycal/agent/packageLookup" + "github.com/tactycal/agent/packagelookup" ) // local returns host information and installed packages as json string func local() (string, error) { - host, err := GetHostInfo() + host, err := getHostInfo() if err != nil { return "", err } - packages, err := packageLookup.Get(host.Distribution) + packages, err := packagelookup.Get(host.Distribution) if err != nil { return "", err } - b, err := json.Marshal(&SendPackagesRequestBody{host, packages}) + b, err := json.Marshal(&sendPackagesRequestBody{host, packages}) return string(b), err } diff --git a/local_test.go b/local_test.go index 8f1502a..e1137d7 100644 --- a/local_test.go +++ b/local_test.go @@ -4,16 +4,16 @@ import ( "reflect" "testing" - "github.com/tactycal/agent/stubUtils" + "github.com/tactycal/agent/stubutils" ) func TestLocal(t *testing.T) { - s := stubUtils.NewStubs(t, - &stubUtils.ReadFileStub{Path: "/etc/os-release", Output: []byte("ID=amzn\nVERSION_ID=\"2016.09\"")}, - &stubUtils.CmdStub{Cmd: "uname", Args: []string{"-m"}, Output: []byte("ARCH")}, - &stubUtils.CmdStub{Cmd: "uname", Args: []string{"-r"}, Output: []byte("KERN")}, - &stubUtils.CmdStub{Cmd: "hostname", Args: []string{"-f"}, Output: []byte("FQDN")}, - &stubUtils.CmdStub{Cmd: "rpm", Args: []string{`-qa`, `--queryformat`, + s := stubutils.NewStubs(t, + &stubutils.ReadFileStub{Path: "/etc/os-release", Output: []byte("ID=amzn\nVERSION_ID=\"2016.09\"")}, + &stubutils.CmdStub{Cmd: "uname", Args: []string{"-m"}, Output: []byte("ARCH")}, + &stubutils.CmdStub{Cmd: "uname", Args: []string{"-r"}, Output: []byte("KERN")}, + &stubutils.CmdStub{Cmd: "hostname", Args: []string{"-f"}, Output: []byte("FQDN")}, + &stubutils.CmdStub{Cmd: "rpm", Args: []string{`-qa`, `--queryformat`, `Name: %{NAME}\nArchitecture: %{ARCH}\nVersion: %{VERSION}\nRelease: %{RELEASE}\nVendor: %{VENDOR}\nSource: %{SOURCERPM}\nEpoch: %{EPOCH}\n\n`}, Output: []byte("Name: libverto\nArchitecture: x86_64\nVersion: 0.2.5\nRelease: 4.9\nVendor: unknown\nSource: libverto-0.2.5-4.9.src.rpm\nEpoch: (none)")}, ) @@ -28,21 +28,21 @@ func TestLocal(t *testing.T) { } // 2. error expected from get host info - s.Add(&stubUtils.ReadFileStub{Path: "/etc/os-release", Err: stubUtils.OhNoErr}) + s.Add(&stubutils.ReadFileStub{Path: "/etc/os-release", Err: stubutils.ErrOhNo}) _, err := local() if err == nil { t.Error("An error was expected") } - // 3. error is expected from packageLookup - s.Add(&stubUtils.ReadFileStub{Path: "/etc/os-release", Output: []byte("ID=amzn\nVERSION_ID=\"2016.09\"")}, - &stubUtils.CmdStub{Cmd: "uname", Args: []string{"-m"}, Output: []byte("ARCH")}, - &stubUtils.CmdStub{Cmd: "uname", Args: []string{"-r"}, Output: []byte("KERN")}, - &stubUtils.CmdStub{Cmd: "hostname", Args: []string{"-f"}, Output: []byte("FQDN")}, - &stubUtils.CmdStub{Cmd: "rpm", Args: []string{`-qa`, `--queryformat`, + // 3. error is expected from packagelookup + s.Add(&stubutils.ReadFileStub{Path: "/etc/os-release", Output: []byte("ID=amzn\nVERSION_ID=\"2016.09\"")}, + &stubutils.CmdStub{Cmd: "uname", Args: []string{"-m"}, Output: []byte("ARCH")}, + &stubutils.CmdStub{Cmd: "uname", Args: []string{"-r"}, Output: []byte("KERN")}, + &stubutils.CmdStub{Cmd: "hostname", Args: []string{"-f"}, Output: []byte("FQDN")}, + &stubutils.CmdStub{Cmd: "rpm", Args: []string{`-qa`, `--queryformat`, `Name: %{NAME}\nArchitecture: %{ARCH}\nVersion: %{VERSION}\nRelease: %{RELEASE}\nVendor: %{VENDOR}\nSource: %{SOURCERPM}\nEpoch: %{EPOCH}\n\n`}, - Err: stubUtils.OhNoErr}, + Err: stubutils.ErrOhNo}, ) _, err = local() diff --git a/main.go b/main.go index 532be40..c640c48 100644 --- a/main.go +++ b/main.go @@ -4,21 +4,21 @@ import ( "flag" "fmt" - "github.com/tactycal/agent/packageLookup" + "github.com/tactycal/agent/packagelookup" ) func main() { - configFile := flag.String("f", DefaultConfigurationFile, "use a configuration file") + configFile := flag.String("f", defaultConfigurationFile, "use a configuration file") showVersion := flag.Bool("v", false, "print version and exit") debugMode := flag.Bool("d", false, "show debug messages") - statePath := flag.String("s", DefaultStatePath, "path to where tactycal can write its state") - clientTimeout := flag.Duration("t", DefaultClientTimeout, "client timeout for request in seconds") + statePath := flag.String("s", defaultStatePath, "path to where tactycal can write its state") + clientTimeout := flag.Duration("t", defaultClientTimeout, "client timeout for request in seconds") localOutput := flag.Bool("l", false, "print host information and installed packages to standard output as json string and exit") flag.Parse() if *showVersion { - fmt.Printf("tactycal %s-%s\n", Version, GitCommit) + fmt.Printf("tactycal %s-%s\n", version, gitCommit) return } @@ -34,25 +34,25 @@ func main() { initLogging(*debugMode) - log.Infof("Starting tactycal %s-%s", Version, GitCommit) + log.Infof("Starting tactycal %s-%s", version, gitCommit) - config, err := NewConfig(*configFile, *statePath, *clientTimeout) + config, err := newConfig(*configFile, *statePath, *clientTimeout) if err != nil { log.Fatalf("Failed to read configuration; err = %v", err) } - host, err := GetHostInfo() + host, err := getHostInfo() if err != nil { log.Fatalf("Failed to get host info; err = %v", err) } - packages, err := packageLookup.Get(host.Distribution) + packages, err := packagelookup.Get(host.Distribution) if err != nil { log.Fatalf("Failed to fetch a list of installed packages; err = %v", err) } log.Debugf("Found %d installed packages", len(packages)) - client := NewClient(config, host, NewState(*statePath), *clientTimeout) + client := newClient(config, host, newState(*statePath), *clientTimeout) if err := client.SendPackageList(packages); err != nil { log.Fatalf("Failed to submit list of installed packages; err = %v", err) } diff --git a/osDiscovery/LICENSE b/osdiscovery/LICENSE similarity index 100% rename from osDiscovery/LICENSE rename to osdiscovery/LICENSE diff --git a/osDiscovery/Makefile b/osdiscovery/Makefile similarity index 100% rename from osDiscovery/Makefile rename to osdiscovery/Makefile diff --git a/osDiscovery/README.md b/osdiscovery/README.md similarity index 61% rename from osDiscovery/README.md rename to osdiscovery/README.md index a924252..731677f 100644 --- a/osDiscovery/README.md +++ b/osdiscovery/README.md @@ -1,7 +1,7 @@ ### About -Package `osDiscovery` implements functions to get basic operating system -identification data for Linux operating system. +Package `osdiscovery` implements functions to get basic operating system +identification data for Linux operating system. The following informations are provided: * Distribution name @@ -17,11 +17,11 @@ package main import ( "fmt" - "github.com/tactycal/agent/osDiscovery" + "github.com/tactycal/agent/osdiscovery" ) func main() { - osInfo, err := osDiscovery.Get() + osInfo, err := osdiscovery.Get() if err != nil { fmt.Println(err) } else { diff --git a/osDiscovery/distributionRelease.go b/osdiscovery/distributionRelease.go similarity index 91% rename from osDiscovery/distributionRelease.go rename to osdiscovery/distributionRelease.go index 1f0f1d6..51929e5 100644 --- a/osDiscovery/distributionRelease.go +++ b/osdiscovery/distributionRelease.go @@ -1,4 +1,4 @@ -package osDiscovery +package osdiscovery import ( "fmt" @@ -15,7 +15,7 @@ var distributionSpecificFiles = []string{ "/etc/system-release-cpe", } -var distributionSpecificFilePrefixToDistroId = map[string]string{ +var distributionSpecificFilePrefixToDistroID = map[string]string{ "Debian": "debian", "Ubuntu": "ubuntu", "CentOS": "centos", @@ -28,7 +28,7 @@ var distributionSpecificFilePrefixToDistroId = map[string]string{ "SUSE": "sles", } -var lsbDistributionNameToIdDistributionName = map[string]string{ +var lsbDistributionNameToIDDistributionName = map[string]string{ "Debian": "debian", "Ubuntu": "ubuntu", "RedHatEnterpriseServer": "rhel", @@ -56,7 +56,7 @@ func checkDistributionReleaseValue(distribution, release string) (string, string func parseLsbReleaseContent(content string) (string, string, error) { distribution, release := getValues("Distributor ID:", "Release:", content) - if d, ok := lsbDistributionNameToIdDistributionName[distribution]; ok { + if d, ok := lsbDistributionNameToIDDistributionName[distribution]; ok { distribution = d } @@ -87,7 +87,7 @@ func getValues(regexpField1, regexpField2, content string) (string, string) { // parseSpecificFileContent returns distribution and release if file content prefix // matches distribution specific file prefix. Otherwise an error is returned func parseSpecificFileContent(content string) (string, string, error) { - for k, v := range distributionSpecificFilePrefixToDistroId { + for k, v := range distributionSpecificFilePrefixToDistroID { if strings.HasPrefix(content, k) { if distribution, release := getDistributionReleaseFromSpecificFileContent(v, content); release != "" { return distribution, release, nil @@ -98,8 +98,8 @@ func parseSpecificFileContent(content string) (string, string, error) { return "", "", ErrUnknownDistribution } -func getDistributionReleaseFromSpecificFileContent(distroId, content string) (string, string) { - switch distroId { +func getDistributionReleaseFromSpecificFileContent(distroID, content string) (string, string) { + switch distroID { case "ubuntu": return "ubuntu", getReleaseFromSpecificFileContentDefault("\\d+\\.\\d+", content) case "debian": diff --git a/osDiscovery/distributionRelease_test.go b/osdiscovery/distributionRelease_test.go similarity index 99% rename from osDiscovery/distributionRelease_test.go rename to osdiscovery/distributionRelease_test.go index 7fc5a90..d1e3cfd 100644 --- a/osDiscovery/distributionRelease_test.go +++ b/osdiscovery/distributionRelease_test.go @@ -1,4 +1,4 @@ -package osDiscovery +package osdiscovery import ( "encoding/json" diff --git a/osDiscovery/example_test.go b/osdiscovery/example_test.go similarity index 97% rename from osDiscovery/example_test.go rename to osdiscovery/example_test.go index 717edce..a74d59c 100644 --- a/osDiscovery/example_test.go +++ b/osdiscovery/example_test.go @@ -1,4 +1,4 @@ -package osDiscovery +package osdiscovery import "fmt" diff --git a/osDiscovery/osDiscovery.go b/osdiscovery/osDiscovery.go similarity index 83% rename from osDiscovery/osDiscovery.go rename to osdiscovery/osDiscovery.go index a4800fd..46d3936 100644 --- a/osDiscovery/osDiscovery.go +++ b/osdiscovery/osDiscovery.go @@ -1,4 +1,4 @@ -// Package osDiscovery implements functions to get basic operating system +// Package osdiscovery implements functions to get basic operating system // identification data for Linux operating system. The following informations // are provided: // @@ -10,13 +10,13 @@ // // If any of the called function could not retrieve the information the error // will be returned. -package osDiscovery +package osdiscovery import ( "errors" "strings" - "github.com/tactycal/agent/stubUtils" + "github.com/tactycal/agent/stubutils" ) // OsInfo contains information about the operating system. @@ -28,6 +28,7 @@ type OsInfo struct { Fqdn string `json:"fqdn"` } +// List of possible errors var ( ErrUnknownDistribution = errors.New("Unknown distribution") ErrUnknownRelease = errors.New("Unknown release") @@ -77,19 +78,19 @@ func GetDistributionRelease() (string, string, error) { var err error // os-release - if out, err = stubUtils.ReadFile("/etc/os-release"); err == nil { + if out, err = stubutils.ReadFile("/etc/os-release"); err == nil { distribution, release := getValues("ID=", "VERSION_ID=", string(out)) return checkDistributionReleaseValue(distribution, release) } // fallback to LSB - if out, err = stubUtils.ExecCommand("lsb_release", "-ir"); err == nil { + if out, err = stubutils.ExecCommand("lsb_release", "-ir"); err == nil { return parseLsbReleaseContent(string(out)) } // distro specific for _, f := range distributionSpecificFiles { - if out, err = stubUtils.ReadFile(f); err == nil { + if out, err = stubutils.ReadFile(f); err == nil { distribution, release, err := parseSpecificFileContent(string(out)) if err == nil { return distribution, release, nil @@ -102,7 +103,7 @@ func GetDistributionRelease() (string, string, error) { // GetArchitecture returns a machine hardware name. func GetArchitecture() (string, error) { - if out, err := stubUtils.ExecCommand("uname", "-m"); err == nil { + if out, err := stubutils.ExecCommand("uname", "-m"); err == nil { return strings.TrimSuffix(string(out), "\n"), nil } return "", ErrUnknownArchitecture @@ -110,7 +111,7 @@ func GetArchitecture() (string, error) { // GetKernel returns a kernel release. func GetKernel() (string, error) { - if out, err := stubUtils.ExecCommand("uname", "-r"); err == nil { + if out, err := stubutils.ExecCommand("uname", "-r"); err == nil { return strings.TrimSuffix(string(out), "\n"), nil } return "", ErrUnknownKernel @@ -118,11 +119,11 @@ func GetKernel() (string, error) { // GetFqdn returns the fully qualified domain name (FQDN). func GetFqdn() (string, error) { - if out, err := stubUtils.ExecCommand("hostname", "-f"); err == nil { + if out, err := stubutils.ExecCommand("hostname", "-f"); err == nil { return strings.TrimSuffix(string(out), "\n"), nil } - if out, err := stubUtils.ReadFile("/etc/hostname"); err == nil { + if out, err := stubutils.ReadFile("/etc/hostname"); err == nil { return strings.TrimSuffix(string(out), "\n"), nil } diff --git a/osDiscovery/osDiscovery_test.go b/osdiscovery/osDiscovery_test.go similarity index 56% rename from osDiscovery/osDiscovery_test.go rename to osdiscovery/osDiscovery_test.go index 4c4e426..a7d5100 100644 --- a/osDiscovery/osDiscovery_test.go +++ b/osdiscovery/osDiscovery_test.go @@ -1,23 +1,23 @@ -package osDiscovery +package osdiscovery import ( "reflect" "testing" - "github.com/tactycal/agent/stubUtils" + "github.com/tactycal/agent/stubutils" ) func TestGet(t *testing.T) { - s := stubUtils.NewStubs(t, - &stubUtils.ReadFileStub{Path: "/etc/os-release", Err: stubUtils.OhNoErr}, - &stubUtils.CmdStub{Cmd: "lsb_release", Args: []string{"-ir"}, Err: stubUtils.OhNoErr}, - &stubUtils.ReadFileStub{Path: "/etc/issue", Output: []byte("unknown 8 \n \\l")}, - &stubUtils.ReadFileStub{Path: "/etc/centos-release", Err: stubUtils.OhNoErr}, - &stubUtils.ReadFileStub{Path: "/etc/redhat-release", Output: []byte("unknown 8 \n \\l")}, - &stubUtils.ReadFileStub{Path: "/etc/SuSE-release", Output: []byte("SUSE Linux Enterprise\nVERSION = 12\nPATCHLEVEL = 0\n# This file is d")}, - &stubUtils.CmdStub{Cmd: "uname", Args: []string{"-m"}, Output: []byte("ARCH")}, - &stubUtils.CmdStub{Cmd: "uname", Args: []string{"-r"}, Output: []byte("KERN")}, - &stubUtils.CmdStub{Cmd: "hostname", Args: []string{"-f"}, Output: []byte("FQDN")}, + s := stubutils.NewStubs(t, + &stubutils.ReadFileStub{Path: "/etc/os-release", Err: stubutils.ErrOhNo}, + &stubutils.CmdStub{Cmd: "lsb_release", Args: []string{"-ir"}, Err: stubutils.ErrOhNo}, + &stubutils.ReadFileStub{Path: "/etc/issue", Output: []byte("unknown 8 \n \\l")}, + &stubutils.ReadFileStub{Path: "/etc/centos-release", Err: stubutils.ErrOhNo}, + &stubutils.ReadFileStub{Path: "/etc/redhat-release", Output: []byte("unknown 8 \n \\l")}, + &stubutils.ReadFileStub{Path: "/etc/SuSE-release", Output: []byte("SUSE Linux Enterprise\nVERSION = 12\nPATCHLEVEL = 0\n# This file is d")}, + &stubutils.CmdStub{Cmd: "uname", Args: []string{"-m"}, Output: []byte("ARCH")}, + &stubutils.CmdStub{Cmd: "uname", Args: []string{"-r"}, Output: []byte("KERN")}, + &stubutils.CmdStub{Cmd: "hostname", Args: []string{"-f"}, Output: []byte("FQDN")}, ) defer s.Close() @@ -36,14 +36,14 @@ func TestGet(t *testing.T) { } // 2: unknown distribution - s.Add(&stubUtils.ReadFileStub{Path: "/etc/os-release", Err: stubUtils.OhNoErr}, - &stubUtils.CmdStub{Cmd: "lsb_release", Args: []string{"-ir"}, Err: stubUtils.OhNoErr}, - &stubUtils.ReadFileStub{Path: "/etc/issue", Output: []byte("unknown 8 \n \\l")}, - &stubUtils.ReadFileStub{Path: "/etc/centos-release", Err: stubUtils.OhNoErr}, - &stubUtils.ReadFileStub{Path: "/etc/redhat-release", Output: []byte("unknown 8 \n \\l")}, - &stubUtils.ReadFileStub{Path: "/etc/SuSE-release", Err: stubUtils.OhNoErr}, - &stubUtils.ReadFileStub{Path: "/etc/system-release", Err: stubUtils.OhNoErr}, - &stubUtils.ReadFileStub{Path: "/etc/system-release-cpe", Err: stubUtils.OhNoErr}, + s.Add(&stubutils.ReadFileStub{Path: "/etc/os-release", Err: stubutils.ErrOhNo}, + &stubutils.CmdStub{Cmd: "lsb_release", Args: []string{"-ir"}, Err: stubutils.ErrOhNo}, + &stubutils.ReadFileStub{Path: "/etc/issue", Output: []byte("unknown 8 \n \\l")}, + &stubutils.ReadFileStub{Path: "/etc/centos-release", Err: stubutils.ErrOhNo}, + &stubutils.ReadFileStub{Path: "/etc/redhat-release", Output: []byte("unknown 8 \n \\l")}, + &stubutils.ReadFileStub{Path: "/etc/SuSE-release", Err: stubutils.ErrOhNo}, + &stubutils.ReadFileStub{Path: "/etc/system-release", Err: stubutils.ErrOhNo}, + &stubutils.ReadFileStub{Path: "/etc/system-release-cpe", Err: stubutils.ErrOhNo}, ) _, err := Get() @@ -54,12 +54,12 @@ func TestGet(t *testing.T) { } func TestGetDistributionRelease(t *testing.T) { - s := stubUtils.NewStubs(t) + s := stubutils.NewStubs(t) defer s.Close() // 1: os-release // 1.1: all good - s.Add(&stubUtils.ReadFileStub{Path: "/etc/os-release", Output: []byte("ID=ubuntu\nID_LIKE=debian\nVERSION_ID=\"14.04\"\nHOME_URL=\"http://www.ubuntu.com/\"")}) + s.Add(&stubutils.ReadFileStub{Path: "/etc/os-release", Output: []byte("ID=ubuntu\nID_LIKE=debian\nVERSION_ID=\"14.04\"\nHOME_URL=\"http://www.ubuntu.com/\"")}) distribution, release, _ := GetDistributionRelease() if distribution != "ubuntu" { @@ -70,7 +70,7 @@ func TestGetDistributionRelease(t *testing.T) { } // 1.2: unknown distribution - s.Add(&stubUtils.ReadFileStub{Path: "/etc/os-release", Output: []byte("\nID_LIKE=debian\nVERSION_ID=\"14.04\"\nHOME_URL=\"http://www.ubuntu.com/\"")}) + s.Add(&stubutils.ReadFileStub{Path: "/etc/os-release", Output: []byte("\nID_LIKE=debian\nVERSION_ID=\"14.04\"\nHOME_URL=\"http://www.ubuntu.com/\"")}) _, _, err := GetDistributionRelease() if err != ErrUnknownDistribution { @@ -78,7 +78,7 @@ func TestGetDistributionRelease(t *testing.T) { } // 1.3: unknown release - s.Add(&stubUtils.ReadFileStub{Path: "/etc/os-release", Output: []byte("ID=ubuntu\nID_LIKE=debian\nHOME_URL=\"http://www.ubuntu.com/\"")}) + s.Add(&stubutils.ReadFileStub{Path: "/etc/os-release", Output: []byte("ID=ubuntu\nID_LIKE=debian\nHOME_URL=\"http://www.ubuntu.com/\"")}) _, _, err = GetDistributionRelease() if err != ErrUnknownRelease { @@ -87,8 +87,8 @@ func TestGetDistributionRelease(t *testing.T) { // 2: lsbFallback // 2.1: all good - s.Add(&stubUtils.ReadFileStub{Path: "/etc/os-release", Err: stubUtils.OhNoErr}, - &stubUtils.CmdStub{Cmd: "lsb_release", Args: []string{"-ir"}, Output: []byte("Description: Red Hat \n Distributor ID: RedHatEnterpriseServer\nRelease: 7.3")}) + s.Add(&stubutils.ReadFileStub{Path: "/etc/os-release", Err: stubutils.ErrOhNo}, + &stubutils.CmdStub{Cmd: "lsb_release", Args: []string{"-ir"}, Output: []byte("Description: Red Hat \n Distributor ID: RedHatEnterpriseServer\nRelease: 7.3")}) distribution, release, _ = GetDistributionRelease() if distribution != "rhel" { @@ -99,8 +99,8 @@ func TestGetDistributionRelease(t *testing.T) { } // 2.2: unknown distribution - s.Add(&stubUtils.ReadFileStub{Path: "/etc/os-release", Err: stubUtils.OhNoErr}, - &stubUtils.CmdStub{Cmd: "lsb_release", Args: []string{"-ir"}, Output: []byte("Description: Red Hat \n Missing ID: RedHatEnterpriseServer\nRelease: 7.3")}) + s.Add(&stubutils.ReadFileStub{Path: "/etc/os-release", Err: stubutils.ErrOhNo}, + &stubutils.CmdStub{Cmd: "lsb_release", Args: []string{"-ir"}, Output: []byte("Description: Red Hat \n Missing ID: RedHatEnterpriseServer\nRelease: 7.3")}) _, _, err = GetDistributionRelease() if err != ErrUnknownDistribution { @@ -108,8 +108,8 @@ func TestGetDistributionRelease(t *testing.T) { } // 2.3: unknown release - s.Add(&stubUtils.ReadFileStub{Path: "/etc/os-release", Err: stubUtils.OhNoErr}, - &stubUtils.CmdStub{Cmd: "lsb_release", Args: []string{"-ir"}, Output: []byte("Description: Red Hat \n Distributor ID: RedHatEnterpriseServer\nMissing: 7.3")}) + s.Add(&stubutils.ReadFileStub{Path: "/etc/os-release", Err: stubutils.ErrOhNo}, + &stubutils.CmdStub{Cmd: "lsb_release", Args: []string{"-ir"}, Output: []byte("Description: Red Hat \n Distributor ID: RedHatEnterpriseServer\nMissing: 7.3")}) _, _, err = GetDistributionRelease() if err != ErrUnknownRelease { @@ -118,9 +118,9 @@ func TestGetDistributionRelease(t *testing.T) { // 3: distribution specific // 3.1: all good - s.Add(&stubUtils.ReadFileStub{Path: "/etc/os-release", Err: stubUtils.OhNoErr}, - &stubUtils.CmdStub{Cmd: "lsb_release", Args: []string{"-ir"}, Err: stubUtils.OhNoErr}, - &stubUtils.ReadFileStub{Path: "/etc/issue", Output: []byte("Debian GNU/Linux 8 \n \\l")}) + s.Add(&stubutils.ReadFileStub{Path: "/etc/os-release", Err: stubutils.ErrOhNo}, + &stubutils.CmdStub{Cmd: "lsb_release", Args: []string{"-ir"}, Err: stubutils.ErrOhNo}, + &stubutils.ReadFileStub{Path: "/etc/issue", Output: []byte("Debian GNU/Linux 8 \n \\l")}) distribution, release, _ = GetDistributionRelease() if distribution != "debian" { @@ -131,14 +131,14 @@ func TestGetDistributionRelease(t *testing.T) { } // 3.2: unknown - s.Add(&stubUtils.ReadFileStub{Path: "/etc/os-release", Err: stubUtils.OhNoErr}, - &stubUtils.CmdStub{Cmd: "lsb_release", Args: []string{"-ir"}, Err: stubUtils.OhNoErr}, - &stubUtils.ReadFileStub{Path: "/etc/issue", Output: []byte("unknown 8 \n \\l")}, - &stubUtils.ReadFileStub{Path: "/etc/centos-release", Err: stubUtils.OhNoErr}, - &stubUtils.ReadFileStub{Path: "/etc/redhat-release", Output: []byte("unknown 8 \n \\l")}, - &stubUtils.ReadFileStub{Path: "/etc/SuSE-release", Err: stubUtils.OhNoErr}, - &stubUtils.ReadFileStub{Path: "/etc/system-release", Output: []byte("unknown 8 \n \\l")}, - &stubUtils.ReadFileStub{Path: "/etc/system-release-cpe", Err: stubUtils.OhNoErr}, + s.Add(&stubutils.ReadFileStub{Path: "/etc/os-release", Err: stubutils.ErrOhNo}, + &stubutils.CmdStub{Cmd: "lsb_release", Args: []string{"-ir"}, Err: stubutils.ErrOhNo}, + &stubutils.ReadFileStub{Path: "/etc/issue", Output: []byte("unknown 8 \n \\l")}, + &stubutils.ReadFileStub{Path: "/etc/centos-release", Err: stubutils.ErrOhNo}, + &stubutils.ReadFileStub{Path: "/etc/redhat-release", Output: []byte("unknown 8 \n \\l")}, + &stubutils.ReadFileStub{Path: "/etc/SuSE-release", Err: stubutils.ErrOhNo}, + &stubutils.ReadFileStub{Path: "/etc/system-release", Output: []byte("unknown 8 \n \\l")}, + &stubutils.ReadFileStub{Path: "/etc/system-release-cpe", Err: stubutils.ErrOhNo}, ) _, _, err = GetDistributionRelease() @@ -148,31 +148,31 @@ func TestGetDistributionRelease(t *testing.T) { } func TestGetFqdn(t *testing.T) { - s := stubUtils.NewStubs(t) + s := stubutils.NewStubs(t) defer s.Close() // 1: all good - s.Add(&stubUtils.CmdStub{Cmd: "hostname", Args: []string{"-f"}, Output: []byte("HOST")}) + s.Add(&stubutils.CmdStub{Cmd: "hostname", Args: []string{"-f"}, Output: []byte("HOST")}) if out, _ := GetFqdn(); out != "HOST" { t.Errorf("Expected \"host\"; got %s", out) } // 2: new line - s.Add(&stubUtils.CmdStub{Cmd: "hostname", Args: []string{"-f"}, Output: []byte("HOST\n")}) + s.Add(&stubutils.CmdStub{Cmd: "hostname", Args: []string{"-f"}, Output: []byte("HOST\n")}) if out, _ := GetFqdn(); out != "HOST" { t.Errorf("Expected \"host\"; got %s", out) } // 3: file - s.Add(&stubUtils.CmdStub{Cmd: "hostname", Args: []string{"-f"}, Err: stubUtils.OhNoErr}, - &stubUtils.ReadFileStub{Path: "/etc/hostname", Output: []byte("HOST")}) + s.Add(&stubutils.CmdStub{Cmd: "hostname", Args: []string{"-f"}, Err: stubutils.ErrOhNo}, + &stubutils.ReadFileStub{Path: "/etc/hostname", Output: []byte("HOST")}) if out, _ := GetFqdn(); out != "HOST" { t.Errorf("Expected \"host\"; got %s", out) } // 4: unknown - s.Add(&stubUtils.CmdStub{Cmd: "hostname", Args: []string{"-f"}, Err: stubUtils.OhNoErr}, - &stubUtils.ReadFileStub{Path: "/etc/hostname", Err: stubUtils.OhNoErr}) + s.Add(&stubutils.CmdStub{Cmd: "hostname", Args: []string{"-f"}, Err: stubutils.ErrOhNo}, + &stubutils.ReadFileStub{Path: "/etc/hostname", Err: stubutils.ErrOhNo}) if _, err := GetFqdn(); err != ErrUnknownFqdn { t.Errorf("Expected error \"%s\"; got %s", ErrUnknownFqdn.Error(), err.Error()) } @@ -180,10 +180,10 @@ func TestGetFqdn(t *testing.T) { } func TestGetArchitecture(t *testing.T) { - s := stubUtils.NewStubs(t, - &stubUtils.CmdStub{Cmd: "uname", Args: []string{"-m"}, Output: []byte("ARCH")}, - &stubUtils.CmdStub{Cmd: "uname", Args: []string{"-m"}, Output: []byte("ARCH\n")}, - &stubUtils.CmdStub{Cmd: "uname", Args: []string{"-m"}, Err: stubUtils.OhNoErr}) + s := stubutils.NewStubs(t, + &stubutils.CmdStub{Cmd: "uname", Args: []string{"-m"}, Output: []byte("ARCH")}, + &stubutils.CmdStub{Cmd: "uname", Args: []string{"-m"}, Output: []byte("ARCH\n")}, + &stubutils.CmdStub{Cmd: "uname", Args: []string{"-m"}, Err: stubutils.ErrOhNo}) defer s.Close() // 1: all good @@ -204,10 +204,10 @@ func TestGetArchitecture(t *testing.T) { } func TestGetKernel(t *testing.T) { - s := stubUtils.NewStubs(t, - &stubUtils.CmdStub{Cmd: "uname", Args: []string{"-r"}, Output: []byte("KERN")}, - &stubUtils.CmdStub{Cmd: "uname", Args: []string{"-r"}, Output: []byte("KERN\n")}, - &stubUtils.CmdStub{Cmd: "uname", Args: []string{"-r"}, Err: stubUtils.OhNoErr}) + s := stubutils.NewStubs(t, + &stubutils.CmdStub{Cmd: "uname", Args: []string{"-r"}, Output: []byte("KERN")}, + &stubutils.CmdStub{Cmd: "uname", Args: []string{"-r"}, Output: []byte("KERN\n")}, + &stubutils.CmdStub{Cmd: "uname", Args: []string{"-r"}, Err: stubutils.ErrOhNo}) defer s.Close() // 1: all good diff --git a/osDiscovery/testdata/distroSpecific.json b/osdiscovery/testdata/distroSpecific.json similarity index 100% rename from osDiscovery/testdata/distroSpecific.json rename to osdiscovery/testdata/distroSpecific.json diff --git a/osDiscovery/testdata/lsbFallback.json b/osdiscovery/testdata/lsbFallback.json similarity index 100% rename from osDiscovery/testdata/lsbFallback.json rename to osdiscovery/testdata/lsbFallback.json diff --git a/packageLookup/LICENSE b/packagelookup/LICENSE similarity index 100% rename from packageLookup/LICENSE rename to packagelookup/LICENSE diff --git a/packageLookup/Makefile b/packagelookup/Makefile similarity index 100% rename from packageLookup/Makefile rename to packagelookup/Makefile diff --git a/packageLookup/README.md b/packagelookup/README.md similarity index 68% rename from packageLookup/README.md rename to packagelookup/README.md index 2c25135..fb5e758 100644 --- a/packageLookup/README.md +++ b/packagelookup/README.md @@ -1,6 +1,6 @@ ### About -Package `packageLookup` provides function to get list of installed packages. +Package `packagelookup` provides function to get list of installed packages. Supported operating systems: @@ -20,11 +20,11 @@ package main import ( "fmt" - "github.com/tactycal/agent/packageLookup" + "github.com/tactycal/agent/packagelookup" ) func main() { - packages, err := packageLookup.Get("ubuntu") + packages, err := packagelookup.Get("ubuntu") if err != nil { fmt.Println(err) } else { diff --git a/packageLookup/apt.go b/packagelookup/apt.go similarity index 96% rename from packageLookup/apt.go rename to packagelookup/apt.go index 62e7414..9d5d2a4 100644 --- a/packageLookup/apt.go +++ b/packagelookup/apt.go @@ -1,10 +1,10 @@ -package packageLookup +package packagelookup import ( "regexp" "strings" - "github.com/tactycal/agent/stubUtils" + "github.com/tactycal/agent/stubutils" ) const ( @@ -19,7 +19,7 @@ const ( // getApt returns packages for distribution using a APT package manager func getApt(aptMaintainer, aptPatch string) ([]*Package, error) { // read status of all installed packages - data, err := stubUtils.ReadFile(dpkgStatusPath) + data, err := stubutils.ReadFile(dpkgStatusPath) if err != nil { return nil, err } @@ -121,7 +121,7 @@ func extractPackageNameFromSource(source string) string { // official repositories. func getRepositoriesFromSourcesList() ([]string, error) { // Collect all "official" repositories from /etc/apt/sources.list - data, err := stubUtils.ReadFile(sourcesListPath) + data, err := stubutils.ReadFile(sourcesListPath) if err != nil { return nil, err } @@ -146,7 +146,7 @@ func getRepositoriesFromSourcesList() ([]string, error) { // get keys from repositories map keys := []string{} - for key, _ := range repositories { + for key := range repositories { keys = append(keys, key) } return keys, nil @@ -156,7 +156,7 @@ func getRepositoriesFromSourcesList() ([]string, error) { func getAptCachePolicy(packages []string) (map[string][]string, error) { // Call `apt-cache policy pkg1 pkg2 ...` to collect possible package sources. args := append([]string{"policy"}, packages...) - output, err := stubUtils.ExecCommand("apt-cache", args...) + output, err := stubutils.ExecCommand("apt-cache", args...) if err != nil { return nil, err } diff --git a/packageLookup/apt_test.go b/packagelookup/apt_test.go similarity index 90% rename from packageLookup/apt_test.go rename to packagelookup/apt_test.go index bca2825..4dd5339 100644 --- a/packageLookup/apt_test.go +++ b/packagelookup/apt_test.go @@ -1,18 +1,18 @@ -package packageLookup +package packagelookup import ( "reflect" "regexp" "testing" - "github.com/tactycal/agent/stubUtils" + "github.com/tactycal/agent/stubutils" ) func TestGetPackages(t *testing.T) { - s := stubUtils.NewStubs(t, - &stubUtils.ReadFileStub{Path: "/var/lib/dpkg/status", StubFile: "testdata/ubuntu_status"}, - &stubUtils.ReadFileStub{Path: "/etc/apt/sources.list", StubFile: "testdata/ubuntu_source"}, - &stubUtils.CmdStub{Cmd: "apt-cache", StubFile: "testdata/ubuntu_apt_cache"}) + s := stubutils.NewStubs(t, + &stubutils.ReadFileStub{Path: "/var/lib/dpkg/status", StubFile: "testdata/ubuntu_status"}, + &stubutils.ReadFileStub{Path: "/etc/apt/sources.list", StubFile: "testdata/ubuntu_source"}, + &stubutils.CmdStub{Cmd: "apt-cache", StubFile: "testdata/ubuntu_apt_cache"}) defer s.Close() expectedResult := []*Package{ @@ -97,8 +97,8 @@ func TestExtractPackageNameFromSource(t *testing.T) { } func TestGetRepositoriesFromSourcesList(t *testing.T) { - s := stubUtils.NewStubs(t, - &stubUtils.ReadFileStub{Path: "/etc/apt/sources.list", StubFile: "testdata/ubuntu_source"}) + s := stubutils.NewStubs(t, + &stubutils.ReadFileStub{Path: "/etc/apt/sources.list", StubFile: "testdata/ubuntu_source"}) defer s.Close() expectedResult := []string{ @@ -132,9 +132,9 @@ func TestGetNamesOfPackages(t *testing.T) { } func TestGetAptCachePolicy(t *testing.T) { - s := stubUtils.NewStubs(t, - &stubUtils.CmdStub{Cmd: "apt-cache", StubFile: "testdata/ubuntu_apt_cache"}, // 0.1 - &stubUtils.CmdStub{Cmd: "apt-cache", Err: stubUtils.OhNoErr}) // 0.2 + s := stubutils.NewStubs(t, + &stubutils.CmdStub{Cmd: "apt-cache", StubFile: "testdata/ubuntu_apt_cache"}, // 0.1 + &stubutils.CmdStub{Cmd: "apt-cache", Err: stubutils.ErrOhNo}) // 0.2 defer s.Close() testCase := []string{ @@ -247,9 +247,9 @@ func TestIsPackageSourceFromOfficialRepositories(t *testing.T) { } func TestSetOfficialApt(t *testing.T) { - s := stubUtils.NewStubs(t, - &stubUtils.ReadFileStub{Path: "/etc/apt/sources.list", StubFile: "testdata/ubuntu_source"}, - &stubUtils.CmdStub{Cmd: "apt-cache", StubFile: "testdata/ubuntu_apt_cache"}) + s := stubutils.NewStubs(t, + &stubutils.ReadFileStub{Path: "/etc/apt/sources.list", StubFile: "testdata/ubuntu_source"}, + &stubutils.CmdStub{Cmd: "apt-cache", StubFile: "testdata/ubuntu_apt_cache"}) defer s.Close() testCase := []*Package{ diff --git a/packageLookup/example_test.go b/packagelookup/example_test.go similarity index 87% rename from packageLookup/example_test.go rename to packagelookup/example_test.go index a271888..4d62f26 100644 --- a/packageLookup/example_test.go +++ b/packagelookup/example_test.go @@ -1,4 +1,4 @@ -package packageLookup +package packagelookup import "fmt" diff --git a/packageLookup/packageLookup.go b/packagelookup/packageLookup.go similarity index 81% rename from packageLookup/packageLookup.go rename to packagelookup/packageLookup.go index 4b5ce76..38e1970 100644 --- a/packageLookup/packageLookup.go +++ b/packagelookup/packageLookup.go @@ -1,4 +1,4 @@ -// Package packageLookup provides function to get list of installed packages. +// Package packagelookup provides function to get list of installed packages. // Supported operating systems: // // - Ubuntu @@ -8,11 +8,11 @@ // - Amazon Linux AMI // - openSUSE // - SUSE Linux Enterprise Server -package packageLookup +package packagelookup import "errors" -// Constants show supported operating systems and can be used as osId argument +// Constants show supported operating systems and can be used as osID argument // in Get function. const ( // Ubuntu @@ -31,7 +31,10 @@ const ( SLES = "sles" ) -var ErrDistributionNotSupported = errors.New("Distribution is not supported") +// List of possible errors +var ( + ErrDistributionNotSupported = errors.New("Distribution is not supported") +) // Package represent installed package. type Package struct { @@ -50,10 +53,10 @@ type Package struct { maintainer string } -// Returns installed packages for a given operating system. osId argument must +// Get returns installed packages for a given operating system. osID argument must // be valid operating system distributor id provided in /etc/os-release file. -func Get(osId string) ([]*Package, error) { - switch osId { +func Get(osID string) ([]*Package, error) { + switch osID { case UBUNTU: return getApt(aptMaintainerUbuntu, aptPatchUbuntu) case DEBIAN: diff --git a/packageLookup/rpm.go b/packagelookup/rpm.go similarity index 93% rename from packageLookup/rpm.go rename to packagelookup/rpm.go index b389ee1..38fb46a 100644 --- a/packageLookup/rpm.go +++ b/packagelookup/rpm.go @@ -1,11 +1,11 @@ -package packageLookup +package packagelookup import ( "fmt" "regexp" "strings" - "github.com/tactycal/agent/stubUtils" + "github.com/tactycal/agent/stubutils" ) const ( @@ -18,7 +18,7 @@ const ( // returns packages for distribution using a RPM package manager func getRpm(rpmVendor string) ([]*Package, error) { - b, err := stubUtils.ExecCommand(`rpm`, `-qa`, `--queryformat`, `Name: %{NAME}\nArchitecture: %{ARCH}\nVersion: %{VERSION}\nRelease: %{RELEASE}\nVendor: %{VENDOR}\nSource: %{SOURCERPM}\nEpoch: %{EPOCH}\n\n`) + b, err := stubutils.ExecCommand(`rpm`, `-qa`, `--queryformat`, `Name: %{NAME}\nArchitecture: %{ARCH}\nVersion: %{VERSION}\nRelease: %{RELEASE}\nVendor: %{VENDOR}\nSource: %{SOURCERPM}\nEpoch: %{EPOCH}\n\n`) if err != nil { return nil, err diff --git a/packageLookup/rpm_test.go b/packagelookup/rpm_test.go similarity index 89% rename from packageLookup/rpm_test.go rename to packagelookup/rpm_test.go index 0b5d76d..d3e237b 100644 --- a/packageLookup/rpm_test.go +++ b/packagelookup/rpm_test.go @@ -1,10 +1,10 @@ -package packageLookup +package packagelookup import ( "reflect" "testing" - "github.com/tactycal/agent/stubUtils" + "github.com/tactycal/agent/stubutils" ) func TestGetSourceName(t *testing.T) { @@ -30,8 +30,8 @@ func TestGetSourceName(t *testing.T) { } func TestGet_amzn(t *testing.T) { - s := stubUtils.NewStubs(t, - &stubUtils.CmdStub{Cmd: "rpm", Args: []string{`-qa`, `--queryformat`, + s := stubutils.NewStubs(t, + &stubutils.CmdStub{Cmd: "rpm", Args: []string{`-qa`, `--queryformat`, `Name: %{NAME}\nArchitecture: %{ARCH}\nVersion: %{VERSION}\nRelease: %{RELEASE}\nVendor: %{VENDOR}\nSource: %{SOURCERPM}\nEpoch: %{EPOCH}\n\n`}, StubFile: "testdata/amzn_rpm"}) defer s.Close() @@ -62,8 +62,8 @@ func TestGet_amzn(t *testing.T) { } func TestGet_opensuse(t *testing.T) { - s := stubUtils.NewStubs(t, - &stubUtils.CmdStub{Cmd: "rpm", Args: []string{`-qa`, `--queryformat`, + s := stubutils.NewStubs(t, + &stubutils.CmdStub{Cmd: "rpm", Args: []string{`-qa`, `--queryformat`, `Name: %{NAME}\nArchitecture: %{ARCH}\nVersion: %{VERSION}\nRelease: %{RELEASE}\nVendor: %{VENDOR}\nSource: %{SOURCERPM}\nEpoch: %{EPOCH}\n\n`}, StubFile: "testdata/opensuse_rpm"}) defer s.Close() @@ -92,8 +92,8 @@ func TestGet_opensuse(t *testing.T) { } func TestGet_sles(t *testing.T) { - s := stubUtils.NewStubs(t, - &stubUtils.CmdStub{Cmd: "rpm", Args: []string{`-qa`, `--queryformat`, + s := stubutils.NewStubs(t, + &stubutils.CmdStub{Cmd: "rpm", Args: []string{`-qa`, `--queryformat`, `Name: %{NAME}\nArchitecture: %{ARCH}\nVersion: %{VERSION}\nRelease: %{RELEASE}\nVendor: %{VENDOR}\nSource: %{SOURCERPM}\nEpoch: %{EPOCH}\n\n`}, StubFile: "testdata/sles_rpm"}) defer s.Close() @@ -123,10 +123,10 @@ func TestGet_sles(t *testing.T) { } func TestGet_rhel(t *testing.T) { - s := stubUtils.NewStubs(t, - &stubUtils.CmdStub{Cmd: "rpm", Args: []string{`-qa`, `--queryformat`, + s := stubutils.NewStubs(t, + &stubutils.CmdStub{Cmd: "rpm", Args: []string{`-qa`, `--queryformat`, `Name: %{NAME}\nArchitecture: %{ARCH}\nVersion: %{VERSION}\nRelease: %{RELEASE}\nVendor: %{VENDOR}\nSource: %{SOURCERPM}\nEpoch: %{EPOCH}\n\n`}, StubFile: "testdata/rhel_rpm"}, // 0.1 - &stubUtils.CmdStub{Err: stubUtils.OhNoErr}) // 0.2 + &stubutils.CmdStub{Err: stubutils.ErrOhNo}) // 0.2 defer s.Close() // 0.1 @@ -174,8 +174,8 @@ func TestGet_rhel(t *testing.T) { } func TestGet_centos(t *testing.T) { - s := stubUtils.NewStubs(t, - &stubUtils.CmdStub{Cmd: "rpm", Args: []string{`-qa`, `--queryformat`, + s := stubutils.NewStubs(t, + &stubutils.CmdStub{Cmd: "rpm", Args: []string{`-qa`, `--queryformat`, `Name: %{NAME}\nArchitecture: %{ARCH}\nVersion: %{VERSION}\nRelease: %{RELEASE}\nVendor: %{VENDOR}\nSource: %{SOURCERPM}\nEpoch: %{EPOCH}\n\n`}, StubFile: "testdata/centos_rpm"}) defer s.Close() diff --git a/packageLookup/testdata/amzn_rpm b/packagelookup/testdata/amzn_rpm similarity index 100% rename from packageLookup/testdata/amzn_rpm rename to packagelookup/testdata/amzn_rpm diff --git a/packageLookup/testdata/centos_rpm b/packagelookup/testdata/centos_rpm similarity index 100% rename from packageLookup/testdata/centos_rpm rename to packagelookup/testdata/centos_rpm diff --git a/packageLookup/testdata/opensuse_rpm b/packagelookup/testdata/opensuse_rpm similarity index 100% rename from packageLookup/testdata/opensuse_rpm rename to packagelookup/testdata/opensuse_rpm diff --git a/packageLookup/testdata/rhel_rpm b/packagelookup/testdata/rhel_rpm similarity index 100% rename from packageLookup/testdata/rhel_rpm rename to packagelookup/testdata/rhel_rpm diff --git a/packageLookup/testdata/sles_rpm b/packagelookup/testdata/sles_rpm similarity index 100% rename from packageLookup/testdata/sles_rpm rename to packagelookup/testdata/sles_rpm diff --git a/packageLookup/testdata/ubuntu_apt_cache b/packagelookup/testdata/ubuntu_apt_cache similarity index 100% rename from packageLookup/testdata/ubuntu_apt_cache rename to packagelookup/testdata/ubuntu_apt_cache diff --git a/packageLookup/testdata/ubuntu_source b/packagelookup/testdata/ubuntu_source similarity index 100% rename from packageLookup/testdata/ubuntu_source rename to packagelookup/testdata/ubuntu_source diff --git a/packageLookup/testdata/ubuntu_status b/packagelookup/testdata/ubuntu_status similarity index 100% rename from packageLookup/testdata/ubuntu_status rename to packagelookup/testdata/ubuntu_status diff --git a/state.go b/state.go index cf6aed2..4d91120 100644 --- a/state.go +++ b/state.go @@ -4,31 +4,31 @@ import ( "encoding/json" "os" - "github.com/tactycal/agent/stubUtils" + "github.com/tactycal/agent/stubutils" ) -const DefaultStatePath = "/var/opt/tactycal/state" +const defaultStatePath = "/var/opt/tactycal/state" type ( - State struct { + state struct { statePath string - data *StateData + data *stateData } - StateData struct { + stateData struct { Token string } ) -func NewState(path string) *State { - return &State{ +func newState(path string) *state { + return &state{ statePath: path, - data: &StateData{}, + data: &stateData{}, } } -func (s *State) read() error { +func (s *state) read() error { // try to read existing state - b, err := stubUtils.ReadFile(s.statePath) + b, err := stubutils.ReadFile(s.statePath) if err != nil { return err } @@ -41,7 +41,7 @@ func (s *State) read() error { return nil } -func (s *State) save() error { +func (s *state) save() error { // encode data b, err := json.Marshal(s.data) if err != nil { @@ -49,18 +49,18 @@ func (s *State) save() error { } // write data to file - if err := stubUtils.WriteFile(s.statePath, b, 0600); err != nil { + if err := stubutils.WriteFile(s.statePath, b, 0600); err != nil { return err } return nil } -func (s *State) Reset() error { +func (s *state) Reset() error { return os.Remove(s.statePath) } -func (s *State) GetToken() (string, error) { +func (s *state) GetToken() (string, error) { if err := s.read(); err != nil { return "", err } @@ -68,7 +68,7 @@ func (s *State) GetToken() (string, error) { return s.data.Token, nil } -func (s *State) SetToken(token string) error { +func (s *state) SetToken(token string) error { s.data.Token = token return s.save() } diff --git a/state_test.go b/state_test.go index 08dc9be..e3a9138 100644 --- a/state_test.go +++ b/state_test.go @@ -5,7 +5,7 @@ import ( "os" "testing" - "github.com/tactycal/agent/stubUtils" + "github.com/tactycal/agent/stubutils" ) var testStatePath = "testdata/state" @@ -14,7 +14,7 @@ func TestStateReset_Ok(t *testing.T) { tmpFile, _ := ioutil.TempFile("", "tactycal-agent-ut") defer os.Remove(tmpFile.Name()) // try to delete just in case - state := NewState(tmpFile.Name()) + state := newState(tmpFile.Name()) // call reset err := state.Reset() @@ -32,7 +32,7 @@ func TestStateReset_Ok(t *testing.T) { func TestStateReset_Err(t *testing.T) { // create state with unexisting file - state := NewState("/should/not/exists") + state := newState("/should/not/exists") err := state.Reset() @@ -43,11 +43,11 @@ func TestStateReset_Err(t *testing.T) { } func TestStateGetToken_Ok(t *testing.T) { - stub := stubUtils.NewStubs(t, - &stubUtils.ReadFileStub{Path: testStatePath, Output: []byte(`{"token": "TOKEN"}`)}) + stub := stubutils.NewStubs(t, + &stubutils.ReadFileStub{Path: testStatePath, Output: []byte(`{"token": "TOKEN"}`)}) defer stub.Close() - s := NewState(testStatePath) + s := newState(testStatePath) token, err := s.GetToken() @@ -63,11 +63,11 @@ func TestStateGetToken_Ok(t *testing.T) { } func TestStateGetToken_InvalidJson(t *testing.T) { - stub := stubUtils.NewStubs(t, - &stubUtils.ReadFileStub{Path: testStatePath, Output: []byte("How to break JSON?")}) + stub := stubutils.NewStubs(t, + &stubutils.ReadFileStub{Path: testStatePath, Output: []byte("How to break JSON?")}) defer stub.Close() - s := NewState(testStatePath) + s := newState(testStatePath) token, err := s.GetToken() @@ -83,17 +83,17 @@ func TestStateGetToken_InvalidJson(t *testing.T) { } func TestStateGetToken_SomeError(t *testing.T) { - stub := stubUtils.NewStubs(t, - &stubUtils.ReadFileStub{Path: testStatePath, Err: stubUtils.OhNoErr}) + stub := stubutils.NewStubs(t, + &stubutils.ReadFileStub{Path: testStatePath, Err: stubutils.ErrOhNo}) defer stub.Close() - s := NewState(testStatePath) + s := newState(testStatePath) token, err := s.GetToken() // check error - if err != stubUtils.OhNoErr { - t.Errorf("Expected error %v; got %v", stubUtils.OhNoErr, err) + if err != stubutils.ErrOhNo { + t.Errorf("Expected error %v; got %v", stubutils.ErrOhNo, err) } // check token @@ -103,11 +103,11 @@ func TestStateGetToken_SomeError(t *testing.T) { } func TestStateSetToken_Ok(t *testing.T) { - stub := stubUtils.NewStubs(t, - &stubUtils.WriteFileStub{Path: testStatePath, Data: []byte(`{"Token":"TOKEN"}`), Mode: 0600}) + stub := stubutils.NewStubs(t, + &stubutils.WriteFileStub{Path: testStatePath, Data: []byte(`{"Token":"TOKEN"}`), Mode: 0600}) defer stub.Close() - state := NewState(testStatePath) + state := newState(testStatePath) err := state.SetToken("TOKEN") @@ -118,11 +118,11 @@ func TestStateSetToken_Ok(t *testing.T) { } func TestStateSetToken_Error(t *testing.T) { - stub := stubUtils.NewStubs(t, - &stubUtils.WriteFileStub{Err: stubUtils.OhNoErr}) + stub := stubutils.NewStubs(t, + &stubutils.WriteFileStub{Err: stubutils.ErrOhNo}) defer stub.Close() - state := NewState(testStatePath) + state := newState(testStatePath) err := state.SetToken("TOKEN") if err == nil { diff --git a/stubUtils/LICENSE b/stubutils/LICENSE similarity index 100% rename from stubUtils/LICENSE rename to stubutils/LICENSE diff --git a/stubUtils/Makefile b/stubutils/Makefile similarity index 100% rename from stubUtils/Makefile rename to stubutils/Makefile diff --git a/stubUtils/README.md b/stubutils/README.md similarity index 65% rename from stubUtils/README.md rename to stubutils/README.md index d622612..b083236 100644 --- a/stubUtils/README.md +++ b/stubutils/README.md @@ -1,10 +1,10 @@ ### About -Package stubUtils provides wrapper functions for reading from file, writing +Package `stubutils` provides wrapper functions for reading from file, writing to file, executing a command and stub interface for unit testing. -A stubUtils package has predefined structs for mocking the wrapper functions +A `stubutils` package has predefined structs for mocking the wrapper functions which has been mentioned above. All those sturcts implements ioStub interface which will inform you through Tester interface if any of the passing arguments to functions or their outputs will not match expected. diff --git a/stubUtils/example_test.go b/stubutils/example_test.go similarity index 98% rename from stubUtils/example_test.go rename to stubutils/example_test.go index 0935656..276fd4b 100644 --- a/stubUtils/example_test.go +++ b/stubutils/example_test.go @@ -1,4 +1,4 @@ -package stubUtils +package stubutils import "testing" diff --git a/stubUtils/stubUtils.go b/stubutils/stubUtils.go similarity index 83% rename from stubUtils/stubUtils.go rename to stubutils/stubUtils.go index 5e028ea..81f7c83 100644 --- a/stubUtils/stubUtils.go +++ b/stubutils/stubUtils.go @@ -1,11 +1,11 @@ -// Package stubUtils provides wrapper functions for reading from file, writing +// Package stubutils provides wrapper functions for reading from file, writing // to file, executing a command and stub interface for unit testing. // -// A stubUtils package has predefined structs for mocking the wrapper functions +// A stubutils package has predefined structs for mocking the wrapper functions // which has been mentioned above. All those sturcts implements ioStub interface -// which will inform you through Tester interface if any of the passing +// which will inform you through tester interface if any of the passing // arguments to functions or their outputs will not match expected. -package stubUtils +package stubutils import ( "errors" @@ -16,12 +16,12 @@ import ( "reflect" ) -// Readfile is a wrapper function for ioutil.ReadFile. +// ReadFile is a wrapper function for ioutil.ReadFile. var ReadFile = func(path string) ([]byte, error) { return ioutil.ReadFile(path) } -// Writefile is a wrapper function for ioutil.WriteFile. +// WriteFile is a wrapper function for ioutil.WriteFile. var WriteFile = func(filename string, data []byte, perm os.FileMode) error { return ioutil.WriteFile(filename, data, perm) } @@ -31,24 +31,27 @@ var ExecCommand = func(cmd string, args ...string) ([]byte, error) { return exec.Command(cmd, args...).Output() } -// Mock error for testing. -var OhNoErr = errors.New("oh no") +// List of mocked errors for testing +var ( + ErrOhNo = errors.New("oh no") +) type ( + // Stubs is a wrapper for a stub command Stubs struct { queue []ioStub - t Tester + t tester origExecCommand func(string, ...string) ([]byte, error) origReadFile func(string) ([]byte, error) origWriteFile func(string, []byte, os.FileMode) error } ioStub interface { - check(Tester, []string) ([]byte, error) + check(tester, []string) ([]byte, error) } - // A Tester is used by NewStubs. - Tester interface { + // A tester is used by NewStubs. + tester interface { Errorf(format string, args ...interface{}) Fatalf(format string, args ...interface{}) } @@ -68,7 +71,7 @@ type ( Err error } - // ReadFile implements ioStub interface and is used to mock a ReadFile + // ReadFileStub implements ioStub interface and is used to mock a ReadFile // function. ReadFileStub struct { // Path to expected file. @@ -94,7 +97,7 @@ type ( } ) -func (c *CmdStub) check(t Tester, in []string) ([]byte, error) { +func (c *CmdStub) check(t tester, in []string) ([]byte, error) { // check command if c.Cmd != "" && c.Cmd != in[0] { t.Errorf("Expected command \"%s\"; received \"%s\"", c.Cmd, in[0]) @@ -122,7 +125,7 @@ func (c *CmdStub) check(t Tester, in []string) ([]byte, error) { return c.Output, c.Err } -func (r *ReadFileStub) check(t Tester, in []string) ([]byte, error) { +func (r *ReadFileStub) check(t tester, in []string) ([]byte, error) { path := in[0] // check requested path @@ -143,7 +146,7 @@ func (r *ReadFileStub) check(t Tester, in []string) ([]byte, error) { return r.Output, r.Err } -func (w *WriteFileStub) check(t Tester, in []string) ([]byte, error) { +func (w *WriteFileStub) check(t tester, in []string) ([]byte, error) { // check path if w.Path != "" && w.Path != in[0] { t.Errorf("Expected path to equal \"%s\"; got \"%s\"", w.Path, in[0]) @@ -162,8 +165,8 @@ func (w *WriteFileStub) check(t Tester, in []string) ([]byte, error) { return nil, w.Err } -// Creates a new stub collection and stubs the commands. -func NewStubs(t Tester, stubs ...ioStub) *Stubs { +// NewStubs creates a new stub collection and stubs the commands. +func NewStubs(t tester, stubs ...ioStub) *Stubs { s := &Stubs{ t: t, queue: stubs, @@ -173,7 +176,7 @@ func NewStubs(t Tester, stubs ...ioStub) *Stubs { } ReadFile = func(path string) ([]byte, error) { - stub := s.Get() + stub := s.get() // did we get something if stub == nil { @@ -190,7 +193,7 @@ func NewStubs(t Tester, stubs ...ioStub) *Stubs { } ExecCommand = func(cmd string, args ...string) ([]byte, error) { - stub := s.Get() + stub := s.get() // did we get something if stub == nil { @@ -207,7 +210,7 @@ func NewStubs(t Tester, stubs ...ioStub) *Stubs { } WriteFile = func(filename string, data []byte, perm os.FileMode) error { - stub := s.Get() + stub := s.get() // did we get something if stub == nil { @@ -233,7 +236,7 @@ func (s *Stubs) Add(stub ...ioStub) { } // Get pops the first item from the queue. Returns nil if the queue is already empty. -func (s *Stubs) Get() ioStub { +func (s *Stubs) get() ioStub { if len(s.queue) == 0 { return nil } @@ -243,7 +246,7 @@ func (s *Stubs) Get() ioStub { return first } -// Resets stubbed commands and and checks if the queue is empty. +// Close resets stubbed commands and and checks if the queue is empty. func (s *Stubs) Close() { // reset functions ExecCommand = s.origExecCommand diff --git a/stubUtils/stubUtils_test.go b/stubutils/stubUtils_test.go similarity index 97% rename from stubUtils/stubUtils_test.go rename to stubutils/stubUtils_test.go index d34a0e8..ee55f64 100644 --- a/stubUtils/stubUtils_test.go +++ b/stubutils/stubUtils_test.go @@ -1,4 +1,4 @@ -package stubUtils +package stubutils import ( "fmt" @@ -78,7 +78,7 @@ func TestCmdStub(t *testing.T) { } // 7. wrong stub type - expectedErr = fmt.Errorf(`Expected a execCommand stub; got *stubUtils.ReadFileStub`) + expectedErr = fmt.Errorf(`Expected a execCommand stub; got *stubutils.ReadFileStub`) s.Add(&ReadFileStub{Path: "/path"}) _, err = ExecCommand("command", "arg") if !reflect.DeepEqual(err, expectedErr) { @@ -124,7 +124,7 @@ func TestReadFileStub(t *testing.T) { } // 5. wrong stub type - expectedErr = fmt.Errorf(`Expected a readFile stub; got *stubUtils.CmdStub`) + expectedErr = fmt.Errorf(`Expected a readFile stub; got *stubutils.CmdStub`) s.Add(&CmdStub{Cmd: "command"}) _, err = ReadFile("/path") @@ -166,7 +166,7 @@ func TestWriteFileStub(t *testing.T) { } // 5. wrong stub type - expectedErr = fmt.Errorf(`Expected a writeFile stub; got *stubUtils.CmdStub`) + expectedErr = fmt.Errorf(`Expected a writeFile stub; got *stubutils.CmdStub`) s.Add(&CmdStub{Cmd: "command"}) err = WriteFile("/path", nil, 0600) diff --git a/version.go b/version.go index bd17cd6..0f70044 100644 --- a/version.go +++ b/version.go @@ -1,4 +1,6 @@ package main -var GitCommit string -var Version string +var ( + gitCommit string + version string +)