~nskaggs/+junk/xenial-test

« back to all changes in this revision

Viewing changes to src/github.com/juju/cmd/aliasfile.go

  • Committer: Nicholas Skaggs
  • Date: 2016-10-24 20:56:05 UTC
  • Revision ID: nicholas.skaggs@canonical.com-20161024205605-z8lta0uvuhtxwzwl
Initi with beta15

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
// Copyright 2015 Canonical Ltd.
 
2
// Licensed under the LGPLv3, see LICENSE file for details.
 
3
 
 
4
package cmd
 
5
 
 
6
import (
 
7
        "io/ioutil"
 
8
        "strings"
 
9
)
 
10
 
 
11
// ParseAliasFile will read the specified file and convert
 
12
// the content to a map of names to the command line arguments
 
13
// they relate to.  The function will always return a valid map, even
 
14
// if it is empty.
 
15
func ParseAliasFile(aliasFilename string) map[string][]string {
 
16
        result := map[string][]string{}
 
17
        if aliasFilename == "" {
 
18
                return result
 
19
        }
 
20
 
 
21
        content, err := ioutil.ReadFile(aliasFilename)
 
22
        if err != nil {
 
23
                logger.Tracef("unable to read alias file %q: %s", aliasFilename, err)
 
24
                return result
 
25
        }
 
26
 
 
27
        lines := strings.Split(string(content), "\n")
 
28
        for i, line := range lines {
 
29
                line = strings.TrimSpace(line)
 
30
                if line == "" || strings.HasPrefix(line, "#") {
 
31
                        // skip blank lines and comments
 
32
                        continue
 
33
                }
 
34
                parts := strings.SplitN(line, "=", 2)
 
35
                if len(parts) != 2 {
 
36
                        logger.Warningf("line %d bad in alias file: %s", i+1, line)
 
37
                        continue
 
38
                }
 
39
                name, value := strings.TrimSpace(parts[0]), strings.TrimSpace(parts[1])
 
40
                if name == "" {
 
41
                        logger.Warningf("line %d missing alias name in alias file: %s", i+1, line)
 
42
                        continue
 
43
                }
 
44
                if value == "" {
 
45
                        logger.Warningf("line %d missing alias value in alias file: %s", i+1, line)
 
46
                        continue
 
47
                }
 
48
 
 
49
                logger.Tracef("setting alias %q=%q", name, value)
 
50
                result[name] = strings.Fields(value)
 
51
        }
 
52
        return result
 
53
}