-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathroot.go
More file actions
171 lines (144 loc) · 5.59 KB
/
root.go
File metadata and controls
171 lines (144 loc) · 5.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
package cmd
import (
"fmt"
"os"
"path/filepath"
"strings"
"codacy/cli-v2/config"
"codacy/cli-v2/utils/logger"
"codacy/cli-v2/version"
"github.com/fatih/color"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
var rootCmd = &cobra.Command{
Use: "codacy-cli",
Short: fmt.Sprintf("Codacy CLI v%s - A command line interface for Codacy", version.GetVersion()),
Long: "",
Example: getExampleText(),
PersistentPreRun: func(cmd *cobra.Command, args []string) {
// Initialize logger before any command runs
logsDir := filepath.Join(config.Config.LocalCodacyDirectory(), "logs")
if err := logger.Initialize(logsDir); err != nil {
fmt.Printf("Warning: Failed to initialize file logger: %v\n", err)
}
// Create a masked version of the full command for logging
maskedArgs := maskSensitiveArgs(os.Args)
// Log the command being executed with its arguments and flags
logger.Info("Executing CLI command", logrus.Fields{
"command": cmd.Name(),
"full_command": maskedArgs,
"args": args,
})
},
Run: func(cmd *cobra.Command, args []string) {
// Check if .codacy directory exists
if _, err := os.Stat(".codacy"); os.IsNotExist(err) {
// Show welcome message if .codacy doesn't exist
showWelcomeMessage()
return
}
// If .codacy exists, show regular help
cmd.Help()
},
}
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func showWelcomeMessage() {
bold := color.New(color.Bold)
cyan := color.New(color.FgCyan)
yellow := color.New(color.FgYellow)
fmt.Println()
bold.Println("👋 Welcome to Codacy CLI!")
fmt.Println()
fmt.Println("This tool helps you analyze and maintain code quality in your projects.")
fmt.Println()
yellow.Println("To get started, you'll need a Codacy API token.")
fmt.Println("You can find your Project API token in Codacy under:")
fmt.Println("Project > Settings > Integrations > Repository API tokens")
fmt.Println()
cyan.Println("Initialize your project with:")
fmt.Println(" codacy-cli init --repository-token YOUR_TOKEN")
fmt.Println(" codacy-cli init --codacy-api-token YOUR_TOKEN")
fmt.Println()
fmt.Println("Or run without a token to use local configuration:")
fmt.Println(" codacy-cli init")
fmt.Println()
fmt.Println("For more information about available commands, run:")
fmt.Println(" codacy-cli --help")
}
func getExampleText() string {
return color.New(color.FgCyan).Sprint("Initialize a project:") + "\n" +
color.New(color.FgGreen).Sprint(" codacy-cli init") + "\n\n" +
color.New(color.FgCyan).Sprint("Install required tools:") + "\n" +
color.New(color.FgGreen).Sprint(" codacy-cli install") + "\n\n" +
color.New(color.FgCyan).Sprint("Run analysis with ESLint:") + "\n" +
color.New(color.FgGreen).Sprint(" codacy-cli analyze --tool eslint") + "\n\n" +
color.New(color.FgCyan).Sprint("Run analysis and output in SARIF format:") + "\n" +
color.New(color.FgGreen).Sprint(" codacy-cli analyze --tool eslint --format sarif") + "\n\n" +
color.New(color.FgCyan).Sprint("Upload results to Codacy:") + "\n" +
color.New(color.FgGreen).Sprint(" codacy-cli upload -s results.sarif -c <commit-uuid> -t <project-token>")
}
func init() {
// Add global flags here
rootCmd.PersistentFlags().String("config", filepath.Join(".codacy", "codacy.yaml"), "config file")
// Customize help template
rootCmd.SetUsageTemplate(`
` + color.New(color.FgCyan).Sprint("Usage:") + `
{{.UseLine}}{{if .HasAvailableSubCommands}}
{{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}
` + color.New(color.FgCyan).Sprint("Aliases:") + `
{{.NameAndAliases}}{{end}}{{if .HasExample}}
` + color.New(color.FgCyan).Sprint("Examples:") + `
{{.Example}}{{end}}{{if .HasAvailableSubCommands}}
` + color.New(color.FgCyan).Sprint("Available Commands:") + `{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
` + "{{$cmd := .Name}}" + color.New(color.FgGreen).Sprintf("{{rpad .Name .NamePadding}}") + ` {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
` + color.New(color.FgCyan).Sprint("Flags:") + `
{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}
` + color.New(color.FgCyan).Sprint("Global Flags:") + `
{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}
` + color.New(color.FgCyan).Sprint("Additional help topics:") + `{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}
{{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
` + color.New(color.FgCyan).Sprint("Configuration Example") + ` (.codacy/codacy.yaml):
runtimes:
- node@22.2.0
tools:
- eslint@8.57.0
` + color.New(color.FgCyan).Sprint("For more information and examples, visit:") + `
https://github.com/codacy/codacy-cli-v2
`)
}
// maskSensitiveArgs creates a copy of the arguments with sensitive values masked
func maskSensitiveArgs(args []string) []string {
maskedArgs := make([]string, len(args))
copy(maskedArgs, args)
sensitiveFlags := map[string]bool{
"--api-token": true,
"--repository-token": true,
"--project-token": true,
"--codacy-api-token": true,
}
for i, arg := range maskedArgs {
// Skip the first argument (program name)
if i == 0 {
continue
}
// Handle --flag=value format
for flag := range sensitiveFlags {
if strings.HasPrefix(arg, flag+"=") {
maskedArgs[i] = flag + "=***"
break
}
}
// Handle --flag value format
if sensitiveFlags[arg] && i < len(maskedArgs)-1 {
maskedArgs[i+1] = "***"
}
}
return maskedArgs
}