go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/cv/internal/gerrit/metadata/metadata.go (about)

     1  // Copyright 2021 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  // Package metadata can extract metadata from Gerrit CLs.
    16  package metadata
    17  
    18  import (
    19  	"sort"
    20  
    21  	"go.chromium.org/luci/common/git/footer"
    22  
    23  	"go.chromium.org/luci/cv/internal/changelist"
    24  )
    25  
    26  // Extract extracts CL metadata from Gerrit CL description.
    27  //
    28  // Returns key-value pairs sorted by key first, while values are ordered from
    29  // bottom to top of the CL description.
    30  func Extract(clDescription string) []*changelist.StringPair {
    31  	kvs := footer.ParseMessage(clDescription)
    32  	for k, vs := range footer.ParseLegacyMetadata(clDescription) {
    33  		kvs[k] = append(kvs[k], vs...)
    34  	}
    35  	keys := make([]string, len(kvs))
    36  	for k := range kvs {
    37  		keys = append(keys, k)
    38  	}
    39  	sort.Strings(keys)
    40  	// Each key has at least one value.
    41  	out := make([]*changelist.StringPair, 0, len(kvs))
    42  	for _, k := range keys {
    43  		for _, v := range kvs[k] {
    44  			out = append(out, &changelist.StringPair{Key: k, Value: v})
    45  		}
    46  	}
    47  	return out
    48  }