| 1 | package copydesk |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "go/ast" |
| 8 | "go/parser" |
| 9 | "go/token" |
| 10 | "path" |
| 11 | "regexp" |
| 12 | "strconv" |
| 13 | "strings" |
| 14 | "unicode" |
| 15 | ) |
| 16 | |
| 17 | type Contract struct { |
| 18 | Reference []string `json:"reference,omitempty"` |
| 19 | Version int `json:"version"` |
| 20 | Paths []string `json:"paths"` |
| 21 | Bookkeeping []string `json:"bookkeeping"` |
| 22 | Extract []string `json:"extract"` |
| 23 | Apply []string `json:"apply"` |
| 24 | Accept []string `json:"accept"` |
| 25 | Regenerate []string `json:"regenerate"` |
| 26 | Classify []string `json:"classify"` |
| 27 | } |
| 28 | |
| 29 | func SafePath(p string) bool { |
| 30 | return p != "" && p != "." && path.Clean(p) == p && !strings.HasPrefix(p, "/") && p != ".." && !strings.HasPrefix(p, "../") && !strings.ContainsAny(p, "\\\x00\n\r") && !strings.HasPrefix(p, ".git/") && p != ".git" |
| 31 | } |
| 32 | func ParseContract(raw []byte) (Contract, error) { |
| 33 | var c Contract |
| 34 | d := json.NewDecoder(bytes.NewReader(raw)) |
| 35 | d.DisallowUnknownFields() |
| 36 | if len(raw) > 16384 || d.Decode(&c) != nil || c.Version != 1 || len(c.Paths) == 0 || len(c.Paths) > 40 { |
| 37 | return c, errors.New("copy: invalid contract") |
| 38 | } |
| 39 | for _, p := range append(append([]string{}, c.Paths...), c.Bookkeeping...) { |
| 40 | if !SafePath(p) { |
| 41 | return c, errors.New("copy: invalid output path") |
| 42 | } |
| 43 | } |
| 44 | commands := [][]string{c.Extract, c.Apply, c.Accept, c.Regenerate, c.Classify} |
| 45 | if len(c.Reference) > 0 { |
| 46 | commands = append(commands, c.Reference) |
| 47 | } |
| 48 | for _, a := range commands { |
| 49 | if len(a) < 2 || len(a) > 8 || a[0] != "python3" || !SafePath(a[1]) || !strings.HasSuffix(a[1], ".py") { |
| 50 | return c, errors.New("copy: invalid command") |
| 51 | } |
| 52 | for _, v := range a[2:] { |
| 53 | if !regexp.MustCompile(`^[a-z][a-z0-9_-]{0,40}$`).MatchString(v) { |
| 54 | return c, errors.New("copy: invalid command argument") |
| 55 | } |
| 56 | } |
| 57 | } |
| 58 | return c, nil |
| 59 | } |
| 60 | func Excluded(p string) bool { |
| 61 | for _, part := range strings.Split(p, "/") { |
| 62 | if part == "vendor" || part == "node_modules" || part == ".git" || part == "docs" || part == "testdata" || part == "generated" { |
| 63 | return true |
| 64 | } |
| 65 | } |
| 66 | return strings.HasSuffix(p, "_test.go") || strings.HasSuffix(p, ".test.js") || strings.HasSuffix(p, ".test.ts") || strings.HasSuffix(p, ".md") || strings.HasSuffix(p, ".sum") || strings.HasSuffix(p, ".mod") || strings.HasSuffix(p, ".sql") |
| 67 | } |
| 68 | func GenericSupported(name string) bool { |
| 69 | if Excluded(name) { |
| 70 | return false |
| 71 | } |
| 72 | switch path.Ext(name) { |
| 73 | case ".go", ".json", ".js", ".ts", ".jsx", ".tsx", ".html", ".tmpl": |
| 74 | return true |
| 75 | } |
| 76 | return false |
| 77 | } |
| 78 | func Generic(name string, before, after []byte) ([]Literal, error) { |
| 79 | if !GenericSupported(name) || bytes.Equal(before, after) { |
| 80 | return nil, nil |
| 81 | } |
| 82 | extract := func(raw []byte) ([]Literal, error) { |
| 83 | if len(raw) == 0 { |
| 84 | return nil, nil |
| 85 | } |
| 86 | if len(raw) > 1<<20 { |
| 87 | return nil, errors.New("copy: source too large") |
| 88 | } |
| 89 | var out []Literal |
| 90 | add := func(start, end int, text string) { |
| 91 | letter, space := false, false |
| 92 | for _, r := range text { |
| 93 | letter = letter || unicode.IsLetter(r) |
| 94 | space = space || unicode.IsSpace(r) |
| 95 | } |
| 96 | context := string(raw[max(0, start-80):start]) |
| 97 | display := regexp.MustCompile(`(?i)(title|label|placeholder|alt|aria-label|message|error|text)`).MatchString(context) |
| 98 | if letter && (space || display) { |
| 99 | out = append(out, Literal{Path: name, Start: start, End: end, Text: text, Context: context}) |
| 100 | } |
| 101 | } |
| 102 | switch path.Ext(name) { |
| 103 | case ".go": |
| 104 | fs := token.NewFileSet() |
| 105 | f, err := parser.ParseFile(fs, name, raw, parser.ParseComments) |
| 106 | if err != nil { |
| 107 | return nil, err |
| 108 | } |
| 109 | for _, g := range f.Comments { |
| 110 | if strings.Contains(g.Text(), "Code generated") { |
| 111 | return nil, nil |
| 112 | } |
| 113 | } |
| 114 | ast.Inspect(f, func(n ast.Node) bool { |
| 115 | if l, ok := n.(*ast.BasicLit); ok && l.Kind == token.STRING { |
| 116 | start := fs.Position(l.Pos()).Offset + 1 |
| 117 | end := fs.Position(l.End()).Offset - 1 |
| 118 | v, err := strconv.Unquote(l.Value) |
| 119 | if err == nil { |
| 120 | add(start, end, v) |
| 121 | } |
| 122 | } |
| 123 | return true |
| 124 | }) |
| 125 | case ".json": |
| 126 | if !json.Valid(raw) { |
| 127 | return nil, errors.New("copy: invalid JSON") |
| 128 | } |
| 129 | fallthrough |
| 130 | case ".js", ".ts", ".jsx", ".tsx", ".html", ".tmpl": |
| 131 | if regexp.MustCompile(`>[^<{}]*[\p{L}][^<{}]*<`).Match(raw) { |
| 132 | return nil, errors.New("copy: unquoted display text needs a contract") |
| 133 | } |
| 134 | // Comments are consumed before literals. Unterminated quotes remain unknown. |
| 135 | for i := 0; i < len(raw); { |
| 136 | if i+1 < len(raw) && raw[i] == '/' && raw[i+1] == '/' { |
| 137 | j := bytes.IndexByte(raw[i:], '\n') |
| 138 | if j < 0 { |
| 139 | break |
| 140 | } |
| 141 | i += j + 1 |
| 142 | continue |
| 143 | } |
| 144 | if i+1 < len(raw) && raw[i] == '/' && raw[i+1] == '*' { |
| 145 | j := bytes.Index(raw[i+2:], []byte("*/")) |
| 146 | if j < 0 { |
| 147 | return nil, errors.New("copy: unterminated comment") |
| 148 | } |
| 149 | i += j + 4 |
| 150 | continue |
| 151 | } |
| 152 | q := raw[i] |
| 153 | if q != '"' && q != '\'' && q != '`' { |
| 154 | i++ |
| 155 | continue |
| 156 | } |
| 157 | start := i + 1 |
| 158 | i++ |
| 159 | for i < len(raw) && raw[i] != q { |
| 160 | if raw[i] == '\\' { |
| 161 | i++ |
| 162 | } |
| 163 | i++ |
| 164 | } |
| 165 | if i >= len(raw) { |
| 166 | return nil, errors.New("copy: unterminated literal") |
| 167 | } |
| 168 | text := string(raw[start:i]) |
| 169 | if q == '`' && strings.Contains(text, "${") { |
| 170 | return nil, errors.New("copy: template expressions need a contract") |
| 171 | } |
| 172 | if strings.Contains(text, "\\") { |
| 173 | return nil, errors.New("copy: escaped generic literal needs contract") |
| 174 | } |
| 175 | add(start, i, text) |
| 176 | i++ |
| 177 | } |
| 178 | default: |
| 179 | return nil, errors.New("copy: unsupported changed source") |
| 180 | } |
| 181 | return out, nil |
| 182 | } |
| 183 | old, err := extract(before) |
| 184 | if err != nil { |
| 185 | return nil, err |
| 186 | } |
| 187 | next, err := extract(after) |
| 188 | if err != nil { |
| 189 | return nil, err |
| 190 | } |
| 191 | values := map[string]int{} |
| 192 | for _, s := range old { |
| 193 | values[s.Text]++ |
| 194 | } |
| 195 | var changed []Literal |
| 196 | for i, s := range next { |
| 197 | if values[s.Text] > 0 { |
| 198 | values[s.Text]-- |
| 199 | continue |
| 200 | } |
| 201 | s.Key = name + ":" + strconv.Itoa(s.Start) |
| 202 | if i < len(old) { |
| 203 | s.Old = old[i].Text |
| 204 | } |
| 205 | changed = append(changed, s) |
| 206 | } |
| 207 | return changed, nil |
| 208 | } |
| 209 | |