Merge pull request #633 from rumpl/ux-init

Ux init
This commit is contained in:
Jean-Christophe Sirot 2019-09-24 17:35:04 +02:00 коммит произвёл GitHub
Родитель dc0d83c861 c85f3d0186
Коммит cc0d5ee085
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
4 изменённых файлов: 39 добавлений и 81 удалений

Просмотреть файл

@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"io/ioutil"
"os/user"
"path/filepath"
"regexp"
"strings"
@ -76,25 +77,30 @@ func TestInit(t *testing.T) {
cmd, cleanup := dockerCli.createTestCmd()
defer cleanup()
userData, _ := user.Current()
currentUser := ""
if userData != nil {
currentUser = userData.Username
}
composeData := `version: "3.2"
services:
nginx:
image: nginx:latest
command: nginx $NGINX_ARGS ${NGINX_DRY_RUN}
`
meta := `# Version of the application
meta := fmt.Sprintf(`# Version of the application
version: 0.1.0
# Name of the application
name: app-test
# A short description of the application
description: my cool app
description:
# List of application maintainers with name and email for each
maintainers:
- name: dev1
- name: %s
email:
- name: dev2
email: dev2@example.com
`
`, currentUser)
envData := "# some comment\nNGINX_DRY_RUN=-t"
tmpDir := fs.NewDir(t, "app_input",
fs.WithFile(internal.ComposeFileName, composeData),
@ -108,10 +114,7 @@ maintainers:
cmd.Dir = tmpDir.Path()
cmd.Command = dockerCli.Command("app",
"init", testAppName,
"--compose-file", tmpDir.Join(internal.ComposeFileName),
"--description", "my cool app",
"--maintainer", "dev1",
"--maintainer", "dev2:dev2@example.com")
"--compose-file", tmpDir.Join(internal.ComposeFileName))
stdOut := icmd.RunCmd(cmd).Assert(t, icmd.Success).Combined()
golden.Assert(t, stdOut, "init-output.golden")

Просмотреть файл

