1package cmdtest
2
3import (
4 "regexp"
5 "strings"
6)
7
8const ExpId = "\x07id\x07"
9const ExpHumanId = "\x07human-id\x07"
10const ExpTimestamp = "\x07timestamp\x07"
11const ExpISO8601 = "\x07iso8601\x07"
12
13const ExpOrgModeDate = "\x07org-mode-date\x07"
14
15// MakeExpectedRegex transform a raw string of an expected output into a regex suitable for testing.
16// Some markers like ExpId are available to substitute the appropriate regex for element that can vary randomly.
17func MakeExpectedRegex(input string) string {
18 var substitutes = map[string]string{
19 ExpId: `[0-9a-f]{64}`,
20 ExpHumanId: `[0-9a-f]{7}`,
21 ExpTimestamp: `[0-9]{7,10}`,
22 ExpISO8601: `\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?`,
23 ExpOrgModeDate: `\d\d\d\d-\d\d-\d\d [[:alpha:]]{3} \d\d:\d\d`,
24 }
25
26 escaped := []rune(regexp.QuoteMeta(input))
27
28 var result strings.Builder
29 var inSubstitute bool
30 var substitute strings.Builder
31
32 result.WriteString("^")
33
34 for i := 0; i < len(escaped); i++ {
35 r := escaped[i]
36 if !inSubstitute && r == '\x07' {
37 substitute.Reset()
38 substitute.WriteRune(r)
39 inSubstitute = true
40 continue
41 }
42 if inSubstitute && r == '\x07' {
43 substitute.WriteRune(r)
44 sub, ok := substitutes[substitute.String()]
45 if !ok {
46 panic("unknown substitute: " + substitute.String())
47 }
48 result.WriteString(sub)
49 inSubstitute = false
50 continue
51 }
52 if inSubstitute {
53 substitute.WriteRune(r)
54 } else {
55 result.WriteRune(r)
56 }
57 }
58
59 result.WriteString("$")
60
61 return result.String()
62}