Andrew Gerrand | a91ae26 | 2015-05-21 12:09:51 +1000 | [diff] [blame] | 1 | // Copyright 2015 The Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | // Package envutil provides utilities for working with environment variables. |
| 6 | package envutil |
| 7 | |
| 8 | import "strings" |
| 9 | |
| 10 | // Dedup returns a copy of env with any duplicates removed, in favor of |
| 11 | // later values. |
| 12 | // Items are expected to be on the normal environment "key=value" form. |
| 13 | // If caseInsensitive is true, the case of keys is ignored. |
| 14 | func Dedup(caseInsensitive bool, env []string) []string { |
| 15 | out := make([]string, 0, len(env)) |
| 16 | saw := map[string]int{} // to index in the array |
| 17 | for _, kv := range env { |
| 18 | eq := strings.Index(kv, "=") |
| 19 | if eq < 1 { |
| 20 | out = append(out, kv) |
| 21 | continue |
| 22 | } |
| 23 | k := kv[:eq] |
| 24 | if caseInsensitive { |
| 25 | k = strings.ToLower(k) |
| 26 | } |
| 27 | if dupIdx, isDup := saw[k]; isDup { |
| 28 | out[dupIdx] = kv |
| 29 | } else { |
| 30 | saw[k] = len(out) |
| 31 | out = append(out, kv) |
| 32 | } |
| 33 | } |
| 34 | return out |
| 35 | } |