Skip to content

Commit

Permalink
refactor: move normalize, denormalize, version cmd in separate files
Browse files Browse the repository at this point in the history
  • Loading branch information
PhilippHeuer committed Mar 24, 2023
1 parent 4e3e0b6 commit 23d821d
Show file tree
Hide file tree
Showing 9 changed files with 219 additions and 142 deletions.
27 changes: 14 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
## features

- **normalization** - check the env vars and the local repository to provide a [common set of env vars](docs/spec/variables.md) on any ci platform.
- **compatibility** - convert the common env vars into a specific format (ie. gitlab) to run a script made for gitlab on any ci provider.
- **compatibility** - convert the common env vars into a specific format (i.e. gitlab) to run a script made for gitlab on any ci provider.

## installation

Expand All @@ -28,29 +28,30 @@ sudo chmod +x /usr/local/bin/normalizeci

Examples:

| Id | Command | Description |
|-----|------------------------------------------------|-----------------------------------------------------------------------------------|
| 1 | `normalizeci --format export --output nci.env` | generate nci variables in format export for unix systems, stored as file |
| 2 | `normalizeci --format powershell` | generate nci variables in format export for windows powershell, written to stdout |
| 3 | `normalizeci --output nci.env` | generate nci variables in the suggested format for the current system |
| 4 | `normalizeci --hostenv --output nci.env` | additionally to 3 includes all env vars from the host |
| 5 | `normalizeci --format cmd` | generate nci variables in format export for windows cmd, written to stdout |
| 6 | `normalizeci -v` | print version information |
| Id | Command | Description |
|-----|----------------------------------------------------------|-----------------------------------------------------------------------------------|
| 1 | `normalizeci normalize --format export --output nci.env` | generate nci variables in format export for unix systems, stored as file |
| 2 | `normalizeci normalize --format powershell` | generate nci variables in format export for windows powershell, written to stdout |
| 3 | `normalizeci normalize --output nci.env` | generate nci variables in the suggested format for the current system |
| 4 | `normalizeci normalize --hostenv --output nci.env` | additionally to 3 includes all env vars from the host |
| 5 | `normalizeci normalize --format cmd` | generate nci variables in format export for windows cmd, written to stdout |
| 6 | `normalizeci denormalize --target gitlab` | generate a gitlab ci like environment based on the normalized environment |
| 7 | `normalizeci version` | print version information |

#### file based

Linux/MacOS

```bash
normalizeci --format export --output nci.env
normalizeci normalize --format export --output nci.env
source nci.env
rm nci.env
```

Windows

```powershell
normalizeci --format powershell --output nci.ps1
normalizeci normalize --format powershell --output nci.ps1
& .\nci.ps1
rm nci.ps1
```
Expand All @@ -62,13 +63,13 @@ The NormalizeCI CLI will return the commands to set the normalized variables in
Linux/MacOS

```bash
eval $(normalizeci)
eval $(normalizeci normalize)
```

Windows

```powershell
$nenv = normalizeci
$nenv = normalizeci normalize
Invoke-Expression "$nenv"
```

Expand Down
23 changes: 11 additions & 12 deletions cli/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,12 @@ import (
"github.com/rs/zerolog/log"
)

// Version will be set at build time
var Version string

// CommitHash will be set at build time
var CommitHash string

// BuildAt will be set at build time
var BuildAt string
var (
version = "dev"
commit = "none"
date = "unknown"
status = "clean"
)

// Init Hook
func init() {
Expand All @@ -32,10 +30,11 @@ func init() {
zerolog.SetGlobalLevel(zerolog.TraceLevel)
}

// version information
cmd.Version = Version
cmd.CommitHash = CommitHash
cmd.BuildAt = BuildAt
// Set Version Information
cmd.Version = version
cmd.CommitHash = commit
cmd.BuildAt = date
cmd.RepositoryStatus = status
}

// CLI Main Entrypoint
Expand Down
69 changes: 69 additions & 0 deletions cli/cmd/denormalize.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package cmd

