| 1 | /* |
| 2 | Copyright The containerd Authors. |
| 3 | |
| 4 | Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | you may not use this file except in compliance with the License. |
| 6 | You may obtain a copy of the License at |
| 7 | |
| 8 | http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | |
| 10 | Unless required by applicable law or agreed to in writing, software |
| 11 | distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | See the License for the specific language governing permissions and |
| 14 | limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | package main |
| 18 | |
| 19 | import ( |
| 20 | "go/ast" |
| 21 | "regexp" |
| 22 | "strings" |
| 23 | |
| 24 | "golang.org/x/tools/go/ast/astutil" |
| 25 | ) |
| 26 | |
| 27 | func compilePattern(c config) (*regexp.Regexp, error) { |
| 28 | return regexp.Compile(strings.Join(c.acronyms, "|")) |
| 29 | } |
| 30 | |
| 31 | func rewriteNode(pattern *regexp.Regexp, node ast.Node) { |
| 32 | astutil.Apply( |
| 33 | node, |
| 34 | func(c *astutil.Cursor) bool { |
| 35 | node := c.Node() |
| 36 | ident, ok := node.(*ast.Ident) |
| 37 | if !ok { |
| 38 | return true |
| 39 | } |
| 40 | |
| 41 | matches := pattern.FindAllStringSubmatchIndex(ident.Name, -1) |
| 42 | if matches == nil { |
| 43 | return true |
| 44 | } |
| 45 | |
| 46 | var ( |
| 47 | result string |
| 48 | copied int |
| 49 | ) |
| 50 | for _, match := range matches { |
| 51 | // If there are submatches, ignore the first element and only process the submatches. |
| 52 | if len(match) > 2 { |
| 53 | match = match[2:] |
| 54 | } |
| 55 | |
| 56 | for i := 0; i < len(match); i += 2 { |
| 57 | if match[i] == -1 { |
| 58 | continue |
| 59 | } |
| 60 | result += ident.Name[copied:match[i]] |
| 61 | result += strings.ToUpper(ident.Name[match[i]:match[i+1]]) |
| 62 | copied = match[i+1] |
| 63 | } |
| 64 | } |
| 65 | // Copy the rest. |
| 66 | result += ident.Name[copied:len(ident.Name)] |
| 67 | ident.Name = result |
| 68 | return false |
| 69 | }, |
| 70 | nil, |
| 71 | ) |
| 72 | } |