protect.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package cmd
  2. import (
  3. "os"
  4. "path/filepath"
  5. "time"
  6. "github.com/rs/zerolog/log"
  7. "github.com/spf13/cobra"
  8. "github.com/spf13/viper"
  9. "github.com/zricethezav/gitleaks/v8/config"
  10. "github.com/zricethezav/gitleaks/v8/detect"
  11. "github.com/zricethezav/gitleaks/v8/git"
  12. "github.com/zricethezav/gitleaks/v8/report"
  13. )
  14. func init() {
  15. protectCmd.Flags().Bool("staged", false, "detect secrets in a --staged state")
  16. rootCmd.AddCommand(protectCmd)
  17. }
  18. var protectCmd = &cobra.Command{
  19. Use: "protect",
  20. Short: "protect secrets in code",
  21. Run: runProtect,
  22. }
  23. func runProtect(cmd *cobra.Command, args []string) {
  24. initConfig()
  25. var vc config.ViperConfig
  26. viper.Unmarshal(&vc)
  27. cfg, err := vc.Translate()
  28. if err != nil {
  29. log.Fatal().Err(err).Msg("Failed to load config")
  30. }
  31. cfg.Path, _ = cmd.Flags().GetString("config")
  32. source, _ := cmd.Flags().GetString("source")
  33. verbose, _ := cmd.Flags().GetBool("verbose")
  34. redact, _ := cmd.Flags().GetBool("redact")
  35. exitCode, _ := cmd.Flags().GetInt("exit-code")
  36. staged, _ := cmd.Flags().GetBool("staged")
  37. if cfg.Path == "" {
  38. cfg.Path = filepath.Join(source, ".gitleaks.toml")
  39. }
  40. start := time.Now()
  41. files, err := git.GitDiff(source, staged)
  42. if err != nil {
  43. log.Fatal().Err(err).Msg("Failed to get git log")
  44. }
  45. findings := detect.FromGit(files, cfg, detect.Options{Verbose: verbose, Redact: redact})
  46. if len(findings) != 0 {
  47. log.Warn().Msgf("leaks found: %d", len(findings))
  48. } else {
  49. log.Info().Msg("no leaks found")
  50. }
  51. log.Info().Msgf("scan duration: %s", time.Since(start))
  52. reportPath, _ := cmd.Flags().GetString("report-path")
  53. ext, _ := cmd.Flags().GetString("report-format")
  54. if reportPath != "" {
  55. report.Write(findings, cfg, ext, reportPath)
  56. }
  57. if len(findings) != 0 {
  58. os.Exit(exitCode)
  59. }
  60. }