options.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "strconv"
  6. )
  7. // TODO regex on type.. user/organization can be treated as the same:
  8. // hittps://github.com/<user or org>
  9. // hittps://github.com/<user or org>/repo
  10. const usage = `usage: gitleaks [git link] [options]
  11. Options:
  12. -c Concurrency factor (potential number of git files open)
  13. -h --help Display this message
  14. `
  15. // Options for gitleaks
  16. type Options struct {
  17. Concurrency int
  18. UserURL string
  19. OrgURL string
  20. RepoURL string
  21. }
  22. // help prints the usage string and exits
  23. func help() {
  24. os.Stderr.WriteString(usage)
  25. os.Exit(1)
  26. }
  27. // optionsNextInt is a parseOptions helper that returns the value (int) of an option
  28. // if valid.
  29. func optionsNextInt(args []string, i *int) int {
  30. if len(args) > *i+1 {
  31. *i++
  32. } else {
  33. help()
  34. }
  35. argInt, err := strconv.Atoi(args[*i])
  36. if err != nil {
  37. fmt.Printf("Invalid %s option: %s\n", args[*i-1], args[*i])
  38. help()
  39. }
  40. return argInt
  41. }
  42. // optionsNextString is a parseOptions helper that returns the value (string) of an option
  43. // if valid.
  44. func optionsNextString(args []string, i *int) string {
  45. if len(args) > *i+1 {
  46. *i++
  47. } else {
  48. fmt.Printf("Invalid %s option: %s\n", args[*i-1], args[*i])
  49. help()
  50. }
  51. return args[*i]
  52. }
  53. // parseOptions
  54. func parseOptions(args []string) *Options {
  55. opts := &Options{}
  56. // default is repo if no additional options
  57. if len(args) == 1 {
  58. opts.RepoURL = args[0]
  59. return opts
  60. }
  61. for i := 0; i < len(args); i++ {
  62. arg := args[i]
  63. switch arg {
  64. case "-c":
  65. opts.Concurrency = optionsNextInt(args, &i)
  66. case "-o":
  67. opts.OrgURL = optionsNextString(args, &i)
  68. case "-u":
  69. opts.UserURL = optionsNextString(args, &i)
  70. case "-r":
  71. opts.RepoURL = optionsNextString(args, &i)
  72. case "-h", "--help":
  73. help()
  74. return nil
  75. default:
  76. if i == len(args)-1 && opts.OrgURL == "" && opts.RepoURL == "" &&
  77. opts.UserURL == "" {
  78. opts.RepoURL = arg
  79. } else {
  80. fmt.Printf("Uknown option %s\n\n", arg)
  81. help()
  82. return nil
  83. }
  84. }
  85. }
  86. return opts
  87. }