blob: 067ff949a0ff2389af2db872d618ecf80f887b18 [file] [log] [blame]
Andrew Gerranda91ae262015-05-21 12:09:51 +10001// 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.
6package envutil
7
8import "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.
14func 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}