Browse code

Engine: builtin command 'commands' returns a list of registered commands

Docker-DCO-1.1-Signed-off-by: Solomon Hykes <solomon@docker.com> (github: shykes)

Solomon Hykes authored on 2014/02/16 08:06:21
Showing 2 changed files
... ...
@@ -9,6 +9,7 @@ import (
9 9
 	"os"
10 10
 	"path/filepath"
11 11
 	"runtime"
12
+	"sort"
12 13
 	"strings"
13 14
 )
14 15
 
... ...
@@ -110,6 +111,12 @@ func New(root string) (*Engine, error) {
110 110
 		Stderr:   os.Stderr,
111 111
 		Stdin:    os.Stdin,
112 112
 	}
113
+	eng.Register("commands", func(job *Job) Status {
114
+		for _, name := range eng.commands() {
115
+			job.Printf("%s\n", name)
116
+		}
117
+		return StatusOK
118
+	})
113 119
 	// Copy existing global handlers
114 120
 	for k, v := range globalHandlers {
115 121
 		eng.handlers[k] = v
... ...
@@ -121,6 +128,17 @@ func (eng *Engine) String() string {
121 121
 	return fmt.Sprintf("%s|%s", eng.Root(), eng.id[:8])
122 122
 }
123 123
 
124
+// Commands returns a list of all currently registered commands,
125
+// sorted alphabetically.
126
+func (eng *Engine) commands() []string {
127
+	names := make([]string, 0, len(eng.handlers))
128
+	for name := range eng.handlers {
129
+		names = append(names, name)
130
+	}
131
+	sort.Strings(names)
132
+	return names
133
+}
134
+
124 135
 // Job creates a new job which can later be executed.
125 136
 // This function mimics `Command` from the standard os/exec package.
126 137
 func (eng *Engine) Job(name string, args ...string) *Job {
... ...
@@ -1,6 +1,7 @@
1 1
 package engine
2 2
 
3 3
 import (
4
+	"bytes"
4 5
 	"io/ioutil"
5 6
 	"os"
6 7
 	"path"
... ...
@@ -63,6 +64,24 @@ func TestJob(t *testing.T) {
63 63
 	}
64 64
 }
65 65
 
66
+func TestEngineCommands(t *testing.T) {
67
+	eng := newTestEngine(t)
68
+	defer os.RemoveAll(eng.Root())
69
+	handler := func(job *Job) Status { return StatusOK }
70
+	eng.Register("foo", handler)
71
+	eng.Register("bar", handler)
72
+	eng.Register("echo", handler)
73
+	eng.Register("die", handler)
74
+	var output bytes.Buffer
75
+	commands := eng.Job("commands")
76
+	commands.Stdout.Add(&output)
77
+	commands.Run()
78
+	expected := "bar\ncommands\ndie\necho\nfoo\n"
79
+	if result := output.String(); result != expected {
80
+		t.Fatalf("Unexpected output:\nExpected = %v\nResult   = %v\n", expected, result)
81
+	}
82
+}
83
+
66 84
 func TestEngineRoot(t *testing.T) {
67 85
 	tmp, err := ioutil.TempDir("", "docker-test-TestEngineCreateDir")
68 86
 	if err != nil {