// Package uid provides unique identifiers
package uid import ( ) type Context interface { Abs(s string) (string, error) Getenv(key string) string LookupEnv(key string) (string, bool) } // UidF TODO experimental func (, string, ...string) func( string, Context) (*url.URL, error) { return func( string, Context) (*url.URL, error) { if := len(); %2 != 0 { return nil, fmt.Errorf("invalid amount of arguments [Uid]: %v", ) } := &url.URL{ Scheme: , Host: url.PathEscape(), Path: PathEscape(), } if len() > 0 { := .Query() for := 0; < len(); += 2 { if [+1] != "" { // implicitly skip empty values .Set([], [+1]) } } .RawQuery = .Encode() } return , nil } } // Command creates a uid for given command. func ( *cobra.Command) *url.URL { := []string{.Name()} for := .Parent(); != nil; = .Parent() { = append(, url.PathEscape(.Name())) } reverse() // TODO slices.Reverse return &url.URL{ Scheme: "cmd", Host: [0], Path: strings.Join([1:], "/"), } } // reverse reverses the elements of the slice in place. func reverse( []string) { for , := 0, len()-1; < ; , = +1, -1 { [], [] = [], [] } } var mLocalFlags sync.Mutex // Flag creates a uid for given flag. func ( *cobra.Command, *pflagfork.Flag) *url.URL { mLocalFlags.Lock() defer mLocalFlags.Unlock() return flagRecursive(, ) } func flagRecursive( *cobra.Command, *pflagfork.Flag) *url.URL { _ = .LocalFlags() // Force flag merge; not thread-safe internally if .LocalFlags().Lookup(.Name) == nil && .HasParent() { return (.Parent(), ) } := Command() := .Query() .Set("flag", .Name) .RawQuery = .Encode() return } // callerModuleContains checks if any caller's source path contains the given substring. func callerModuleContains( string) bool { := make([]uintptr, 32) := runtime.Callers(0, ) for , := range [:] { if := runtime.FuncForPC(); != nil { if strings.Contains(.Name(), ) { return true } } } return false } // Executable returns the name of the executable. func () string { , := os.Executable() if != nil { return "echo" // safe fallback that should never happen } // windows: strip .exe so the name matches the (extension-less) command name := strings.TrimSuffix(filepath.Base(), ".exe") switch { case "cmd.test": if callerModuleContains("example-multi") { return "example-multi" // for `go test -v ./...` in example-multi } return "example" // for `go test -v ./...` in example case "ld-musl-x86_64.so.1": return filepath.Base(os.Args[0]) // alpine container workaround (gcompat) default: return } } // Map maps values to uids to simplify testing. // // Map( // "go.mod", "file://path/to/go.mod", // "go.sum", "file://path/to/go.sum", // ) func ( ...string) func( string) (*url.URL, error) { return func( string) (*url.URL, error) { for := 0; < len(); += 2 { if [] == { return url.Parse([+1]) } } return &url.URL{}, nil } }