import (
"fmt"
"os"

"github.com/cidverse/normalizeci/pkg/ncispec"
"github.com/cidverse/normalizeci/pkg/normalizeci"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
)

func init() {
rootCmd.AddCommand(denormalizeCmd)
denormalizeCmd.PersistentFlags().StringP("format", "f", normalizeci.GetDefaultFormat(), "The format in which to store the normalized variables. (export, powershell, cmd)")
denormalizeCmd.PersistentFlags().StringP("output", "o", "", "Write output to this file instead of writing it to stdout.")
denormalizeCmd.PersistentFlags().Bool("strict", false, "Validate the generated variables against the spec and fail on errors?")
denormalizeCmd.PersistentFlags().StringArrayP("target", "t", []string{}, "Additionally generates the environment for the target ci services")
}

var denormalizeCmd = &cobra.Command{
Use: "denormalize",
Short: "denormalizes information about the current CI environment",
Run: func(cmd *cobra.Command, args []string) {
format, _ := cmd.Flags().GetString("format")
outputFile, _ := cmd.Flags().GetString("output")
strict, _ := cmd.Flags().GetBool("strict")
targets, _ := cmd.Flags().GetStringArray("target")

// run normalization
var normalized = normalizeci.Normalize()
outputEnv := make(map[string]string)
normalizeci.SetProcessEnvironment(ncispec.ToMap(normalized))

// targets
if len(targets) > 0 {
for _, target := range targets {
denormalized := normalizeci.Denormalize(target, normalized)
for key, value := range denormalized {
outputEnv[key] = value
}
}
}

// content?
content, err := normalizeci.FormatEnvironment(outputEnv, format)
if err != nil {
log.Fatal().Str("format", format).Str("supported", "export,powershell,cmd").Msg("unsupported format!")
}

// validate?
if strict {
errors := normalized.Validate()
if len(errors) > 0 {
for _, line := range errors {
fmt.Printf("%s: %s [%s]\n", line.Field, line.Description, line.Value)
}
os.Exit(1)
}
}

// output
if len(outputFile) > 0 {
fileOutput(outputFile, content)
} else {
consoleOutput(content)
}
},
}
70 changes: 70 additions & 0 deletions cli/cmd/normalize.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package cmd

import (
"fmt"
"os"

"github.com/cidverse/normalizeci/pkg/ncispec"
"github.com/cidverse/normalizeci/pkg/normalizeci"
"github.com/rs/zerolog/log"
"github.com/spf13/cobra"
)

func init() {
rootCmd.AddCommand(normalizeCmd)
normalizeCmd.PersistentFlags().StringP("format", "f", normalizeci.GetDefaultFormat(), "The format in which to store the normalized variables. (export, powershell, cmd)")
normalizeCmd.PersistentFlags().StringP("output", "o", "", "Write output to this file instead of writing it to stdout.")
normalizeCmd.PersistentFlags().Bool("strict", false, "Validate the generated variables against the spec and fail on errors?")
normalizeCmd.PersistentFlags().BoolP("version", "v", false, "all software has versions, this prints version information for normalizeci")
normalizeCmd.PersistentFlags().StringArrayP("target", "t", []string{}, "Additionally generates the environment for the target ci services")
}

var normalizeCmd = &cobra.Command{
Use: "normalize",
Short: "normalizes information about the current CI environment",
Run: func(cmd *cobra.Command, args []string) {
format, _ := cmd.Flags().GetString("format")
outputFile, _ := cmd.Flags().GetString("output")
strict, _ := cmd.Flags().GetBool("strict")
targets, _ := cmd.Flags().GetStringArray("target")

// run normalization
var normalized = normalizeci.Normalize()
outputEnv := ncispec.ToMap(normalized)
normalizeci.SetProcessEnvironment(ncispec.ToMap(normalized))

// targets
if len(targets) > 0 {
for _, target := range targets {
denormalized := normalizeci.Denormalize(target, normalized)
for key, value := range denormalized {
outputEnv[key] = value
}
}
}

// format content
content, err := normalizeci.FormatEnvironment(outputEnv, format)
if err != nil {
log.Fatal().Str("format", format).Str("supported", "export,powershell,cmd").Msg("unsupported format!")
}

// validate?
if strict {
errors := normalized.Validate()
if len(errors) > 0 {
for _, line := range errors {
fmt.Printf("%s: %s [%s]\n", line.Field, line.Description, line.Value)
}
os.Exit(1)
}
}

// output
if len(outputFile) > 0 {
fileOutput(outputFile, content)
} else {
consoleOutput(content)
}
},
}
51 changes: 4 additions & 47 deletions cli/cmd/root.go
Original file line number Diff line number Diff line change
@@ -1,65 +1,22 @@
package cmd

