...

Source file src/github.com/distribution/reference/sort.go

Documentation: github.com/distribution/reference

     1  /*
     2     Copyright The containerd 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 reference
    18  
    19  import (
    20  	"sort"
    21  )
    22  
    23  // Sort sorts string references preferring higher information references.
    24  //
    25  // The precedence is as follows:
    26  //
    27  //  1. [Named] + [Tagged] + [Digested] (e.g., "docker.io/library/busybox:latest@sha256:<digest>")
    28  //  2. [Named] + [Tagged]              (e.g., "docker.io/library/busybox:latest")
    29  //  3. [Named] + [Digested]            (e.g., "docker.io/library/busybo@sha256:<digest>")
    30  //  4. [Named]                         (e.g., "docker.io/library/busybox")
    31  //  5. [Digested]                      (e.g., "docker.io@sha256:<digest>")
    32  //  6. Parse error
    33  func Sort(references []string) []string {
    34  	var prefs []Reference
    35  	var bad []string
    36  
    37  	for _, ref := range references {
    38  		pref, err := ParseAnyReference(ref)
    39  		if err != nil {
    40  			bad = append(bad, ref)
    41  		} else {
    42  			prefs = append(prefs, pref)
    43  		}
    44  	}
    45  	sort.Slice(prefs, func(a, b int) bool {
    46  		ar := refRank(prefs[a])
    47  		br := refRank(prefs[b])
    48  		if ar == br {
    49  			return prefs[a].String() < prefs[b].String()
    50  		}
    51  		return ar < br
    52  	})
    53  	sort.Strings(bad)
    54  	var refs []string
    55  	for _, pref := range prefs {
    56  		refs = append(refs, pref.String())
    57  	}
    58  	return append(refs, bad...)
    59  }
    60  
    61  func refRank(ref Reference) uint8 {
    62  	if _, ok := ref.(Named); ok {
    63  		if _, ok = ref.(Tagged); ok {
    64  			if _, ok = ref.(Digested); ok {
    65  				return 1
    66  			}
    67  			return 2
    68  		}
    69  		if _, ok = ref.(Digested); ok {
    70  			return 3
    71  		}
    72  		return 4
    73  	}
    74  	return 5
    75  }
    76  

View as plain text