github.com/konsorten/ktn-build-info@v1.0.11/ver/update_ordering.go (about)

     1  package ver
     2  
     3  import (
     4  	"sort"
     5  	"strings"
     6  )
     7  
     8  type orderedUpdate struct {
     9  	Path   string
    10  	Update string
    11  }
    12  
    13  func (s *orderedUpdate) weight() int {
    14  	// no action?
    15  	if !strings.HasPrefix(s.Update, "$") {
    16  		return 200
    17  	}
    18  
    19  	// delete actions come first
    20  	if strings.HasPrefix(s.Update, "$delete") {
    21  		return 110
    22  	}
    23  
    24  	// create actions
    25  	if strings.HasPrefix(s.Update, "$create") {
    26  		return 120
    27  	}
    28  
    29  	// ensure actions
    30  	if strings.HasPrefix(s.Update, "$ensure") {
    31  		return 130
    32  	}
    33  
    34  	// ordinary action
    35  	return 199
    36  }
    37  
    38  type orderedUpdates []orderedUpdate
    39  
    40  func (s orderedUpdates) Len() int {
    41  	return len(s)
    42  }
    43  
    44  func (s orderedUpdates) Less(i, j int) bool {
    45  	a := &s[i]
    46  	b := &s[j]
    47  
    48  	wa := a.weight()
    49  	wb := b.weight()
    50  
    51  	if wa != wb {
    52  		return wa < wb
    53  	}
    54  
    55  	return a.Path < b.Path
    56  }
    57  
    58  func (s orderedUpdates) Swap(i, j int) {
    59  	s[i], s[j] = s[j], s[i]
    60  }
    61  
    62  func (s orderedUpdates) Sort() {
    63  	sort.Sort(s)
    64  }
    65  
    66  func orderUpdates(updates UpdateActions) orderedUpdates {
    67  	var ret = make(orderedUpdates, len(updates))
    68  	index := 0
    69  
    70  	for path, update := range updates {
    71  		ret[index] = orderedUpdate{path, update}
    72  
    73  		index++
    74  	}
    75  
    76  	// sort the entries
    77  	ret.Sort()
    78  
    79  	return ret
    80  }