envutil: move dedupEnv function from gomote to new package

Change-Id: Ib6856cdfced65e1bec818ac3a80d03a5269e2bd0
Reviewed-on: https://go-review.googlesource.com/10301
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
diff --git a/envutil/dedup.go b/envutil/dedup.go
new file mode 100644
index 0000000..067ff94
--- /dev/null
+++ b/envutil/dedup.go
@@ -0,0 +1,35 @@
+// Copyright 2015 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+// Package envutil provides utilities for working with environment variables.
+package envutil
+
+import "strings"
+
+// Dedup returns a copy of env with any duplicates removed, in favor of
+// later values.
+// Items are expected to be on the normal environment "key=value" form.
+// If caseInsensitive is true, the case of keys is ignored.
+func Dedup(caseInsensitive bool, env []string) []string {
+	out := make([]string, 0, len(env))
+	saw := map[string]int{} // to index in the array
+	for _, kv := range env {
+		eq := strings.Index(kv, "=")
+		if eq < 1 {
+			out = append(out, kv)
+			continue
+		}
+		k := kv[:eq]
+		if caseInsensitive {
+			k = strings.ToLower(k)
+		}
+		if dupIdx, isDup := saw[k]; isDup {
+			out[dupIdx] = kv
+		} else {
+			saw[k] = len(out)
+			out = append(out, kv)
+		}
+	}
+	return out
+}