protect.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package cmd
  2. import (
  3. "time"
  4. "github.com/spf13/cobra"
  5. "github.com/zricethezav/gitleaks/v8/cmd/scm"
  6. "github.com/zricethezav/gitleaks/v8/detect"
  7. "github.com/zricethezav/gitleaks/v8/logging"
  8. "github.com/zricethezav/gitleaks/v8/report"
  9. "github.com/zricethezav/gitleaks/v8/sources"
  10. )
  11. func init() {
  12. protectCmd.Flags().Bool("staged", false, "detect secrets in a --staged state")
  13. protectCmd.Flags().String("log-opts", "", "git log options")
  14. protectCmd.Flags().StringP("source", "s", ".", "path to source")
  15. rootCmd.AddCommand(protectCmd)
  16. }
  17. var protectCmd = &cobra.Command{
  18. Use: "protect",
  19. Short: "protect secrets in code",
  20. Run: runProtect,
  21. Hidden: true,
  22. }
  23. func runProtect(cmd *cobra.Command, args []string) {
  24. // start timer
  25. start := time.Now()
  26. source := mustGetStringFlag(cmd, "source")
  27. // setup config (aka, the thing that defines rules)
  28. initConfig(source)
  29. cfg := Config(cmd)
  30. // create detector
  31. detector := Detector(cmd, cfg, source)
  32. // parse flags
  33. exitCode := mustGetIntFlag(cmd, "exit-code")
  34. staged := mustGetBoolFlag(cmd, "staged")
  35. // start git scan
  36. var (
  37. findings []report.Finding
  38. err error
  39. gitCmd *sources.GitCmd
  40. remote *detect.RemoteInfo
  41. )
  42. if gitCmd, err = sources.NewGitDiffCmd(source, staged); err != nil {
  43. logging.Fatal().Err(err).Msg("could not create Git diff cmd")
  44. }
  45. remote = &detect.RemoteInfo{Platform: scm.NoPlatform}
  46. if findings, err = detector.DetectGit(gitCmd, remote); err != nil {
  47. // don't exit on error, just log it
  48. logging.Error().Err(err).Msg("failed to scan Git repository")
  49. }
  50. findingSummaryAndExit(detector, findings, exitCode, start, err)
  51. }