Skip to content

Commit

Permalink
chore: golangci linting (#389)
Browse files Browse the repository at this point in the history
  • Loading branch information
decleaver committed Feb 5, 2024
1 parent d69f7ad commit fb738f6
Show file tree
Hide file tree
Showing 20 changed files with 77 additions and 39 deletions.
5 changes: 4 additions & 1 deletion .github/workflows/scan-lint.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,13 @@ jobs:
- name: Install goimports
run: go install golang.org/x/tools/cmd/goimports@latest

- name: Install golangci-lint
run: curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.55.2

- name: Run pre-commit
uses: pre-commit/action@c7d159c2092cbfaab7352e2d8211ab536aa2267c #
with:
args: --all-files --verbose # pre-commit run --all-files --verbose
extra_args: --all-files --verbose # pre-commit run --all-files --verbose

- name: Run Revive Action by pulling pre-built image
uses: docker://morphy/revive-action:v2@sha256:dad5d9525a11d42ea2a36237f6a4082aef3db37cbd280eabf5e7b87eb033d0d4
Expand Down
5 changes: 5 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ repos:
rev: v0.5.1
hooks:
- id: go-imports
- repo: https://github.com/golangci/golangci-lint
rev: v1.55.2
hooks:
- id: golangci-lint
args: [--timeout=5m]
- repo: local
hooks:
- id: check-docs-and-schema
Expand Down
5 changes: 4 additions & 1 deletion src/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,10 @@ var rootCmd = &cobra.Command{
Short: lang.RootCmdShort,
Run: func(cmd *cobra.Command, args []string) {
_, _ = fmt.Fprintln(os.Stderr)
cmd.Help()
err := cmd.Help()
if err != nil {
message.Fatal(err, "error calling help command")
}
},
}

Expand Down
6 changes: 5 additions & 1 deletion src/cmd/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,11 @@ var runCmd = &cobra.Command{
for _, task := range tasksFile.Tasks {
rows = append(rows, []string{task.Name, task.Description})
}
pterm.DefaultTable.WithHasHeader().WithData(rows).Render()
err := pterm.DefaultTable.WithHasHeader().WithData(rows).Render()
if err != nil {
message.Fatal(err, "error listing tasks")
}

os.Exit(0)
}

Expand Down
2 changes: 0 additions & 2 deletions src/pkg/bundle/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,8 +180,6 @@ func (b *Bundler) ValidateBundleResources(bundle *types.UDSBundle, spinner *mess
return err
}
defer os.Remove(publicKeyPath)
} else {
publicKeyPath = ""
}