import (
"fmt"
"os"
"runtime"

"github.com/spf13/cobra"
)

// Version will be set at build time
var Version string

// CommitHash will be set at build time
var CommitHash string

// BuildAt will be set at build time
var BuildAt string

var rootCmd = &cobra.Command{
Use: `normalizeci`,
Short: `normalizeci provides a foundation for platform-agnostic CICD processes.`,
Long: `normalizeci provides a foundation for platform-agnostic CICD processes.`,
PreRunE: func(cmd *cobra.Command, args []string) error {
version, _ := cmd.Flags().GetBool("version")
if version {
printVersion()
os.Exit(0)
}
return nil
},
Short: `normalizeci provides a foundation for platform-agnostic CI-CD processes.`,
Long: `normalizeci provides a foundation for platform-agnostic CI-CD processes.`,
Run: func(cmd *cobra.Command, args []string) {
format, _ := cmd.Flags().GetString("format")
format = defaultFormat(format)
output, _ := cmd.Flags().GetString("output")
strict, _ := cmd.Flags().GetBool("strict")
targets, _ := cmd.Flags().GetStringArray("target")

normalizationCommand(format, output, strict, targets)
_ = cmd.Help()
os.Exit(0)
},
}

func init() {
rootCmd.PersistentFlags().StringP("format", "f", "systemdefault", "The format in which to store the normalized variables. (export, powershell, cmd)")
rootCmd.PersistentFlags().StringP("output", "o", "", "Write output to this file instead of writing it to stdout.")
rootCmd.PersistentFlags().Bool("hostenv", false, "Should include os env along with normalized variables into the target?")
rootCmd.PersistentFlags().Bool("strict", false, "Validate the generated variables against the spec and fail on errors?")
rootCmd.PersistentFlags().BoolP("version", "v", false, "all software has versions, this prints version information for normalizeci")
rootCmd.PersistentFlags().StringArrayP("target", "t", []string{}, "Additionally generates the environment for the target ci services")
}

// Execute executes the root command.
func Execute() error {
return rootCmd.Execute()
}

func printVersion() {
fmt.Fprintf(os.Stdout, "GitVersion: %s\n", Version)
fmt.Fprintf(os.Stdout, "GitCommit: %s\n", CommitHash)
fmt.Fprintf(os.Stdout, "GitTreeState: %s\n", "clean")
fmt.Fprintf(os.Stdout, "BuildDate: %s\n", BuildAt)
fmt.Fprintf(os.Stdout, "GoVersion: %s\n", runtime.Version())
fmt.Fprintf(os.Stdout, "Compiler: %s\n", runtime.Compiler)
fmt.Fprintf(os.Stdout, "Platform: %s\n", runtime.GOOS+"/"+runtime.GOARCH)
}
56 changes: 0 additions & 56 deletions cli/cmd/run.go

This file was deleted.

9 changes: 0 additions & 9 deletions cli/cmd/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,9 @@ import (
"io"
"os"

"github.com/cidverse/normalizeci/pkg/normalizeci"
"github.com/rs/zerolog/log"
)

func defaultFormat(value string) string {
if value == "systemdefault" {
return normalizeci.GetDefaultFormat()
}

return value
}

func fileOutput(file string, content string) {
contentByteArray := []byte(content)
err := os.WriteFile(file, contentByteArray, 0644)
Expand Down
Loading

0 comments on commit 23d821d

Please sign in to comment.