Skip to content

Commit

Permalink
Add the cleanupexamples tool
Browse files Browse the repository at this point in the history
Signed-off-by: Fatih Türken <[email protected]>
  • Loading branch information
turkenf committed Aug 27, 2024
1 parent 5aa444d commit 6f881a9
Show file tree
Hide file tree
Showing 3 changed files with 145 additions and 1 deletion.
137 changes: 137 additions & 0 deletions cmd/cleanup/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
package main

Check warning on line 1 in cmd/cleanup/main.go

View workflow job for this annotation

GitHub Actions / lint

package-comments: should have a package comment (revive)

import (
"bytes"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"

"github.com/alecthomas/kingpin/v2"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
kyaml "k8s.io/apimachinery/pkg/util/yaml"
"sigs.k8s.io/yaml"
)

func processYAML(yamlData []byte) ([]byte, error) {

Check failure on line 18 in cmd/cleanup/main.go

View workflow job for this annotation

GitHub Actions / lint

cyclomatic complexity 11 of func `processYAML` is high (> 10) (gocyclo)
yamlData = bytes.Replace(yamlData, []byte("${Rand.RFC1123Subdomain}"), []byte("random"), -1)

Check failure on line 19 in cmd/cleanup/main.go

View workflow job for this annotation

GitHub Actions / lint

wrapperFunc: use bytes.ReplaceAll method in `bytes.Replace(yamlData, []byte("${Rand.RFC1123Subdomain}"), []byte("random"), -1)` (gocritic)

decoder := kyaml.NewYAMLOrJSONDecoder(bytes.NewReader(yamlData), 1024)
var modifiedYAMLs []byte
separator := []byte("---\n")
var first bool = true

Check warning on line 24 in cmd/cleanup/main.go

View workflow job for this annotation

GitHub Actions / lint

var-declaration: should omit type bool from declaration of var first; it will be inferred from the right-hand side (revive)

for {
u := &unstructured.Unstructured{}
if err := decoder.Decode(&u); err != nil {
if errors.Is(err, io.EOF) {
break
}
return nil, fmt.Errorf("cannot decode the YAML file: %w", err)
}

annotations := u.GetAnnotations()
if annotations != nil {
annotationsToRemove := []string{
"upjet.upbound.io/",
"uptest.upbound.io/",
}

for key := range annotations {
for _, prefix := range annotationsToRemove {
if strings.HasPrefix(key, prefix) {
delete(annotations, key)
break
}
}
}

if len(annotations) == 0 {
u.SetAnnotations(nil)
} else {
u.SetAnnotations(annotations)
}
}

modifiedYAML, err := yaml.Marshal(u.Object)
if err != nil {
return nil, fmt.Errorf("cannot marshal the YAML file: %w", err)
}

if !first {
modifiedYAMLs = append(modifiedYAMLs, separator...)
}
modifiedYAMLs = append(modifiedYAMLs, modifiedYAML...)
first = false
}

return modifiedYAMLs, nil
}

func processDirectory(inputDir string, outputDir string) error {

Check failure on line 73 in cmd/cleanup/main.go

View workflow job for this annotation

GitHub Actions / lint

cyclomatic complexity 12 of func `processDirectory` is high (> 10) (gocyclo)
// Walk through the input directory
err := filepath.Walk(inputDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return fmt.Errorf("error accessing path %s: %w", path, err)
}

// Check if it's a directory, skip processing but ensure the directory exists in outputDir
if info.IsDir() {
relativePath, err := filepath.Rel(inputDir, path)
if err != nil {
return fmt.Errorf("error finding relative path: %w", err)
}
newDir := filepath.Join(outputDir, relativePath)
if _, err := os.Stat(newDir); os.IsNotExist(err) {
err = os.MkdirAll(newDir, 0755)

Check failure on line 88 in cmd/cleanup/main.go

View workflow job for this annotation

GitHub Actions / lint

G301: Expect directory permissions to be 0750 or less (gosec)
if err != nil {
return fmt.Errorf("cannot create directory %s: %w", newDir, err)
}
}
return nil
}

// Only process YAML files
if filepath.Ext(path) == ".yaml" || filepath.Ext(path) == ".yml" {
yamlFile, err := os.ReadFile(path)

Check failure on line 98 in cmd/cleanup/main.go

View workflow job for this annotation

GitHub Actions / lint

G304: Potential file inclusion via variable (gosec)
if err != nil {
return fmt.Errorf("cannot read the YAML file %s: %w", path, err)
}

modifiedYAMLs, err := processYAML(yamlFile)
if err != nil {
return fmt.Errorf("error processing YAML file %s: %w", path, err)
}

// Create the output path, preserving directory structure
relativePath, err := filepath.Rel(inputDir, path)
if err != nil {
return fmt.Errorf("error finding relative path: %w", err)
}
outputPath := filepath.Join(outputDir, relativePath)
err = os.WriteFile(outputPath, modifiedYAMLs, 0644)

Check failure on line 114 in cmd/cleanup/main.go

View workflow job for this annotation

GitHub Actions / lint

G306: Expect WriteFile permissions to be 0600 or less (gosec)
if err != nil {
return fmt.Errorf("cannot write the YAML file %s: %w", outputPath, err)
}
}
return nil
})
return err
}