if len(pkg.OptionalComponents) > 0 {
Expand Down
7 changes: 6 additions & 1 deletion src/pkg/bundle/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,12 @@ func (b *Bundler) Create() error {
if err := os.Chdir(b.cfg.CreateOpts.SourceDirectory); err != nil {
return err
}
defer os.Chdir(cwd)
defer func() {
err := os.Chdir(cwd)
if err != nil {
fmt.Println("Error changing back to the original directory:", err)
}
}()

// read the bundle's metadata into memory
if err := utils.ReadYaml(b.cfg.CreateOpts.BundleFile, &b.bundle); err != nil {
Expand Down
2 changes: 1 addition & 1 deletion src/pkg/bundle/deploy.go
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,7 @@ func addOverrideValue(overrides map[string]map[string]*values.Options, component
if err != nil {
return err
}
jsonStrs[i] = fmt.Sprintf("%s", j)
jsonStrs[i] = string(j)
}
// use JSONValues because we can easily marshal the YAML to JSON and Helm understands it
jsonVals := fmt.Sprintf("%s=[%s]", valuePath, strings.Join(jsonStrs, ","))
Expand Down
3 changes: 3 additions & 0 deletions src/pkg/bundle/remote.go
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,9 @@ func ValidateArch(arch string) error {
// compare bundle arch and cluster arch
var clusterArchs []string
c, err := cluster.NewCluster()
if err != nil {
return err
}
if c != nil {
clusterArchs, err = c.GetArchitectures()
if err == nil {
Expand Down
5 changes: 1 addition & 4 deletions src/pkg/cache/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,7 @@ func Exists(layerDigest string) bool {
cacheDir := config.CommonOptions.CachePath
layerCachePath := filepath.Join(expandTilde(cacheDir), "images", layerDigest)
_, err := os.Stat(layerCachePath)
if !os.IsNotExist(err) {
return true
}
return false
return !os.IsNotExist(err)
}

// Use copies a layer from the cache to the dst dir
Expand Down
39 changes: 19 additions & 20 deletions src/pkg/runner/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,6 @@ func Run(tasksFile types.TasksFile, taskName string, setVariables map[string]str
return err
}

err = runner.processIncludes(task, tasksFile, setVariables)
if err != nil {
return err
}

if err = runner.checkForTaskLoops(task, tasksFile, setVariables); err != nil {
return err
}
Expand Down Expand Up @@ -85,19 +80,17 @@ func Run(tasksFile types.TasksFile, taskName string, setVariables map[string]str
return err
}

func (r *Runner) processIncludes(task types.Task, tasksFile types.TasksFile, setVariables map[string]string) error {
for _, a := range task.Actions {
if strings.Contains(a.TaskReference, ":") {
taskReferenceName := strings.Split(a.TaskReference, ":")[0]
for _, include := range tasksFile.Includes {
if include[taskReferenceName] != "" {
referencedIncludes := []map[string]string{include}
err := r.importTasks(referencedIncludes, config.TaskFileLocation, setVariables)
if err != nil {
return err
}
break
func (r *Runner) processIncludes(tasksFile types.TasksFile, setVariables map[string]string, action types.Action) error {
if strings.Contains(action.TaskReference, ":") {
taskReferenceName := strings.Split(action.TaskReference, ":")[0]
for _, include := range tasksFile.Includes {
if include[taskReferenceName] != "" {
referencedIncludes := []map[string]string{include}
err := r.importTasks(referencedIncludes, config.TaskFileLocation, setVariables)
if err != nil {
return err
}
break
}
}
}
Expand Down Expand Up @@ -457,7 +450,15 @@ func (r *Runner) checkForTaskLoops(task types.Task, tasksFile types.TasksFile, s
// Filtering unique task actions allows for rerunning tasks in the same execution
uniqueTaskActions := getUniqueTaskActions(task.Actions)
for _, action := range uniqueTaskActions {
if action.TaskReference != "" {
taskReferenceName := strings.Split(task.Name, ":")[0]
actionReferenceName := strings.Split(action.TaskReference, ":")[0]
// don't need to process if references are the same since that indicates the task and action task are in the same file
if action.TaskReference != "" && (taskReferenceName != actionReferenceName) {
// process includes for action, which will import all tasks for include file
if err := r.processIncludes(tasksFile, setVariables, action); err != nil {
return err
}

exists := r.TaskNameMap[action.TaskReference]
if exists {
return fmt.Errorf("task loop detected, ensure no cyclic loops in tasks or includes files")
Expand All @@ -467,8 +468,6 @@ func (r *Runner) checkForTaskLoops(task types.Task, tasksFile types.TasksFile, s
if err != nil {
return err
}
// check new task includes
r.processIncludes(newTask, tasksFile, setVariables)
if err = r.checkForTaskLoops(newTask, tasksFile, setVariables); err != nil {
return err
}
Expand Down
7 changes: 7 additions & 0 deletions src/pkg/sources/remote.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,10 @@ func (r *RemoteBundle) LoadPackageMetadata(dst *layout.PackagePaths, _ bool, _ b

// look at Zarf pkg manifest, grab zarf.yaml desc and download it
pkgManifest, err := r.Remote.FetchManifest(pkgManifestDesc)
if err != nil {
return err
}

var zarfYAMLDesc ocispec.Descriptor
for _, layer := range pkgManifest.Layers {
if layer.Annotations[ocispec.AnnotationTitle] == config.ZarfYAML {
Expand All @@ -108,6 +112,9 @@ func (r *RemoteBundle) LoadPackageMetadata(dst *layout.PackagePaths, _ bool, _ b
return err
}
err = zarfUtils.WriteYaml(filepath.Join(dst.Base, config.ZarfYAML), zarfYAML, 0644)
if err != nil {
return err
}

// grab checksums.txt so we can validate pkg integrity
var checksumLayer ocispec.Descriptor
Expand Down
3 changes: 3 additions & 0 deletions src/pkg/utils/oci.go
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,9 @@ func GetIndex(remote *oci.OrasRemote, ref string) (*ocispec.Index, error) {
// if an index exists, save it so we can update it after pushing the bundle's root manifest
if existingRootDesc.MediaType == ocispec.MediaTypeImageIndex {
rc, err := remote.Repo().Fetch(context.TODO(), existingRootDesc)
if err != nil {
return nil, err
}
defer rc.Close()
b, err := content.ReadAll(rc, existingRootDesc)
if err != nil {
Expand Down
3 changes: 3 additions & 0 deletions src/pkg/utils/sbom.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ func CreateSBOMArtifact(SBOMArtifactPathMap map[string]string) error {
}
format := archiver.Tar{}
err = format.Archive(context.TODO(), out, files)
if err != nil {
return err
}
return nil
}

Expand Down
2 changes: 1 addition & 1 deletion src/pkg/utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ func IsValidTarballPath(path string) bool {
// UseLogFile writes output to stderr and a logFile.
func UseLogFile() {
// LogWriter is the stream to write logs to.
var LogWriter io.Writer = os.Stderr
var LogWriter io.Writer

// Write logs to stderr and a buffer for logFile generation.
var logFile *os.File
Expand Down
2 changes: 1 addition & 1 deletion src/test/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ func (e2e *UDSE2ETest) GetGitRevision() (string, error) {
// HelmDepUpdate runs 'helm dependency update .' on the given path
func (e2e *UDSE2ETest) HelmDepUpdate(t *testing.T, path string) {
cmd := "helm"
args := strings.Split(fmt.Sprintf("dependency update ."), " ")
args := strings.Split("dependency update .", " ")
tmp := exec.PrintCfg()
tmp.Dir = path
_, _, err := exec.CmdWithContext(context.TODO(), tmp, cmd, args...)
Expand Down
2 changes: 1 addition & 1 deletion src/test/e2e/bundle_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func TestCreateWithNoPath(t *testing.T) {
defer os.Remove(fmt.Sprintf("uds-bundle-simple-vars-%s-0.0.1.tar.zst", e2e.Arch))

// create
cmd := strings.Split(fmt.Sprintf("create --confirm --insecure"), " ")
cmd := strings.Split("create --confirm --insecure", " ")
_, _, err = e2e.UDS(cmd...)
require.NoError(t, err)
}
Expand Down
7 changes: 5 additions & 2 deletions src/test/e2e/commands_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ func deploy(t *testing.T, tarballPath string) (stdout string, stderr string) {
}

func runCmd(t *testing.T, input string) (stdout string, stderr string) {
cmd := strings.Split(fmt.Sprintf(input), " ")
cmd := strings.Split(input, " ")
stdout, stderr, err := e2e.UDS(cmd...)
require.NoError(t, err)
return stdout, stderr
Expand Down Expand Up @@ -239,10 +239,13 @@ func queryIndex(t *testing.T, registryURL, bundlePath string) (ocispec.Index, er
require.NoError(t, err)
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
index := ocispec.Index{}
if err != nil {
return index, err
}
if strings.Contains(string(body), "errors") {
require.Fail(t, fmt.Sprintf("Received the following error from GHCR: %s", string(body)))
}
index := ocispec.Index{}
err = json.Unmarshal(body, &index)
return index, err
}
4 changes: 2 additions & 2 deletions src/test/e2e/ghcr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func TestBundleDeployFromOCIFromGHCR(t *testing.T) {
bundleRef := registry.Reference{
Registry: registryURL,
Repository: "ghcr-test",
Reference: fmt.Sprintf("0.0.1"),
Reference: "0.0.1",
}

createLocal(t, bundleDir, "arm64")
Expand Down Expand Up @@ -61,7 +61,7 @@ func TestBundleCreateAndDeployGHCR(t *testing.T) {
bundleRef := registry.Reference{
Registry: registryURL,
Repository: "ghcr-test",
Reference: fmt.Sprintf("0.0.1"),
Reference: "0.0.1",
}
createRemote(t, bundleDir, registryURL, "arm64")
createRemote(t, bundleDir, registryURL, "amd64")
Expand Down
5 changes: 4 additions & 1 deletion src/test/e2e/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,10 @@ const (
// TestMain lets us customize the test run. See https://medium.com/goingogo/why-use-testmain-for-testing-in-go-dafb52b406bc.
func TestMain(m *testing.M) {
// Work from the root directory of the project
os.Chdir("../../../")
err := os.Chdir("../../../")
if err != nil {
fmt.Println(err)
}

// K3d use the intern package, which requires this to be set in go 1.19
os.Setenv("ASSUME_NO_MOVING_GC_UNSAFE_RISK_IT_WITH", "go1.19")
Expand Down
2 changes: 2 additions & 0 deletions src/test/e2e/variable_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,9 @@ func TestBundleWithEnvVarHelmOverrides(t *testing.T) {
color := "purple"
b64Secret := "dGhhdCBhaW50IG15IHRydWNr"
err := os.Setenv("UDS_CONFIG", filepath.Join("src/test/bundles/07-helm-overrides", "uds-config.yaml"))
require.NoError(t, err)
err = os.Setenv("UDS_UI_COLOR", color)
require.NoError(t, err)
err = os.Setenv("UDS_SECRET_VAL", b64Secret)
require.NoError(t, err)

Expand Down

0 comments on commit fb738f6

Please sign in to comment.