github.com/sercand/please@v13.4.0+incompatible/src/fs/sort.go (about)

     1  package fs
     2  
     3  import (
     4  	"sort"
     5  	"strings"
     6  )
     7  
     8  // SortPaths sorts a list of filepaths in lexicographic order by component
     9  // (i.e. so all files in a directory sort after all subdirectories).
    10  func SortPaths(files []string) []string {
    11  	sort.Slice(files, func(i, j int) bool {
    12  		si, sj := commonPrefix(strings.Split(files[i], "/"), strings.Split(files[j], "/"))
    13  		if len(si) == 1 && len(sj) > 1 {
    14  			return false // si is a leaf and sj is not
    15  		} else if len(sj) == 1 && len(si) > 1 {
    16  			return true // sj is a leaf and si is not
    17  		} else if len(si) == 0 || len(sj) == 0 {
    18  			return len(si) < len(sj) // one or the other is empty.
    19  		}
    20  		return si[0] < sj[0]
    21  	})
    22  	return files
    23  }
    24  
    25  // commonPrefix extracts common directory components from two slices.
    26  func commonPrefix(a, b []string) ([]string, []string) {
    27  	for i, x := range a {
    28  		if i >= len(b) {
    29  			return a[i:], nil
    30  		} else if x != b[i] {
    31  			return a[i:], b[i:]
    32  		}
    33  	}
    34  	// If we get here a was a prefix of b
    35  	return nil, b[len(a):]
    36  }