/timegaps/time-gaps.go

https://bitbucket.org/marthjod/scripts · Go · 118 lines · 96 code · 21 blank · 1 comment · 18 complexity · 5e2f2fa525b7d8f06ababcf167dc38ce MD5 · raw file

  1. package main
  2. import (
  3. "bufio"
  4. "flag"
  5. "fmt"
  6. "os"
  7. "regexp"
  8. "time"
  9. )
  10. func readLinesFromFile(path string) []string {
  11. var (
  12. file *os.File
  13. scanner *bufio.Scanner
  14. list []string
  15. err error
  16. )
  17. list = []string{}
  18. file, err = os.Open(path)
  19. if err != nil {
  20. fmt.Printf("%v\n", err)
  21. }
  22. scanner = bufio.NewScanner(file)
  23. for scanner.Scan() {
  24. list = append(list, scanner.Text())
  25. }
  26. return list
  27. }
  28. func formatTimes(timeStr string) string {
  29. var (
  30. re *regexp.Regexp
  31. err error
  32. times string
  33. )
  34. times = ""
  35. if re, err = regexp.Compile("[0-9]{4}-[0-9]{2}-[0-9]{2}T"); err == nil {
  36. times = re.ReplaceAllString(timeStr, "")
  37. if re, err = regexp.Compile("Z"); err == nil {
  38. times = re.ReplaceAllString(times, "")
  39. }
  40. }
  41. return times
  42. }
  43. func main() {
  44. var (
  45. lines []string
  46. path string
  47. prefix string
  48. stamp string
  49. i int
  50. re *regexp.Regexp
  51. err error
  52. current time.Time
  53. last time.Time
  54. diff time.Duration
  55. minDiffStr string
  56. minDiff time.Duration
  57. diffs map[string]time.Duration
  58. )
  59. flag.StringVar(&path, "f", "none", "File to parse")
  60. flag.StringVar(&prefix, "t", "", "Timestamp pattern in file (regex)")
  61. flag.StringVar(&minDiffStr, "min-duration", "1s", "Minimum duration to consider in output")
  62. flag.Parse()
  63. re, err = regexp.Compile(prefix)
  64. if err != nil {
  65. fmt.Printf("Cannot compile regex: %v\n", err.Error())
  66. os.Exit(1)
  67. }
  68. minDiff, err = time.ParseDuration(minDiffStr)
  69. if err != nil {
  70. fmt.Printf("No valid duration format: %v\n", err.Error())
  71. os.Exit(1)
  72. }
  73. diffs = make(map[string]time.Duration, 10)
  74. lines = readLinesFromFile(path)
  75. for i = 0; i < len(lines); i++ {
  76. if re.MatchString(lines[i]) {
  77. stamp = re.FindStringSubmatch(lines[i])[0]
  78. t, err := time.Parse(time.ANSIC, "Mon Jan 01 "+stamp+" 2104")
  79. if err != nil {
  80. fmt.Printf("%v\n", err.Error())
  81. } else {
  82. current = t
  83. diff = current.Sub(last)
  84. if diff >= minDiff {
  85. diffs[formatTimes(last.Format(time.RFC3339))+
  86. "-"+
  87. formatTimes(current.Format(time.RFC3339))] = diff
  88. }
  89. last = current
  90. }
  91. }
  92. }
  93. // print durations
  94. for times, diff := range diffs {
  95. fmt.Printf("%v\t\t(%v)\n", diff, times)
  96. }
  97. }