Skip to content

Commit

Permalink
Refactored commands back into cmd package
Browse files Browse the repository at this point in the history
  • Loading branch information
Mike Schinkel committed Oct 21, 2022
1 parent 955c455 commit 051eff5
Show file tree
Hide file tree
Showing 19 changed files with 240 additions and 246 deletions.
21 changes: 20 additions & 1 deletion cmd/audit.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
package cmd

import (
"context"
"os"

"github.com/ribice/glice/v3/pkg"
"github.com/spf13/cobra"
)

// auditCmd represents the audit command
var auditCmd = &cobra.Command{
Use: "audit",
Run: glice.RunAudit,
Run: RunAudit,
Short: "Audit your project's path for disallowed open-source licenses",
Long: `Audit your project's path for Go-specific dependencies using disallowed open-source licenses ` +
`while comparing with allowed licenses and dependency overrides in glice.yaml and only auditing ` +
Expand All @@ -21,3 +24,19 @@ func init() {
addTTLFlag(auditCmd)
auditCmd.Flags().Bool("overrides", false, "Write an `overrides.yaml` file if any disallowed licenses are found.")
}

func RunAudit(cmd *cobra.Command, args []string) {
ctx := context.Background()
glice.Notef("\n")
glice.Notef("\nBeginning License Audit")
deps := ScanningDependencies(ctx)
pf := AuditingProjectDependencies(ctx, "run", deps)
glice.Notef("\n\n")
HandleChanges(ctx, pf)
exceptions := HasDisalloweds(ctx, pf)
GeneratingOverrides(ctx, cmd, pf, glice.WarnLevel)
if exceptions {
os.Exit(glice.ExitAuditFoundDisallowedLicenses)
}
glice.Notef("\n\n")
}
13 changes: 12 additions & 1 deletion cmd/init.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
package cmd

import (
"context"
"github.com/ribice/glice/v3/pkg"
"github.com/spf13/cobra"
)

// initCmd represents the init command
var initCmd = &cobra.Command{
Use: "init",
Run: glice.RunInit,
Run: RunInit,
Short: "Initialize a 'glice.yaml' command in your project's path",
Long: `Initialize a 'glice.yaml' command in your project's path. ` +
`'init' will scan the go.mod file for dependencies and write ` +
Expand All @@ -21,3 +22,13 @@ var initCmd = &cobra.Command{
func init() {
rootCmd.AddCommand(initCmd)
}

func RunInit(cmd *cobra.Command, args []string) {
ctx := context.Background()
glice.Notef("\n")
glice.Notef("\nInitializing %s for project", glice.AppName)
pf := CreatingProjectFile(ctx)
pf.Dependencies = ScanningDependencies(ctx)
SavingProjectFile(ctx, pf)
glice.Notef("\n\n")
}
15 changes: 13 additions & 2 deletions cmd/overrides.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
package cmd

import (
glice "github.com/ribice/glice/v3/pkg"
"context"
"github.com/ribice/glice/v3/pkg"
"github.com/spf13/cobra"
)

// overridesCmd represents the overrides command
var overridesCmd = &cobra.Command{
Use: "overrides",
Run: glice.RunOverrides,
Run: RunOverrides,
Short: "Generate overrides.yaml for editing",
Long: `Generate overrides.yaml for manual copying into glice.yaml and then manual editing to by the user`,
}
Expand All @@ -17,3 +18,13 @@ func init() {
rootCmd.AddCommand(overridesCmd)
addTTLFlag(overridesCmd)
}

func RunOverrides(cmd *cobra.Command, args []string) {
ctx := context.Background()
glice.Notef("\n")
glice.Notef("\nGenerating Overrides file")
deps := ScanningDependencies(ctx)
pf := AuditingProjectDependencies(ctx, "generate", deps)
glice.Notef("\n\n")
GeneratingOverrides(ctx, cmd, pf, glice.ErrorLevel)
}
2 changes: 1 addition & 1 deletion cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func init() {
pf.Lookup("verbose").NoOptDefVal = strconv.Itoa(glice.InfoLevel)
pf.BoolVar(&logOutput, "log", false, "Log output to default logging filepath.")
pf.StringVar(&logfile, "logfile", "", "File to log output to.")
pf.StringVar(&source, "source", glice.SourceDir(""), "Source directory where go.mod for the repo to audit is located.")
pf.StringVar(&source, "source", glice.SourceDir(""), "Source directory where go.mod.")
pf.StringVar(&cachefile, "cache-file", glice.CacheFilepath(), "Full filepath to the cachefile to create.")
pf.BoolVar(&nocache, "nocache", false, "Disable use of caching")

Expand Down
162 changes: 162 additions & 0 deletions cmd/util.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
package cmd

import (
"context"
"github.com/ribice/glice/v3/pkg"
"github.com/spf13/cobra"
)

func ExtractingEditorsAndOOverrides(ctx context.Context, pf *glice.ProjectFile, of *glice.OverridesFile) {
glice.Notef("\nExtracting editors and overrides")
of.Editors, of.Overrides = pf.Disalloweds.ToEditorsAndOverrides(ctx)
glice.Notef("\nEditors and overrides extracted")
}

func SavingOverridesFile(ctx context.Context, of *glice.OverridesFile) {
glice.Notef("\nSaving %s", of.Filepath)
err := of.Save()
if err != nil {
glice.Failf(glice.ExitCannotSaveFile,
"Failed to create file %s: %s",
of.Filepath,
err.Error())
}
glice.Notef("\nOverrides files saved.")
}

func LoadingProfileFile(ctx context.Context, task string) *glice.ProjectFile {
glice.Notef("\nLoading `%s`", glice.ProjectFilename)
pf, err := glice.LoadProjectFile(glice.GetOptions().SourceDir)
if err != nil {
glice.Failf(glice.ExitFileDoesNotExist,
"Cannot %s %s; %s",
task,
glice.CallerName(),
err.Error())
}
glice.Notef("\nLoaded `%s`", pf.Filepath)
return pf
}

func ScanningDependencies(ctx context.Context) (deps glice.Dependencies) {
var err error

glice.Notef("\nScanning dependencies...")
deps, err = glice.ScanDependencies(ctx, glice.GetOptions())
if err != nil {
glice.Failf(glice.ExitCannotScanDependencies,
"Failed while scanning dependencies: %s",
err.Error())
}
return deps
}

func SavingProjectFile(ctx context.Context, pf *glice.ProjectFile) {
glice.Notef("\nSaving %s", glice.ProjectFilename)
err := pf.Save()
if err != nil {
glice.Failf(glice.ExitCannotSaveFile,
"Failed to save %s: %s",
pf.Filepath,
err.Error())
}
glice.Notef("\nProject file saved")
}

func CreatingProjectFile(ctx context.Context) (pf *glice.ProjectFile) {
glice.Notef("\nCreating %s", glice.ProjectFilename)
pf = glice.NewProjectFile(glice.GetOptions().SourceDir)
if pf.Exists() {
glice.Failf(glice.ExitFileExistsCannotOverwrite,
"Cannot overwrite existing file %s.\nRename or delete file then re-run 'glice init'.",
pf.Filepath)
}
pf.Editors = glice.Editors{
{Name: "Name goes here", Email: "email-alias@singlestore.com"},
}
pf.Overrides = glice.Overrides{
{
DependencyImport: "https://github.com/example.com/sample",
LicenseID: "MIT",
VerifiedBy: "*email-alias",
LastVerified: glice.Timestamp()[:10],
Notes: "This is a sample override added by 'glice init' command",
},
}
glice.Notef("\nFile %s created", pf.Filepath)
return pf
}

func CreatingOverridesFile(ctx context.Context, onExists int) *glice.OverridesFile {
glice.Notef("\nCreating %s", glice.OverridesFilename)

of := glice.NewOverridesFile(glice.GetOptions().SourceDir)
if !of.Exists() {
goto end
}
switch onExists {
case glice.WarnLevel:
glice.Warnf(
"\nCannot overwrite existing file %s.\nRename or delete file then re-run 'glice overrides'.",
of.Filepath)
default:
glice.Failf(glice.ExitFileExistsCannotOverwrite,
"\nCannot overwrite existing file %s.\nRename or delete file then re-run 'glice overrides'.",
of.Filepath)
}
end:
return of
}

func AuditingProjectDependencies(ctx context.Context, task string, deps glice.Dependencies) (pf *glice.ProjectFile) {
pf = LoadingProfileFile(ctx, task)
glice.Notef("\nAuditing dependencies...")
pf.Changes, pf.Disalloweds = pf.AuditDependencies(deps)
glice.Notef("\nAudit complete.")
return pf
}

func HasDisalloweds(ctx context.Context, pf *glice.ProjectFile) (has bool) {
if len(pf.Disalloweds) == 0 {
glice.Notef("\n")
glice.Notef("\nOnly allowed licenses detected")
glice.Notef("\nAudit completed successfully\n")
goto end
}
has = true
glice.Errorf("\n")
glice.Errorf("\nDisallowed licenses detected:")
glice.Errorf("\n")
pf.Disalloweds.LogPrint()
glice.Errorf("\n")
glice.Errorf("\nAudit FAILED!")
glice.Errorf("\n\n")
end:
return has
}

func HandleChanges(ctx context.Context, pf *glice.ProjectFile) {
changes := pf.Changes
if !changes.HasChanges() {
glice.Notef("\n")
glice.Notef("\nNo chances detected")
glice.Notef("\n\n")
} else {
glice.Notef("\n")
changes.Print()
}
}

func ShouldGenerateOverrides(cmd *cobra.Command) bool {
return cmd.Name() == "overrides" || glice.Flag(cmd, "overrides") == "true"
}

func GeneratingOverrides(ctx context.Context, cmd *cobra.Command, pf *glice.ProjectFile, onExists int) {
if ShouldGenerateOverrides(cmd) {
glice.Notef("\n")
of := CreatingOverridesFile(ctx, onExists)
ExtractingEditorsAndOOverrides(ctx, pf, of)
SavingOverridesFile(ctx, of)
glice.Notef("\n\n")
}
}
4 changes: 2 additions & 2 deletions pkg/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,14 +13,14 @@ var cacheFilepath = filepath.Join(CacheDir(), CacheFilename)
func CacheDir() string {
dir, err := os.UserCacheDir()
if err != nil {
Failf(exitCannotGetCacheDir,
Failf(ExitCannotGetCacheDir,
"Unable to get cache dir as %s",
err.Error())
}
dir = filepath.Join(dir, CacheSubDir)
err = os.MkdirAll(dir, os.ModePerm)
if err != nil {
Failf(exitCannotCreateCacheDir,
Failf(ExitCannotCreateCacheDir,
"Unable to get create cache subdir %s: %s",
err.Error())
}
Expand Down
26 changes: 13 additions & 13 deletions pkg/exit.go
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
package glice

const (
exitAuditFoundDisallowedLicenses = 1
exitCannotGetWorkingDir = 2
exitCannotGetCacheDir = 3
exitCannotCreateCacheDir = 4
exitCannotParseDependencies = 5
exitCannotCreateFile = 6
exitCannotStatFile = 7
exitFileExistsCannotOverwrite = 8
exitFileDoesNotExist = 9
exitRepoInfoGetterIsNil = 10
exitCannotGetRepositoryGetter = 11
exitCannotSetOptions = 12
exitHostNotYetSupported = 13
ExitAuditFoundDisallowedLicenses = 1
ExitCannotGetWorkingDir = 2
ExitCannotGetCacheDir = 3
ExitCannotCreateCacheDir = 4
ExitCannotScanDependencies = 5
ExitCannotSaveFile = 6
ExitCannotStatFile = 7
ExitFileExistsCannotOverwrite = 8
ExitFileDoesNotExist = 9
ExitRepoInfoGetterIsNil = 10
ExitCannotGetRepositoryGetter = 11
ExitCannotSetOptions = 12
ExitHostNotYetSupported = 1
)
4 changes: 2 additions & 2 deletions pkg/github.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,13 +81,13 @@ func (c *GitHubRepoClient) GetRepoName() string {

func (c *GitHubRepoClient) checkRepoInfoGetter() {
if c.repoInfoGetter == nil {
Failf(exitRepoInfoGetterIsNil,
Failf(ExitRepoInfoGetterIsNil,
"Must set Repository.repoInfoGetter before calling GitHubRepoClient.%s()",
CallerName())
}
}

func (c *GitHubRepoClient) UpVoteRepository(ctx context.Context, options *Options) {
func (c *GitHubRepoClient) UpVoteRepository(ctx context.Context) {
var r *github.Response
var err error

Expand Down
2 changes: 1 addition & 1 deletion pkg/interfaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ type RepositoryLicenseGetter interface {
GetRepositoryLicense(context.Context, *Options) (*RepositoryLicense, error)
}
type RepositoryUpVoter interface {
UpVoteRepository(context.Context, *Options)
UpVoteRepository(context.Context)
}
type HostClientSetter interface {
SetHostClient(client *HostClient)
Expand Down
2 changes: 1 addition & 1 deletion pkg/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func GetOptions() *Options {
func SetOptions(o *Options) {
err := o.setLogging()
if err != nil {
Failf(exitCannotSetOptions,
Failf(ExitCannotSetOptions,
"Unable to set options: %s",
err.Error())
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/overrides_file.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,6 @@ func (of *OverridesFile) ensureValidProperties() {
}
}

func (of *OverridesFile) Create() error {
return CreateYAMLFile(of)
func (of *OverridesFile) Save() error {
return SaveYAMLFile(of)
}
8 changes: 5 additions & 3 deletions pkg/project_file.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@ type ProjectFile struct {
Editors Editors `yaml:"editors"`
Generated string `yaml:"generated"`
AllowedLicenses LicenseIDs `yaml:"allowed"`
allowedMap LicenseIDMap `yaml:"-"`
Overrides Overrides `yaml:"overrides"`
Dependencies Dependencies `yaml:"dependencies"`
allowedMap LicenseIDMap `yaml:"-"`
Disalloweds Dependencies `yaml:"-"`
Changes *Changes `yaml:"-"`
}

func NewProjectFile(dir string) *ProjectFile {
Expand Down Expand Up @@ -73,8 +75,8 @@ func LoadProjectFile(dir string) (pf *ProjectFile, err error) {
return fg.(*ProjectFile), err
}

func (pf *ProjectFile) Initialize() (err error) {
return CreateYAMLFile(pf)
func (pf *ProjectFile) Save() (err error) {
return SaveYAMLFile(pf)
}

// removeOverridden accepts a DependencyMap and removes any found to be
Expand Down
2 changes: 1 addition & 1 deletion pkg/project_file_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ func TestProjectFileInit(t *testing.T) {
t.Errorf("failed to parse dependencies: %s", err.Error())
}
pf.Filepath = glice.GetProjectFilepath(TestDataDir)
err = pf.Initialize()
err = pf.Save()
if err != nil {
t.Errorf("failed to create `glice.yaml` file %s: %s",
options.SourceDir,
Expand Down
Loading

0 comments on commit 051eff5

Please sign in to comment.