Explorar o código

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 %!s(int64=11) %!d(string=hai) anos
pai
achega
cd846ecb60
Modificáronse 2 ficheiros con 37 adicións e 0 borrados
  1. 18 0
      engine/engine.go
  2. 19 0
      engine/engine_test.go

+ 18 - 0
engine/engine.go

@@ -9,6 +9,7 @@ import (
 	"os"
 	"os"
 	"path/filepath"
 	"path/filepath"
 	"runtime"
 	"runtime"
+	"sort"
 	"strings"
 	"strings"
 )
 )
 
 
@@ -110,6 +111,12 @@ func New(root string) (*Engine, error) {
 		Stderr:   os.Stderr,
 		Stderr:   os.Stderr,
 		Stdin:    os.Stdin,
 		Stdin:    os.Stdin,
 	}
 	}
+	eng.Register("commands", func(job *Job) Status {
+		for _, name := range eng.commands() {
+			job.Printf("%s\n", name)
+		}
+		return StatusOK
+	})
 	// Copy existing global handlers
 	// Copy existing global handlers
 	for k, v := range globalHandlers {
 	for k, v := range globalHandlers {
 		eng.handlers[k] = v
 		eng.handlers[k] = v
@@ -121,6 +128,17 @@ func (eng *Engine) String() string {
 	return fmt.Sprintf("%s|%s", eng.Root(), eng.id[:8])
 	return fmt.Sprintf("%s|%s", eng.Root(), eng.id[:8])
 }
 }
 
 
+// Commands returns a list of all currently registered commands,
+// sorted alphabetically.
+func (eng *Engine) commands() []string {
+	names := make([]string, 0, len(eng.handlers))
+	for name := range eng.handlers {
+		names = append(names, name)
+	}
+	sort.Strings(names)
+	return names
+}
+
 // Job creates a new job which can later be executed.
 // Job creates a new job which can later be executed.
 // This function mimics `Command` from the standard os/exec package.
 // This function mimics `Command` from the standard os/exec package.
 func (eng *Engine) Job(name string, args ...string) *Job {
 func (eng *Engine) Job(name string, args ...string) *Job {

+ 19 - 0
engine/engine_test.go

@@ -1,6 +1,7 @@
 package engine
 package engine
 
 
 import (
 import (
+	"bytes"
 	"io/ioutil"
 	"io/ioutil"
 	"os"
 	"os"
 	"path"
 	"path"
@@ -63,6 +64,24 @@ func TestJob(t *testing.T) {
 	}
 	}
 }
 }
 
 
+func TestEngineCommands(t *testing.T) {
+	eng := newTestEngine(t)
+	defer os.RemoveAll(eng.Root())
+	handler := func(job *Job) Status { return StatusOK }
+	eng.Register("foo", handler)
+	eng.Register("bar", handler)
+	eng.Register("echo", handler)
+	eng.Register("die", handler)
+	var output bytes.Buffer
+	commands := eng.Job("commands")
+	commands.Stdout.Add(&output)
+	commands.Run()
+	expected := "bar\ncommands\ndie\necho\nfoo\n"
+	if result := output.String(); result != expected {
+		t.Fatalf("Unexpected output:\nExpected = %v\nResult   = %v\n", expected, result)
+	}
+}
+
 func TestEngineRoot(t *testing.T) {
 func TestEngineRoot(t *testing.T) {
 	tmp, err := ioutil.TempDir("", "docker-test-TestEngineCreateDir")
 	tmp, err := ioutil.TempDir("", "docker-test-TestEngineCreateDir")
 	if err != nil {
 	if err != nil {