go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/cv/internal/gerrit/whom.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 gerrit
    16  
    17  import (
    18  	"fmt"
    19  	"sort"
    20  
    21  	gerritpb "go.chromium.org/luci/common/proto/gerrit"
    22  )
    23  
    24  // Whoms is a collection of `Whom`s.
    25  type Whoms []Whom
    26  
    27  // Dedupe removes duplicates and sorts the whoms in-place.
    28  func (whoms Whoms) Dedupe() {
    29  	if len(whoms) <= 1 {
    30  		return
    31  	}
    32  	whomMap := make(map[Whom]struct{}, len(whoms))
    33  	for _, w := range whoms {
    34  		whomMap[w] = struct{}{}
    35  	}
    36  	whoms = whoms[:0]
    37  	for w := range whomMap {
    38  		whoms = append(whoms, w)
    39  	}
    40  	sort.Slice(whoms, func(i, j int) bool {
    41  		return whoms[i] < whoms[j]
    42  	})
    43  }
    44  
    45  // ToAccountIDsSorted translates whom to actual Gerrit account ids in a CL.
    46  func (whoms Whoms) ToAccountIDsSorted(ci *gerritpb.ChangeInfo) []int64 {
    47  	accountSet := make(map[int64]struct{})
    48  	for _, whom := range whoms {
    49  		switch whom {
    50  		case Whom_OWNER:
    51  			accountSet[ci.GetOwner().GetAccountId()] = struct{}{}
    52  		case Whom_REVIEWERS:
    53  			for _, reviewer := range ci.GetReviewers().GetReviewers() {
    54  				accountSet[reviewer.GetAccountId()] = struct{}{}
    55  			}
    56  		case Whom_CQ_VOTERS:
    57  			for _, vote := range ci.GetLabels()["Commit-Queue"].GetAll() {
    58  				if vote.GetValue() > 0 {
    59  					accountSet[vote.GetUser().GetAccountId()] = struct{}{}
    60  				}
    61  			}
    62  		case Whom_PS_UPLOADER:
    63  			accountSet[ci.GetRevisions()[ci.GetCurrentRevision()].GetUploader().GetAccountId()] = struct{}{}
    64  		default:
    65  			panic(fmt.Sprintf("unknown whom: %s", whom))
    66  		}
    67  	}
    68  	ret := make([]int64, 0, len(accountSet))
    69  	for acct := range accountSet {
    70  		ret = append(ret, acct)
    71  	}
    72  	sort.Slice(ret, func(i, j int) bool { return ret[i] < ret[j] })
    73  	return ret
    74  }