detect.go 2.1 KB

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