github.com/afking/bazel-gazelle@v0.0.0-20180301150245-c02bc0f529e8/internal/packages/fileinfo_proto.go (about)

     1  /* Copyright 2017 The Bazel Authors. All rights reserved.
     2  
     3  Licensed under the Apache License, Version 2.0 (the "License");
     4  you may not use this file except in compliance with the License.
     5  You may obtain a copy of the License at
     6  
     7     http://www.apache.org/licenses/LICENSE-2.0
     8  
     9  Unless required by applicable law or agreed to in writing, software
    10  distributed under the License is distributed on an "AS IS" BASIS,
    11  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  See the License for the specific language governing permissions and
    13  limitations under the License.
    14  */
    15  
    16  package packages
    17  
    18  import (
    19  	"bytes"
    20  	"io/ioutil"
    21  	"log"
    22  	"path"
    23  	"regexp"
    24  	"sort"
    25  	"strconv"
    26  	"strings"
    27  	"unicode"
    28  
    29  	"github.com/bazelbuild/bazel-gazelle/internal/config"
    30  )
    31  
    32  var protoRe = buildProtoRegexp()
    33  
    34  const (
    35  	importSubexpIndex    = 1
    36  	packageSubexpIndex   = 2
    37  	goPackageSubexpIndex = 3
    38  	serviceSubexpIndex   = 4
    39  )
    40  
    41  func protoFileInfo(c *config.Config, dir, rel, name string) fileInfo {
    42  	info := fileNameInfo(dir, rel, name)
    43  	content, err := ioutil.ReadFile(info.path)
    44  	if err != nil {
    45  		log.Printf("%s: error reading proto file: %v", info.path, err)
    46  		return info
    47  	}
    48  
    49  	for _, match := range protoRe.FindAllSubmatch(content, -1) {
    50  		switch {
    51  		case match[importSubexpIndex] != nil:
    52  			imp := unquoteProtoString(match[importSubexpIndex])
    53  			info.imports = append(info.imports, imp)
    54  
    55  		case match[packageSubexpIndex] != nil:
    56  			pkg := string(match[packageSubexpIndex])
    57  			if info.packageName == "" {
    58  				info.packageName = strings.Replace(pkg, ".", "_", -1)
    59  			}
    60  
    61  		case match[goPackageSubexpIndex] != nil:
    62  			gopkg := unquoteProtoString(match[goPackageSubexpIndex])
    63  			// If there's no / in the package option, then it's just a
    64  			// simple package name, not a full import path.
    65  			if strings.LastIndexByte(gopkg, '/') == -1 {
    66  				info.packageName = gopkg
    67  			} else {
    68  				if i := strings.LastIndexByte(gopkg, ';'); i != -1 {
    69  					info.importPath = gopkg[:i]
    70  					info.packageName = gopkg[i+1:]
    71  				} else {
    72  					info.importPath = gopkg
    73  					info.packageName = path.Base(gopkg)
    74  				}
    75  			}
    76  
    77  		case match[serviceSubexpIndex] != nil:
    78  			info.hasServices = true
    79  
    80  		default:
    81  			// Comment matched. Nothing to extract.
    82  		}
    83  	}
    84  	sort.Strings(info.imports)
    85  
    86  	if info.packageName == "" {
    87  		stem := strings.TrimSuffix(name, ".proto")
    88  		fs := strings.FieldsFunc(stem, func(r rune) bool {
    89  			return !(unicode.IsLetter(r) || unicode.IsNumber(r) || r == '_')
    90  		})
    91  		info.packageName = strings.Join(fs, "_")
    92  	}
    93  
    94  	return info
    95  }
    96  
    97  // Based on https://developers.google.com/protocol-buffers/docs/reference/proto3-spec
    98  func buildProtoRegexp() *regexp.Regexp {
    99  	hexEscape := `\\[xX][0-9a-fA-f]{2}`
   100  	octEscape := `\\[0-7]{3}`
   101  	charEscape := `\\[abfnrtv'"\\]`
   102  	charValue := strings.Join([]string{hexEscape, octEscape, charEscape, "[^\x00\\'\\\"\\\\]"}, "|")
   103  	strLit := `'(?:` + charValue + `|")*'|"(?:` + charValue + `|')*"`
   104  	ident := `[A-Za-z][A-Za-z0-9_]*`
   105  	fullIdent := ident + `(?:\.` + ident + `)*`
   106  	importStmt := `\bimport\s*(?:public|weak)?\s*(?P<import>` + strLit + `)\s*;`
   107  	packageStmt := `\bpackage\s*(?P<package>` + fullIdent + `)\s*;`
   108  	goPackageStmt := `\boption\s*go_package\s*=\s*(?P<go_package>` + strLit + `)\s*;`
   109  	serviceStmt := `(?P<service>service)`
   110  	comment := `//[^\n]*`
   111  	protoReSrc := strings.Join([]string{importStmt, packageStmt, goPackageStmt, serviceStmt, comment}, "|")
   112  	return regexp.MustCompile(protoReSrc)
   113  }
   114  
   115  func unquoteProtoString(q []byte) string {
   116  	// Adjust quotes so that Unquote is happy. We need a double quoted string
   117  	// without unescaped double quote characters inside.
   118  	noQuotes := bytes.Split(q[1:len(q)-1], []byte{'"'})
   119  	if len(noQuotes) != 1 {
   120  		for i := 0; i < len(noQuotes)-1; i++ {
   121  			if len(noQuotes[i]) == 0 || noQuotes[i][len(noQuotes[i])-1] != '\\' {
   122  				noQuotes[i] = append(noQuotes[i], '\\')
   123  			}
   124  		}
   125  		q = append([]byte{'"'}, bytes.Join(noQuotes, []byte{'"'})...)
   126  		q = append(q, '"')
   127  	}
   128  	if q[0] == '\'' {
   129  		q[0] = '"'
   130  		q[len(q)-1] = '"'
   131  	}
   132  
   133  	s, err := strconv.Unquote(string(q))
   134  	if err != nil {
   135  		log.Panicf("unquoting string literal %s from proto: %v", q, err)
   136  	}
   137  	return s
   138  }