Skip to content

Commit 1ba1138

Browse files
author
Guillaume J. Charmes
committed
Refactor Opts
1 parent 8b99e4e commit 1ba1138

6 files changed

Lines changed: 178 additions & 115 deletions

File tree

buildfile.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -241,7 +241,7 @@ func (b *buildFile) CmdVolume(args string) error {
241241
volume = []string{args}
242242
}
243243
if b.config.Volumes == nil {
244-
b.config.Volumes = PathOpts{}
244+
b.config.Volumes = map[string]struct{}{}
245245
}
246246
for _, v := range volume {
247247
b.config.Volumes[v] = struct{}{}

commands.go

Lines changed: 28 additions & 89 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ import (
2323
"os"
2424
"os/signal"
2525
"path"
26-
"path/filepath"
2726
"reflect"
2827
"regexp"
2928
"runtime"
@@ -1635,54 +1634,6 @@ func (cli *DockerCli) CmdSearch(args ...string) error {
16351634
// Ports type - Used to parse multiple -p flags
16361635
type ports []int
16371636

1638-
// AttachOpts stores arguments to 'docker run -a', eg. which streams to attach to
1639-
type AttachOpts map[string]bool
1640-
1641-
func (opts AttachOpts) String() string { return fmt.Sprintf("%v", map[string]bool(opts)) }
1642-
func (opts AttachOpts) Set(val string) error {
1643-
if val != "stdin" && val != "stdout" && val != "stderr" {
1644-
return fmt.Errorf("Unsupported stream name: %s", val)
1645-
}
1646-
opts[val] = true
1647-
return nil
1648-
}
1649-
1650-
// LinkOpts stores arguments to `docker run -link`
1651-
type LinkOpts []string
1652-
1653-
func (link *LinkOpts) String() string { return fmt.Sprintf("%v", []string(*link)) }
1654-
func (link *LinkOpts) Set(val string) error {
1655-
if _, err := parseLink(val); err != nil {
1656-
return err
1657-
}
1658-
*link = append(*link, val)
1659-
return nil
1660-
}
1661-
1662-
// PathOpts stores a unique set of absolute paths
1663-
type PathOpts map[string]struct{}
1664-
1665-
func (opts PathOpts) String() string { return fmt.Sprintf("%v", map[string]struct{}(opts)) }
1666-
func (opts PathOpts) Set(val string) error {
1667-
var containerPath string
1668-
1669-
splited := strings.SplitN(val, ":", 2)
1670-
if len(splited) == 1 {
1671-
containerPath = splited[0]
1672-
val = filepath.Clean(splited[0])
1673-
} else {
1674-
containerPath = splited[1]
1675-
val = fmt.Sprintf("%s:%s", splited[0], filepath.Clean(splited[1]))
1676-
}
1677-
1678-
if !filepath.IsAbs(containerPath) {
1679-
utils.Debugf("%s is not an absolute path", containerPath)
1680-
return fmt.Errorf("%s is not an absolute path", containerPath)
1681-
}
1682-
opts[val] = struct{}{}
1683-
return nil
1684-
}
1685-
16861637
func (cli *DockerCli) CmdTag(args ...string) error {
16871638
cmd := cli.Subcmd("tag", "[OPTIONS] IMAGE REPOSITORY[:TAG]", "Tag an image into a repository")
16881639
force := cmd.Bool("f", false, "Force")
@@ -1728,16 +1679,16 @@ func ParseRun(args []string, capabilities *Capabilities) (*Config, *HostConfig,
17281679
func parseRun(cmd *flag.FlagSet, args []string, capabilities *Capabilities) (*Config, *HostConfig, *flag.FlagSet, error) {
17291680
var (
17301681
// FIXME: use utils.ListOpts for attach and volumes?
1731-
flAttach = AttachOpts{}
1732-
flVolumes = PathOpts{}
1733-
flLinks = LinkOpts{}
1682+
flAttach = NewListOpts(ValidateAttach)
1683+
flVolumes = NewListOpts(ValidatePath)
1684+
flLinks = NewListOpts(ValidateLink)
1685+
flEnv = NewListOpts(ValidateEnv)
17341686

1735-
flPublish utils.ListOpts
1736-
flExpose utils.ListOpts
1737-
flEnv utils.ListOpts
1738-
flDns utils.ListOpts
1739-
flVolumesFrom utils.ListOpts
1740-
flLxcOpts utils.ListOpts
1687+
flPublish ListOpts
1688+
flExpose ListOpts
1689+
flDns ListOpts
1690+
flVolumesFrom ListOpts
1691+
flLxcOpts ListOpts
17411692

17421693
flAutoRemove = cmd.Bool("rm", false, "Automatically remove the container when it exits (incompatible with -d)")
17431694
flDetach = cmd.Bool("d", false, "Detached mode: Run container in the background, print new container id")
@@ -1759,13 +1710,13 @@ func parseRun(cmd *flag.FlagSet, args []string, capabilities *Capabilities) (*Co
17591710
_ = cmd.String("name", "", "Assign a name to the container")
17601711
)
17611712

1762-
cmd.Var(flAttach, "a", "Attach to stdin, stdout or stderr.")
1763-
cmd.Var(flVolumes, "v", "Bind mount a volume (e.g. from the host: -v /host:/container, from docker: -v /container)")
1713+
cmd.Var(&flAttach, "a", "Attach to stdin, stdout or stderr.")
1714+
cmd.Var(&flVolumes, "v", "Bind mount a volume (e.g. from the host: -v /host:/container, from docker: -v /container)")
17641715
cmd.Var(&flLinks, "link", "Add link to another container (name:alias)")
1716+
cmd.Var(&flEnv, "e", "Set environment variables")
17651717

17661718
cmd.Var(&flPublish, "p", fmt.Sprintf("Publish a container's port to the host (format: %s) (use 'docker port' to see the actual mapping)", PortSpecTemplateFormat))
17671719
cmd.Var(&flExpose, "expose", "Expose a port from the container without publishing it to your host")
1768-
cmd.Var(&flEnv, "e", "Set environment variables")
17691720
cmd.Var(&flDns, "dns", "Set custom dns servers")
17701721
cmd.Var(&flVolumesFrom, "volumes-from", "Mount volumes from the specified container(s)")
17711722
cmd.Var(&flLxcOpts, "lxc-conf", "Add custom lxc options -lxc-conf=\"lxc.cgroup.cpuset.cpus = 0,1\"")
@@ -1780,7 +1731,7 @@ func parseRun(cmd *flag.FlagSet, args []string, capabilities *Capabilities) (*Co
17801731
}
17811732

17821733
// Validate input params
1783-
if *flDetach && len(flAttach) > 0 {
1734+
if *flDetach && flAttach.Len() > 0 {
17841735
return nil, nil, cmd, ErrConflictAttachDetach
17851736
}
17861737
if *flWorkingDir != "" && !path.IsAbs(*flWorkingDir) {
@@ -1791,7 +1742,7 @@ func parseRun(cmd *flag.FlagSet, args []string, capabilities *Capabilities) (*Co
17911742
}
17921743

17931744
// If neither -d or -a are set, attach to everything by default
1794-
if len(flAttach) == 0 && !*flDetach {
1745+
if flAttach.Len() == 0 && !*flDetach {
17951746
if !*flDetach {
17961747
flAttach.Set("stdout")
17971748
flAttach.Set("stderr")
@@ -1801,17 +1752,6 @@ func parseRun(cmd *flag.FlagSet, args []string, capabilities *Capabilities) (*Co
18011752
}
18021753
}
18031754

1804-
var envs []string
1805-
for _, env := range flEnv {
1806-
arr := strings.Split(env, "=")
1807-
if len(arr) > 1 {
1808-
envs = append(envs, env)
1809-
} else {
1810-
v := os.Getenv(env)
1811-
envs = append(envs, env+"="+v)
1812-
}
1813-
}
1814-
18151755
var flMemory int64
18161756
if *flMemoryString != "" {
18171757
parsedMemory, err := utils.RAMInBytes(*flMemoryString)
@@ -1823,16 +1763,15 @@ func parseRun(cmd *flag.FlagSet, args []string, capabilities *Capabilities) (*Co
18231763

18241764
var binds []string
18251765
// add any bind targets to the list of container volumes
1826-
for bind := range flVolumes {
1827-
arr := strings.Split(bind, ":")
1828-
if len(arr) > 1 {
1766+
for bind := range flVolumes.GetMap() {
1767+
if arr := strings.Split(bind, ":"); len(arr) > 1 {
18291768
if arr[0] == "/" {
18301769
return nil, nil, cmd, fmt.Errorf("Invalid bind mount: source can't be '/'")
18311770
}
18321771
dstDir := arr[1]
1833-
flVolumes[dstDir] = struct{}{}
1772+
flVolumes.Set(dstDir)
18341773
binds = append(binds, bind)
1835-
delete(flVolumes, bind)
1774+
flVolumes.Delete(bind)
18361775
}
18371776
}
18381777

@@ -1867,13 +1806,13 @@ func parseRun(cmd *flag.FlagSet, args []string, capabilities *Capabilities) (*Co
18671806
domainname = parts[1]
18681807
}
18691808

1870-
ports, portBindings, err := parsePortSpecs(flPublish)
1809+
ports, portBindings, err := parsePortSpecs(flPublish.GetAll())
18711810
if err != nil {
18721811
return nil, nil, cmd, err
18731812
}
18741813

18751814
// Merge in exposed ports to the map of published ports
1876-
for _, e := range flExpose {
1815+
for _, e := range flExpose.GetAll() {
18771816
if strings.Contains(e, ":") {
18781817
return nil, nil, cmd, fmt.Errorf("Invalid port format for -expose: %s", e)
18791818
}
@@ -1894,15 +1833,15 @@ func parseRun(cmd *flag.FlagSet, args []string, capabilities *Capabilities) (*Co
18941833
OpenStdin: *flStdin,
18951834
Memory: flMemory,
18961835
CpuShares: *flCpuShares,
1897-
AttachStdin: flAttach["stdin"],
1898-
AttachStdout: flAttach["stdout"],
1899-
AttachStderr: flAttach["stderr"],
1900-
Env: envs,
1836+
AttachStdin: flAttach.Get("stdin"),
1837+
AttachStdout: flAttach.Get("stdout"),
1838+
AttachStderr: flAttach.Get("stderr"),
1839+
Env: flEnv.GetAll(),
19011840
Cmd: runCmd,
1902-
Dns: flDns,
1841+
Dns: flDns.GetAll(),
19031842
Image: image,
1904-
Volumes: flVolumes,
1905-
VolumesFrom: strings.Join(flVolumesFrom, ","),
1843+
Volumes: flVolumes.GetMap(),
1844+
VolumesFrom: strings.Join(flVolumesFrom.GetAll(), ","),
19061845
Entrypoint: entrypoint,
19071846
WorkingDir: *flWorkingDir,
19081847
}
@@ -1913,7 +1852,7 @@ func parseRun(cmd *flag.FlagSet, args []string, capabilities *Capabilities) (*Co
19131852
LxcConf: lxcConf,
19141853
Privileged: *flPrivileged,
19151854
PortBindings: portBindings,
1916-
Links: flLinks,
1855+
Links: flLinks.GetAll(),
19171856
PublishAllPorts: *flPublishAll,
19181857
}
19191858

docker/docker.go

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -33,26 +33,30 @@ func main() {
3333
flRoot := flag.String("g", "/var/lib/docker", "Path to use as the root of the docker runtime")
3434
flEnableCors := flag.Bool("api-enable-cors", false, "Enable CORS headers in the remote API")
3535
flDns := flag.String("dns", "", "Force docker to use specific DNS servers")
36-
flHosts := utils.ListOpts{fmt.Sprintf("unix://%s", docker.DEFAULTUNIXSOCKET)}
37-
flag.Var(&flHosts, "H", "Multiple tcp://host:port or unix://path/to/socket to bind in daemon mode, single connection otherwise")
36+
3837
flEnableIptables := flag.Bool("iptables", true, "Disable docker's addition of iptables rules")
3938
flDefaultIp := flag.String("ip", "0.0.0.0", "Default IP address to use when binding container ports")
4039
flInterContainerComm := flag.Bool("icc", true, "Enable inter-container communication")
4140
flGraphDriver := flag.String("s", "", "Force the docker runtime to use a specific storage driver")
4241

42+
flHosts := docker.ListOpts{}
43+
flHosts.Set(fmt.Sprintf("unix://%s", docker.DEFAULTUNIXSOCKET))
44+
flag.Var(&flHosts, "H", "Multiple tcp://host:port or unix://path/to/socket to bind in daemon mode, single connection otherwise")
45+
4346
flag.Parse()
4447

4548
if *flVersion {
4649
showVersion()
4750
return
4851
}
49-
if len(flHosts) > 1 {
50-
flHosts = flHosts[1:] //trick to display a nice default value in the usage
51-
}
52-
for i, flHost := range flHosts {
52+
// if flHosts.Len() > 1 {
53+
// flHosts = flHosts[1:] //trick to display a nice default value in the usage
54+
// }
55+
for _, flHost := range flHosts.GetAll() {
5356
host, err := utils.ParseHost(docker.DEFAULTHTTPHOST, docker.DEFAULTHTTPPORT, flHost)
5457
if err == nil {
55-
flHosts[i] = host
58+
flHosts.Set(host)
59+
flHosts.Delete(flHost)
5660
} else {
5761
log.Fatal(err)
5862
}
@@ -88,16 +92,16 @@ func main() {
8892
log.Fatal(err)
8993
}
9094
// Serve api
91-
job = eng.Job("serveapi", flHosts...)
95+
job = eng.Job("serveapi", flHosts.GetAll()...)
9296
job.SetenvBool("Logging", true)
9397
if err := job.Run(); err != nil {
9498
log.Fatal(err)
9599
}
96100
} else {
97-
if len(flHosts) > 1 {
101+
if flHosts.Len() > 1 {
98102
log.Fatal("Please specify only one -H")
99103
}
100-
protoAddrParts := strings.SplitN(flHosts[0], "://", 2)
104+
protoAddrParts := strings.SplitN(flHosts.GetAll()[0], "://", 2)
101105
if err := docker.ParseCommands(protoAddrParts[0], protoAddrParts[1], flag.Args()...); err != nil {
102106
if sterr, ok := err.(*utils.StatusError); ok {
103107
os.Exit(sterr.Status)

0 commit comments

Comments
 (0)