github.com/rothwerx/packer@v0.9.0/post-processor/atlas/util.go (about)

     1  package atlas
     2  
     3  import (
     4  	"math"
     5  	"path/filepath"
     6  	"strings"
     7  )
     8  
     9  // longestCommonPrefix finds the longest common prefix for all the strings
    10  // given as an argument, or returns the empty string if a prefix can't be
    11  // found.
    12  //
    13  // This function just uses brute force instead of a more optimized algorithm.
    14  func longestCommonPrefix(vs []string) string {
    15  	var length int64
    16  	// Find the shortest string
    17  	var shortest string
    18  	length = math.MaxUint32
    19  	for _, v := range vs {
    20  		if int64(len(v)) < length {
    21  			shortest = v
    22  			length = int64(len(v))
    23  		}
    24  	}
    25  
    26  	// Now go through and find a prefix to all the strings using this
    27  	// short string, which itself must contain the prefix.
    28  	for i := len(shortest); i > 0; i-- {
    29  		// We only care about prefixes with path seps
    30  		if shortest[i-1] != filepath.Separator {
    31  			continue
    32  		}
    33  
    34  		bad := false
    35  		prefix := shortest[0:i]
    36  		for _, v := range vs {
    37  			if !strings.HasPrefix(v, prefix) {
    38  				bad = true
    39  				break
    40  			}
    41  		}
    42  
    43  		if !bad {
    44  			return prefix
    45  		}
    46  	}
    47  
    48  	return ""
    49  }