github.com/jhump/protocompile@v0.0.0-20221021153901-4f6f732835e8/internal/options.go (about)

     1  package internal
     2  
     3  import (
     4  	"google.golang.org/protobuf/types/descriptorpb"
     5  
     6  	"github.com/jhump/protocompile/ast"
     7  	"github.com/jhump/protocompile/reporter"
     8  )
     9  
    10  type hasOptionNode interface {
    11  	OptionNode(part *descriptorpb.UninterpretedOption) ast.OptionDeclNode
    12  	FileNode() ast.FileDeclNode // needed in order to query for NodeInfo
    13  }
    14  
    15  func FindOption(res hasOptionNode, handler *reporter.Handler, scope string, opts []*descriptorpb.UninterpretedOption, name string) (int, error) {
    16  	found := -1
    17  	for i, opt := range opts {
    18  		if len(opt.Name) != 1 {
    19  			continue
    20  		}
    21  		if opt.Name[0].GetIsExtension() || opt.Name[0].GetNamePart() != name {
    22  			continue
    23  		}
    24  		if found >= 0 {
    25  			optNode := res.OptionNode(opt)
    26  			fn := res.FileNode()
    27  			node := optNode.GetName()
    28  			nodeInfo := fn.NodeInfo(node)
    29  			return -1, handler.HandleErrorf(nodeInfo.Start(), "%s: option %s cannot be defined more than once", scope, name)
    30  		}
    31  		found = i
    32  	}
    33  	return found, nil
    34  }
    35  
    36  func RemoveOption(uo []*descriptorpb.UninterpretedOption, indexToRemove int) []*descriptorpb.UninterpretedOption {
    37  	if indexToRemove == 0 {
    38  		return uo[1:]
    39  	} else if indexToRemove == len(uo)-1 {
    40  		return uo[:len(uo)-1]
    41  	} else {
    42  		return append(uo[:indexToRemove], uo[indexToRemove+1:]...)
    43  	}
    44  }