detect.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. rootCmd.AddCommand(detectCmd)
  16. detectCmd.Flags().String("log-opts", "", "git log options")
  17. detectCmd.Flags().Bool("no-git", false, "treat git repo as a regular directory and scan those files, --log-opts has no effect on the scan when --no-git is set")
  18. }
  19. var detectCmd = &cobra.Command{
  20. Use: "detect",
  21. Short: "detect secrets in code",
  22. Run: runDetect,
  23. }
  24. func runDetect(cmd *cobra.Command, args []string) {
  25. initConfig()
  26. var (
  27. vc config.ViperConfig
  28. findings []*report.Finding
  29. err error
  30. )
  31. viper.Unmarshal(&vc)
  32. cfg, err := vc.Translate()
  33. if err != nil {
  34. log.Fatal().Err(err).Msg("Failed to load config")
  35. }
  36. cfg.Path, _ = cmd.Flags().GetString("config")
  37. source, _ := cmd.Flags().GetString("source")
  38. logOpts, _ := cmd.Flags().GetString("log-opts")
  39. verbose, _ := cmd.Flags().GetBool("verbose")
  40. redact, _ := cmd.Flags().GetBool("redact")
  41. noGit, _ := cmd.Flags().GetBool("no-git")
  42. exitCode, _ := cmd.Flags().GetInt("exit-code")
  43. if cfg.Path == "" {
  44. cfg.Path = filepath.Join(source, ".gitleaks.toml")
  45. }
  46. start := time.Now()
  47. if noGit {
  48. if logOpts != "" {
  49. log.Fatal().Err(err).Msg("--log-opts cannot be used with --no-git")
  50. }
  51. findings, err = detect.FromFiles(source, cfg, detect.Options{
  52. Verbose: verbose,
  53. Redact: redact,
  54. })
  55. if err != nil {
  56. log.Fatal().Err(err).Msg("Failed to scan files")
  57. }
  58. } else {
  59. files, err := git.GitLog(source, logOpts)
  60. if err != nil {
  61. log.Fatal().Err(err).Msg("Failed to get git log")
  62. }
  63. findings = detect.FromGit(files, cfg, detect.Options{Verbose: verbose, Redact: redact})
  64. }
  65. if len(findings) != 0 {
  66. log.Warn().Msgf("leaks found: %d", len(findings))
  67. } else {
  68. log.Info().Msg("no leaks found")
  69. }
  70. log.Info().Msgf("scan completed in %s", time.Since(start))
  71. reportPath, _ := cmd.Flags().GetString("report-path")
  72. ext, _ := cmd.Flags().GetString("report-format")
  73. if reportPath != "" {
  74. report.Write(findings, cfg, ext, reportPath)
  75. }
  76. if len(findings) != 0 {
  77. os.Exit(exitCode)
  78. }
  79. }