protect.go 1.6 KB

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