Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: trim named returns in pkg #2950 #2979

Merged
merged 16 commits into from
Sep 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion src/pkg/cluster/state.go
Original file line number Diff line number Diff line change
Expand Up @@ -193,12 +193,14 @@ func (c *Cluster) InitZarfState(ctx context.Context, initOptions types.ZarfInitO
}

// LoadZarfState returns the current zarf/zarf-state secret data or an empty ZarfState.
func (c *Cluster) LoadZarfState(ctx context.Context) (state *types.ZarfState, err error) {
func (c *Cluster) LoadZarfState(ctx context.Context) (*types.ZarfState, error) {
stateErr := errors.New("failed to load the Zarf State from the cluster, has Zarf been initiated?")
secret, err := c.Clientset.CoreV1().Secrets(ZarfNamespaceName).Get(ctx, ZarfStateSecretName, metav1.GetOptions{})
if err != nil {
return nil, fmt.Errorf("%w: %w", stateErr, err)
}

state := &types.ZarfState{}
err = json.Unmarshal(secret.Data[ZarfStateDataKey], &state)
if err != nil {
return nil, fmt.Errorf("%w: %w", stateErr, err)
Expand Down
11 changes: 6 additions & 5 deletions src/pkg/cluster/zarf.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ func (c *Cluster) RecordPackageDeploymentAndWait(ctx context.Context, pkg v1alph
}

// RecordPackageDeployment saves metadata about a package that has been deployed to the cluster.
func (c *Cluster) RecordPackageDeployment(ctx context.Context, pkg v1alpha1.ZarfPackage, components []types.DeployedComponent, generation int) (deployedPackage *types.DeployedPackage, err error) {
func (c *Cluster) RecordPackageDeployment(ctx context.Context, pkg v1alpha1.ZarfPackage, components []types.DeployedComponent, generation int) (*types.DeployedPackage, error) {
packageName := pkg.Metadata.Name

// Attempt to load information about webhooks for the package
Expand All @@ -187,7 +187,7 @@ func (c *Cluster) RecordPackageDeployment(ctx context.Context, pkg v1alpha1.Zarf
componentWebhooks = existingPackageSecret.ComponentWebhooks
}

// TODO: This is done for backwards compartibility and could be removed in the future.
// TODO: This is done for backwards compatibility and could be removed in the future.
connectStrings := types.ConnectStrings{}
for _, comp := range components {
for _, chart := range comp.InstalledCharts {
Expand All @@ -197,7 +197,7 @@ func (c *Cluster) RecordPackageDeployment(ctx context.Context, pkg v1alpha1.Zarf
}
}

deployedPackage = &types.DeployedPackage{
deployedPackage := &types.DeployedPackage{
Name: packageName,
CLIVersion: config.CLIVersion,
Data: pkg,
Expand Down Expand Up @@ -285,12 +285,13 @@ func (c *Cluster) DisableRegHPAScaleDown(ctx context.Context) error {
}

// GetInstalledChartsForComponent returns any installed Helm Charts for the provided package component.
func (c *Cluster) GetInstalledChartsForComponent(ctx context.Context, packageName string, component v1alpha1.ZarfComponent) (installedCharts []types.InstalledChart, err error) {
func (c *Cluster) GetInstalledChartsForComponent(ctx context.Context, packageName string, component v1alpha1.ZarfComponent) ([]types.InstalledChart, error) {
deployedPackage, err := c.GetDeployedPackage(ctx, packageName)
if err != nil {
return installedCharts, err
return nil, err
}

installedCharts := make([]types.InstalledChart, 0)
for _, deployedComponent := range deployedPackage.DeployedComponents {
if deployedComponent.Name == component.Name {
installedCharts = append(installedCharts, deployedComponent.InstalledCharts...)
Expand Down
9 changes: 7 additions & 2 deletions src/pkg/interactive/components.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import (
)

// SelectOptionalComponent prompts to confirm optional components
func SelectOptionalComponent(component v1alpha1.ZarfComponent) (confirm bool, err error) {
func SelectOptionalComponent(component v1alpha1.ZarfComponent) (bool, error) {
message.HorizontalRule()

displayComponent := component
Expand All @@ -30,7 +30,12 @@ func SelectOptionalComponent(component v1alpha1.ZarfComponent) (confirm bool, er
Default: component.Default,
}

return confirm, survey.AskOne(prompt, &confirm)
var confirm bool
err := survey.AskOne(prompt, &confirm)
if err != nil {
return false, err
}
return confirm, nil
}

// SelectChoiceGroup prompts to select component groups
Expand Down
15 changes: 12 additions & 3 deletions src/pkg/interactive/prompt.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,15 @@ func PromptSigPassword() ([]byte, error) {
prompt := &survey.Password{
Message: "Private key password (empty for no password): ",
}
return []byte(password), survey.AskOne(prompt, &password)
err := survey.AskOne(prompt, &password)
if err != nil {
return []byte{}, err
}
return []byte(password), nil
}

// PromptVariable prompts the user for a value for a variable
func PromptVariable(variable v1alpha1.InteractiveVariable) (value string, err error) {
func PromptVariable(variable v1alpha1.InteractiveVariable) (string, error) {
if variable.Description != "" {
message.Question(variable.Description)
}
Expand All @@ -33,5 +37,10 @@ func PromptVariable(variable v1alpha1.InteractiveVariable) (value string, err er
Default: variable.Default,
}

return value, survey.AskOne(prompt, &value)
var value string
err := survey.AskOne(prompt, &value)
if err != nil {
return "", err
}
return value, nil
}
26 changes: 13 additions & 13 deletions src/pkg/layout/component.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ type Components struct {
var ErrNotLoaded = fmt.Errorf("not loaded")

// Archive archives a component.
func (c *Components) Archive(component v1alpha1.ZarfComponent, cleanupTemp bool) (err error) {
func (c *Components) Archive(component v1alpha1.ZarfComponent, cleanupTemp bool) error {
name := component.Name
if _, ok := c.Dirs[name]; !ok {
return &fs.PathError{
Expand Down Expand Up @@ -75,7 +75,7 @@ func (c *Components) Archive(component v1alpha1.ZarfComponent, cleanupTemp bool)
}

// Unarchive unarchives a component.
func (c *Components) Unarchive(component v1alpha1.ZarfComponent) (err error) {
func (c *Components) Unarchive(component v1alpha1.ZarfComponent) error {
name := component.Name
tb, ok := c.Tarballs[name]
if !ok {
Expand Down Expand Up @@ -138,7 +138,7 @@ func (c *Components) Unarchive(component v1alpha1.ZarfComponent) (err error) {
}

// Create creates a new component directory structure.
func (c *Components) Create(component v1alpha1.ZarfComponent) (cp *ComponentPaths, err error) {
func (c *Components) Create(component v1alpha1.ZarfComponent) (*ComponentPaths, error) {
name := component.Name

_, ok := c.Tarballs[name]
Expand All @@ -150,41 +150,41 @@ func (c *Components) Create(component v1alpha1.ZarfComponent) (cp *ComponentPath
}
}

if err = helpers.CreateDirectory(c.Base, helpers.ReadWriteExecuteUser); err != nil {
if err := helpers.CreateDirectory(c.Base, helpers.ReadWriteExecuteUser); err != nil {
return nil, err
}

base := filepath.Join(c.Base, name)

if err = helpers.CreateDirectory(base, helpers.ReadWriteExecuteUser); err != nil {
if err := helpers.CreateDirectory(base, helpers.ReadWriteExecuteUser); err != nil {
return nil, err
}

cp = &ComponentPaths{
cp := &ComponentPaths{
Base: base,
}

cp.Temp = filepath.Join(base, TempDir)
if err = helpers.CreateDirectory(cp.Temp, helpers.ReadWriteExecuteUser); err != nil {
if err := helpers.CreateDirectory(cp.Temp, helpers.ReadWriteExecuteUser); err != nil {
return nil, err
}

if len(component.Files) > 0 {
cp.Files = filepath.Join(base, FilesDir)
if err = helpers.CreateDirectory(cp.Files, helpers.ReadWriteExecuteUser); err != nil {
if err := helpers.CreateDirectory(cp.Files, helpers.ReadWriteExecuteUser); err != nil {
return nil, err
}
}

if len(component.Charts) > 0 {
cp.Charts = filepath.Join(base, ChartsDir)
if err = helpers.CreateDirectory(cp.Charts, helpers.ReadWriteExecuteUser); err != nil {
if err := helpers.CreateDirectory(cp.Charts, helpers.ReadWriteExecuteUser); err != nil {
return nil, err
}
for _, chart := range component.Charts {
cp.Values = filepath.Join(base, ValuesDir)
if len(chart.ValuesFiles) > 0 {
if err = helpers.CreateDirectory(cp.Values, helpers.ReadWriteExecuteUser); err != nil {
if err := helpers.CreateDirectory(cp.Values, helpers.ReadWriteExecuteUser); err != nil {
return nil, err
}
break
Expand All @@ -194,21 +194,21 @@ func (c *Components) Create(component v1alpha1.ZarfComponent) (cp *ComponentPath

if len(component.Repos) > 0 {
cp.Repos = filepath.Join(base, ReposDir)
if err = helpers.CreateDirectory(cp.Repos, helpers.ReadWriteExecuteUser); err != nil {
if err := helpers.CreateDirectory(cp.Repos, helpers.ReadWriteExecuteUser); err != nil {
return nil, err
}
}

if len(component.Manifests) > 0 {
cp.Manifests = filepath.Join(base, ManifestsDir)
if err = helpers.CreateDirectory(cp.Manifests, helpers.ReadWriteExecuteUser); err != nil {
if err := helpers.CreateDirectory(cp.Manifests, helpers.ReadWriteExecuteUser); err != nil {
return nil, err
}
}

if len(component.DataInjections) > 0 {
cp.DataInjections = filepath.Join(base, DataInjectionsDir)
if err = helpers.CreateDirectory(cp.DataInjections, helpers.ReadWriteExecuteUser); err != nil {
if err := helpers.CreateDirectory(cp.DataInjections, helpers.ReadWriteExecuteUser); err != nil {
return nil, err
}
}
Expand Down
7 changes: 5 additions & 2 deletions src/pkg/layout/package.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,14 @@ func New(baseDir string) *PackagePaths {

// ReadZarfYAML reads a zarf.yaml file into memory,
// checks if it's using the legacy layout, and migrates deprecated component configs.
func (pp *PackagePaths) ReadZarfYAML() (pkg v1alpha1.ZarfPackage, warnings []string, err error) {
func (pp *PackagePaths) ReadZarfYAML() (v1alpha1.ZarfPackage, []string, error) {
var pkg v1alpha1.ZarfPackage

if err := utils.ReadYaml(pp.ZarfYAML, &pkg); err != nil {
return v1alpha1.ZarfPackage{}, nil, fmt.Errorf("unable to read zarf.yaml: %w", err)
}

warnings := make([]string, 0)
if pp.IsLegacyLayout() {
warnings = append(warnings, "Detected deprecated package layout, migrating to new layout - support for this package will be dropped in v1.0.0")
}
Expand All @@ -74,7 +77,7 @@ func (pp *PackagePaths) ReadZarfYAML() (pkg v1alpha1.ZarfPackage, warnings []str
}

// MigrateLegacy migrates a legacy package layout to the new layout.
func (pp *PackagePaths) MigrateLegacy() (err error) {
func (pp *PackagePaths) MigrateLegacy() error {
var pkg v1alpha1.ZarfPackage
base := pp.Base

Expand Down
17 changes: 11 additions & 6 deletions src/pkg/layout/sbom.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ type SBOMs struct {
}

// Unarchive unarchives the package's SBOMs.
func (s *SBOMs) Unarchive() (err error) {
func (s *SBOMs) Unarchive() error {
if s.Path == "" || helpers.InvalidPath(s.Path) {
return &fs.PathError{
Op: "stat",
Expand All @@ -47,7 +47,7 @@ func (s *SBOMs) Unarchive() (err error) {
}

// Archive archives the package's SBOMs.
func (s *SBOMs) Archive() (err error) {
func (s *SBOMs) Archive() error {
if s.Path == "" || helpers.InvalidPath(s.Path) {
return &fs.PathError{
Op: "stat",
Expand All @@ -68,18 +68,23 @@ func (s *SBOMs) Archive() (err error) {
return os.RemoveAll(dir)
}

// StageSBOMViewFiles copies SBOM viewer HTML files to the Zarf SBOM directory.
func (s *SBOMs) StageSBOMViewFiles() (sbomViewFiles, warnings []string, err error) {
// StageSBOMViewFiles copies SBOM viewer HTML files to the Zarf SBOM directory. Returns sbomViewFiles, warnings, and an
// error.
func (s *SBOMs) StageSBOMViewFiles() ([]string, []string, error) {
sbomViewFiles := make([]string, 0)
warnings := make([]string, 0)

if s.IsTarball() {
return nil, nil, fmt.Errorf("unable to process the SBOM files for this package: %s is a tarball", s.Path)
}

// If SBOMs were loaded, temporarily place them in the deploy directory
if !helpers.InvalidPath(s.Path) {
sbomViewFiles, err = filepath.Glob(filepath.Join(s.Path, "sbom-viewer-*"))
files, err := filepath.Glob(filepath.Join(s.Path, "sbom-viewer-*"))
if err != nil {
return nil, nil, err
}
sbomViewFiles = files

if _, err := s.OutputSBOMFiles(SBOMDir, ""); err != nil {
// Don't stop the deployment, let the user decide if they want to continue the deployment
Expand Down Expand Up @@ -107,6 +112,6 @@ func (s *SBOMs) OutputSBOMFiles(outputDir, packageName string) (string, error) {
}

// IsTarball returns true if the SBOMs are a tarball.
func (s SBOMs) IsTarball() bool {
func (s *SBOMs) IsTarball() bool {
return !helpers.IsDir(s.Path) && filepath.Ext(s.Path) == ".tar"
}
9 changes: 4 additions & 5 deletions src/pkg/lint/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ func validateAction(action v1alpha1.ZarfComponentAction) error {

// validateReleaseName validates a release name against DNS 1035 spec, using chartName as fallback.
// https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#rfc-1035-label-names
func validateReleaseName(chartName, releaseName string) (err error) {
func validateReleaseName(chartName, releaseName string) error {
// Fallback to chartName if releaseName is empty
// NOTE: Similar fallback mechanism happens in src/internal/packager/helm/chart.go:InstallOrUpgradeChart
if releaseName == "" {
Expand All @@ -243,16 +243,15 @@ func validateReleaseName(chartName, releaseName string) (err error) {

// Check if the final releaseName is empty and return an error if so
if releaseName == "" {
err = errors.New(errChartReleaseNameEmpty)
return
return errors.New(errChartReleaseNameEmpty)
}

// Validate the releaseName against DNS 1035 label spec
if errs := validation.IsDNS1035Label(releaseName); len(errs) > 0 {
err = fmt.Errorf("invalid release name '%s': %s", releaseName, strings.Join(errs, "; "))
return fmt.Errorf("invalid release name '%s': %s", releaseName, strings.Join(errs, "; "))
}

return
return nil
}

// validateChart runs all validation checks on a chart.
Expand Down
2 changes: 1 addition & 1 deletion src/pkg/message/pausable.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,6 @@ func (pw *PausableWriter) Resume() {
}

// Write writes the data to the underlying output writer
func (pw *PausableWriter) Write(p []byte) (n int, err error) {
func (pw *PausableWriter) Write(p []byte) (int, error) {
return pw.out.Write(p)
}
26 changes: 15 additions & 11 deletions src/pkg/transform/image.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,32 +62,36 @@ func ImageTransformHostWithoutChecksum(targetHost, srcReference string) (string,
}

// ParseImageRef parses a source reference into an Image struct
func ParseImageRef(srcReference string) (out Image, err error) {
func ParseImageRef(srcReference string) (Image, error) {
srcReference = strings.TrimPrefix(srcReference, helpers.OCIURLPrefix)

ref, err := reference.ParseAnyReference(srcReference)
if err != nil {
return out, err
return Image{}, err
}

// Parse the reference into its components
if named, ok := ref.(reference.Named); ok {
out.Name = named.Name()
out.Path = reference.Path(named)
out.Host = reference.Domain(named)
out.Reference = ref.String()
} else {
return out, fmt.Errorf("unable to parse image name from %s", srcReference)
named, ok := ref.(reference.Named)
if !ok {
return Image{}, fmt.Errorf("unable to parse image name from %s", srcReference)
}

out := Image{
Name: named.Name(),
Path: reference.Path(named),
Host: reference.Domain(named),
Reference: ref.String(),
}

// TODO(mkcp): This rewriting tag and digest code could probably be consolidated with types
// Parse the tag and add it to digestOrReference
if tagged, ok := ref.(reference.Tagged); ok {
if tagged, tagOK := ref.(reference.Tagged); tagOK {
out.Tag = tagged.Tag()
out.TagOrDigest = fmt.Sprintf(":%s", tagged.Tag())
}

// Parse the digest and override digestOrReference
if digested, ok := ref.(reference.Digested); ok {
if digested, digOK := ref.(reference.Digested); digOK {
out.Digest = digested.Digest().String()
out.TagOrDigest = fmt.Sprintf("@%s", digested.Digest().String())
}
Expand Down
Loading