github.com/GoogleCloudPlatform/testgrid@v0.0.174/config/fields.go (about)

     1  /*
     2  Copyright 2021 The TestGrid Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package config
    18  
    19  import (
    20  	"fmt"
    21  
    22  	configpb "github.com/GoogleCloudPlatform/testgrid/pb/config"
    23  	"google.golang.org/protobuf/reflect/protoreflect"
    24  )
    25  
    26  type protoPath struct {
    27  	name  string
    28  	count map[string]int64
    29  }
    30  
    31  func (pp protoPath) countRecursive(fd protoreflect.FieldDescriptor, val protoreflect.Value) bool {
    32  	if pp.name != "" {
    33  		pp.name = fmt.Sprintf("%s.%s", pp.name, fd.Name())
    34  	} else {
    35  		pp.name = string(fd.Name())
    36  	}
    37  
    38  	if fd.Kind() == protoreflect.MessageKind {
    39  		if fd.IsList() {
    40  			for i := 0; i < val.List().Len(); i++ {
    41  				val.List().Get(i).Message().Range(pp.countRecursive)
    42  			}
    43  			return true
    44  		}
    45  		// Does not support maps of messages; there aren't any in config.proto
    46  		val.Message().Range(pp.countRecursive)
    47  		return true
    48  	}
    49  	pp.count[pp.name]++
    50  	return true
    51  }
    52  
    53  // Fields returns counts of all of the primitive fields in this configuration
    54  //
    55  // Field names in the map are qualified with where they are nested; this is not the same as a message's "FullName"
    56  // Ex: A dashboard tab's name is "dashboards.dashboard_tab.name"
    57  func Fields(cfg *configpb.Configuration) map[string]int64 {
    58  	pp := protoPath{
    59  		count: map[string]int64{},
    60  	}
    61  
    62  	cfg.ProtoReflect().Range(pp.countRecursive)
    63  	return pp.count
    64  }