Skip to content

Commit d95bede

Browse files
feat: linting action and fixes (#83)
Signed-off-by: jmeridth <jmeridth@gmail.com> Co-authored-by: Eddie Knight <knight@linux.com>
1 parent caf5d30 commit d95bede

File tree

10 files changed

+64
-74
lines changed

10 files changed

+64
-74
lines changed

.github/workflows/lint.yml

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
name: lint
2+
on:
3+
push:
4+
branches:
5+
- main
6+
pull_request:
7+
workflow_dispatch:
8+
9+
permissions:
10+
contents: read
11+
pull-requests: read
12+
13+
jobs:
14+
lint:
15+
name: lint
16+
runs-on: ubuntu-latest
17+
steps:
18+
- uses: actions/checkout@v4.2.2
19+
- uses: actions/setup-go@v5.4.0
20+
with:
21+
go-version: stable
22+
- name: golangci-lint
23+
uses: golangci/golangci-lint-action@1481404843c368bc19ca9406f87d6e0fc97bdcfd
24+
with:
25+
version: v2.0.2

command/plugin.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -76,10 +76,10 @@ func versionCommand(
7676
Run: func(cmd *cobra.Command, args []string) {
7777
writer := tabwriter.NewWriter(os.Stdout, 1, 1, 1, ' ', 0)
7878
if viper.GetBool("verbose") {
79-
fmt.Fprintf(writer, "Version:\t%s\n", buildVersion)
80-
fmt.Fprintf(writer, "Commit:\t%s\n", buildGitCommitHash)
81-
fmt.Fprintf(writer, "Build Time:\t%s\n", buildTime)
82-
writer.Flush()
79+
_, _ = fmt.Fprintf(writer, "Version:\t%s\n", buildVersion)
80+
_, _ = fmt.Fprintf(writer, "Commit:\t%s\n", buildGitCommitHash)
81+
_, _ = fmt.Fprintf(writer, "Build Time:\t%s\n", buildTime)
82+
_ = writer.Flush()
8383
} else {
8484
fmt.Println(buildVersion)
8585
}

config/config.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ func NewConfig(requiredVars []string) Config {
145145
func defaultWritePath() string {
146146
home, err := os.UserHomeDir()
147147
datetime := time.Now().Local().Format(time.RFC3339)
148-
dirName := strings.Replace(datetime, ":", "", -1)
148+
dirName := strings.ReplaceAll(datetime, ":", "")
149149
if err != nil {
150150
return ""
151151
}

config/config_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -466,7 +466,7 @@ func TestNewConfig(t *testing.T) {
466466
t.Errorf("expected write directory to be default, but got '%s'", c.WriteDirectory)
467467
}
468468

469-
if c.Policy.ControlCatalogs == nil || len(c.Policy.ControlCatalogs) == 0 {
469+
if len(c.Policy.ControlCatalogs) == 0 {
470470
t.Errorf("expected policy to be set, but got %v", c.Policy)
471471
}
472472

pluginkit/errors.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,13 @@ import (
99
// Errors with no parameters
1010
var (
1111
CORRUPTION_FOUND = func() error {
12-
return errors.New("Target state may be corrupted! Halting to prevent futher damage. See logs for more information")
12+
return errors.New("target state may be corrupted! Halting to prevent futher damage. See logs for more information")
1313
}
1414
NO_EVALUATION_SUITES = func() error {
15-
return errors.New("No control evaluations provided by the plugin")
15+
return errors.New("no control evaluations provided by the plugin")
1616
}
1717
EVAL_NAME_MISSING = func() error {
18-
return errors.New("EvaluationSuite name must not be empty")
18+
return errors.New("evaluationSuite name must not be empty")
1919
}
2020
)
2121

@@ -25,9 +25,9 @@ var (
2525
return fmt.Errorf("expected service and plugin names to be set. ServiceName='%s' PluginName='%s'", serviceName, pluginName)
2626
}
2727
WRITE_FAILED = func(name, err string) error {
28-
return fmt.Errorf("Failed to write results for evaluation suite. name: %s, error: %s", name, err)
28+
return fmt.Errorf("failed to write results for evaluation suite. name: %s, error: %s", name, err)
2929
}
3030
BAD_LOADER = func(pluginName string, err error) error {
31-
return fmt.Errorf("Failed to load payload for %s: %s", pluginName, err)
31+
return fmt.Errorf("failed to load payload for %s: %s", pluginName, err)
3232
}
3333
)

pluginkit/evaluation_suite.go

Lines changed: 17 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,8 @@ import (
44
"encoding/json"
55
"fmt"
66
"os"
7-
"os/signal"
87
"path"
98
"strings"
10-
"syscall"
119
"time"
1210

1311
"github.com/privateerproj/privateer-sdk/config"
@@ -32,12 +30,9 @@ type EvaluationSuite struct {
3230
loader DataLoader // loader is the function to load the payload
3331
config *config.Config // config is the global configuration for the plugin
3432

35-
assessmentSuccesses int // successes is the number of successful evaluations
36-
assessmentWarnings int // attempts is the number of evaluations attempted
37-
assessmentFailures int // failures is the number of failed evaluations
38-
evalSuccesses int // successes is the number of successful evaluations
39-
evalFailures int // failures is the number of failed evaluations
40-
evalWarnings int // warnings is the number of evaluations that need review
33+
evalSuccesses int // successes is the number of successful evaluations
34+
evalFailures int // failures is the number of failed evaluations
35+
evalWarnings int // warnings is the number of evaluations that need review
4136
}
4237

4338
// Execute is used to execute a list of ControlEvaluations provided by a Plugin and customized by user config
@@ -62,11 +57,15 @@ func (e *EvaluationSuite) Evaluate(name string) error {
6257
// Log each assessment result as a separate line
6358
for _, assessment := range evaluation.Assessments {
6459
message := fmt.Sprintf("%s: %s", assessment.Requirement_Id, assessment.Message)
65-
if assessment.Result == layer4.Passed {
60+
// switch case the code below
61+
switch assessment.Result {
62+
case layer4.Passed:
6663
e.config.Logger.Info(message)
67-
} else if assessment.Result == layer4.NeedsReview {
64+
case layer4.NeedsReview:
6865
e.config.Logger.Warn(message)
69-
} else if assessment.Result == layer4.Failed || assessment.Result == layer4.Unknown {
66+
case layer4.Failed:
67+
e.config.Logger.Error(message)
68+
case layer4.Unknown:
7069
e.config.Logger.Error(message)
7170
}
7271
}
@@ -90,11 +89,12 @@ func (e *EvaluationSuite) Evaluate(name string) error {
9089
if e.Corrupted_State {
9190
return CORRUPTION_FOUND()
9291
}
93-
if e.Result == layer4.Passed {
92+
switch e.Result {
93+
case layer4.Passed:
9494
e.config.Logger.Info(output)
95-
} else if e.Result == layer4.NotRun {
95+
case layer4.NotRun:
9696
e.config.Logger.Trace(output)
97-
} else {
97+
default:
9898
e.config.Logger.Error(output)
9999
}
100100
return nil
@@ -158,7 +158,9 @@ func (e *EvaluationSuite) writeControlEvaluationsToFile(serviceName string, resu
158158
e.config.Logger.Error("Error opening file", "filepath", filepath)
159159
return err
160160
}
161-
defer file.Close()
161+
defer func() {
162+
_ = file.Close()
163+
}()
162164

163165
_, err = file.Write(result)
164166
if err != nil {
@@ -177,24 +179,3 @@ func (e *EvaluationSuite) cleanup() (passed bool) {
177179
}
178180
return !e.Corrupted_State
179181
}
180-
181-
// closeHandler creates a 'listener' on a new goroutine which will notify the
182-
// program if it receives an interrupt from the OS. We then handle this by calling
183-
// our clean up procedure and exiting the program.
184-
// Ref: https://golangcode.com/handle-ctrl-c-exit-in-terminal/
185-
func (e *EvaluationSuite) closeHandler() {
186-
c := make(chan os.Signal, 1)
187-
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
188-
go func() {
189-
<-c
190-
e.config.Logger.Error("[ERROR] Execution aborted - %v", "SIGTERM")
191-
e.config.Logger.Warn("[WARN] Attempting to revert changes made by the terminated Plugin. Do not interrupt this process.")
192-
if e.cleanup() {
193-
e.config.Logger.Info("Cleanup did not encounter an error.")
194-
os.Exit(0)
195-
} else {
196-
e.config.Logger.Error("[ERROR] Cleanup returned an error, and may not be complete.")
197-
os.Exit(2)
198-
}
199-
}()
200-
}

pluginkit/test_data.go

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ import (
1111

1212
type testingData struct {
1313
testName string
14-
serviceName string
1514
evals []*layer4.ControlEvaluation
1615
expectedEvalSuiteError error
1716
expectedCorruption bool
@@ -136,17 +135,6 @@ type PayloadTypeExample struct {
136135
CustomPayloadField bool
137136
}
138137

139-
func step_checkPayload(payloadData interface{}, _ map[string]*layer4.Change) (result layer4.Result, message string) {
140-
payload, ok := payloadData.(*PayloadTypeExample)
141-
if !ok {
142-
return layer4.Unknown, fmt.Sprintf("Malformed assessment: expected payload type %T, got %T (%v)", &PayloadTypeExample{}, payloadData, payloadData)
143-
}
144-
if payload.CustomPayloadField {
145-
return layer4.Passed, "Multi-factor authentication is configured"
146-
}
147-
return layer4.Unknown, "Not implemented"
148-
}
149-
150138
func step_Pass(data interface{}, changes map[string]*layer4.Change) (result layer4.Result, message string) {
151139
if changes != nil && changes["good-change"] != nil {
152140
changes["good-change"].Apply("target_name", "target_object", data)
@@ -162,10 +150,6 @@ func step_NeedsReview(_ interface{}, _ map[string]*layer4.Change) (result layer4
162150
return layer4.NeedsReview, "This step always needs review"
163151
}
164152

165-
func step_Unknown(_ interface{}, _ map[string]*layer4.Change) (result layer4.Result, message string) {
166-
return layer4.Unknown, "This step always returns unknown"
167-
}
168-
169153
func step_Corrupted(data interface{}, changes map[string]*layer4.Change) (result layer4.Result, message string) {
170154
changes["corrupted-change"].Apply("target_name", "target_object", data)
171155
return layer4.Unknown, "This step always returns unknown and applies a corrupted change"

pluginkit/vessel.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,9 @@ func (v *Vessel) writeResultsToFile(serviceName string, result []byte, extension
150150
v.config.Logger.Error("Error opening file", "filepath", filepath)
151151
return err
152152
}
153-
defer file.Close()
153+
defer func() {
154+
_ = file.Close()
155+
}()
154156

155157
_, err = file.Write(result)
156158
if err != nil {

pluginkit/vessel_test.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ func TestAddEvaluationSuite(t *testing.T) {
7777
v := NewVessel("test", nil, []string{})
7878
v.config = setBasicConfig()
7979
v.AddEvaluationSuite("test", nil, test.evals)
80-
if v.possibleSuites == nil || len(v.possibleSuites) == 0 {
80+
if len(v.possibleSuites) == 0 {
8181
t.Error("Expected evaluation suites to be set")
8282
return
8383
}
@@ -107,7 +107,7 @@ func TestMobilize(t *testing.T) {
107107
v := NewVessel("test", nil, []string{})
108108
v.config = setLimitedConfig()
109109

110-
catalogName := strings.Replace(test.testName, " ", "-", -1)
110+
catalogName := strings.ReplaceAll(test.testName, " ", "-")
111111
v.AddEvaluationSuite(catalogName, examplePayload, test.evals)
112112

113113
// grab a count of the applicable evaluations when config is limited
@@ -129,7 +129,7 @@ func TestMobilize(t *testing.T) {
129129
}
130130

131131
func runMobilizeTests(t *testing.T, test testingData, invasive bool, limitedConfigEvaluationCount int) {
132-
catalogName := strings.Replace(test.testName, " ", "-", -1)
132+
catalogName := strings.ReplaceAll(test.testName, " ", "-")
133133

134134
v := NewVessel("test", nil, []string{})
135135
v.config = setBasicConfig()
@@ -142,7 +142,7 @@ func runMobilizeTests(t *testing.T, test testingData, invasive bool, limitedConf
142142
if err != nil {
143143
t.Errorf("Expected no error, but got %v", err)
144144
}
145-
if v.possibleSuites == nil || len(v.possibleSuites) == 0 {
145+
if len(v.possibleSuites) == 0 {
146146
t.Errorf("Expected evaluation suites to be set, but got %v", v.possibleSuites)
147147
return
148148
}
@@ -153,8 +153,8 @@ func runMobilizeTests(t *testing.T, test testingData, invasive bool, limitedConf
153153

154154
// Now we set the catalog to be applicable, then run Mobilize again to find results
155155
v.config.Policy.ControlCatalogs = []string{catalogName}
156-
v.Mobilize()
157-
if v.Evaluation_Suites == nil || len(v.Evaluation_Suites) == 0 {
156+
_ = v.Mobilize()
157+
if len(v.Evaluation_Suites) == 0 {
158158
t.Errorf("Expected evaluation suites to be set, but got %v", v.Evaluation_Suites)
159159
return
160160
}

utils/utils.go

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -77,14 +77,12 @@ func ReformatError(e string, v ...interface{}) error {
7777
b.WriteString("[ERROR] ")
7878
b.WriteString(e)
7979

80-
s := fmt.Sprintf(b.String(), v...)
81-
82-
return fmt.Errorf(s)
80+
return fmt.Errorf(b.String(), v...)
8381
}
8482

8583
// ReplaceBytesValue replaces a substring with a new value for a given string in bytes
8684
func ReplaceBytesValue(b []byte, old string, new string) []byte {
87-
newString := strings.Replace(string(b), old, new, -1)
85+
newString := strings.ReplaceAll(string(b), old, new)
8886
return []byte(newString)
8987
}
9088

0 commit comments

Comments
 (0)