@ -11,19 +11,17 @@ import (
var (
initComposeFile string
initDescription string
initMaintainers []string
)
func initCmd(dockerCli command.Cli) *cobra.Command {
cmd := &cobra.Command{
Use: "init APP_NAME [--compose-file COMPOSE_FILE] [--description DESCRIPTION] [--maintainer NAME:EMAIL ...] [OPTIONS]",
Use: "init APP_NAME [--compose-file COMPOSE_FILE] [OPTIONS]",
Short: "Initialize Docker Application definition",
Long: `Start building a Docker Application package. If there is a docker-compose.yml file in the current directory it will be copied and used.`,
Example: `$ docker app init myapp --description "a useful description"`,
Example: `$ docker app init myapp`,
Args: cli.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
created, err := packager.Init(args[0], initComposeFile, initDescription, initMaintainers)
created, err := packager.Init(args[0], initComposeFile)
if err != nil {
return err
}
@ -32,7 +30,5 @@ func initCmd(dockerCli command.Cli) *cobra.Command {
},
}
cmd.Flags().StringVar(&initComposeFile, "compose-file", "", "Compose file to use as application base (optional)")
cmd.Flags().StringVar(&initDescription, "description", "", "Human readable description of your application (optional)")
cmd.Flags().StringArrayVar(&initMaintainers, "maintainer", []string{}, "Name and email address of person responsible for the application (name:email) (optional)")
return cmd
}

Просмотреть файл

@ -27,7 +27,7 @@ import (
// Init is the entrypoint initialization function.
// It generates a new application definition based on the provided parameters
// and returns the path to the created application definition.
func Init(name string, composeFile string, description string, maintainers []string) (string, error) {
func Init(name string, composeFile string) (string, error) {
if err := internal.ValidateAppName(name); err != nil {
return "", err
}
@ -41,15 +41,10 @@ func Init(name string, composeFile string, description string, maintainers []str
os.RemoveAll(dirName)
}
}()
if err = writeMetadataFile(name, dirName, description, maintainers); err != nil {
if err = writeMetadataFile(name, dirName); err != nil {
return "", err
}
if composeFile == "" {
if _, err := os.Stat(internal.ComposeFileName); err == nil {
composeFile = internal.ComposeFileName
}
}
if composeFile == "" {
err = initFromScratch(name)
} else {
@ -183,8 +178,8 @@ description: {{ .Description }}
# email: john@doe.com
{{ end }}`
func writeMetadataFile(name, dirName string, description string, maintainers []string) error {
meta := newMetadata(name, description, maintainers)
func writeMetadataFile(name, dirName string) error {
meta := newMetadata(name)
tmpl, err := template.New("metadata").Parse(metaTemplate)
if err != nil {
return errors.Wrap(err, "internal error parsing metadata template")
@ -196,34 +191,14 @@ func writeMetadataFile(name, dirName string, description string, maintainers []s
return ioutil.WriteFile(filepath.Join(dirName, internal.MetadataFileName), resBuf.Bytes(), 0644)
}
// parseMaintainersData parses user-provided data through the maintainers flag and returns
// a slice of Maintainer instances
func parseMaintainersData(maintainers []string) []metadata.Maintainer {
var res []metadata.Maintainer
for _, m := range maintainers {
ne := strings.SplitN(m, ":", 2)
var email string
if len(ne) > 1 {
email = ne[1]
}
res = append(res, metadata.Maintainer{Name: ne[0], Email: email})
}
return res
}
func newMetadata(name string, description string, maintainers []string) metadata.AppMetadata {
func newMetadata(name string) metadata.AppMetadata {
res := metadata.AppMetadata{
Version: "0.1.0",
Name: name,
Description: description,
Version: "0.1.0",
Name: name,
}
if len(maintainers) == 0 {
userData, _ := user.Current()
if userData != nil && userData.Username != "" {
res.Maintainers = []metadata.Maintainer{{Name: userData.Username}}
}
} else {
res.Maintainers = parseMaintainersData(maintainers)
userData, _ := user.Current()
if userData != nil && userData.Username != "" {
res.Maintainers = []metadata.Maintainer{{Name: userData.Username}}
}
return res
}

Просмотреть файл

@ -1,10 +1,11 @@
package packager
import (
"fmt"
"os/user"
"testing"
"github.com/docker/app/internal"
"github.com/docker/app/types/metadata"
"gotest.tools/assert"
"gotest.tools/fs"
)
@ -159,10 +160,16 @@ func TestWriteMetadataFile(t *testing.T) {
tmpdir := fs.NewDir(t, appName)
defer tmpdir.Remove()
err := writeMetadataFile(appName, tmpdir.Path(), "", []string{"dev:dev@example.com"})
err := writeMetadataFile(appName, tmpdir.Path())
assert.NilError(t, err)
data := `# Version of the application
userData, _ := user.Current()
currentUser := ""
if userData != nil {
currentUser = userData.Username
}
data := fmt.Sprintf(`# Version of the application
version: 0.1.0
# Name of the application
name: writemetadata_test
@ -170,35 +177,12 @@ name: writemetadata_test
description:
# List of application maintainers with name and email for each
maintainers:
- name: dev
email: dev@example.com
`
- name: %s
email:
`, currentUser)
manifest := fs.Expected(t,
fs.WithFile(internal.MetadataFileName, data, fs.WithMode(0644)),
)
assert.Assert(t, fs.Equal(tmpdir.Path(), manifest))
}
func TestParseMaintainersData(t *testing.T) {
input := []string{
"sakuya:sakuya.izayoi@touhou.jp",
"marisa.kirisame",
"Reimu Hakurei",
"Hong Meiling:kurenai.misuzu@touhou.jp",
" : ",
"perfect:cherry:blossom",
}
expectedOutput := []metadata.Maintainer{
{Name: "sakuya", Email: "sakuya.izayoi@touhou.jp"},
{Name: "marisa.kirisame", Email: ""},
{Name: "Reimu Hakurei", Email: ""},
{Name: "Hong Meiling", Email: "kurenai.misuzu@touhou.jp"},
{Name: " ", Email: " "},
{Name: "perfect", Email: "cherry:blossom"},
}
output := parseMaintainersData(input)
assert.DeepEqual(t, output, expectedOutput)
}