|
| 1 | +package parser |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "reflect" |
| 7 | + "regexp" |
| 8 | + |
| 9 | + "github.com/fatih/color" |
| 10 | +) |
| 11 | + |
| 12 | +type NodeLogging struct { |
| 13 | + Type string `json:"type"` |
| 14 | + Data any `json:"data"` |
| 15 | +} |
| 16 | + |
| 17 | +type Logger struct { |
| 18 | + enableLogging bool |
| 19 | +} |
| 20 | + |
| 21 | +func NewLogger(enableLogging bool) *Logger { |
| 22 | + return &Logger{enableLogging: enableLogging} |
| 23 | +} |
| 24 | + |
| 25 | +var ( |
| 26 | + colorizeKey = color.New(color.FgHiCyan).SprintFunc() |
| 27 | + colorizeString = color.New(color.FgHiYellow).SprintFunc() |
| 28 | + colorizeValue = color.New(color.FgHiMagenta).SprintFunc() |
| 29 | +) |
| 30 | + |
| 31 | +func colorizeJSON(s string) string { |
| 32 | + keyRe := regexp.MustCompile(`"([^"]+)"\s*:`) |
| 33 | + s = keyRe.ReplaceAllString(s, colorizeKey(`"$1"`)+":") |
| 34 | + |
| 35 | + // "string" |
| 36 | + strRe := regexp.MustCompile(`:\s*"([^"]*)"`) |
| 37 | + s = strRe.ReplaceAllString(s, ": "+colorizeString(`"$1"`)) |
| 38 | + |
| 39 | + // números, bool, null |
| 40 | + valRe := regexp.MustCompile(`:\s*(\d+|true|false|null)`) |
| 41 | + s = valRe.ReplaceAllString(s, ": "+colorizeValue(`$1`)) |
| 42 | + |
| 43 | + return s |
| 44 | +} |
| 45 | + |
| 46 | +func WrapNodeLogging(n Node) any { |
| 47 | + if n == nil { |
| 48 | + return nil |
| 49 | + } |
| 50 | + |
| 51 | + v := reflect.ValueOf(n) |
| 52 | + t := reflect.TypeOf(n) |
| 53 | + |
| 54 | + // unwrap ponteiro |
| 55 | + if t.Kind() == reflect.Pointer { |
| 56 | + t = t.Elem() |
| 57 | + v = v.Elem() |
| 58 | + } |
| 59 | + |
| 60 | + // percorre campos e reembrulha Nodes internos |
| 61 | + m := make(map[string]interface{}) |
| 62 | + for i := 0; i < t.NumField(); i++ { |
| 63 | + field := t.Field(i) |
| 64 | + value := v.Field(i).Interface() |
| 65 | + |
| 66 | + switch v := value.(type) { |
| 67 | + case Node: |
| 68 | + m[field.Tag.Get("json")] = WrapNodeLogging(v) |
| 69 | + |
| 70 | + case []Node: |
| 71 | + arr := make([]interface{}, 0, len(v)) |
| 72 | + for _, n := range v { |
| 73 | + arr = append(arr, WrapNodeLogging(n)) |
| 74 | + } |
| 75 | + m[field.Tag.Get("json")] = arr |
| 76 | + |
| 77 | + default: |
| 78 | + if tag := field.Tag.Get("json"); tag != "-" && tag != "" { |
| 79 | + m[tag] = value |
| 80 | + } |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + return NodeLogging{ |
| 85 | + Type: t.Name(), |
| 86 | + Data: m, |
| 87 | + } |
| 88 | +} |
| 89 | + |
| 90 | +func (l *Logger) JSON(m ModuleNode) (int, error) { |
| 91 | + if l.enableLogging { |
| 92 | + bs, err := json.MarshalIndent(WrapNodeLogging(m), "", " ") |
| 93 | + if err != nil { |
| 94 | + return 0, err |
| 95 | + } |
| 96 | + return fmt.Println(colorizeJSON(string(bs))) |
| 97 | + } |
| 98 | + return 0, nil |
| 99 | +} |
0 commit comments