func main() {
inputDir := kingpin.Arg("inputDir", "Directory containing the input YAML files.").Required().String()
outputDir := kingpin.Arg("outputDir", "Directory to save the processed YAML files.").Required().String()

kingpin.Parse()

err := processDirectory(*inputDir, *outputDir)
if err != nil {
fmt.Printf("error processing directory: %v\n", err)
return
}

fmt.Printf("All YAML files processed and saved to: %s\n", *outputDir)
}
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ go 1.21
require (
cloud.google.com/go/storage v1.27.0
github.com/adrg/frontmatter v0.2.0
github.com/alecthomas/kingpin/v2 v2.4.0
github.com/alecthomas/kong v0.7.1
github.com/crossplane/crossplane v1.10.0
github.com/crossplane/crossplane-runtime v0.20.0-rc.0.0.20230406155702-4e1673b7141f
Expand Down Expand Up @@ -87,6 +88,7 @@ require (
github.com/peterbourgon/diskv v2.0.1+incompatible // indirect
github.com/prometheus/client_model v0.3.0 // indirect
github.com/prometheus/procfs v0.8.0 // indirect
github.com/xhit/go-str2duration/v2 v2.1.0 // indirect
github.com/xlab/treeprint v1.1.0 // indirect
github.com/yuin/goldmark v1.5.3 // indirect
go.opencensus.io v0.24.0 // indirect
Expand Down
7 changes: 6 additions & 1 deletion go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ github.com/adrg/frontmatter v0.2.0 h1:/DgnNe82o03riBd1S+ZDjd43wAmC6W35q67NHeLkPd
github.com/adrg/frontmatter v0.2.0/go.mod h1:93rQCj3z3ZlwyxxpQioRKC1wDLto4aXHrbqIsnH9wmE=
github.com/alecthomas/assert/v2 v2.1.0 h1:tbredtNcQnoSd3QBhQWI7QZ3XHOVkw1Moklp2ojoH/0=
github.com/alecthomas/assert/v2 v2.1.0/go.mod h1:b/+1DI2Q6NckYi+3mXyH3wFb8qG37K/DuK80n7WefXA=
github.com/alecthomas/kingpin/v2 v2.4.0 h1:f48lwail6p8zpO1bC4TxtqACaGqHYA22qkHjHpqDjYY=
github.com/alecthomas/kingpin/v2 v2.4.0/go.mod h1:0gyi0zQnjuFk8xrkNKamJoyUo382HRL7ATRpFZCw6tE=
github.com/alecthomas/kong v0.7.1 h1:azoTh0IOfwlAX3qN9sHWTxACE2oV8Bg2gAwBsMwDQY4=
github.com/alecthomas/kong v0.7.1/go.mod h1:n1iCIO2xS46oE8ZfYCNDqdR0b0wZNrXAIAqro/2132U=
github.com/alecthomas/repr v0.1.0 h1:ENn2e1+J3k09gyj2shc0dHr/yjaWSHRlrJ4DPMevDqE=
Expand Down Expand Up @@ -390,15 +392,18 @@ github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8=
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/tufin/oasdiff v1.2.6 h1:npdeFfs1lvTTcsT5HB/zDJZntl6tG2oMMK0dfFSF+yM=
github.com/tufin/oasdiff v1.2.6/go.mod h1:7Ukdw7vE8EFNl8mf7e9rNX/aXptYn0RGtXoPCjjjlBU=
github.com/vbatts/tar-split v0.11.2 h1:Via6XqJr0hceW4wff3QRzD5gAk/tatMw/4ZA7cTlIME=
github.com/vbatts/tar-split v0.11.2/go.mod h1:vV3ZuO2yWSVsz+pfFzDG/upWH1JhjOiEaWq6kXyQ3VI=
github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU=
github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ=
github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y=
github.com/xhit/go-str2duration/v2 v2.1.0 h1:lxklc02Drh6ynqX+DdPyp5pCKLUQpRT8bp8Ydu2Bstc=
github.com/xhit/go-str2duration/v2 v2.1.0/go.mod h1:ohY8p+0f07DiV6Em5LKB0s2YpLtXVyJfNt1+BlmyAsU=
github.com/xlab/treeprint v1.1.0 h1:G/1DjNkPpfZCFt9CSh6b5/nY4VimlbHF3Rh4obvtzDk=
github.com/xlab/treeprint v1.1.0/go.mod h1:gj5Gd3gPdKtR1ikdDK6fnFLdmIS0X30kTTuNd/WEJu0=
github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
Expand Down

0 comments on commit 6f881a9

Please sign in to comment.