From 87aab4e9225c943906c6a5cd5b52e15b8e5b6734 Mon Sep 17 00:00:00 2001 From: Dirk Brand Date: Thu, 19 Dec 2013 15:50:38 +0200 Subject: [PATCH] Added project source --- CodeFormatter.sublime-settings | 12 + ProtoBufCodeFormatter.py | 152 ++ .../descriptor/FormattedString.go | 892 +++++++++++ .../descriptor/descriptor.pb.go | 1427 +++++++++++++++++ .../descriptor/descriptor.proto | 622 +++++++ .../descriptor/gostring.go | 202 +++ .../descriptor/helper.go | 274 ++++ .../descriptor/wrapperTypes.go | 370 +++++ src/ProtoBufCodeFormatter/main.go | 33 + src/ProtoBufCodeFormatter/parser/parse.go | 71 + 10 files changed, 4055 insertions(+) create mode 100644 CodeFormatter.sublime-settings create mode 100644 ProtoBufCodeFormatter.py create mode 100644 src/ProtoBufCodeFormatter/descriptor/FormattedString.go create mode 100644 src/ProtoBufCodeFormatter/descriptor/descriptor.pb.go create mode 100644 src/ProtoBufCodeFormatter/descriptor/descriptor.proto create mode 100644 src/ProtoBufCodeFormatter/descriptor/gostring.go create mode 100644 src/ProtoBufCodeFormatter/descriptor/helper.go create mode 100644 src/ProtoBufCodeFormatter/descriptor/wrapperTypes.go create mode 100644 src/ProtoBufCodeFormatter/main.go create mode 100644 src/ProtoBufCodeFormatter/parser/parse.go diff --git a/CodeFormatter.sublime-settings b/CodeFormatter.sublime-settings new file mode 100644 index 0000000..5473c94 --- /dev/null +++ b/CodeFormatter.sublime-settings @@ -0,0 +1,12 @@ +{ + "enabled": true, + + // Set the path to where the go binary is installed (Comma separated list of paths) + // All paths are checked, a Error will be displayed if the binary is not found + // e.g "GOBIN": ["/usr/go/bin/"] + // or "GOBIN": ["C:/Go/bin/"] + "GOBIN": ["C:/GoWorkspace/bin", "~/bin", "~/GoWorkspace/bin", "/usr/local/go/bin", "/usr/local/opt/go/bin,", "/usr/local/bin", "/usr/bin"], + + // Set path to where protocol buffer files may reside (Comma seperated list of paths) + "PROTOPATH": ["/home/dirk-mint/ProtocolBuffers", "/home/dirk-mint/GoWorkspace/src/github.com/DirkBrand/protobuf-code-formatter/protoc-gen-pretty/"] +} diff --git a/ProtoBufCodeFormatter.py b/ProtoBufCodeFormatter.py new file mode 100644 index 0000000..7cc40bb --- /dev/null +++ b/ProtoBufCodeFormatter.py @@ -0,0 +1,152 @@ +import sublime +import sublime_plugin +import subprocess +import os +import re +from sys import platform as _platform +import functools + +PLUGIN_NAME = "ProtoBufCodeFormatter" + + +def Proto(name): + return bool(re.search('.proto$', name)) + + +class AutoformatOnSave(sublime_plugin.EventListener): + + def on_post_save(self, view): + + # if is_enabled_in_view(view) and + # get_setting_for_active_view('autoformat_on_save', default=False) + + print os.path.basename(view.file_name()) + if Proto(view.file_name()): + if sublime.load_settings("CodeFormatter.sublime-settings").get('enabled', True): + if view.file_name(): + self.process(view) + + sublime.set_timeout( + functools.partial(view.run_command, 'revert'), 50) + regions = view.sel() + view.show(regions[0].begin(), True) + + def process(self, view): + self.view = view + self.startupinfo = None + plugPath = sublime.packages_path() + # Get gopath and format for stdin + self.getenv() + self.gobin = self._env.get('GOBIN', '') + self.protopath = self._env.get('PROTOPATH', '') + + # Check OS and build the executable path + if _platform == "win32": + # Startup info stuff, to block cmd window flash + self.startupinfo = subprocess.STARTUPINFO() + self.startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW + # Windows + processPath = os.path.join( + plugPath, "ProtoBufCodeFormatter", "bin", "ProtoBufCodeFormatter.exe") + else: + # linux and OS X + processPath = os.path.join( + plugPath, "ProtoBufCodeFormatter", "bin", "ProtoBufCodeFormatter") + + buildpath = os.path.join( + plugPath, "ProtoBufCodeFormatter", "src", "ProtoBufCodeFormatter") + + # Check exe build + if not os.path.isfile(processPath): + sublime.status_message('Installing CodeFormatter dependencies...') + try: + os.makedirs(processPath) + except: + pass + gocmd = os.path.join(self.gobin, 'go') + + subprocess.call([gocmd, 'build', '-o', processPath], + cwd=buildpath, + startupinfo=self.startupinfo) + + # Open subprocess + fileDir = os.path.dirname(view.file_name()) + self.protopath = os.pathsep.join( + [self.protopath, fileDir, os.path.dirname(fileDir)]) + + print self.protopath + + self.p = subprocess.Popen( + [processPath, view.file_name(), self.protopath], + startupinfo=self.startupinfo, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + stdin=subprocess.PIPE) + + issues = self.p.communicate()[0] + log_file = open('error.log', 'a') + log_file.write("\n") + log_file.write(issues) + log_file.write("\n") + log_file.close() + + print view.file_name(), "was formatted" + + def getenv(self): + binflag = False + s = sublime.load_settings("CodeFormatter.sublime-settings") + _env = {} + vars = [ + 'GOPATH', + 'GOROOT', + ] + + cmdl = [] + for k in vars: + cmdl.append('[[[$' + k + ']]' + k + '[[%' + k + '%]]]') + cmd_str = ' '.join(cmdl) + p = subprocess.Popen(['echo', cmd_str], + startupinfo=self.startupinfo, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + stdin=subprocess.PIPE, + shell=True) + out, err = p.communicate() + if err: + print "Popen Error:" + err + + mats = re.findall( + r'\[\[\[(.*?)\]\](%s)\[\[(.*?)\]\]\]' % '|'.join(vars), out) + for m in mats: + a, k, b = m + v = '' + if a != '$' + k: + v = a + elif b != '%' + k + '%': + v = b + + if v: + _env[k] = v + + if s.get('GOPATH'): + _env['GOPATH'] = os.pathsep.join(s.get('GOPATH')) + else: + print "GOPATH could not be set" + + if s.get('GOBIN'): + bpath = s.get('GOBIN') + for b in bpath: + if os.path.exists(b): + _env['GOBIN'] = os.path.normcase(b) + binflag = True + break + if not binflag: + print "CodeFormatter: GOBIN could not be set!" + sublime.status_message("CodeFormatter: GOBIN could not be set!") + + if s.get('PROTOPATH'): + _env['PROTOPATH'] = os.pathsep.join(s.get('PROTOPATH')) + else: + print "CodeFormatter: PROTOPATH could not be set!" + + self._env = _env diff --git a/src/ProtoBufCodeFormatter/descriptor/FormattedString.go b/src/ProtoBufCodeFormatter/descriptor/FormattedString.go new file mode 100644 index 0000000..a9348af --- /dev/null +++ b/src/ProtoBufCodeFormatter/descriptor/FormattedString.go @@ -0,0 +1,892 @@ +/* + +Copyright (c) 2013, Dirk Brand +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted +provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of + conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, this list of + conditions and the following disclaimer in the documentation and/or other materials provided + with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED +WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS +BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, +OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +*/ + +package descriptor + +import ( + "bytes" + proto "code.google.com/p/gogoprotobuf/proto" + "encoding/binary" + fmt "fmt" + sort "sort" + strings "strings" +) + +const ( + INDENT = " " +) + +var importsList []string +var allFiles []*FileDescriptor + +var commentsMap map[string]*SourceCodeInfo_Location + +// Handles the set of Files (but for provided filename only) +func (this *FileDescriptorSet) Fmt(fileToFormat string) string { + // Loop through all the FileDescriptorProto + allFiles = make([]*FileDescriptor, len(this.File)) + WrapTypes(this) + for _, tmpFile := range allFiles { + if tmpFile.GetName() == fileToFormat { + return tmpFile.Fmt(0) + } + } + return "" +} + +// Handles entire file +func (this *FileDescriptor) Fmt(depth int) string { + if this == nil { + return "nil" + } + currentFile = *this + + var s []string + + counter := 0 + + // SourceCodeInfo + // Generates a map of comments to paths to use in the construction of the program + //source := this.GetSourceCodeInfo() + //fmt.Println(len(source.GetLocation())) + //commentsMap = source.ExtractComments() + + // the package + if len(this.GetPackage()) > 0 { + s = append(s, LeadingComments(fmt.Sprintf("%d", packagePath), depth)) + s = append(s, `package `) + s = append(s, this.GetPackage()) + s = append(s, ";\n") + s = append(s, TrailingComments(fmt.Sprintf("%d", packagePath), depth)) + + counter += 1 + } + + // For each import + if len(this.GetDependency()) > 0 && counter > 0 { + s = append(s, "\n") + } + if len(this.GetDependency()) > 0 { + importsList = make([]string, len(this.GetDependency())) + i := 0 + + sort.Strings(this.GetDependency()) + for ind, imp := range this.GetDependency() { + importsList[i] = strings.Split(imp, "/")[len(strings.Split(imp, "/"))-1] + i += 1 + + s = append(s, LeadingComments(fmt.Sprintf("%d,%d", importPath, ind), depth)) + s = append(s, `import "`) + s = append(s, imp) + s = append(s, `";`) + s = append(s, "\n") + s = append(s, TrailingComments(fmt.Sprintf("%d,%d", importPath, ind), depth)) + } + + counter += 1 + } + + // For each extend + extendGroups := make(map[string]string) + for i, ext := range this.ext { + extendGroups[ext.GetExtendee()] = extendGroups[ext.GetExtendee()] + LeadingComments(fmt.Sprintf("%d,%d", extendPath, i), depth+1) + ext.Fmt(depth+1) + ";\n" + TrailingComments(fmt.Sprintf("%d,%d", extendPath, i), depth+1) + + } + if len(extendGroups) > 0 && counter > 0 { + s = append(s, "\n") + } + ind := 0 + for i := range extendGroups { + group := extendGroups[i] + if ind == 0 { + s = append(s, LeadingComments(fmt.Sprintf("%d", extendPath), depth)) + } else { + s = append(s, "\n") + s = append(s, LeadingComments(fmt.Sprintf("%d,%d", extendPath, ind*1000), depth)) + } + s = append(s, getIndentation(depth)) + s = append(s, `extend `) + s = append(s, strings.Replace(i, ".", "", 1)) + s = append(s, " {\n") + s = append(s, group) + s = append(s, getIndentation(depth)) + s = append(s, "}\n") + + if ind == 0 { + s = append(s, TrailingComments(fmt.Sprintf("%d", extendPath), depth)) + } else { + s = append(s, TrailingComments(fmt.Sprintf("%d,%d", extendPath, ind*1000), depth)) + } + + ind += 1 + counter += 1 + } + + // File Options + options := this.GetOptions() + if options != nil && len(options.ExtensionMap()) > 0 { + s = append(s, "\n") + theOption := getFormattedOptionsFromExtensionMap(options.ExtensionMap(), -1, false, fmt.Sprintf("%d", optionsPath)) + s = append(s, theOption) + + counter += 1 + } + + // Enums + if len(this.enum) > 0 && counter > 0 { + s = append(s, "\n") + } + for _, enum := range this.enum { + s = append(s, enum.Fmt(depth)) + s = append(s, "\n") + + counter += 1 + } + + // Messages + if len(this.desc) > 0 && counter > 0 { + s = append(s, "\n") + } + for _, message := range this.desc { + if message.parent == nil { + s = append(s, message.Fmt(depth, false, nil)) + s = append(s, "\n") + + counter += 1 + } + } + + // Services + if len(this.serv) > 0 && counter > 0 { + s = append(s, "\n") + } + for _, service := range this.serv { + s = append(s, service.Fmt(depth)) + s = append(s, "\n") + + counter += 1 + } + + return strings.Join(s, "") +} + +// Handles Messages +func (this *Descriptor) Fmt(depth int, isGroup bool, groupField *FieldDescriptorProto) string { + if this == nil { + return "nil" + } + var s []string + contentCount := 0 + + // For groups logic + nestedMessages := this.nested + + // Message Header + s = append(s, LeadingComments(this.path, depth)) + + if isGroup { + s = append(s, getIndentation(depth)) + s = append(s, fieldDescriptorProtoLabel_StringValue(*groupField.Label)) + s = append(s, ` group `) + s = append(s, this.GetName()) + s = append(s, " = ") + s = append(s, fmt.Sprintf("%v", *groupField.Number)) + s = append(s, ` {`) + } else { + s = append(s, getIndentation(depth)) + s = append(s, `message `) + s = append(s, this.GetName()) + s = append(s, ` {`) + } + tc := TrailingComments(this.path, depth+1) + if len(tc) > 0 { + s = append(s, "\n") + s = append(s, tc) + } + + // Extension Range + if len(this.GetExtensionRange()) > 0 { + s = append(s, "\n") + contentCount += 1 + } + for extensionIndex, ext := range this.GetExtensionRange() { + if extensionIndex == 0 { + s = append(s, LeadingComments(fmt.Sprintf("%s,%d", this.path, messageExtensionRangePath), depth+1)) + } else { + s = append(s, "\n") + s = append(s, LeadingComments(fmt.Sprintf("%s,%d,%d", this.path, messageExtensionRangePath, extensionIndex*1000), depth+1)) + } + s = append(s, ext.Fmt(depth+1)) + + if extensionIndex == 0 { + s = append(s, TrailingComments(fmt.Sprintf("%s,%d", this.path, messageExtensionRangePath), depth+1)) + } else { + s = append(s, "\n") + s = append(s, TrailingComments(fmt.Sprintf("%s,%d,%d", this.path, messageExtensionRangePath, extensionIndex*1000), depth+1)) + } + } + + // For each extend + if len(this.ext) > 0 { + s = append(s, "\n") + contentCount += 1 + } + extendGroups := make(map[string]string) + for index, ext := range this.ext { + if depth == 0 { + extendGroups[ext.GetExtendee()] = extendGroups[ext.GetExtendee()] + LeadingComments(fmt.Sprintf("%s,%d,%d", this.path, messageExtensionPath, index), depth+2) + getIndentation(depth+1) + ext.Fmt(depth+1) + ";\n" + TrailingComments(fmt.Sprintf("%s,%d,%d", this.path, messageExtensionPath, index), depth+2) + } else { + extendGroups[ext.GetExtendee()] = extendGroups[ext.GetExtendee()] + LeadingComments(fmt.Sprintf("%s,%d,%d", this.path, messageExtensionPath, index), depth+2) + ext.Fmt(depth+1) + ";\n" + TrailingComments(fmt.Sprintf("%s,%d,%d", this.path, messageExtensionPath, index), depth+2) + } + + } + index := 0 + for i := range extendGroups { + group := extendGroups[i] + if index == 0 { + s = append(s, LeadingComments(fmt.Sprintf("%s,%d", this.path, messageExtensionPath), depth+1)) + } else { + s = append(s, "\n") + s = append(s, LeadingComments(fmt.Sprintf("%s,%d,%d", this.path, messageExtensionPath, index*1000), depth+1)) + } + s = append(s, getIndentation(depth+1)) + s = append(s, `extend `) + s = append(s, getLastWordFromPath(i, ".")) + s = append(s, " {\n") + if index == 0 { + tc := TrailingComments(fmt.Sprintf("%s,%d", this.path, messageExtensionPath), depth+1) + if len(tc) > 0 { + s = append(s, getIndentation(depth+1)) + s = append(s, tc) + s = append(s, "\n") + } + } else { + tc := TrailingComments(fmt.Sprintf("%s,%d,%d", this.path, messageExtensionPath, index*1000), depth+1) + if len(tc) > 0 { + s = append(s, getIndentation(depth+1)) + s = append(s, tc) + s = append(s, "\n") + } + } + + s = append(s, group) + s = append(s, getIndentation(depth+1)) + s = append(s, "}\n") + + index += 1 + } + + // Options + mesOptions := this.GetOptions() + if mesOptions != nil && len(mesOptions.ExtensionMap()) > 0 { + s = append(s, "\n") + contentCount += 1 + + s = append(s, getFormattedOptionsFromExtensionMap(mesOptions.ExtensionMap(), depth, false, fmt.Sprintf("%d,%d", this.path, messageOptionsPath))) + } + + // Fields + if len(this.field) > 0 { + s = append(s, "\n") + contentCount += 1 + } + for i, field := range this.field { + + if field.GetType() == FieldDescriptorProto_TYPE_GROUP { + for i := 0; i < len(nestedMessages); i += 1 { + nestedMes := nestedMessages[i] + // Found group + if strings.ToLower(nestedMes.GetName()) == field.GetName() { + s = append(s, "\n") + tempStr := nestedMes.Fmt(depth+1, true, field.FieldDescriptorProto) + s = append(s, tempStr) + nestedMessages = append(nestedMessages[:i], nestedMessages[i+1:]...) + } + } + } else { + s = append(s, LeadingComments(fmt.Sprintf("%s,%d,%d", this.path, messageFieldPath, i), depth+1)) + s = append(s, field.Fmt(depth+1)) + s = append(s, ";\n") + s = append(s, TrailingComments(fmt.Sprintf("%s,%d,%d", this.path, messageFieldPath, i), depth+1)) + } + } + + // Enums + if len(this.GetEnumType()) > 0 { + s = append(s, "\n") + contentCount += 1 + } + for _, enum := range this.enum { + s = append(s, enum.Fmt(depth+1)) + } + + // Nested Messages + if len(nestedMessages) > 0 { + s = append(s, "\n") + contentCount += 1 + } + for _, nestedMessage := range nestedMessages { + s = append(s, nestedMessage.Fmt(depth+1, false, nil)) + } + + if contentCount > 0 { + s = append(s, getIndentation(depth)) + } + s = append(s, "}\n") + + return strings.Join(s, "") +} + +// Handles Fields +func (this *FieldDescriptor) Fmt(depth int) string { + if this == nil { + return "nil" + } + var s []string + + //s = append(s, LeadingComments(this.path)) + s = append(s, getIndentation(depth)) + s = append(s, fieldDescriptorProtoLabel_StringValue(*this.Label)) + s = append(s, ` `) + // If referencing a message + if *this.Type == FieldDescriptorProto_TYPE_MESSAGE || *this.Type == FieldDescriptorProto_TYPE_ENUM { + var found bool + typeName := getLastWordFromPath(this.GetTypeName(), ".") + for _, mes := range currentFile.GetMessageType() { + if mes.GetName() == typeName { + found = true + } + } + if found { + s = append(s, typeName) + } else { + typeName = this.GetTypeName() + if strings.HasPrefix(typeName, ".") { + typeName = typeName[1:] + } + s = append(s, typeName) + } + + } else { + s = append(s, fieldDescriptorProtoType_StringValue(*this.Type)) + } + s = append(s, ` `) + s = append(s, this.GetName()) + s = append(s, ` = `) + s = append(s, fmt.Sprintf("%v", this.GetNumber())) + + // OPTIONS + options := this.GetOptions() + i := 0 + if options != nil { + if options.GetPacked() || options.GetLazy() || options.GetDeprecated() || len(this.GetDefaultValue()) > 0 || len(options.ExtensionMap()) > 0 { + s = append(s, ` [`) + + if len(options.ExtensionMap()) > 0 { + s = append(s, getFormattedOptionsFromExtensionMap(options.ExtensionMap(), -1, true, "")) + i += 1 + } + + if len(this.GetDefaultValue()) > 0 { + if i >= 1 { + s = append(s, ", ") + } + s = append(s, `default = `) + s = append(s, this.GetDefaultValue()) + } + + if options.GetPacked() { + if i >= 1 { + s = append(s, ", ") + } + s = append(s, `packed = true`) + } + + if options.GetLazy() { + if i >= 1 { + s = append(s, ", ") + } + s = append(s, `lazy = true`) + } + + if options.GetDeprecated() { + if i >= 1 { + s = append(s, ", ") + } + s = append(s, `deprecated = true`) + } + + s = append(s, `]`) + } + } + return strings.Join(s, "") +} + +// Handles Enums +func (this *EnumDescriptor) Fmt(depth int) string { + if this == nil { + return "nil" + } + var s []string + + // Comments of the enum + s = append(s, LeadingComments(this.path, depth)) + + s = append(s, getIndentation(depth)) + s = append(s, `enum `) + s = append(s, this.GetName()) + s = append(s, ` {`) + + tc := TrailingComments(this.path, depth+1) + if len(tc) > 0 { + s = append(s, "\n") + s = append(s, tc) + } + + // Options + options := this.GetOptions() + if options != nil && len(options.ExtensionMap()) > 0 { + s = append(s, "\n") + + s = append(s, getFormattedOptionsFromExtensionMap(options.ExtensionMap(), depth, false, fmt.Sprintf("%d,%d", this.path, enumOptionsPath))) + } + + if len(this.GetValue()) > 0 { + s = append(s, "\n") + } + for i, enumValue := range this.GetValue() { + + // Comments of the enum fields + s = append(s, LeadingComments(fmt.Sprintf("%s,%d,%d", this.path, enumValuePath, i), depth+1)) + + s = append(s, getIndentation(depth+1)) + s = append(s, enumValue.GetName()) + s = append(s, ` = `) + s = append(s, fmt.Sprintf("%v", enumValue.GetNumber())) + + // OPTIONS + valueOptions := enumValue.GetOptions() + if valueOptions != nil { + s = append(s, ` [`) + s = append(s, getFormattedOptionsFromExtensionMap(valueOptions.ExtensionMap(), -1, true, fmt.Sprintf("%d,%d", this.path, enumValueOptionsPath))) + s = append(s, `]`) + } + + s = append(s, ";\n") + + s = append(s, TrailingComments(fmt.Sprintf("%s,%d,%d", this.path, enumValuePath, i), depth+1)) + } + + s = append(s, getIndentation(depth)) + s = append(s, "}\n") + + return strings.Join(s, "") +} + +// Handles Extension Ranges +func (this *DescriptorProto_ExtensionRange) Fmt(depth int) string { + if this == nil { + return "nil" + } + var s []string + s = append(s, getIndentation(depth)) + s = append(s, `extensions `) + s = append(s, fmt.Sprintf("%v", this.GetStart())) + s = append(s, ` to `) + if this.GetEnd() >= 1<<29-1 { + s = append(s, "max;\n") + } else { + s = append(s, fmt.Sprintf("%v", this.GetEnd()-1)) + s = append(s, ";\n") + } + + return strings.Join(s, "") +} + +// Handles Services +func (this *ServiceDescriptor) Fmt(depth int) string { + if this == nil { + return "nil" + } + var s []string + + s = append(s, LeadingComments(this.path, depth)) + s = append(s, getIndentation(depth)) + s = append(s, `service `) + s = append(s, this.GetName()) + s = append(s, ` {`) + s = append(s, "\n") + + tc := TrailingComments(this.path, depth+1) + if len(tc) > 0 { + s = append(s, tc) + s = append(s, "\n") + } + + // Service Options + options := this.GetOptions() + if options != nil { + s = append(s, getFormattedOptionsFromExtensionMap(options.ExtensionMap(), depth, false, fmt.Sprintf("%s,%d", this.path, serviceOptionsPath))) + } + + // Methods + if len(this.GetMethod()) > 0 { + s = append(s, "\n") + } + for i, method := range this.GetMethod() { + s = append(s, LeadingComments(fmt.Sprintf("%s,%d,%d", this.path, methodDescriptorPath, i), depth+1)) + s = append(s, getIndentation(depth+1)) + s = append(s, `rpc `) + s = append(s, method.GetName()) + s = append(s, `(`) + if len(method.GetInputType()) > 0 { + s = append(s, getLastWordFromPath(method.GetInputType(), ".")) + } + s = append(s, `)`) + if len(method.GetOutputType()) > 0 { + s = append(s, ` returns(`) + s = append(s, getLastWordFromPath(method.GetOutputType(), ".")) + s = append(s, `)`) + } + s = append(s, " {\n") + tc := TrailingComments(fmt.Sprintf("%s,%d,%d", this.path, methodDescriptorPath, i), depth+2) + if len(tc) > 0 { + s = append(s, tc) + s = append(s, "\n") + } + + methodOptions := method.GetOptions() + s = append(s, getFormattedOptionsFromExtensionMap(methodOptions.ExtensionMap(), depth+1, false, fmt.Sprintf("%s,%d,%d,%d", this.path, methodDescriptorPath, i, methodOptionsPath))) + + s = append(s, getIndentation(depth+1)) + s = append(s, "}\n") + + } + s = append(s, getIndentation(depth)) + s = append(s, "}") + + return strings.Join(s, "") +} + +func getFormattedOptionsFromExtensionMap(extensionMap map[int32]proto.Extension, depth int, fieldOption bool, pathIncludingParent string) string { + var s []string + counter := 0 + if len(extensionMap) > 0 { + commentsIndex := 0 + for optInd := range extensionMap { + // Loop through all imported files + for _, curFile := range allFiles { + extensions := curFile.GetExtension() + + // Loop through extensions in the FileDescriptorProto + for _, ext := range extensions { + if ext.GetNumber() == optInd { + bytes, _ := proto.GetRawExtension(extensionMap, optInd) + key, n := proto.DecodeVarint(bytes) + + wt := key & 0x7 + + var val string + + // Enums are special + if ext.GetType() == FieldDescriptorProto_TYPE_ENUM { + // Loop through enums to find right one + for _, myEnum := range curFile.GetEnumType() { + if myEnum.GetName() == getLastWordFromPath(ext.GetTypeName(), ".") { + for _, enumVal := range myEnum.GetValue() { + d, _ := proto.DecodeVarint(bytes[n:]) + + if uint64(enumVal.GetNumber()) == d { + val = enumVal.GetName() + } + } + } + } + + s = append(s, LeadingComments(fmt.Sprintf("%s,%d,%d", pathIncludingParent, 999, commentsIndex), depth+1)) + + if !fieldOption { + s = append(s, getIndentation(depth+1)) + s = append(s, `option (`) + } else { + if counter >= 1 { + s = append(s, ", ") + } + s = append(s, `(`) + } + + if curFile.GetName() != currentFile.GetName() && len(curFile.GetPackage()) > 0 { + s = append(s, curFile.GetPackage()) + s = append(s, ".") + } + s = append(s, ext.GetName()) + s = append(s, ") = ") + s = append(s, val) + + if !fieldOption { + s = append(s, ";\n") + } + comm := TrailingComments(fmt.Sprintf("%s,%d,%d", pathIncludingParent, 999, commentsIndex), depth+1) + if len(comm) > 0 { + s = append(s, comm) + if counter < len(extensionMap)-1 { + s = append(s, "\n") + } + } + + commentsIndex += 1 + counter += 1 + + } else if wt == 2 && ext.GetType() != FieldDescriptorProto_TYPE_STRING { // Messages are special (for method options) + payload, m := proto.DecodeVarint(bytes[n:]) + n += m + //fmt.Printf("payload: %v\n", payload) + for ind := uint64(0); ind < payload-1; ind += 1 { + firstInt, a := proto.DecodeVarint(bytes[n:]) + n += a + wiretype := firstInt & 0x7 + var packType FieldDescriptorProto_Type + switch wiretype { + case 0: + packType = FieldDescriptorProto_TYPE_INT32 + + case 1: + packType = FieldDescriptorProto_TYPE_FIXED64 + + case 2: + packType = FieldDescriptorProto_TYPE_STRING + + case 5: + packType = FieldDescriptorProto_TYPE_FIXED32 + } + + packVal, b := byteToValueString(bytes, n, packType) + n += b + //fmt.Printf("%v\n", packVal) + + if ext.GetType() == FieldDescriptorProto_TYPE_MESSAGE { + tagNum := firstInt >> 3 + //fmt.Printf("tagnum: %v\n", tagNum) + + // Loop through messages to find right one + myMessage := curFile.GetMessage(getLastWordFromPath(ext.GetTypeName(), ".")) + //fmt.Println(myMessage.GetName()) + for _, field := range myMessage.GetField() { + if uint64(field.GetNumber()) == tagNum { + val = `.` + field.GetName() + " = " + packVal + } + } + } + + s = append(s, LeadingComments(fmt.Sprintf("%s,%d,%d", pathIncludingParent, 999, commentsIndex), depth+1)) + + if !fieldOption { + s = append(s, getIndentation(depth+1)) + s = append(s, `option (`) + } else { + if counter >= 1 { + s = append(s, ", ") + } + s = append(s, `(`) + } + + if curFile.GetName() != currentFile.GetName() && len(curFile.GetPackage()) > 0 { + s = append(s, curFile.GetPackage()) + s = append(s, ".") + } + s = append(s, ext.GetName()) + s = append(s, ")") + s = append(s, val) + if !fieldOption { + s = append(s, ";\n") + } + comm := TrailingComments(fmt.Sprintf("%s,%d,%d", pathIncludingParent, 999, commentsIndex), depth+1) + if len(comm) > 0 { + s = append(s, comm) + if counter < len(extensionMap) { + s = append(s, "\n") + } + } + commentsIndex += 1 + counter += 1 + + } + + } else { + val, _ = byteToValueString(bytes, n, ext.GetType()) + + s = append(s, LeadingComments(fmt.Sprintf("%s,%d,%d", pathIncludingParent, 999, commentsIndex), depth+1)) + + if !fieldOption { + s = append(s, getIndentation(depth+1)) + s = append(s, `option (`) + } else { + if counter >= 1 { + s = append(s, ", ") + } + s = append(s, `(`) + } + + if curFile.GetName() != currentFile.GetName() && len(curFile.GetPackage()) > 0 { + s = append(s, curFile.GetPackage()) + s = append(s, ".") + } + s = append(s, ext.GetName()) + s = append(s, ") = ") + s = append(s, val) + + if !fieldOption { + s = append(s, ";\n") + } + comm := TrailingComments(fmt.Sprintf("%s,%d,%d", pathIncludingParent, 999, commentsIndex), depth+1) + if len(comm) > 0 { + s = append(s, comm) + if counter < len(extensionMap) { + s = append(s, "\n") + } + } + commentsIndex += 1 + counter += 1 + } + + } + } + } + } + } + + return strings.Join(s, "") +} + +// Determines depth of indentation +func getIndentation(depth int) string { + s := "" + for i := 0; i < depth; i++ { + s += INDENT + } + return s +} + +// returns the string representation of a field label +func fieldDescriptorProtoLabel_StringValue(label FieldDescriptorProto_Label) string { + switch label { + case FieldDescriptorProto_LABEL_OPTIONAL: + return "optional" + case FieldDescriptorProto_LABEL_REQUIRED: + return "required" + case FieldDescriptorProto_LABEL_REPEATED: + return "repeated" + } + + return "nil" +} + +// returns the string representation of a field type +func fieldDescriptorProtoType_StringValue(fieldType FieldDescriptorProto_Type) string { + switch fieldType { + case FieldDescriptorProto_TYPE_DOUBLE: + return "double" + case FieldDescriptorProto_TYPE_FLOAT: + return "float" + case FieldDescriptorProto_TYPE_INT64: + return "int64" + case FieldDescriptorProto_TYPE_UINT64: + return "uint64" + case FieldDescriptorProto_TYPE_INT32: + return "int32" + case FieldDescriptorProto_TYPE_FIXED64: + return "fixed64" + case FieldDescriptorProto_TYPE_FIXED32: + return "fixed32" + case FieldDescriptorProto_TYPE_BOOL: + return "bool" + case FieldDescriptorProto_TYPE_STRING: + return "string" + case FieldDescriptorProto_TYPE_GROUP: + return "group" + case FieldDescriptorProto_TYPE_MESSAGE: + return "message" + case FieldDescriptorProto_TYPE_BYTES: + return "bytes" + case FieldDescriptorProto_TYPE_UINT32: + return "uint32" + case FieldDescriptorProto_TYPE_ENUM: + return "enum" + case FieldDescriptorProto_TYPE_SFIXED32: + return "sfixed32" + case FieldDescriptorProto_TYPE_SFIXED64: + return "sfixed64" + case FieldDescriptorProto_TYPE_SINT32: + return "sint32" + case FieldDescriptorProto_TYPE_SINT64: + return "sint64" + } + + return "nil" +} + +func byteToValueString(b []byte, lastReadIndex int, t FieldDescriptorProto_Type) (string, int) { + var val string + // All the types of options + switch t { + case FieldDescriptorProto_TYPE_BOOL: + d, _ := proto.DecodeVarint(b[lastReadIndex:]) + if int(d) == 1 { + val = "true" + } else { + val = "false" + } + lastReadIndex += 1 + + case FieldDescriptorProto_TYPE_UINT32, FieldDescriptorProto_TYPE_INT32, FieldDescriptorProto_TYPE_UINT64, FieldDescriptorProto_TYPE_INT64: + d, _ := proto.DecodeVarint(b[lastReadIndex:]) + lastReadIndex += 1 + val = fmt.Sprintf("%v", d) + + case FieldDescriptorProto_TYPE_FLOAT, FieldDescriptorProto_TYPE_SFIXED32, FieldDescriptorProto_TYPE_FIXED32: + var f float32 + binary.Read(bytes.NewBuffer(b[lastReadIndex:]), binary.LittleEndian, &f) + lastReadIndex += 1 + val = fmt.Sprintf("%v", f) + + case FieldDescriptorProto_TYPE_DOUBLE, FieldDescriptorProto_TYPE_SFIXED64, FieldDescriptorProto_TYPE_FIXED64: + var f float64 + binary.Read(bytes.NewBuffer(b[lastReadIndex:]), binary.LittleEndian, &f) + lastReadIndex += 1 + val = fmt.Sprintf("%v", f) + + case FieldDescriptorProto_TYPE_STRING: + _, n := proto.DecodeVarint(b[lastReadIndex:]) + lastReadIndex += n + val = `"` + string(b[lastReadIndex:]) + `"` + + } + + return val, lastReadIndex +} + +func getLastWordFromPath(s string, d string) string { + return strings.Split(s, d)[len(strings.Split(s, d))-1] +} diff --git a/src/ProtoBufCodeFormatter/descriptor/descriptor.pb.go b/src/ProtoBufCodeFormatter/descriptor/descriptor.pb.go new file mode 100644 index 0000000..88ad9ac --- /dev/null +++ b/src/ProtoBufCodeFormatter/descriptor/descriptor.pb.go @@ -0,0 +1,1427 @@ +// Code generated by protoc-gen-gogo. +// source: descriptor.proto +// DO NOT EDIT! + +package descriptor + +import proto "code.google.com/p/gogoprotobuf/proto" +import json "encoding/json" +import math "math" + +// Reference proto, json, and math imports to suppress error if they are not otherwise used. +var _ = proto.Marshal +var _ = &json.SyntaxError{} +var _ = math.Inf + +type FieldDescriptorProto_Type int32 + +const ( + // 0 is reserved for errors. + // Order is weird for historical reasons. + FieldDescriptorProto_TYPE_DOUBLE FieldDescriptorProto_Type = 1 + FieldDescriptorProto_TYPE_FLOAT FieldDescriptorProto_Type = 2 + // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if + // negative values are likely. + FieldDescriptorProto_TYPE_INT64 FieldDescriptorProto_Type = 3 + FieldDescriptorProto_TYPE_UINT64 FieldDescriptorProto_Type = 4 + // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if + // negative values are likely. + FieldDescriptorProto_TYPE_INT32 FieldDescriptorProto_Type = 5 + FieldDescriptorProto_TYPE_FIXED64 FieldDescriptorProto_Type = 6 + FieldDescriptorProto_TYPE_FIXED32 FieldDescriptorProto_Type = 7 + FieldDescriptorProto_TYPE_BOOL FieldDescriptorProto_Type = 8 + FieldDescriptorProto_TYPE_STRING FieldDescriptorProto_Type = 9 + FieldDescriptorProto_TYPE_GROUP FieldDescriptorProto_Type = 10 + FieldDescriptorProto_TYPE_MESSAGE FieldDescriptorProto_Type = 11 + // New in version 2. + FieldDescriptorProto_TYPE_BYTES FieldDescriptorProto_Type = 12 + FieldDescriptorProto_TYPE_UINT32 FieldDescriptorProto_Type = 13 + FieldDescriptorProto_TYPE_ENUM FieldDescriptorProto_Type = 14 + FieldDescriptorProto_TYPE_SFIXED32 FieldDescriptorProto_Type = 15 + FieldDescriptorProto_TYPE_SFIXED64 FieldDescriptorProto_Type = 16 + FieldDescriptorProto_TYPE_SINT32 FieldDescriptorProto_Type = 17 + FieldDescriptorProto_TYPE_SINT64 FieldDescriptorProto_Type = 18 +) + +var FieldDescriptorProto_Type_name = map[int32]string{ + 1: "TYPE_DOUBLE", + 2: "TYPE_FLOAT", + 3: "TYPE_INT64", + 4: "TYPE_UINT64", + 5: "TYPE_INT32", + 6: "TYPE_FIXED64", + 7: "TYPE_FIXED32", + 8: "TYPE_BOOL", + 9: "TYPE_STRING", + 10: "TYPE_GROUP", + 11: "TYPE_MESSAGE", + 12: "TYPE_BYTES", + 13: "TYPE_UINT32", + 14: "TYPE_ENUM", + 15: "TYPE_SFIXED32", + 16: "TYPE_SFIXED64", + 17: "TYPE_SINT32", + 18: "TYPE_SINT64", +} +var FieldDescriptorProto_Type_value = map[string]int32{ + "TYPE_DOUBLE": 1, + "TYPE_FLOAT": 2, + "TYPE_INT64": 3, + "TYPE_UINT64": 4, + "TYPE_INT32": 5, + "TYPE_FIXED64": 6, + "TYPE_FIXED32": 7, + "TYPE_BOOL": 8, + "TYPE_STRING": 9, + "TYPE_GROUP": 10, + "TYPE_MESSAGE": 11, + "TYPE_BYTES": 12, + "TYPE_UINT32": 13, + "TYPE_ENUM": 14, + "TYPE_SFIXED32": 15, + "TYPE_SFIXED64": 16, + "TYPE_SINT32": 17, + "TYPE_SINT64": 18, +} + +func (x FieldDescriptorProto_Type) Enum() *FieldDescriptorProto_Type { + p := new(FieldDescriptorProto_Type) + *p = x + return p +} +func (x FieldDescriptorProto_Type) String() string { + return proto.EnumName(FieldDescriptorProto_Type_name, int32(x)) +} +func (x *FieldDescriptorProto_Type) UnmarshalJSON(data []byte) error { + value, err := proto.UnmarshalJSONEnum(FieldDescriptorProto_Type_value, data, "FieldDescriptorProto_Type") + if err != nil { + return err + } + *x = FieldDescriptorProto_Type(value) + return nil +} + +type FieldDescriptorProto_Label int32 + +const ( + // 0 is reserved for errors + FieldDescriptorProto_LABEL_OPTIONAL FieldDescriptorProto_Label = 1 + FieldDescriptorProto_LABEL_REQUIRED FieldDescriptorProto_Label = 2 + FieldDescriptorProto_LABEL_REPEATED FieldDescriptorProto_Label = 3 +) + +var FieldDescriptorProto_Label_name = map[int32]string{ + 1: "LABEL_OPTIONAL", + 2: "LABEL_REQUIRED", + 3: "LABEL_REPEATED", +} +var FieldDescriptorProto_Label_value = map[string]int32{ + "LABEL_OPTIONAL": 1, + "LABEL_REQUIRED": 2, + "LABEL_REPEATED": 3, +} + +func (x FieldDescriptorProto_Label) Enum() *FieldDescriptorProto_Label { + p := new(FieldDescriptorProto_Label) + *p = x + return p +} +func (x FieldDescriptorProto_Label) String() string { + return proto.EnumName(FieldDescriptorProto_Label_name, int32(x)) +} +func (x *FieldDescriptorProto_Label) UnmarshalJSON(data []byte) error { + value, err := proto.UnmarshalJSONEnum(FieldDescriptorProto_Label_value, data, "FieldDescriptorProto_Label") + if err != nil { + return err + } + *x = FieldDescriptorProto_Label(value) + return nil +} + +// Generated classes can be optimized for speed or code size. +type FileOptions_OptimizeMode int32 + +const ( + FileOptions_SPEED FileOptions_OptimizeMode = 1 + // etc. + FileOptions_CODE_SIZE FileOptions_OptimizeMode = 2 + FileOptions_LITE_RUNTIME FileOptions_OptimizeMode = 3 +) + +var FileOptions_OptimizeMode_name = map[int32]string{ + 1: "SPEED", + 2: "CODE_SIZE", + 3: "LITE_RUNTIME", +} +var FileOptions_OptimizeMode_value = map[string]int32{ + "SPEED": 1, + "CODE_SIZE": 2, + "LITE_RUNTIME": 3, +} + +func (x FileOptions_OptimizeMode) Enum() *FileOptions_OptimizeMode { + p := new(FileOptions_OptimizeMode) + *p = x + return p +} +func (x FileOptions_OptimizeMode) String() string { + return proto.EnumName(FileOptions_OptimizeMode_name, int32(x)) +} +func (x *FileOptions_OptimizeMode) UnmarshalJSON(data []byte) error { + value, err := proto.UnmarshalJSONEnum(FileOptions_OptimizeMode_value, data, "FileOptions_OptimizeMode") + if err != nil { + return err + } + *x = FileOptions_OptimizeMode(value) + return nil +} + +type FieldOptions_CType int32 + +const ( + // Default mode. + FieldOptions_STRING FieldOptions_CType = 0 + FieldOptions_CORD FieldOptions_CType = 1 + FieldOptions_STRING_PIECE FieldOptions_CType = 2 +) + +var FieldOptions_CType_name = map[int32]string{ + 0: "STRING", + 1: "CORD", + 2: "STRING_PIECE", +} +var FieldOptions_CType_value = map[string]int32{ + "STRING": 0, + "CORD": 1, + "STRING_PIECE": 2, +} + +func (x FieldOptions_CType) Enum() *FieldOptions_CType { + p := new(FieldOptions_CType) + *p = x + return p +} +func (x FieldOptions_CType) String() string { + return proto.EnumName(FieldOptions_CType_name, int32(x)) +} +func (x *FieldOptions_CType) UnmarshalJSON(data []byte) error { + value, err := proto.UnmarshalJSONEnum(FieldOptions_CType_value, data, "FieldOptions_CType") + if err != nil { + return err + } + *x = FieldOptions_CType(value) + return nil +} + +// The protocol compiler can output a FileDescriptorSet containing the .proto +// files it parses. +type FileDescriptorSet struct { + File []*FileDescriptorProto `protobuf:"bytes,1,rep,name=file" json:"file,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *FileDescriptorSet) Reset() { *m = FileDescriptorSet{} } +func (m *FileDescriptorSet) String() string { return proto.CompactTextString(m) } +func (*FileDescriptorSet) ProtoMessage() {} + +func (m *FileDescriptorSet) GetFile() []*FileDescriptorProto { + if m != nil { + return m.File + } + return nil +} + +// Describes a complete .proto file. +type FileDescriptorProto struct { + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + Package *string `protobuf:"bytes,2,opt,name=package" json:"package,omitempty"` + // Names of files imported by this file. + Dependency []string `protobuf:"bytes,3,rep,name=dependency" json:"dependency,omitempty"` + // Indexes of the public imported files in the dependency list above. + PublicDependency []int32 `protobuf:"varint,10,rep,name=public_dependency" json:"public_dependency,omitempty"` + // Indexes of the weak imported files in the dependency list. + // For Google-internal migration only. Do not use. + WeakDependency []int32 `protobuf:"varint,11,rep,name=weak_dependency" json:"weak_dependency,omitempty"` + // All top-level definitions in this file. + MessageType []*DescriptorProto `protobuf:"bytes,4,rep,name=message_type" json:"message_type,omitempty"` + EnumType []*EnumDescriptorProto `protobuf:"bytes,5,rep,name=enum_type" json:"enum_type,omitempty"` + Service []*ServiceDescriptorProto `protobuf:"bytes,6,rep,name=service" json:"service,omitempty"` + Extension []*FieldDescriptorProto `protobuf:"bytes,7,rep,name=extension" json:"extension,omitempty"` + Options *FileOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"` + // This field contains optional information about the original source code. + // You may safely remove this entire field whithout harming runtime + // functionality of the descriptors -- the information is needed only by + // development tools. + SourceCodeInfo *SourceCodeInfo `protobuf:"bytes,9,opt,name=source_code_info" json:"source_code_info,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *FileDescriptorProto) Reset() { *m = FileDescriptorProto{} } +func (m *FileDescriptorProto) String() string { return proto.CompactTextString(m) } +func (*FileDescriptorProto) ProtoMessage() {} + +func (m *FileDescriptorProto) GetName() string { + if m != nil && m.Name != nil { + return *m.Name + } + return "" +} + +func (m *FileDescriptorProto) GetPackage() string { + if m != nil && m.Package != nil { + return *m.Package + } + return "" +} + +func (m *FileDescriptorProto) GetDependency() []string { + if m != nil { + return m.Dependency + } + return nil +} + +func (m *FileDescriptorProto) GetPublicDependency() []int32 { + if m != nil { + return m.PublicDependency + } + return nil +} + +func (m *FileDescriptorProto) GetWeakDependency() []int32 { + if m != nil { + return m.WeakDependency + } + return nil +} + +func (m *FileDescriptorProto) GetMessageType() []*DescriptorProto { + if m != nil { + return m.MessageType + } + return nil +} + +func (m *FileDescriptorProto) GetEnumType() []*EnumDescriptorProto { + if m != nil { + return m.EnumType + } + return nil +} + +func (m *FileDescriptorProto) GetService() []*ServiceDescriptorProto { + if m != nil { + return m.Service + } + return nil +} + +func (m *FileDescriptorProto) GetExtension() []*FieldDescriptorProto { + if m != nil { + return m.Extension + } + return nil +} + +func (m *FileDescriptorProto) GetOptions() *FileOptions { + if m != nil { + return m.Options + } + return nil +} + +func (m *FileDescriptorProto) GetSourceCodeInfo() *SourceCodeInfo { + if m != nil { + return m.SourceCodeInfo + } + return nil +} + +// Describes a message type. +type DescriptorProto struct { + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + Field []*FieldDescriptorProto `protobuf:"bytes,2,rep,name=field" json:"field,omitempty"` + Extension []*FieldDescriptorProto `protobuf:"bytes,6,rep,name=extension" json:"extension,omitempty"` + NestedType []*DescriptorProto `protobuf:"bytes,3,rep,name=nested_type" json:"nested_type,omitempty"` + EnumType []*EnumDescriptorProto `protobuf:"bytes,4,rep,name=enum_type" json:"enum_type,omitempty"` + ExtensionRange []*DescriptorProto_ExtensionRange `protobuf:"bytes,5,rep,name=extension_range" json:"extension_range,omitempty"` + Options *MessageOptions `protobuf:"bytes,7,opt,name=options" json:"options,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *DescriptorProto) Reset() { *m = DescriptorProto{} } +func (m *DescriptorProto) String() string { return proto.CompactTextString(m) } +func (*DescriptorProto) ProtoMessage() {} + +func (m *DescriptorProto) GetName() string { + if m != nil && m.Name != nil { + return *m.Name + } + return "" +} + +func (m *DescriptorProto) GetField() []*FieldDescriptorProto { + if m != nil { + return m.Field + } + return nil +} + +func (m *DescriptorProto) GetExtension() []*FieldDescriptorProto { + if m != nil { + return m.Extension + } + return nil +} + +func (m *DescriptorProto) GetNestedType() []*DescriptorProto { + if m != nil { + return m.NestedType + } + return nil +} + +func (m *DescriptorProto) GetEnumType() []*EnumDescriptorProto { + if m != nil { + return m.EnumType + } + return nil +} + +func (m *DescriptorProto) GetExtensionRange() []*DescriptorProto_ExtensionRange { + if m != nil { + return m.ExtensionRange + } + return nil +} + +func (m *DescriptorProto) GetOptions() *MessageOptions { + if m != nil { + return m.Options + } + return nil +} + +type DescriptorProto_ExtensionRange struct { + Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"` + End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *DescriptorProto_ExtensionRange) Reset() { *m = DescriptorProto_ExtensionRange{} } +func (m *DescriptorProto_ExtensionRange) String() string { return proto.CompactTextString(m) } +func (*DescriptorProto_ExtensionRange) ProtoMessage() {} + +func (m *DescriptorProto_ExtensionRange) GetStart() int32 { + if m != nil && m.Start != nil { + return *m.Start + } + return 0 +} + +func (m *DescriptorProto_ExtensionRange) GetEnd() int32 { + if m != nil && m.End != nil { + return *m.End + } + return 0 +} + +// Describes a field within a message. +type FieldDescriptorProto struct { + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + Number *int32 `protobuf:"varint,3,opt,name=number" json:"number,omitempty"` + Label *FieldDescriptorProto_Label `protobuf:"varint,4,opt,name=label,enum=google.protobuf.FieldDescriptorProto_Label" json:"label,omitempty"` + // If type_name is set, this need not be set. If both this and type_name + // are set, this must be either TYPE_ENUM or TYPE_MESSAGE. + Type *FieldDescriptorProto_Type `protobuf:"varint,5,opt,name=type,enum=google.protobuf.FieldDescriptorProto_Type" json:"type,omitempty"` + // For message and enum types, this is the name of the type. If the name + // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping + // rules are used to find the type (i.e. first the nested types within this + // message are searched, then within the parent, on up to the root + // namespace). + TypeName *string `protobuf:"bytes,6,opt,name=type_name" json:"type_name,omitempty"` + // For extensions, this is the name of the type being extended. It is + // resolved in the same manner as type_name. + Extendee *string `protobuf:"bytes,2,opt,name=extendee" json:"extendee,omitempty"` + // For numeric types, contains the original text representation of the value. + // For booleans, "true" or "false". + // For strings, contains the default text contents (not escaped in any way). + // For bytes, contains the C escaped value. All bytes >= 128 are escaped. + // TODO(kenton): Base-64 encode? + DefaultValue *string `protobuf:"bytes,7,opt,name=default_value" json:"default_value,omitempty"` + Options *FieldOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *FieldDescriptorProto) Reset() { *m = FieldDescriptorProto{} } +func (m *FieldDescriptorProto) String() string { return proto.CompactTextString(m) } +func (*FieldDescriptorProto) ProtoMessage() {} + +func (m *FieldDescriptorProto) GetName() string { + if m != nil && m.Name != nil { + return *m.Name + } + return "" +} + +func (m *FieldDescriptorProto) GetNumber() int32 { + if m != nil && m.Number != nil { + return *m.Number + } + return 0 +} + +func (m *FieldDescriptorProto) GetLabel() FieldDescriptorProto_Label { + if m != nil && m.Label != nil { + return *m.Label + } + return FieldDescriptorProto_LABEL_OPTIONAL +} + +func (m *FieldDescriptorProto) GetType() FieldDescriptorProto_Type { + if m != nil && m.Type != nil { + return *m.Type + } + return FieldDescriptorProto_TYPE_DOUBLE +} + +func (m *FieldDescriptorProto) GetTypeName() string { + if m != nil && m.TypeName != nil { + return *m.TypeName + } + return "" +} + +func (m *FieldDescriptorProto) GetExtendee() string { + if m != nil && m.Extendee != nil { + return *m.Extendee + } + return "" +} + +func (m *FieldDescriptorProto) GetDefaultValue() string { + if m != nil && m.DefaultValue != nil { + return *m.DefaultValue + } + return "" +} + +func (m *FieldDescriptorProto) GetOptions() *FieldOptions { + if m != nil { + return m.Options + } + return nil +} + +// Describes an enum type. +type EnumDescriptorProto struct { + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + Value []*EnumValueDescriptorProto `protobuf:"bytes,2,rep,name=value" json:"value,omitempty"` + Options *EnumOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *EnumDescriptorProto) Reset() { *m = EnumDescriptorProto{} } +func (m *EnumDescriptorProto) String() string { return proto.CompactTextString(m) } +func (*EnumDescriptorProto) ProtoMessage() {} + +func (m *EnumDescriptorProto) GetName() string { + if m != nil && m.Name != nil { + return *m.Name + } + return "" +} + +func (m *EnumDescriptorProto) GetValue() []*EnumValueDescriptorProto { + if m != nil { + return m.Value + } + return nil +} + +func (m *EnumDescriptorProto) GetOptions() *EnumOptions { + if m != nil { + return m.Options + } + return nil +} + +// Describes a value within an enum. +type EnumValueDescriptorProto struct { + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + Number *int32 `protobuf:"varint,2,opt,name=number" json:"number,omitempty"` + Options *EnumValueOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *EnumValueDescriptorProto) Reset() { *m = EnumValueDescriptorProto{} } +func (m *EnumValueDescriptorProto) String() string { return proto.CompactTextString(m) } +func (*EnumValueDescriptorProto) ProtoMessage() {} + +func (m *EnumValueDescriptorProto) GetName() string { + if m != nil && m.Name != nil { + return *m.Name + } + return "" +} + +func (m *EnumValueDescriptorProto) GetNumber() int32 { + if m != nil && m.Number != nil { + return *m.Number + } + return 0 +} + +func (m *EnumValueDescriptorProto) GetOptions() *EnumValueOptions { + if m != nil { + return m.Options + } + return nil +} + +// Describes a service. +type ServiceDescriptorProto struct { + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + Method []*MethodDescriptorProto `protobuf:"bytes,2,rep,name=method" json:"method,omitempty"` + Options *ServiceOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *ServiceDescriptorProto) Reset() { *m = ServiceDescriptorProto{} } +func (m *ServiceDescriptorProto) String() string { return proto.CompactTextString(m) } +func (*ServiceDescriptorProto) ProtoMessage() {} + +func (m *ServiceDescriptorProto) GetName() string { + if m != nil && m.Name != nil { + return *m.Name + } + return "" +} + +func (m *ServiceDescriptorProto) GetMethod() []*MethodDescriptorProto { + if m != nil { + return m.Method + } + return nil +} + +func (m *ServiceDescriptorProto) GetOptions() *ServiceOptions { + if m != nil { + return m.Options + } + return nil +} + +// Describes a method of a service. +type MethodDescriptorProto struct { + Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"` + // Input and output type names. These are resolved in the same way as + // FieldDescriptorProto.type_name, but must refer to a message type. + InputType *string `protobuf:"bytes,2,opt,name=input_type" json:"input_type,omitempty"` + OutputType *string `protobuf:"bytes,3,opt,name=output_type" json:"output_type,omitempty"` + Options *MethodOptions `protobuf:"bytes,4,opt,name=options" json:"options,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *MethodDescriptorProto) Reset() { *m = MethodDescriptorProto{} } +func (m *MethodDescriptorProto) String() string { return proto.CompactTextString(m) } +func (*MethodDescriptorProto) ProtoMessage() {} + +func (m *MethodDescriptorProto) GetName() string { + if m != nil && m.Name != nil { + return *m.Name + } + return "" +} + +func (m *MethodDescriptorProto) GetInputType() string { + if m != nil && m.InputType != nil { + return *m.InputType + } + return "" +} + +func (m *MethodDescriptorProto) GetOutputType() string { + if m != nil && m.OutputType != nil { + return *m.OutputType + } + return "" +} + +func (m *MethodDescriptorProto) GetOptions() *MethodOptions { + if m != nil { + return m.Options + } + return nil +} + +type FileOptions struct { + // Sets the Java package where classes generated from this .proto will be + // placed. By default, the proto package is used, but this is often + // inappropriate because proto packages do not normally start with backwards + // domain names. + JavaPackage *string `protobuf:"bytes,1,opt,name=java_package" json:"java_package,omitempty"` + // If set, all the classes from the .proto file are wrapped in a single + // outer class with the given name. This applies to both Proto1 + // (equivalent to the old "--one_java_file" option) and Proto2 (where + // a .proto always translates to a single class, but you may want to + // explicitly choose the class name). + JavaOuterClassname *string `protobuf:"bytes,8,opt,name=java_outer_classname" json:"java_outer_classname,omitempty"` + // If set true, then the Java code generator will generate a separate .java + // file for each top-level message, enum, and service defined in the .proto + // file. Thus, these types will *not* be nested inside the outer class + // named by java_outer_classname. However, the outer class will still be + // generated to contain the file's getDescriptor() method as well as any + // top-level extensions defined in the file. + JavaMultipleFiles *bool `protobuf:"varint,10,opt,name=java_multiple_files,def=0" json:"java_multiple_files,omitempty"` + // If set true, then the Java code generator will generate equals() and + // hashCode() methods for all messages defined in the .proto file. This is + // purely a speed optimization, as the AbstractMessage base class includes + // reflection-based implementations of these methods. + JavaGenerateEqualsAndHash *bool `protobuf:"varint,20,opt,name=java_generate_equals_and_hash,def=0" json:"java_generate_equals_and_hash,omitempty"` + OptimizeFor *FileOptions_OptimizeMode `protobuf:"varint,9,opt,name=optimize_for,enum=google.protobuf.FileOptions_OptimizeMode,def=1" json:"optimize_for,omitempty"` + // Sets the Go package where structs generated from this .proto will be + // placed. There is no default. + GoPackage *string `protobuf:"bytes,11,opt,name=go_package" json:"go_package,omitempty"` + // Should generic services be generated in each language? "Generic" services + // are not specific to any particular RPC system. They are generated by the + // main code generators in each language (without additional plugins). + // Generic services were the only kind of service generation supported by + // early versions of proto2. + // + // Generic services are now considered deprecated in favor of using plugins + // that generate code specific to your particular RPC system. Therefore, + // these default to false. Old code which depends on generic services should + // explicitly set them to true. + CcGenericServices *bool `protobuf:"varint,16,opt,name=cc_generic_services,def=0" json:"cc_generic_services,omitempty"` + JavaGenericServices *bool `protobuf:"varint,17,opt,name=java_generic_services,def=0" json:"java_generic_services,omitempty"` + PyGenericServices *bool `protobuf:"varint,18,opt,name=py_generic_services,def=0" json:"py_generic_services,omitempty"` + // The parser stores options it doesn't recognize here. See above. + UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option" json:"uninterpreted_option,omitempty"` + XXX_extensions map[int32]proto.Extension `json:"-"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *FileOptions) Reset() { *m = FileOptions{} } +func (m *FileOptions) String() string { return proto.CompactTextString(m) } +func (*FileOptions) ProtoMessage() {} + +var extRange_FileOptions = []proto.ExtensionRange{ + {1000, 536870911}, +} + +func (*FileOptions) ExtensionRangeArray() []proto.ExtensionRange { + return extRange_FileOptions +} +func (m *FileOptions) ExtensionMap() map[int32]proto.Extension { + if m.XXX_extensions == nil { + m.XXX_extensions = make(map[int32]proto.Extension) + } + return m.XXX_extensions +} + +const Default_FileOptions_JavaMultipleFiles bool = false +const Default_FileOptions_JavaGenerateEqualsAndHash bool = false +const Default_FileOptions_OptimizeFor FileOptions_OptimizeMode = FileOptions_SPEED +const Default_FileOptions_CcGenericServices bool = false +const Default_FileOptions_JavaGenericServices bool = false +const Default_FileOptions_PyGenericServices bool = false + +func (m *FileOptions) GetJavaPackage() string { + if m != nil && m.JavaPackage != nil { + return *m.JavaPackage + } + return "" +} + +func (m *FileOptions) GetJavaOuterClassname() string { + if m != nil && m.JavaOuterClassname != nil { + return *m.JavaOuterClassname + } + return "" +} + +func (m *FileOptions) GetJavaMultipleFiles() bool { + if m != nil && m.JavaMultipleFiles != nil { + return *m.JavaMultipleFiles + } + return Default_FileOptions_JavaMultipleFiles +} + +func (m *FileOptions) GetJavaGenerateEqualsAndHash() bool { + if m != nil && m.JavaGenerateEqualsAndHash != nil { + return *m.JavaGenerateEqualsAndHash + } + return Default_FileOptions_JavaGenerateEqualsAndHash +} + +func (m *FileOptions) GetOptimizeFor() FileOptions_OptimizeMode { + if m != nil && m.OptimizeFor != nil { + return *m.OptimizeFor + } + return Default_FileOptions_OptimizeFor +} + +func (m *FileOptions) GetGoPackage() string { + if m != nil && m.GoPackage != nil { + return *m.GoPackage + } + return "" +} + +func (m *FileOptions) GetCcGenericServices() bool { + if m != nil && m.CcGenericServices != nil { + return *m.CcGenericServices + } + return Default_FileOptions_CcGenericServices +} + +func (m *FileOptions) GetJavaGenericServices() bool { + if m != nil && m.JavaGenericServices != nil { + return *m.JavaGenericServices + } + return Default_FileOptions_JavaGenericServices +} + +func (m *FileOptions) GetPyGenericServices() bool { + if m != nil && m.PyGenericServices != nil { + return *m.PyGenericServices + } + return Default_FileOptions_PyGenericServices +} + +func (m *FileOptions) GetUninterpretedOption() []*UninterpretedOption { + if m != nil { + return m.UninterpretedOption + } + return nil +} + +type MessageOptions struct { + // Set true to use the old proto1 MessageSet wire format for extensions. + // This is provided for backwards-compatibility with the MessageSet wire + // format. You should not use this for any other reason: It's less + // efficient, has fewer features, and is more complicated. + // + // The message must be defined exactly as follows: + // message Foo { + // option message_set_wire_format = true; + // extensions 4 to max; + // } + // Note that the message cannot have any defined fields; MessageSets only + // have extensions. + // + // All extensions of your type must be singular messages; e.g. they cannot + // be int32s, enums, or repeated messages. + // + // Because this is an option, the above two restrictions are not enforced by + // the protocol compiler. + MessageSetWireFormat *bool `protobuf:"varint,1,opt,name=message_set_wire_format,def=0" json:"message_set_wire_format,omitempty"` + // Disables the generation of the standard "descriptor()" accessor, which can + // conflict with a field of the same name. This is meant to make migration + // from proto1 easier; new code should avoid fields named "descriptor". + NoStandardDescriptorAccessor *bool `protobuf:"varint,2,opt,name=no_standard_descriptor_accessor,def=0" json:"no_standard_descriptor_accessor,omitempty"` + // The parser stores options it doesn't recognize here. See above. + UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option" json:"uninterpreted_option,omitempty"` + XXX_extensions map[int32]proto.Extension `json:"-"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *MessageOptions) Reset() { *m = MessageOptions{} } +func (m *MessageOptions) String() string { return proto.CompactTextString(m) } +func (*MessageOptions) ProtoMessage() {} + +var extRange_MessageOptions = []proto.ExtensionRange{ + {1000, 536870911}, +} + +func (*MessageOptions) ExtensionRangeArray() []proto.ExtensionRange { + return extRange_MessageOptions +} +func (m *MessageOptions) ExtensionMap() map[int32]proto.Extension { + if m.XXX_extensions == nil { + m.XXX_extensions = make(map[int32]proto.Extension) + } + return m.XXX_extensions +} + +const Default_MessageOptions_MessageSetWireFormat bool = false +const Default_MessageOptions_NoStandardDescriptorAccessor bool = false + +func (m *MessageOptions) GetMessageSetWireFormat() bool { + if m != nil && m.MessageSetWireFormat != nil { + return *m.MessageSetWireFormat + } + return Default_MessageOptions_MessageSetWireFormat +} + +func (m *MessageOptions) GetNoStandardDescriptorAccessor() bool { + if m != nil && m.NoStandardDescriptorAccessor != nil { + return *m.NoStandardDescriptorAccessor + } + return Default_MessageOptions_NoStandardDescriptorAccessor +} + +func (m *MessageOptions) GetUninterpretedOption() []*UninterpretedOption { + if m != nil { + return m.UninterpretedOption + } + return nil +} + +type FieldOptions struct { + // The ctype option instructs the C++ code generator to use a different + // representation of the field than it normally would. See the specific + // options below. This option is not yet implemented in the open source + // release -- sorry, we'll try to include it in a future version! + Ctype *FieldOptions_CType `protobuf:"varint,1,opt,name=ctype,enum=google.protobuf.FieldOptions_CType,def=0" json:"ctype,omitempty"` + // The packed option can be enabled for repeated primitive fields to enable + // a more efficient representation on the wire. Rather than repeatedly + // writing the tag and type for each element, the entire array is encoded as + // a single length-delimited blob. + Packed *bool `protobuf:"varint,2,opt,name=packed" json:"packed,omitempty"` + // Should this field be parsed lazily? Lazy applies only to message-type + // fields. It means that when the outer message is initially parsed, the + // inner message's contents will not be parsed but instead stored in encoded + // form. The inner message will actually be parsed when it is first accessed. + // + // This is only a hint. Implementations are free to choose whether to use + // eager or lazy parsing regardless of the value of this option. However, + // setting this option true suggests that the protocol author believes that + // using lazy parsing on this field is worth the additional bookkeeping + // overhead typically needed to implement it. + // + // This option does not affect the public interface of any generated code; + // all method signatures remain the same. Furthermore, thread-safety of the + // interface is not affected by this option; const methods remain safe to + // call from multiple threads concurrently, while non-const methods continue + // to require exclusive access. + // + // + // Note that implementations may choose not to check required fields within + // a lazy sub-message. That is, calling IsInitialized() on the outher message + // may return true even if the inner message has missing required fields. + // This is necessary because otherwise the inner message would have to be + // parsed in order to perform the check, defeating the purpose of lazy + // parsing. An implementation which chooses not to check required fields + // must be consistent about it. That is, for any particular sub-message, the + // implementation must either *always* check its required fields, or *never* + // check its required fields, regardless of whether or not the message has + // been parsed. + Lazy *bool `protobuf:"varint,5,opt,name=lazy,def=0" json:"lazy,omitempty"` + // Is this field deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for accessors, or it will be completely ignored; in the very least, this + // is a formalization for deprecating fields. + Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"` + // EXPERIMENTAL. DO NOT USE. + // For "map" fields, the name of the field in the enclosed type that + // is the key for this map. For example, suppose we have: + // message Item { + // required string name = 1; + // required string value = 2; + // } + // message Config { + // repeated Item items = 1 [experimental_map_key="name"]; + // } + // In this situation, the map key for Item will be set to "name". + // TODO: Fully-implement this, then remove the "experimental_" prefix. + ExperimentalMapKey *string `protobuf:"bytes,9,opt,name=experimental_map_key" json:"experimental_map_key,omitempty"` + // For Google-internal migration only. Do not use. + Weak *bool `protobuf:"varint,10,opt,name=weak,def=0" json:"weak,omitempty"` + InterpretedCustomtype *string `protobuf:"bytes,616,opt,name=interpreted_customtype" json:"interpreted_customtype,omitempty"` + // The parser stores options it doesn't recognize here. See above. + UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option" json:"uninterpreted_option,omitempty"` + XXX_extensions map[int32]proto.Extension `json:"-"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *FieldOptions) Reset() { *m = FieldOptions{} } +func (m *FieldOptions) String() string { return proto.CompactTextString(m) } +func (*FieldOptions) ProtoMessage() {} + +var extRange_FieldOptions = []proto.ExtensionRange{ + {1000, 536870911}, +} + +func (*FieldOptions) ExtensionRangeArray() []proto.ExtensionRange { + return extRange_FieldOptions +} +func (m *FieldOptions) ExtensionMap() map[int32]proto.Extension { + if m.XXX_extensions == nil { + m.XXX_extensions = make(map[int32]proto.Extension) + } + return m.XXX_extensions +} + +const Default_FieldOptions_Ctype FieldOptions_CType = FieldOptions_STRING +const Default_FieldOptions_Lazy bool = false +const Default_FieldOptions_Deprecated bool = false +const Default_FieldOptions_Weak bool = false + +func (m *FieldOptions) GetCtype() FieldOptions_CType { + if m != nil && m.Ctype != nil { + return *m.Ctype + } + return Default_FieldOptions_Ctype +} + +func (m *FieldOptions) GetPacked() bool { + if m != nil && m.Packed != nil { + return *m.Packed + } + return false +} + +func (m *FieldOptions) GetLazy() bool { + if m != nil && m.Lazy != nil { + return *m.Lazy + } + return Default_FieldOptions_Lazy +} + +func (m *FieldOptions) GetDeprecated() bool { + if m != nil && m.Deprecated != nil { + return *m.Deprecated + } + return Default_FieldOptions_Deprecated +} + +func (m *FieldOptions) GetExperimentalMapKey() string { + if m != nil && m.ExperimentalMapKey != nil { + return *m.ExperimentalMapKey + } + return "" +} + +func (m *FieldOptions) GetWeak() bool { + if m != nil && m.Weak != nil { + return *m.Weak + } + return Default_FieldOptions_Weak +} + +func (m *FieldOptions) GetInterpretedCustomtype() string { + if m != nil && m.InterpretedCustomtype != nil { + return *m.InterpretedCustomtype + } + return "" +} + +func (m *FieldOptions) GetUninterpretedOption() []*UninterpretedOption { + if m != nil { + return m.UninterpretedOption + } + return nil +} + +type EnumOptions struct { + // Set this option to false to disallow mapping different tag names to a same + // value. + AllowAlias *bool `protobuf:"varint,2,opt,name=allow_alias,def=1" json:"allow_alias,omitempty"` + // The parser stores options it doesn't recognize here. See above. + UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option" json:"uninterpreted_option,omitempty"` + XXX_extensions map[int32]proto.Extension `json:"-"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *EnumOptions) Reset() { *m = EnumOptions{} } +func (m *EnumOptions) String() string { return proto.CompactTextString(m) } +func (*EnumOptions) ProtoMessage() {} + +var extRange_EnumOptions = []proto.ExtensionRange{ + {1000, 536870911}, +} + +func (*EnumOptions) ExtensionRangeArray() []proto.ExtensionRange { + return extRange_EnumOptions +} +func (m *EnumOptions) ExtensionMap() map[int32]proto.Extension { + if m.XXX_extensions == nil { + m.XXX_extensions = make(map[int32]proto.Extension) + } + return m.XXX_extensions +} + +const Default_EnumOptions_AllowAlias bool = true + +func (m *EnumOptions) GetAllowAlias() bool { + if m != nil && m.AllowAlias != nil { + return *m.AllowAlias + } + return Default_EnumOptions_AllowAlias +} + +func (m *EnumOptions) GetUninterpretedOption() []*UninterpretedOption { + if m != nil { + return m.UninterpretedOption + } + return nil +} + +type EnumValueOptions struct { + // The parser stores options it doesn't recognize here. See above. + UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option" json:"uninterpreted_option,omitempty"` + XXX_extensions map[int32]proto.Extension `json:"-"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *EnumValueOptions) Reset() { *m = EnumValueOptions{} } +func (m *EnumValueOptions) String() string { return proto.CompactTextString(m) } +func (*EnumValueOptions) ProtoMessage() {} + +var extRange_EnumValueOptions = []proto.ExtensionRange{ + {1000, 536870911}, +} + +func (*EnumValueOptions) ExtensionRangeArray() []proto.ExtensionRange { + return extRange_EnumValueOptions +} +func (m *EnumValueOptions) ExtensionMap() map[int32]proto.Extension { + if m.XXX_extensions == nil { + m.XXX_extensions = make(map[int32]proto.Extension) + } + return m.XXX_extensions +} + +func (m *EnumValueOptions) GetUninterpretedOption() []*UninterpretedOption { + if m != nil { + return m.UninterpretedOption + } + return nil +} + +type ServiceOptions struct { + // The parser stores options it doesn't recognize here. See above. + UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option" json:"uninterpreted_option,omitempty"` + XXX_extensions map[int32]proto.Extension `json:"-"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *ServiceOptions) Reset() { *m = ServiceOptions{} } +func (m *ServiceOptions) String() string { return proto.CompactTextString(m) } +func (*ServiceOptions) ProtoMessage() {} + +var extRange_ServiceOptions = []proto.ExtensionRange{ + {1000, 536870911}, +} + +func (*ServiceOptions) ExtensionRangeArray() []proto.ExtensionRange { + return extRange_ServiceOptions +} +func (m *ServiceOptions) ExtensionMap() map[int32]proto.Extension { + if m.XXX_extensions == nil { + m.XXX_extensions = make(map[int32]proto.Extension) + } + return m.XXX_extensions +} + +func (m *ServiceOptions) GetUninterpretedOption() []*UninterpretedOption { + if m != nil { + return m.UninterpretedOption + } + return nil +} + +type MethodOptions struct { + // The parser stores options it doesn't recognize here. See above. + UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option" json:"uninterpreted_option,omitempty"` + XXX_extensions map[int32]proto.Extension `json:"-"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *MethodOptions) Reset() { *m = MethodOptions{} } +func (m *MethodOptions) String() string { return proto.CompactTextString(m) } +func (*MethodOptions) ProtoMessage() {} + +var extRange_MethodOptions = []proto.ExtensionRange{ + {1000, 536870911}, +} + +func (*MethodOptions) ExtensionRangeArray() []proto.ExtensionRange { + return extRange_MethodOptions +} +func (m *MethodOptions) ExtensionMap() map[int32]proto.Extension { + if m.XXX_extensions == nil { + m.XXX_extensions = make(map[int32]proto.Extension) + } + return m.XXX_extensions +} + +func (m *MethodOptions) GetUninterpretedOption() []*UninterpretedOption { + if m != nil { + return m.UninterpretedOption + } + return nil +} + +// A message representing a option the parser does not recognize. This only +// appears in options protos created by the compiler::Parser class. +// DescriptorPool resolves these when building Descriptor objects. Therefore, +// options protos in descriptor objects (e.g. returned by Descriptor::options(), +// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions +// in them. +type UninterpretedOption struct { + Name []*UninterpretedOption_NamePart `protobuf:"bytes,2,rep,name=name" json:"name,omitempty"` + // The value of the uninterpreted option, in whatever type the tokenizer + // identified it as during parsing. Exactly one of these should be set. + IdentifierValue *string `protobuf:"bytes,3,opt,name=identifier_value" json:"identifier_value,omitempty"` + PositiveIntValue *uint64 `protobuf:"varint,4,opt,name=positive_int_value" json:"positive_int_value,omitempty"` + NegativeIntValue *int64 `protobuf:"varint,5,opt,name=negative_int_value" json:"negative_int_value,omitempty"` + DoubleValue *float64 `protobuf:"fixed64,6,opt,name=double_value" json:"double_value,omitempty"` + StringValue []byte `protobuf:"bytes,7,opt,name=string_value" json:"string_value,omitempty"` + AggregateValue *string `protobuf:"bytes,8,opt,name=aggregate_value" json:"aggregate_value,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *UninterpretedOption) Reset() { *m = UninterpretedOption{} } +func (m *UninterpretedOption) String() string { return proto.CompactTextString(m) } +func (*UninterpretedOption) ProtoMessage() {} + +func (m *UninterpretedOption) GetName() []*UninterpretedOption_NamePart { + if m != nil { + return m.Name + } + return nil +} + +func (m *UninterpretedOption) GetIdentifierValue() string { + if m != nil && m.IdentifierValue != nil { + return *m.IdentifierValue + } + return "" +} + +func (m *UninterpretedOption) GetPositiveIntValue() uint64 { + if m != nil && m.PositiveIntValue != nil { + return *m.PositiveIntValue + } + return 0 +} + +func (m *UninterpretedOption) GetNegativeIntValue() int64 { + if m != nil && m.NegativeIntValue != nil { + return *m.NegativeIntValue + } + return 0 +} + +func (m *UninterpretedOption) GetDoubleValue() float64 { + if m != nil && m.DoubleValue != nil { + return *m.DoubleValue + } + return 0 +} + +func (m *UninterpretedOption) GetStringValue() []byte { + if m != nil { + return m.StringValue + } + return nil +} + +func (m *UninterpretedOption) GetAggregateValue() string { + if m != nil && m.AggregateValue != nil { + return *m.AggregateValue + } + return "" +} + +// The name of the uninterpreted option. Each string represents a segment in +// a dot-separated name. is_extension is true iff a segment represents an +// extension (denoted with parentheses in options specs in .proto files). +// E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents +// "foo.(bar.baz).qux". +type UninterpretedOption_NamePart struct { + NamePart *string `protobuf:"bytes,1,req,name=name_part" json:"name_part,omitempty"` + IsExtension *bool `protobuf:"varint,2,req,name=is_extension" json:"is_extension,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *UninterpretedOption_NamePart) Reset() { *m = UninterpretedOption_NamePart{} } +func (m *UninterpretedOption_NamePart) String() string { return proto.CompactTextString(m) } +func (*UninterpretedOption_NamePart) ProtoMessage() {} + +func (m *UninterpretedOption_NamePart) GetNamePart() string { + if m != nil && m.NamePart != nil { + return *m.NamePart + } + return "" +} + +func (m *UninterpretedOption_NamePart) GetIsExtension() bool { + if m != nil && m.IsExtension != nil { + return *m.IsExtension + } + return false +} + +// Encapsulates information about the original source file from which a +// FileDescriptorProto was generated. +type SourceCodeInfo struct { + // A Location identifies a piece of source code in a .proto file which + // corresponds to a particular definition. This information is intended + // to be useful to IDEs, code indexers, documentation generators, and similar + // tools. + // + // For example, say we have a file like: + // message Foo { + // optional string foo = 1; + // } + // Let's look at just the field definition: + // optional string foo = 1; + // ^ ^^ ^^ ^ ^^^ + // a bc de f ghi + // We have the following locations: + // span path represents + // [a,i) [ 4, 0, 2, 0 ] The whole field definition. + // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional). + // [c,d) [ 4, 0, 2, 0, 5 ] The type (string). + // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo). + // [g,h) [ 4, 0, 2, 0, 3 ] The number (1). + // + // Notes: + // - A location may refer to a repeated field itself (i.e. not to any + // particular index within it). This is used whenever a set of elements are + // logically enclosed in a single code segment. For example, an entire + // extend block (possibly containing multiple extension definitions) will + // have an outer location whose path refers to the "extensions" repeated + // field without an index. + // - Multiple locations may have the same path. This happens when a single + // logical declaration is spread out across multiple places. The most + // obvious example is the "extend" block again -- there may be multiple + // extend blocks in the same scope, each of which will have the same path. + // - A location's span is not always a subset of its parent's span. For + // example, the "extendee" of an extension declaration appears at the + // beginning of the "extend" block and is shared by all extensions within + // the block. + // - Just because a location's span is a subset of some other location's span + // does not mean that it is a descendent. For example, a "group" defines + // both a type and a field in a single declaration. Thus, the locations + // corresponding to the type and field and their components will overlap. + // - Code which tries to interpret locations should probably be designed to + // ignore those that it doesn't understand, as more types of locations could + // be recorded in the future. + Location []*SourceCodeInfo_Location `protobuf:"bytes,1,rep,name=location" json:"location,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *SourceCodeInfo) Reset() { *m = SourceCodeInfo{} } +func (m *SourceCodeInfo) String() string { return proto.CompactTextString(m) } +func (*SourceCodeInfo) ProtoMessage() {} + +func (m *SourceCodeInfo) GetLocation() []*SourceCodeInfo_Location { + if m != nil { + return m.Location + } + return nil +} + +type SourceCodeInfo_Location struct { + // Identifies which part of the FileDescriptorProto was defined at this + // location. + // + // Each element is a field number or an index. They form a path from + // the root FileDescriptorProto to the place where the definition. For + // example, this path: + // [ 4, 3, 2, 7, 1 ] + // refers to: + // file.message_type(3) // 4, 3 + // .field(7) // 2, 7 + // .name() // 1 + // This is because FileDescriptorProto.message_type has field number 4: + // repeated DescriptorProto message_type = 4; + // and DescriptorProto.field has field number 2: + // repeated FieldDescriptorProto field = 2; + // and FieldDescriptorProto.name has field number 1: + // optional string name = 1; + // + // Thus, the above path gives the location of a field name. If we removed + // the last element: + // [ 4, 3, 2, 7 ] + // this path refers to the whole field declaration (from the beginning + // of the label to the terminating semicolon). + Path []int32 `protobuf:"varint,1,rep,packed,name=path" json:"path,omitempty"` + // Always has exactly three or four elements: start line, start column, + // end line (optional, otherwise assumed same as start line), end column. + // These are packed into a single field for efficiency. Note that line + // and column numbers are zero-based -- typically you will want to add + // 1 to each before displaying to a user. + Span []int32 `protobuf:"varint,2,rep,packed,name=span" json:"span,omitempty"` + // If this SourceCodeInfo represents a complete declaration, these are any + // comments appearing before and after the declaration which appear to be + // attached to the declaration. + // + // A series of line comments appearing on consecutive lines, with no other + // tokens appearing on those lines, will be treated as a single comment. + // + // Only the comment content is provided; comment markers (e.g. //) are + // stripped out. For block comments, leading whitespace and an asterisk + // will be stripped from the beginning of each line other than the first. + // Newlines are included in the output. + // + // Examples: + // + // optional int32 foo = 1; // Comment attached to foo. + // // Comment attached to bar. + // optional int32 bar = 2; + // + // optional string baz = 3; + // // Comment attached to baz. + // // Another line attached to baz. + // + // // Comment attached to qux. + // // + // // Another line attached to qux. + // optional double qux = 4; + // + // optional string corge = 5; + // /* Block comment attached + // * to corge. Leading asterisks + // * will be removed. */ + // /* Block comment attached to + // * grault. */ + // optional int32 grault = 6; + LeadingComments *string `protobuf:"bytes,3,opt,name=leading_comments" json:"leading_comments,omitempty"` + TrailingComments *string `protobuf:"bytes,4,opt,name=trailing_comments" json:"trailing_comments,omitempty"` + XXX_unrecognized []byte `json:"-"` +} + +func (m *SourceCodeInfo_Location) Reset() { *m = SourceCodeInfo_Location{} } +func (m *SourceCodeInfo_Location) String() string { return proto.CompactTextString(m) } +func (*SourceCodeInfo_Location) ProtoMessage() {} + +func (m *SourceCodeInfo_Location) GetPath() []int32 { + if m != nil { + return m.Path + } + return nil +} + +func (m *SourceCodeInfo_Location) GetSpan() []int32 { + if m != nil { + return m.Span + } + return nil +} + +func (m *SourceCodeInfo_Location) GetLeadingComments() string { + if m != nil && m.LeadingComments != nil { + return *m.LeadingComments + } + return "" +} + +func (m *SourceCodeInfo_Location) GetTrailingComments() string { + if m != nil && m.TrailingComments != nil { + return *m.TrailingComments + } + return "" +} + +func init() { + proto.RegisterEnum("google.protobuf.FieldDescriptorProto_Type", FieldDescriptorProto_Type_name, FieldDescriptorProto_Type_value) + proto.RegisterEnum("google.protobuf.FieldDescriptorProto_Label", FieldDescriptorProto_Label_name, FieldDescriptorProto_Label_value) + proto.RegisterEnum("google.protobuf.FileOptions_OptimizeMode", FileOptions_OptimizeMode_name, FileOptions_OptimizeMode_value) + proto.RegisterEnum("google.protobuf.FieldOptions_CType", FieldOptions_CType_name, FieldOptions_CType_value) +} diff --git a/src/ProtoBufCodeFormatter/descriptor/descriptor.proto b/src/ProtoBufCodeFormatter/descriptor/descriptor.proto new file mode 100644 index 0000000..3d35c62 --- /dev/null +++ b/src/ProtoBufCodeFormatter/descriptor/descriptor.proto @@ -0,0 +1,622 @@ +// Protocol Buffers - Google's data interchange format +// Copyright 2008 Google Inc. All rights reserved. +// http://code.google.com/p/protobuf/ +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Google Inc. nor the names of its +// contributors may be used to endorse or promote products derived from +// this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +// Author: kenton@google.com (Kenton Varda) +// Based on original Protocol Buffers design by +// Sanjay Ghemawat, Jeff Dean, and others. +// +// The messages in this file describe the definitions found in .proto files. +// A valid .proto file can be translated directly to a FileDescriptorProto +// without any other information (e.g. without reading its imports). + + + +package google.protobuf; +option java_package = "com.google.protobuf"; +option java_outer_classname = "DescriptorProtos"; + +// descriptor.proto must be optimized for speed because reflection-based +// algorithms don't work during bootstrapping. +option optimize_for = SPEED; + +// The protocol compiler can output a FileDescriptorSet containing the .proto +// files it parses. +message FileDescriptorSet { + repeated FileDescriptorProto file = 1; +} + +// Describes a complete .proto file. +message FileDescriptorProto { + optional string name = 1; // file name, relative to root of source tree + optional string package = 2; // e.g. "foo", "foo.bar", etc. + + // Names of files imported by this file. + repeated string dependency = 3; + // Indexes of the public imported files in the dependency list above. + repeated int32 public_dependency = 10; + // Indexes of the weak imported files in the dependency list. + // For Google-internal migration only. Do not use. + repeated int32 weak_dependency = 11; + + // All top-level definitions in this file. + repeated DescriptorProto message_type = 4; + repeated EnumDescriptorProto enum_type = 5; + repeated ServiceDescriptorProto service = 6; + repeated FieldDescriptorProto extension = 7; + + optional FileOptions options = 8; + + // This field contains optional information about the original source code. + // You may safely remove this entire field whithout harming runtime + // functionality of the descriptors -- the information is needed only by + // development tools. + optional SourceCodeInfo source_code_info = 9; +} + +// Describes a message type. +message DescriptorProto { + optional string name = 1; + + repeated FieldDescriptorProto field = 2; + repeated FieldDescriptorProto extension = 6; + + repeated DescriptorProto nested_type = 3; + repeated EnumDescriptorProto enum_type = 4; + + message ExtensionRange { + optional int32 start = 1; + optional int32 end = 2; + } + repeated ExtensionRange extension_range = 5; + + optional MessageOptions options = 7; +} + +// Describes a field within a message. +message FieldDescriptorProto { + enum Type { + // 0 is reserved for errors. + // Order is weird for historical reasons. + TYPE_DOUBLE = 1; + TYPE_FLOAT = 2; + // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if + // negative values are likely. + TYPE_INT64 = 3; + TYPE_UINT64 = 4; + // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if + // negative values are likely. + TYPE_INT32 = 5; + TYPE_FIXED64 = 6; + TYPE_FIXED32 = 7; + TYPE_BOOL = 8; + TYPE_STRING = 9; + TYPE_GROUP = 10; // Tag-delimited aggregate. + TYPE_MESSAGE = 11; // Length-delimited aggregate. + + // New in version 2. + TYPE_BYTES = 12; + TYPE_UINT32 = 13; + TYPE_ENUM = 14; + TYPE_SFIXED32 = 15; + TYPE_SFIXED64 = 16; + TYPE_SINT32 = 17; // Uses ZigZag encoding. + TYPE_SINT64 = 18; // Uses ZigZag encoding. + }; + + enum Label { + // 0 is reserved for errors + LABEL_OPTIONAL = 1; + LABEL_REQUIRED = 2; + LABEL_REPEATED = 3; + // TODO(sanjay): Should we add LABEL_MAP? + }; + + optional string name = 1; + optional int32 number = 3; + optional Label label = 4; + + // If type_name is set, this need not be set. If both this and type_name + // are set, this must be either TYPE_ENUM or TYPE_MESSAGE. + optional Type type = 5; + + // For message and enum types, this is the name of the type. If the name + // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping + // rules are used to find the type (i.e. first the nested types within this + // message are searched, then within the parent, on up to the root + // namespace). + optional string type_name = 6; + + // For extensions, this is the name of the type being extended. It is + // resolved in the same manner as type_name. + optional string extendee = 2; + + // For numeric types, contains the original text representation of the value. + // For booleans, "true" or "false". + // For strings, contains the default text contents (not escaped in any way). + // For bytes, contains the C escaped value. All bytes >= 128 are escaped. + // TODO(kenton): Base-64 encode? + optional string default_value = 7; + + optional FieldOptions options = 8; +} + +// Describes an enum type. +message EnumDescriptorProto { + optional string name = 1; + + repeated EnumValueDescriptorProto value = 2; + + optional EnumOptions options = 3; +} + +// Describes a value within an enum. +message EnumValueDescriptorProto { + optional string name = 1; + optional int32 number = 2; + + optional EnumValueOptions options = 3; +} + +// Describes a service. +message ServiceDescriptorProto { + optional string name = 1; + repeated MethodDescriptorProto method = 2; + + optional ServiceOptions options = 3; +} + +// Describes a method of a service. +message MethodDescriptorProto { + optional string name = 1; + + // Input and output type names. These are resolved in the same way as + // FieldDescriptorProto.type_name, but must refer to a message type. + optional string input_type = 2; + optional string output_type = 3; + + optional MethodOptions options = 4; +} + + +// =================================================================== +// Options + +// Each of the definitions above may have "options" attached. These are +// just annotations which may cause code to be generated slightly differently +// or may contain hints for code that manipulates protocol messages. +// +// Clients may define custom options as extensions of the *Options messages. +// These extensions may not yet be known at parsing time, so the parser cannot +// store the values in them. Instead it stores them in a field in the *Options +// message called uninterpreted_option. This field must have the same name +// across all *Options messages. We then use this field to populate the +// extensions when we build a descriptor, at which point all protos have been +// parsed and so all extensions are known. +// +// Extension numbers for custom options may be chosen as follows: +// * For options which will only be used within a single application or +// organization, or for experimental options, use field numbers 50000 +// through 99999. It is up to you to ensure that you do not use the +// same number for multiple options. +// * For options which will be published and used publicly by multiple +// independent entities, e-mail protobuf-global-extension-registry@google.com +// to reserve extension numbers. Simply provide your project name (e.g. +// Object-C plugin) and your porject website (if available) -- there's no need +// to explain how you intend to use them. Usually you only need one extension +// number. You can declare multiple options with only one extension number by +// putting them in a sub-message. See the Custom Options section of the docs +// for examples: +// http://code.google.com/apis/protocolbuffers/docs/proto.html#options +// If this turns out to be popular, a web service will be set up +// to automatically assign option numbers. + + +message FileOptions { + + // Sets the Java package where classes generated from this .proto will be + // placed. By default, the proto package is used, but this is often + // inappropriate because proto packages do not normally start with backwards + // domain names. + optional string java_package = 1; + + + // If set, all the classes from the .proto file are wrapped in a single + // outer class with the given name. This applies to both Proto1 + // (equivalent to the old "--one_java_file" option) and Proto2 (where + // a .proto always translates to a single class, but you may want to + // explicitly choose the class name). + optional string java_outer_classname = 8; + + // If set true, then the Java code generator will generate a separate .java + // file for each top-level message, enum, and service defined in the .proto + // file. Thus, these types will *not* be nested inside the outer class + // named by java_outer_classname. However, the outer class will still be + // generated to contain the file's getDescriptor() method as well as any + // top-level extensions defined in the file. + optional bool java_multiple_files = 10 [default=false]; + + // If set true, then the Java code generator will generate equals() and + // hashCode() methods for all messages defined in the .proto file. This is + // purely a speed optimization, as the AbstractMessage base class includes + // reflection-based implementations of these methods. + optional bool java_generate_equals_and_hash = 20 [default=false]; + + // Generated classes can be optimized for speed or code size. + enum OptimizeMode { + SPEED = 1; // Generate complete code for parsing, serialization, + // etc. + CODE_SIZE = 2; // Use ReflectionOps to implement these methods. + LITE_RUNTIME = 3; // Generate code using MessageLite and the lite runtime. + } + optional OptimizeMode optimize_for = 9 [default=SPEED]; + + // Sets the Go package where structs generated from this .proto will be + // placed. There is no default. + optional string go_package = 11; + + + + // Should generic services be generated in each language? "Generic" services + // are not specific to any particular RPC system. They are generated by the + // main code generators in each language (without additional plugins). + // Generic services were the only kind of service generation supported by + // early versions of proto2. + // + // Generic services are now considered deprecated in favor of using plugins + // that generate code specific to your particular RPC system. Therefore, + // these default to false. Old code which depends on generic services should + // explicitly set them to true. + optional bool cc_generic_services = 16 [default=false]; + optional bool java_generic_services = 17 [default=false]; + optional bool py_generic_services = 18 [default=false]; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message MessageOptions { + // Set true to use the old proto1 MessageSet wire format for extensions. + // This is provided for backwards-compatibility with the MessageSet wire + // format. You should not use this for any other reason: It's less + // efficient, has fewer features, and is more complicated. + // + // The message must be defined exactly as follows: + // message Foo { + // option message_set_wire_format = true; + // extensions 4 to max; + // } + // Note that the message cannot have any defined fields; MessageSets only + // have extensions. + // + // All extensions of your type must be singular messages; e.g. they cannot + // be int32s, enums, or repeated messages. + // + // Because this is an option, the above two restrictions are not enforced by + // the protocol compiler. + optional bool message_set_wire_format = 1 [default=false]; + + // Disables the generation of the standard "descriptor()" accessor, which can + // conflict with a field of the same name. This is meant to make migration + // from proto1 easier; new code should avoid fields named "descriptor". + optional bool no_standard_descriptor_accessor = 2 [default=false]; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message FieldOptions { + // The ctype option instructs the C++ code generator to use a different + // representation of the field than it normally would. See the specific + // options below. This option is not yet implemented in the open source + // release -- sorry, we'll try to include it in a future version! + optional CType ctype = 1 [default = STRING]; + enum CType { + // Default mode. + STRING = 0; + + CORD = 1; + + STRING_PIECE = 2; + } + // The packed option can be enabled for repeated primitive fields to enable + // a more efficient representation on the wire. Rather than repeatedly + // writing the tag and type for each element, the entire array is encoded as + // a single length-delimited blob. + optional bool packed = 2; + + + + // Should this field be parsed lazily? Lazy applies only to message-type + // fields. It means that when the outer message is initially parsed, the + // inner message's contents will not be parsed but instead stored in encoded + // form. The inner message will actually be parsed when it is first accessed. + // + // This is only a hint. Implementations are free to choose whether to use + // eager or lazy parsing regardless of the value of this option. However, + // setting this option true suggests that the protocol author believes that + // using lazy parsing on this field is worth the additional bookkeeping + // overhead typically needed to implement it. + // + // This option does not affect the public interface of any generated code; + // all method signatures remain the same. Furthermore, thread-safety of the + // interface is not affected by this option; const methods remain safe to + // call from multiple threads concurrently, while non-const methods continue + // to require exclusive access. + // + // + // Note that implementations may choose not to check required fields within + // a lazy sub-message. That is, calling IsInitialized() on the outher message + // may return true even if the inner message has missing required fields. + // This is necessary because otherwise the inner message would have to be + // parsed in order to perform the check, defeating the purpose of lazy + // parsing. An implementation which chooses not to check required fields + // must be consistent about it. That is, for any particular sub-message, the + // implementation must either *always* check its required fields, or *never* + // check its required fields, regardless of whether or not the message has + // been parsed. + optional bool lazy = 5 [default=false]; + + // Is this field deprecated? + // Depending on the target platform, this can emit Deprecated annotations + // for accessors, or it will be completely ignored; in the very least, this + // is a formalization for deprecating fields. + optional bool deprecated = 3 [default=false]; + + // EXPERIMENTAL. DO NOT USE. + // For "map" fields, the name of the field in the enclosed type that + // is the key for this map. For example, suppose we have: + // message Item { + // required string name = 1; + // required string value = 2; + // } + // message Config { + // repeated Item items = 1 [experimental_map_key="name"]; + // } + // In this situation, the map key for Item will be set to "name". + // TODO: Fully-implement this, then remove the "experimental_" prefix. + optional string experimental_map_key = 9; + + // For Google-internal migration only. Do not use. + optional bool weak = 10 [default=false]; + + optional string interpreted_customtype = 616; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message EnumOptions { + + // Set this option to false to disallow mapping different tag names to a same + // value. + optional bool allow_alias = 2 [default=true]; + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message EnumValueOptions { + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message ServiceOptions { + + // Note: Field numbers 1 through 32 are reserved for Google's internal RPC + // framework. We apologize for hoarding these numbers to ourselves, but + // we were already using them long before we decided to release Protocol + // Buffers. + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + +message MethodOptions { + + // Note: Field numbers 1 through 32 are reserved for Google's internal RPC + // framework. We apologize for hoarding these numbers to ourselves, but + // we were already using them long before we decided to release Protocol + // Buffers. + + // The parser stores options it doesn't recognize here. See above. + repeated UninterpretedOption uninterpreted_option = 999; + + // Clients can define custom options in extensions of this message. See above. + extensions 1000 to max; +} + + +// A message representing a option the parser does not recognize. This only +// appears in options protos created by the compiler::Parser class. +// DescriptorPool resolves these when building Descriptor objects. Therefore, +// options protos in descriptor objects (e.g. returned by Descriptor::options(), +// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions +// in them. +message UninterpretedOption { + // The name of the uninterpreted option. Each string represents a segment in + // a dot-separated name. is_extension is true iff a segment represents an + // extension (denoted with parentheses in options specs in .proto files). + // E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents + // "foo.(bar.baz).qux". + message NamePart { + required string name_part = 1; + required bool is_extension = 2; + } + repeated NamePart name = 2; + + // The value of the uninterpreted option, in whatever type the tokenizer + // identified it as during parsing. Exactly one of these should be set. + optional string identifier_value = 3; + optional uint64 positive_int_value = 4; + optional int64 negative_int_value = 5; + optional double double_value = 6; + optional bytes string_value = 7; + optional string aggregate_value = 8; +} + +// =================================================================== +// Optional source code info + +// Encapsulates information about the original source file from which a +// FileDescriptorProto was generated. +message SourceCodeInfo { + // A Location identifies a piece of source code in a .proto file which + // corresponds to a particular definition. This information is intended + // to be useful to IDEs, code indexers, documentation generators, and similar + // tools. + // + // For example, say we have a file like: + // message Foo { + // optional string foo = 1; + // } + // Let's look at just the field definition: + // optional string foo = 1; + // ^ ^^ ^^ ^ ^^^ + // a bc de f ghi + // We have the following locations: + // span path represents + // [a,i) [ 4, 0, 2, 0 ] The whole field definition. + // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional). + // [c,d) [ 4, 0, 2, 0, 5 ] The type (string). + // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo). + // [g,h) [ 4, 0, 2, 0, 3 ] The number (1). + // + // Notes: + // - A location may refer to a repeated field itself (i.e. not to any + // particular index within it). This is used whenever a set of elements are + // logically enclosed in a single code segment. For example, an entire + // extend block (possibly containing multiple extension definitions) will + // have an outer location whose path refers to the "extensions" repeated + // field without an index. + // - Multiple locations may have the same path. This happens when a single + // logical declaration is spread out across multiple places. The most + // obvious example is the "extend" block again -- there may be multiple + // extend blocks in the same scope, each of which will have the same path. + // - A location's span is not always a subset of its parent's span. For + // example, the "extendee" of an extension declaration appears at the + // beginning of the "extend" block and is shared by all extensions within + // the block. + // - Just because a location's span is a subset of some other location's span + // does not mean that it is a descendent. For example, a "group" defines + // both a type and a field in a single declaration. Thus, the locations + // corresponding to the type and field and their components will overlap. + // - Code which tries to interpret locations should probably be designed to + // ignore those that it doesn't understand, as more types of locations could + // be recorded in the future. + repeated Location location = 1; + message Location { + // Identifies which part of the FileDescriptorProto was defined at this + // location. + // + // Each element is a field number or an index. They form a path from + // the root FileDescriptorProto to the place where the definition. For + // example, this path: + // [ 4, 3, 2, 7, 1 ] + // refers to: + // file.message_type(3) // 4, 3 + // .field(7) // 2, 7 + // .name() // 1 + // This is because FileDescriptorProto.message_type has field number 4: + // repeated DescriptorProto message_type = 4; + // and DescriptorProto.field has field number 2: + // repeated FieldDescriptorProto field = 2; + // and FieldDescriptorProto.name has field number 1: + // optional string name = 1; + // + // Thus, the above path gives the location of a field name. If we removed + // the last element: + // [ 4, 3, 2, 7 ] + // this path refers to the whole field declaration (from the beginning + // of the label to the terminating semicolon). + repeated int32 path = 1 [packed=true]; + + // Always has exactly three or four elements: start line, start column, + // end line (optional, otherwise assumed same as start line), end column. + // These are packed into a single field for efficiency. Note that line + // and column numbers are zero-based -- typically you will want to add + // 1 to each before displaying to a user. + repeated int32 span = 2 [packed=true]; + + // If this SourceCodeInfo represents a complete declaration, these are any + // comments appearing before and after the declaration which appear to be + // attached to the declaration. + // + // A series of line comments appearing on consecutive lines, with no other + // tokens appearing on those lines, will be treated as a single comment. + // + // Only the comment content is provided; comment markers (e.g. //) are + // stripped out. For block comments, leading whitespace and an asterisk + // will be stripped from the beginning of each line other than the first. + // Newlines are included in the output. + // + // Examples: + // + // optional int32 foo = 1; // Comment attached to foo. + // // Comment attached to bar. + // optional int32 bar = 2; + // + // optional string baz = 3; + // // Comment attached to baz. + // // Another line attached to baz. + // + // // Comment attached to qux. + // // + // // Another line attached to qux. + // optional double qux = 4; + // + // optional string corge = 5; + // /* Block comment attached + // * to corge. Leading asterisks + // * will be removed. */ + // /* Block comment attached to + // * grault. */ + // optional int32 grault = 6; + optional string leading_comments = 3; + optional string trailing_comments = 4; + } +} diff --git a/src/ProtoBufCodeFormatter/descriptor/gostring.go b/src/ProtoBufCodeFormatter/descriptor/gostring.go new file mode 100644 index 0000000..11ee662 --- /dev/null +++ b/src/ProtoBufCodeFormatter/descriptor/gostring.go @@ -0,0 +1,202 @@ +// Extensions for Protocol Buffers to create more go like structures. +// +// Copyright (c) 2013, Vastech SA (PTY) LTD. All rights reserved. +// http://code.google.com/p/gogoprotobuf/gogoproto +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package descriptor + +import fmt "fmt" +import strings "strings" +import code_google_com_p_gogoprotobuf_proto "code.google.com/p/gogoprotobuf/proto" +import sort "sort" +import strconv "strconv" +import reflect "reflect" + +func (this *FileDescriptorSet) GoString() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&google_protobuf.FileDescriptorSet{` + `File:` + fmt.Sprintf("%#v", this.File), `XXX_unrecognized:` + fmt.Sprintf("%#v", this.XXX_unrecognized) + `}`}, ", ") + return s +} +func (this *FileDescriptorProto) GoString() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&google_protobuf.FileDescriptorProto{` + `Name:` + valueToGoStringDescriptor(this.Name, "string"), `Package:` + valueToGoStringDescriptor(this.Package, "string"), `Dependency:` + fmt.Sprintf("%#v", this.Dependency), `PublicDependency:` + fmt.Sprintf("%#v", this.PublicDependency), `WeakDependency:` + fmt.Sprintf("%#v", this.WeakDependency), `MessageType:` + fmt.Sprintf("%#v", this.MessageType), `EnumType:` + fmt.Sprintf("%#v", this.EnumType), `Service:` + fmt.Sprintf("%#v", this.Service), `Extension:` + fmt.Sprintf("%#v", this.Extension), `Options:` + fmt.Sprintf("%#v", this.Options), `SourceCodeInfo:` + fmt.Sprintf("%#v", this.SourceCodeInfo), `XXX_unrecognized:` + fmt.Sprintf("%#v", this.XXX_unrecognized) + `}`}, ", ") + return s +} +func (this *DescriptorProto) GoString() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&google_protobuf.DescriptorProto{` + `Name:` + valueToGoStringDescriptor(this.Name, "string"), `Field:` + fmt.Sprintf("%#v", this.Field), `Extension:` + fmt.Sprintf("%#v", this.Extension), `NestedType:` + fmt.Sprintf("%#v", this.NestedType), `EnumType:` + fmt.Sprintf("%#v", this.EnumType), `ExtensionRange:` + fmt.Sprintf("%#v", this.ExtensionRange), `Options:` + fmt.Sprintf("%#v", this.Options), `XXX_unrecognized:` + fmt.Sprintf("%#v", this.XXX_unrecognized) + `}`}, ", ") + return s +} +func (this *DescriptorProto_ExtensionRange) GoString() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&google_protobuf.DescriptorProto_ExtensionRange{` + `Start:` + valueToGoStringDescriptor(this.Start, "int32"), `End:` + valueToGoStringDescriptor(this.End, "int32"), `XXX_unrecognized:` + fmt.Sprintf("%#v", this.XXX_unrecognized) + `}`}, ", ") + return s +} +func (this *FieldDescriptorProto) GoString() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&google_protobuf.FieldDescriptorProto{` + `Name:` + valueToGoStringDescriptor(this.Name, "string"), `Number:` + valueToGoStringDescriptor(this.Number, "int32"), `Label:` + valueToGoStringDescriptor(this.Label, "google_protobuf.FieldDescriptorProto_Label"), `Type:` + valueToGoStringDescriptor(this.Type, "google_protobuf.FieldDescriptorProto_Type"), `TypeName:` + valueToGoStringDescriptor(this.TypeName, "string"), `Extendee:` + valueToGoStringDescriptor(this.Extendee, "string"), `DefaultValue:` + valueToGoStringDescriptor(this.DefaultValue, "string"), `Options:` + fmt.Sprintf("%#v", this.Options), `XXX_unrecognized:` + fmt.Sprintf("%#v", this.XXX_unrecognized) + `}`}, ", ") + return s +} +func (this *EnumDescriptorProto) GoString() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&google_protobuf.EnumDescriptorProto{` + `Name:` + valueToGoStringDescriptor(this.Name, "string"), `Value:` + fmt.Sprintf("%#v", this.Value), `Options:` + fmt.Sprintf("%#v", this.Options), `XXX_unrecognized:` + fmt.Sprintf("%#v", this.XXX_unrecognized) + `}`}, ", ") + return s +} +func (this *EnumValueDescriptorProto) GoString() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&google_protobuf.EnumValueDescriptorProto{` + `Name:` + valueToGoStringDescriptor(this.Name, "string"), `Number:` + valueToGoStringDescriptor(this.Number, "int32"), `Options:` + fmt.Sprintf("%#v", this.Options), `XXX_unrecognized:` + fmt.Sprintf("%#v", this.XXX_unrecognized) + `}`}, ", ") + return s +} +func (this *ServiceDescriptorProto) GoString() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&google_protobuf.ServiceDescriptorProto{` + `Name:` + valueToGoStringDescriptor(this.Name, "string"), `Method:` + fmt.Sprintf("%#v", this.Method), `Options:` + fmt.Sprintf("%#v", this.Options), `XXX_unrecognized:` + fmt.Sprintf("%#v", this.XXX_unrecognized) + `}`}, ", ") + return s +} +func (this *MethodDescriptorProto) GoString() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&google_protobuf.MethodDescriptorProto{` + `Name:` + valueToGoStringDescriptor(this.Name, "string"), `InputType:` + valueToGoStringDescriptor(this.InputType, "string"), `OutputType:` + valueToGoStringDescriptor(this.OutputType, "string"), `Options:` + fmt.Sprintf("%#v", this.Options), `XXX_unrecognized:` + fmt.Sprintf("%#v", this.XXX_unrecognized) + `}`}, ", ") + return s +} +func (this *FileOptions) GoString() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&google_protobuf.FileOptions{` + `JavaPackage:` + valueToGoStringDescriptor(this.JavaPackage, "string"), `JavaOuterClassname:` + valueToGoStringDescriptor(this.JavaOuterClassname, "string"), `JavaMultipleFiles:` + valueToGoStringDescriptor(this.JavaMultipleFiles, "bool"), `JavaGenerateEqualsAndHash:` + valueToGoStringDescriptor(this.JavaGenerateEqualsAndHash, "bool"), `OptimizeFor:` + valueToGoStringDescriptor(this.OptimizeFor, "google_protobuf.FileOptions_OptimizeMode"), `GoPackage:` + valueToGoStringDescriptor(this.GoPackage, "string"), `CcGenericServices:` + valueToGoStringDescriptor(this.CcGenericServices, "bool"), `JavaGenericServices:` + valueToGoStringDescriptor(this.JavaGenericServices, "bool"), `PyGenericServices:` + valueToGoStringDescriptor(this.PyGenericServices, "bool"), `UninterpretedOption:` + fmt.Sprintf("%#v", this.UninterpretedOption), `XXX_extensions: ` + extensionToGoStringDescriptor(this.XXX_extensions), `XXX_unrecognized:` + fmt.Sprintf("%#v", this.XXX_unrecognized) + `}`}, ", ") + return s +} +func (this *MessageOptions) GoString() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&google_protobuf.MessageOptions{` + `MessageSetWireFormat:` + valueToGoStringDescriptor(this.MessageSetWireFormat, "bool"), `NoStandardDescriptorAccessor:` + valueToGoStringDescriptor(this.NoStandardDescriptorAccessor, "bool"), `UninterpretedOption:` + fmt.Sprintf("%#v", this.UninterpretedOption), `XXX_extensions: ` + extensionToGoStringDescriptor(this.XXX_extensions), `XXX_unrecognized:` + fmt.Sprintf("%#v", this.XXX_unrecognized) + `}`}, ", ") + return s +} +func (this *FieldOptions) GoString() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&google_protobuf.FieldOptions{` + `Ctype:` + valueToGoStringDescriptor(this.Ctype, "google_protobuf.FieldOptions_CType"), `Packed:` + valueToGoStringDescriptor(this.Packed, "bool"), `Lazy:` + valueToGoStringDescriptor(this.Lazy, "bool"), `Deprecated:` + valueToGoStringDescriptor(this.Deprecated, "bool"), `ExperimentalMapKey:` + valueToGoStringDescriptor(this.ExperimentalMapKey, "string"), `Weak:` + valueToGoStringDescriptor(this.Weak, "bool"), `UninterpretedOption:` + fmt.Sprintf("%#v", this.UninterpretedOption), `XXX_extensions: ` + extensionToGoStringDescriptor(this.XXX_extensions), `XXX_unrecognized:` + fmt.Sprintf("%#v", this.XXX_unrecognized) + `}`}, ", ") + return s +} +func (this *EnumOptions) GoString() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&google_protobuf.EnumOptions{` + `AllowAlias:` + valueToGoStringDescriptor(this.AllowAlias, "bool"), `UninterpretedOption:` + fmt.Sprintf("%#v", this.UninterpretedOption), `XXX_extensions: ` + extensionToGoStringDescriptor(this.XXX_extensions), `XXX_unrecognized:` + fmt.Sprintf("%#v", this.XXX_unrecognized) + `}`}, ", ") + return s +} +func (this *EnumValueOptions) GoString() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&google_protobuf.EnumValueOptions{` + `UninterpretedOption:` + fmt.Sprintf("%#v", this.UninterpretedOption), `XXX_extensions: ` + extensionToGoStringDescriptor(this.XXX_extensions), `XXX_unrecognized:` + fmt.Sprintf("%#v", this.XXX_unrecognized) + `}`}, ", ") + return s +} +func (this *ServiceOptions) GoString() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&google_protobuf.ServiceOptions{` + `UninterpretedOption:` + fmt.Sprintf("%#v", this.UninterpretedOption), `XXX_extensions: ` + extensionToGoStringDescriptor(this.XXX_extensions), `XXX_unrecognized:` + fmt.Sprintf("%#v", this.XXX_unrecognized) + `}`}, ", ") + return s +} +func (this *MethodOptions) GoString() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&google_protobuf.MethodOptions{` + `UninterpretedOption:` + fmt.Sprintf("%#v", this.UninterpretedOption), `XXX_extensions: ` + extensionToGoStringDescriptor(this.XXX_extensions), `XXX_unrecognized:` + fmt.Sprintf("%#v", this.XXX_unrecognized) + `}`}, ", ") + return s +} +func (this *UninterpretedOption) GoString() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&google_protobuf.UninterpretedOption{` + `Name:` + fmt.Sprintf("%#v", this.Name), `IdentifierValue:` + valueToGoStringDescriptor(this.IdentifierValue, "string"), `PositiveIntValue:` + valueToGoStringDescriptor(this.PositiveIntValue, "uint64"), `NegativeIntValue:` + valueToGoStringDescriptor(this.NegativeIntValue, "int64"), `DoubleValue:` + valueToGoStringDescriptor(this.DoubleValue, "float64"), `StringValue:` + valueToGoStringDescriptor(this.StringValue, "byte"), `AggregateValue:` + valueToGoStringDescriptor(this.AggregateValue, "string"), `XXX_unrecognized:` + fmt.Sprintf("%#v", this.XXX_unrecognized) + `}`}, ", ") + return s +} +func (this *UninterpretedOption_NamePart) GoString() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&google_protobuf.UninterpretedOption_NamePart{` + `NamePart:` + valueToGoStringDescriptor(this.NamePart, "string"), `IsExtension:` + valueToGoStringDescriptor(this.IsExtension, "bool"), `XXX_unrecognized:` + fmt.Sprintf("%#v", this.XXX_unrecognized) + `}`}, ", ") + return s +} +func (this *SourceCodeInfo) GoString() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&google_protobuf.SourceCodeInfo{` + `Location:` + fmt.Sprintf("%#v", this.Location), `XXX_unrecognized:` + fmt.Sprintf("%#v", this.XXX_unrecognized) + `}`}, ", ") + return s +} +func (this *SourceCodeInfo_Location) GoString() string { + if this == nil { + return "nil" + } + s := strings.Join([]string{`&google_protobuf.SourceCodeInfo_Location{` + `Path:` + fmt.Sprintf("%#v", this.Path), `Span:` + fmt.Sprintf("%#v", this.Span), `LeadingComments:` + valueToGoStringDescriptor(this.LeadingComments, "string"), `TrailingComments:` + valueToGoStringDescriptor(this.TrailingComments, "string"), `XXX_unrecognized:` + fmt.Sprintf("%#v", this.XXX_unrecognized) + `}`}, ", ") + return s +} +func valueToGoStringDescriptor(v interface{}, typ string) string { + rv := reflect.ValueOf(v) + if rv.IsNil() { + return "nil" + } + pv := reflect.Indirect(rv).Interface() + return fmt.Sprintf("func(v %v) *%v { return &v } ( %#v )", typ, typ, pv) +} +func extensionToGoStringDescriptor(e map[int32]code_google_com_p_gogoprotobuf_proto.Extension) string { + if e == nil { + return "nil" + } + s := "map[int32]proto.Extension{" + keys := make([]int, 0, len(e)) + for k := range e { + keys = append(keys, int(k)) + } + sort.Ints(keys) + ss := []string{} + for _, k := range keys { + ss = append(ss, strconv.Itoa(k)+": "+e[int32(k)].GoString()) + } + s += strings.Join(ss, ",") + "}" + return s +} diff --git a/src/ProtoBufCodeFormatter/descriptor/helper.go b/src/ProtoBufCodeFormatter/descriptor/helper.go new file mode 100644 index 0000000..3d090fb --- /dev/null +++ b/src/ProtoBufCodeFormatter/descriptor/helper.go @@ -0,0 +1,274 @@ +// Copyright (c) 2013, Vastech SA (PTY) LTD. All rights reserved. +// http://code.google.com/p/gogoprotobuf +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package descriptor + +import ( + "strings" +) + +func dotToUnderscore(r rune) rune { + if r == '.' { + return '_' + } + return r +} + +func (field *FieldDescriptorProto) WireType() (wire int) { + switch *field.Type { + case FieldDescriptorProto_TYPE_DOUBLE: + return 1 + case FieldDescriptorProto_TYPE_FLOAT: + return 5 + case FieldDescriptorProto_TYPE_INT64: + return 0 + case FieldDescriptorProto_TYPE_UINT64: + return 0 + case FieldDescriptorProto_TYPE_INT32: + return 0 + case FieldDescriptorProto_TYPE_UINT32: + return 0 + case FieldDescriptorProto_TYPE_FIXED64: + return 1 + case FieldDescriptorProto_TYPE_FIXED32: + return 5 + case FieldDescriptorProto_TYPE_BOOL: + return 0 + case FieldDescriptorProto_TYPE_STRING: + return 2 + case FieldDescriptorProto_TYPE_GROUP: + return 2 + case FieldDescriptorProto_TYPE_MESSAGE: + return 2 + case FieldDescriptorProto_TYPE_BYTES: + return 2 + case FieldDescriptorProto_TYPE_ENUM: + return 0 + case FieldDescriptorProto_TYPE_SFIXED32: + return 5 + case FieldDescriptorProto_TYPE_SFIXED64: + return 1 + case FieldDescriptorProto_TYPE_SINT32: + return 0 + case FieldDescriptorProto_TYPE_SINT64: + return 0 + } + panic("unreachable") +} + +func (field *FieldDescriptorProto) GetKeyUint64() (x uint64) { + packed := field.IsPacked() + wireType := field.WireType() + fieldNumber := field.GetNumber() + if packed { + wireType = 2 + } + x = uint64(uint32(fieldNumber)<<3 | uint32(wireType)) + return x +} + +func (field *FieldDescriptorProto) GetKey() []byte { + x := field.GetKeyUint64() + i := 0 + keybuf := make([]byte, 0) + for i = 0; x > 127; i++ { + keybuf = append(keybuf, 0x80|uint8(x&0x7F)) + x >>= 7 + } + keybuf = append(keybuf, uint8(x)) + return keybuf +} + +func (desc *FileDescriptorSet) GetField(packageName, messageName, fieldName string) *FieldDescriptorProto { + msg := desc.GetMessage(packageName, messageName) + if msg == nil { + return nil + } + for _, field := range msg.GetField() { + if field.GetName() == fieldName { + return field + } + } + return nil +} + +func (file *FileDescriptorProto) GetMessage(typeName string) *DescriptorProto { + for _, msg := range file.GetMessageType() { + if msg.GetName() == typeName { + return msg + } + } + return nil +} + +func (desc *FileDescriptorSet) GetMessage(packageName string, typeName string) *DescriptorProto { + for _, file := range desc.GetFile() { + if strings.Map(dotToUnderscore, file.GetPackage()) != strings.Map(dotToUnderscore, packageName) { + continue + } + for _, msg := range file.GetMessageType() { + if msg.GetName() == typeName { + return msg + } + } + for _, msg := range file.GetMessageType() { + for _, nes := range msg.GetNestedType() { + if nes.GetName() == typeName { + return nes + } + if msg.GetName()+"."+nes.GetName() == typeName { + return nes + } + } + } + } + return nil +} + +func (msg *DescriptorProto) IsExtendable() bool { + return len(msg.GetExtensionRange()) > 0 +} + +func (desc *FileDescriptorSet) FindExtension(packageName string, typeName string, fieldName string) (extPackageName string, field *FieldDescriptorProto) { + parent := desc.GetMessage(packageName, typeName) + if parent == nil { + return "", nil + } + if !parent.IsExtendable() { + return "", nil + } + extendee := "." + packageName + "." + typeName + for _, file := range desc.GetFile() { + for _, ext := range file.GetExtension() { + if strings.Map(dotToUnderscore, file.GetPackage()) == strings.Map(dotToUnderscore, packageName) { + if !(ext.GetExtendee() == typeName || ext.GetExtendee() == extendee) { + continue + } + } else { + if ext.GetExtendee() != extendee { + continue + } + } + if ext.GetName() == fieldName { + return file.GetPackage(), ext + } + } + } + return "", nil +} + +func (desc *FileDescriptorSet) FindMessage(packageName string, typeName string, fieldName string) (msgPackageName string, msgName string) { + parent := desc.GetMessage(packageName, typeName) + if parent == nil { + return "", "" + } + field := parent.GetFieldDescriptor(fieldName) + if field == nil { + extPackageName, field := desc.FindExtension(packageName, typeName, fieldName) + if field == nil { + return "", "" + } + packageName = extPackageName + } + typeNames := strings.Split(field.GetTypeName(), ".") + if len(typeNames) == 1 { + msg := desc.GetMessage(packageName, typeName) + if msg == nil { + return "", "" + } + return packageName, msg.GetName() + } + if len(typeNames) > 2 { + for i := 1; i < len(typeNames)-1; i++ { + packageName = strings.Join(typeNames[1:len(typeNames)-i], ".") + typeName = strings.Join(typeNames[len(typeNames)-i:], ".") + msg := desc.GetMessage(packageName, typeName) + if msg != nil { + typeNames := strings.Split(msg.GetName(), ".") + if len(typeNames) == 1 { + return packageName, msg.GetName() + } + return strings.Join(typeNames[1:len(typeNames)-1], "."), typeNames[len(typeNames)-1] + } + } + } + return "", "" +} + +func (msg *DescriptorProto) GetFieldDescriptor(fieldName string) *FieldDescriptorProto { + for _, field := range msg.GetField() { + if field.GetName() == fieldName { + return field + } + } + return nil +} + +func (desc *FileDescriptorSet) GetEnum(packageName string, typeName string) *EnumDescriptorProto { + for _, file := range desc.GetFile() { + if strings.Map(dotToUnderscore, file.GetPackage()) != strings.Map(dotToUnderscore, packageName) { + continue + } + for _, enum := range file.GetEnumType() { + if enum.GetName() == typeName { + return enum + } + } + } + return nil +} + +func (f *FieldDescriptorProto) IsEnum() bool { + return *f.Type == FieldDescriptorProto_TYPE_ENUM +} + +func (f *FieldDescriptorProto) IsMessage() bool { + return *f.Type == FieldDescriptorProto_TYPE_MESSAGE +} + +func (f *FieldDescriptorProto) IsBytes() bool { + return *f.Type == FieldDescriptorProto_TYPE_BYTES +} + +func (f *FieldDescriptorProto) IsRepeated() bool { + return f.Label != nil && *f.Label == FieldDescriptorProto_LABEL_REPEATED +} + +func (f *FieldDescriptorProto) IsString() bool { + return *f.Type == FieldDescriptorProto_TYPE_STRING +} + +func (f *FieldDescriptorProto) IsRequired() bool { + return f.Label != nil && *f.Label == FieldDescriptorProto_LABEL_REQUIRED +} + +func (f *FieldDescriptorProto) IsPacked() bool { + return f.Options != nil && f.GetOptions().GetPacked() +} + +func (m *DescriptorProto) HasExtension() bool { + return len(m.ExtensionRange) > 0 +} diff --git a/src/ProtoBufCodeFormatter/descriptor/wrapperTypes.go b/src/ProtoBufCodeFormatter/descriptor/wrapperTypes.go new file mode 100644 index 0000000..7bcbb6b --- /dev/null +++ b/src/ProtoBufCodeFormatter/descriptor/wrapperTypes.go @@ -0,0 +1,370 @@ +/* + +Copyright (c) 2013, Dirk Brand +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted +provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of + conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, this list of + conditions and the following disclaimer in the documentation and/or other materials provided + with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED +WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS +BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, +OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +*/ + +package descriptor + +import ( + "fmt" + "strconv" + "strings" +) + +const ( + // tag numbers in FileDescriptorProto + packagePath = 2 // package decleration + importPath = 3 // imports + messagePath = 4 // message_type + enumPath = 5 // enum_type + servicePath = 6 // services + extendPath = 7 // extensions + optionsPath = 8 // options + + // tag numbers in DescriptorProto + messageFieldPath = 2 // field + messageMessagePath = 3 // nested_type + messageEnumPath = 4 // enum_type + messageExtensionRangePath = 5 + messageExtensionPath = 6 + messageOptionsPath = 7 + + // tag numbers in EnumDescriptorProto + enumValuePath = 2 // value + enumOptionsPath = 3 + enumValueOptionsPath = 3 + + // tag numbers in ServiceDescriptorProto + methodDescriptorPath = 2 + methodOptionsPath = 4 + serviceOptionsPath = 3 +) + +var currentFile FileDescriptor + +type common struct { + file *FileDescriptorProto // File this object comes from. +} + +type Descriptor struct { + common + *DescriptorProto + parent *Descriptor // The containing message, if any. + nested []*Descriptor // Inner messages, if any. + ext []*FieldDescriptor // Extensions, if any. + field []*FieldDescriptor // Fields, if any. + enum []*EnumDescriptor // Enums, if any. + index int // The index into the container, whether the file or another message. + path string // The SourceCodeInfo path as comma-separated integers. + group bool +} + +type EnumDescriptor struct { + common + *EnumDescriptorProto + parent *Descriptor // The containing message, if any. + path string // The SourceCodeInfo path as comma-separated integers. +} + +type FieldDescriptor struct { + common + *FieldDescriptorProto + parent *Descriptor // The containing message, if any. +} + +type ImportedDescriptor struct { + common +} + +type ServiceDescriptor struct { + common + *ServiceDescriptorProto + path string +} + +type FileDescriptor struct { + *FileDescriptorProto + desc []*Descriptor // All the messages defined in this file. + enum []*EnumDescriptor // All the enums defined in this file. + ext []*FieldDescriptor // All the top-level extensions defined in this file. + serv []*ServiceDescriptor // All the top-level services defined in this file. + imp []*ImportedDescriptor // All types defined in files publicly imported by this file. + + // Comments, stored as a map of path (comma-separated integers) to the comment. + comments map[string]*SourceCodeInfo_Location +} + +func WrapTypes(set *FileDescriptorSet) { + for i, f := range set.File { + // We must wrap the descriptors before we wrap the enums + descs := wrapDescriptors(f) + buildNestedDescriptors(descs) + enums := wrapEnumDescriptors(f, descs) + exts := wrapExtensions(f) + serves := wrapServiceDescriptors(f) + fd := &FileDescriptor{ + FileDescriptorProto: f, + desc: descs, + enum: enums, + ext: exts, + serv: serves, + } + extractComments(fd) + allFiles[i] = fd + } +} + +// Scan the descriptors in this file. For each one, build the slice of nested descriptors +func buildNestedDescriptors(descs []*Descriptor) { + for _, desc := range descs { + if len(desc.NestedType) != 0 { + desc.nested = make([]*Descriptor, len(desc.NestedType)) + n := 0 + for _, nest := range descs { + if nest.parent == desc { + desc.nested[n] = nest + n++ + } + } + } + } +} + +func newDescriptor(desc *DescriptorProto, parent *Descriptor, file *FileDescriptorProto, index int) *Descriptor { + d := &Descriptor{ + common: common{file}, + DescriptorProto: desc, + parent: parent, + index: index, + } + if parent == nil { + d.path = fmt.Sprintf("%d,%d", messagePath, index) + } else { + d.path = fmt.Sprintf("%s,%d,%d", parent.path, messageMessagePath, index) + } + + d.ext = make([]*FieldDescriptor, len(desc.Extension)) + for i, field := range desc.Extension { + d.ext[i] = &FieldDescriptor{common{file}, field, d} + } + + d.field = make([]*FieldDescriptor, len(desc.Field)) + for i, field := range desc.Field { + d.field[i] = &FieldDescriptor{common{file}, field, d} + } + + // Enums within messages. Enums within embedded messages appear in the outer-most message. + d.enum = make([]*EnumDescriptor, len(desc.EnumType)) + for i, enums := range desc.GetEnumType() { + d.enum[i] = newEnumDescriptor(enums, d, d.common.file, i) + } + + return d +} + +// Return a slice of all the Descriptors defined within this file +func wrapDescriptors(file *FileDescriptorProto) []*Descriptor { + sl := make([]*Descriptor, 0, len(file.MessageType)+10) + for i, desc := range file.MessageType { + sl = wrapThisDescriptor(sl, desc, nil, file, i) + } + return sl +} + +func wrapThisDescriptor(sl []*Descriptor, desc *DescriptorProto, parent *Descriptor, file *FileDescriptorProto, index int) []*Descriptor { + sl = append(sl, newDescriptor(desc, parent, file, index)) + me := sl[len(sl)-1] + for i, nested := range desc.NestedType { + sl = wrapThisDescriptor(sl, nested, me, file, i) + } + return sl +} + +// Construct the EnumDescriptor +func newEnumDescriptor(desc *EnumDescriptorProto, parent *Descriptor, file *FileDescriptorProto, index int) *EnumDescriptor { + ed := &EnumDescriptor{ + common: common{file}, + EnumDescriptorProto: desc, + parent: parent, + } + if parent == nil { + ed.path = fmt.Sprintf("%d,%d", enumPath, index) + } else { + ed.path = fmt.Sprintf("%s,%d,%d", parent.path, messageEnumPath, index) + } + return ed +} + +// Return a slice of all the EnumDescriptors defined within this file +func wrapEnumDescriptors(file *FileDescriptorProto, descs []*Descriptor) []*EnumDescriptor { + sl := make([]*EnumDescriptor, 0, len(file.EnumType)+10) + // Top-level enums. + for i, enum := range file.EnumType { + sl = append(sl, newEnumDescriptor(enum, nil, file, i)) + } + + return sl +} + +// Return a slice of all the top-level ExtensionDescriptors defined within this file. +func wrapExtensions(file *FileDescriptorProto) []*FieldDescriptor { + sl := make([]*FieldDescriptor, len(file.Extension)) + for i, field := range file.Extension { + sl[i] = &FieldDescriptor{common{file}, field, nil} + } + return sl +} + +// Construct the EnumDescriptor +func newServiceDescriptor(serv *ServiceDescriptorProto, file *FileDescriptorProto, index int) *ServiceDescriptor { + sd := &ServiceDescriptor{ + common: common{file}, + ServiceDescriptorProto: serv, + } + sd.path = fmt.Sprintf("%d,%d", servicePath, index) + return sd +} + +// Return a slice of all the top-level ExtensionDescriptors defined within this file. +func wrapServiceDescriptors(file *FileDescriptorProto) []*ServiceDescriptor { + sl := make([]*ServiceDescriptor, 0, len(file.Service)+10) + for i, serve := range file.Service { + sl = append(sl, newServiceDescriptor(serve, file, i)) + } + return sl +} + +func extractComments(file *FileDescriptor) { + file.comments = make(map[string]*SourceCodeInfo_Location) + for _, loc := range file.GetSourceCodeInfo().GetLocation() { + if loc.LeadingComments == nil && loc.TrailingComments == nil { + continue + } + //fmt.Println(loc.GoString()) + var p []string + for _, n := range loc.Path { + p = append(p, strconv.Itoa(int(n))) + } + key := strings.Join(p, ",") + + // Comment already exists + if _, ok := file.comments[key]; ok { + + // While comment exists + i := 1000 + _, ok2 := file.comments[key+","+fmt.Sprintf("%d", i)] + for ok2 { + _, ok2 = file.comments[key+","+fmt.Sprintf("%d", i)] + i += 1000 + } + // Assign a new comment + file.comments[key+","+fmt.Sprintf("%d", i)] = loc + //fmt.Println(key + "," + fmt.Sprintf("%d", i)) + } else { + file.comments[key] = loc + //fmt.Println(key) + } + + } +} + +// PrintComments prints any comments from the source .proto file. +// The path is a comma-separated list of integers. +// See descriptor.proto for its format. +func LeadingComments(path string, depth int) string { + if loc, ok := currentFile.comments[path]; ok && loc.LeadingComments != nil { + text := strings.TrimSuffix(loc.GetLeadingComments(), "\n") + var s []string + strCol := strings.Split(text, "\n") + if len(strCol) == 1 { + // Single line comments + s = append(s, getIndentation(depth)) + s = append(s, "// ") + s = append(s, strings.TrimSpace(strCol[0])) + s = append(s, "\n") + } else { + // Multi-line comments + if strings.Contains(text, "/*") || strings.Contains(text, "*/") { + // Block comments cannot nest + for _, line := range strCol { + s = append(s, getIndentation(depth)) + s = append(s, "// ") + s = append(s, strings.TrimSpace(line)) + s = append(s, "\n") + } + } else { + s = append(s, getIndentation(depth)) + s = append(s, "/* ") + s = append(s, strings.TrimSpace(strCol[0])) + s = append(s, "\n ") + for i := 1; i < len(strCol)-1; i += 1 { + line := strCol[i] + s = append(s, getIndentation(depth+1)) + s = append(s, strings.TrimSpace(line)) + s = append(s, "\n ") + } + s = append(s, getIndentation(depth+1)) + s = append(s, strings.TrimSpace(strCol[len(strCol)-1])) + s = append(s, " */\n") + } + + } + return strings.Join(s, "") + + } + + return "" +} + +func TrailingComments(path string, depth int) string { + if loc, ok := currentFile.comments[path]; ok && loc.TrailingComments != nil { + text := strings.TrimSuffix(loc.GetTrailingComments(), "\n") + var s []string + strCol := strings.Split(text, "\n") + if len(strCol) == 1 { + s = append(s, getIndentation(depth)) + s = append(s, "// ") + s = append(s, strings.TrimSuffix(strings.TrimPrefix(strCol[0], " "), " ")) + s = append(s, "\n") + } else { + s = append(s, getIndentation(depth)) + s = append(s, "/* ") + s = append(s, strings.TrimSuffix(strings.TrimPrefix(strCol[0], " "), " ")) + s = append(s, "\n ") + for i := 1; i < len(strCol)-1; i += 1 { + line := strCol[i] + s = append(s, getIndentation(depth+1)) + s = append(s, strings.TrimSuffix(strings.TrimPrefix(line, " "), " ")) + s = append(s, "\n ") + } + s = append(s, getIndentation(depth+1)) + s = append(s, strings.TrimSuffix(strings.TrimPrefix(strCol[len(strCol)-1], " "), " ")) + s = append(s, " */\n") + + } + return strings.Join(s, "") + + } + + return "" +} diff --git a/src/ProtoBufCodeFormatter/main.go b/src/ProtoBufCodeFormatter/main.go new file mode 100644 index 0000000..cf40aaa --- /dev/null +++ b/src/ProtoBufCodeFormatter/main.go @@ -0,0 +1,33 @@ +package main + +import ( + parser "./parser" + "fmt" + "os" + "path" + "path/filepath" + "strings" +) + +func main() { + + testFile := os.Args[1] + var paths []string + if len(os.Args) > 2 { + paths = filepath.SplitList(os.Args[2]) + } + os.Stdout.WriteString("paths joined: " + strings.Join(paths, ":") + "\n") + os.Stdout.WriteString("filename: " + testFile + "\n") + + d, err := parser.ParseFile(testFile, paths) + if err != nil { + fmt.Println(err) + } else { + fo, _ := os.Create(testFile) + + formattedFile := d.Fmt(path.Base(testFile)) + + fo.WriteString(formattedFile) + fo.Close() + } +} diff --git a/src/ProtoBufCodeFormatter/parser/parse.go b/src/ProtoBufCodeFormatter/parser/parse.go new file mode 100644 index 0000000..0584532 --- /dev/null +++ b/src/ProtoBufCodeFormatter/parser/parse.go @@ -0,0 +1,71 @@ +// Extensions for Protocol Buffers to create more go like structures. +// +// Copyright (c) 2013, Vastech SA (PTY) LTD. All rights reserved. +// http://code.google.com/p/gogoprotobuf/gogoproto +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +package parser + +import ( + "os/exec" + "strings" +) +import ".././descriptor" +import "code.google.com/p/gogoprotobuf/proto" + +type errCmd struct { + output []byte + err error +} + +func (this *errCmd) Error() string { + return this.err.Error() + ":" + string(this.output) +} + +func ParseFile(filename string, paths []string) (*descriptor.FileDescriptorSet, error) { + return parseFile(filename, true, true, paths) +} + +func parseFile(filename string, includeSourceInfo bool, includeImports bool, paths []string) (*descriptor.FileDescriptorSet, error) { + args := []string{"--proto_path=" + strings.Join(paths, ":")} + if includeSourceInfo { + args = append(args, "--include_source_info") + } + if includeImports { + args = append(args, "--include_imports") + } + args = append(args, "--descriptor_set_out=/dev/stdout") + args = append(args, filename) + cmd := exec.Command("protoc", args...) + data, err := cmd.CombinedOutput() + if err != nil { + return nil, &errCmd{data, err} + } + fileDesc := &descriptor.FileDescriptorSet{} + if err := proto.Unmarshal(data, fileDesc); err != nil { + return nil, err + } + return fileDesc, nil +}