Skip to content

Commit

Permalink
Feature/get smarter at detecting app name (#81)
Browse files Browse the repository at this point in the history
  • Loading branch information
LucaLanziani committed Aug 18, 2023
1 parent d3180a8 commit c3935eb
Show file tree
Hide file tree
Showing 13 changed files with 114 additions and 64 deletions.
2 changes: 1 addition & 1 deletion src/cli/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func (c CLI) BuildCMD() *cli.Command {
return &cli.Command{
Name: "build",
Usage: "build a container image from the project directory",
Flags: c.CommandFlags(Build),
Flags: c.CommandFlags([]FlagsType{Build, Shared}),
Action: c.Build,
Before: c.baseBeforeFunc,
}
Expand Down
15 changes: 8 additions & 7 deletions src/cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@ func (c *CLI) init(cCtx *cli.Context) error {
version := cCtx.String(appVersionFlag)
projectDirectory := cCtx.String(projectDirectoryFlag)
absProjectDirectory, err := filepath.Abs(cCtx.String(projectDirectoryFlag))
registry := cCtx.String(repoNameFlag)
dockerFileName := cCtx.String(dockerFileNameFlag)

if dockerFileName == "" {
dockerFileName = defaults.GeneratedDockerFile
}

if err != nil {
c.Logger.Warnf("could not get abs of %s", projectDirectory)
Expand All @@ -67,17 +73,12 @@ func (c *CLI) init(cCtx *cli.Context) error {
}

dockerImage := docker.DockerImage{
Registry: cCtx.String(repoNameFlag),
Registry: registry,
Name: dockerImageName,
Directory: absProjectDirectory,
Tag: version,
}

dockerFileName := cCtx.String(dockerFileNameFlag)
if dockerFileName == "" {
dockerFileName = defaults.GeneratedDockerFile
}

dockerService, err := docker.New(project, dockerImage, dockerFileName)
if err != nil {
logger.PrintError("Error creating docker service", err)
Expand All @@ -103,7 +104,7 @@ func (c CLI) Run(args []string) error {
app := &cli.App{
Name: "initium",
Usage: "CLI of the Initium project",
Flags: c.CommandFlags(App),
Flags: c.CommandFlags([]FlagsType{App}),
Commands: []*cli.Command{
c.BuildCMD(),
c.PushCMD(),
Expand Down
2 changes: 1 addition & 1 deletion src/cli/delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func (c *CLI) DeleteCMD() *cli.Command {
return &cli.Command{
Name: "delete",
Usage: "delete the knative service",
Flags: c.CommandFlags(Kubernetes),
Flags: c.CommandFlags([]FlagsType{Kubernetes, Shared}),
Action: c.Delete,
Before: c.baseBeforeFunc,
}
Expand Down
2 changes: 1 addition & 1 deletion src/cli/deploy.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func (c CLI) DeployCMD() *cli.Command {
return &cli.Command{
Name: "deploy",
Usage: "deploy the application as a knative service",
Flags: c.CommandFlags(Kubernetes),
Flags: c.CommandFlags([]FlagsType{Kubernetes, Shared}),
Action: c.Deploy,
Before: c.baseBeforeFunc,
}
Expand Down
47 changes: 31 additions & 16 deletions src/cli/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"strings"

"github.com/nearform/initium-cli/src/services/git"
"github.com/nearform/initium-cli/src/services/project"
"github.com/nearform/initium-cli/src/utils/defaults"
"github.com/urfave/cli/v2"
"gopkg.in/yaml.v2"
Expand All @@ -22,6 +23,7 @@ const (
Registry FlagsType = "registry"
InitGithub FlagsType = "init-github"
App FlagsType = "app"
Shared FlagsType = "shared"
)

const (
Expand Down Expand Up @@ -55,6 +57,13 @@ func init() {
registry = fmt.Sprintf("ghcr.io/%s", org)
}

appName := ""
guess := project.GuessAppName()

if guess != nil {
appName = *guess
}

defaultFlags := map[FlagsType]([]cli.Flag){
Build: []cli.Flag{
&cli.StringFlag{
Expand Down Expand Up @@ -118,10 +127,25 @@ func init() {
},
},
App: []cli.Flag{
&cli.StringFlag{
Name: projectDirectoryFlag,
Usage: "The directory in which your Dockerfile lives",
Value: defaults.ProjectDirectory,
EnvVars: []string{"INITIUM_PROJECT_DIRECTORY"},
},
&cli.StringFlag{
Name: configFileFlag,
Usage: "read parameters from config",
Value: defaults.ConfigFile,
EnvVars: []string{"INITIUM_CONFIG_FILE"},
},
},
Shared: []cli.Flag{
&cli.StringFlag{
Name: appNameFlag,
Usage: "The name of the app",
Required: true,
Value: appName,
Required: appName == "",
EnvVars: []string{"INITIUM_APP_NAME"},
},
&cli.StringFlag{
Expand All @@ -130,12 +154,6 @@ func init() {
Value: defaults.AppVersion,
EnvVars: []string{"INITIUM_VERSION"},
},
&cli.StringFlag{
Name: projectDirectoryFlag,
Usage: "The directory in which your Dockerfile lives",
Value: defaults.ProjectDirectory,
EnvVars: []string{"INITIUM_PROJECT_DIRECTORY"},
},
&cli.StringFlag{
Name: repoNameFlag,
Aliases: []string{"repo-name"}, // keep compatibility with old version of the config
Expand All @@ -149,13 +167,6 @@ func init() {
Usage: "The name of the Dockerfile",
EnvVars: []string{"INITIUM_DOCKERFILE_NAME"},
},
&cli.StringFlag{
Name: configFileFlag,
Usage: "read parameters from config",
Hidden: true,
Value: defaults.ConfigFile,
EnvVars: []string{"INITIUM_CONFIG_FILE"},
},
},
}

Expand Down Expand Up @@ -227,6 +238,10 @@ func (c CLI) loadFlagsFromConfig(ctx *cli.Context) error {
return nil
}

func (c CLI) CommandFlags(command FlagsType) []cli.Flag {
return flags[command]
func (c CLI) CommandFlags(commands []FlagsType) []cli.Flag {
result := []cli.Flag{}
for _, command := range commands {
result = append(result, flags[command]...)
}
return result
}
21 changes: 11 additions & 10 deletions src/cli/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,27 +104,28 @@ func (c CLI) InitServiceAccountCMD(ctx *cli.Context) error {
}

func (c CLI) InitCMD() *cli.Command {
configFlags := c.CommandFlags([]FlagsType{Shared})
configFlags = append(configFlags, &cli.BoolFlag{
Name: persistFlag,
Value: false,
Usage: fmt.Sprintf("will write the file content in %s", defaults.ConfigFile),
})

return &cli.Command{
Name: "init",
Usage: "create configuration for the cli [EXPERIMENTAL]",
Subcommands: []*cli.Command{
{
Name: "github",
Usage: "create a github pipeline yaml file",
Flags: c.CommandFlags(InitGithub),
Flags: c.CommandFlags([]FlagsType{InitGithub, Shared}),
Action: c.InitGithubCMD,
Before: c.baseBeforeFunc,
},
{
Name: "config",
Usage: "create a config file with all available flags set to null",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: persistFlag,
Value: false,
Usage: fmt.Sprintf("will write the file content in %s", defaults.ConfigFile),
},
},
Name: "config",
Usage: "create a config file with all available flags set to null",
Flags: configFlags,
Action: c.InitConfigCMD,
Before: c.baseBeforeFunc,
},
Expand Down
6 changes: 3 additions & 3 deletions src/cli/init_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ func TestInitConfig(t *testing.T) {

// Command line argument wins over config and Environment variable
cli.Writer = new(bytes.Buffer)
if err = cli.Run([]string{"initium", fmt.Sprintf("--config-file=%s", f.Name()), "--app-name=FromParam", "init", "config"}); err != nil {
if err = cli.Run([]string{"initium", fmt.Sprintf("--config-file=%s", f.Name()), "init", "config", "--app-name=FromParam"}); err != nil {
t.Error(err)
}
compareConfig(t, "FromParam", registry, cli.Writer)
Expand All @@ -98,14 +98,14 @@ func TestRepoNameRetrocompatibiliy(t *testing.T) {
}

cli.Writer = new(bytes.Buffer)
if err = cli.Run([]string{"initium", fmt.Sprintf("--config-file=%s", f.Name()), "--app-name=FromParam", "init", "config"}); err != nil {
if err = cli.Run([]string{"initium", fmt.Sprintf("--config-file=%s", f.Name()), "init", "config", "--app-name=FromParam"}); err != nil {
t.Error(err)
}
compareConfig(t, "FromParam", "FromFile", cli.Writer)

//Override from parameter
cli.Writer = new(bytes.Buffer)
if err = cli.Run([]string{"initium", fmt.Sprintf("--config-file=%s", f.Name()), "--app-name=FromParam", "--container-registry=ghcr.io/nearform", "init", "config"}); err != nil {
if err = cli.Run([]string{"initium", fmt.Sprintf("--config-file=%s", f.Name()), "init", "config", "--app-name=FromParam", "--container-registry=ghcr.io/nearform"}); err != nil {
t.Error(err)
}
compareConfig(t, "FromParam", "ghcr.io/nearform", cli.Writer)
Expand Down
11 changes: 7 additions & 4 deletions src/cli/onbranch.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,13 @@ func (c CLI) buildPushDeploy(cCtx *cli.Context) error {
}

func (c CLI) OnBranchCMD() *cli.Command {
flags := []cli.Flag{}
flags = append(flags, c.CommandFlags(Kubernetes)...)
flags = append(flags, c.CommandFlags(Build)...)
flags = append(flags, c.CommandFlags(Registry)...)
flags := c.CommandFlags([]FlagsType{
Kubernetes,
Build,
Registry,
Shared,
})

flags = append(flags, []cli.Flag{
&cli.BoolFlag{
Name: stopOnBuildFlag,
Expand Down
11 changes: 7 additions & 4 deletions src/cli/onmain.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@ import (
)

func (c *CLI) OnMainCMD() *cli.Command {
flags := []cli.Flag{}
flags = append(flags, c.CommandFlags(Kubernetes)...)
flags = append(flags, c.CommandFlags(Build)...)
flags = append(flags, c.CommandFlags(Registry)...)
flags := c.CommandFlags([]FlagsType{
Kubernetes,
Build,
Registry,
Shared,
})
flags = append(flags, []cli.Flag{
&cli.BoolFlag{
Name: stopOnBuildFlag,
Expand All @@ -20,6 +22,7 @@ func (c *CLI) OnMainCMD() *cli.Command {
Value: false,
},
}...)

return &cli.Command{
Name: "onmain",
Usage: "deploy the application as a knative service",
Expand Down
2 changes: 1 addition & 1 deletion src/cli/push.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ func (c *CLI) PushCMD() *cli.Command {
return &cli.Command{
Name: "push",
Usage: "push the container image to a registry",
Flags: c.CommandFlags(Registry),
Flags: c.CommandFlags([]FlagsType{Registry, Shared}),
Action: c.Push,
Before: c.baseBeforeFunc,
}
Expand Down
2 changes: 1 addition & 1 deletion src/cli/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ func (c *CLI) TemplateCMD() *cli.Command {
return &cli.Command{
Name: "template",
Usage: "output the docker file used for this project",
Flags: c.CommandFlags(Build),
Flags: c.CommandFlags([]FlagsType{Build}),
Action: c.template,
Before: c.baseBeforeFunc,
}
Expand Down
47 changes: 32 additions & 15 deletions src/services/git/repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ import (
git "github.com/go-git/go-git/v5"
)

const (
httpgithubprefix = "https://github.com/"
gitgithubprefix = "[email protected]:"
)

func initRepo() (*git.Repository, error) {
wd, err := os.Getwd()

Expand Down Expand Up @@ -38,7 +43,7 @@ func GetHash() (string, error) {
return headRef.Hash().String(), nil
}

func GetGithubOrg() (string, error) {
func getGithubRemote() (string, error) {
repo, err := initRepo()

if err != nil {
Expand All @@ -53,25 +58,37 @@ func GetGithubOrg() (string, error) {
for _, remote := range c.Remotes {
for _, url := range remote.URLs {
// HTTPS (https://github.com/organization/repo.git)
if strings.HasPrefix(url, "https://github.com/") {
splitURL := strings.Split(url, "/")
if len(splitURL) > 3 {
return splitURL[3], nil
}
if strings.HasPrefix(url, httpgithubprefix) {
return strings.Replace(url, httpgithubprefix, "", 1), nil
}
// SSH ([email protected]:organization/repo.git)
if strings.HasPrefix(url, "[email protected]:") {
splitURL := strings.Split(url, ":")
if len(splitURL) > 1 {
splitPath := strings.Split(splitURL[1], "/")
if len(splitPath) > 1 {
return splitPath[0], nil
}
}
if strings.HasPrefix(url, gitgithubprefix) {
return strings.Replace(url, gitgithubprefix, "", 1), nil
}
}
}

return "", fmt.Errorf("no github remote found")
}

func GetRepoName() (string, error) {
remote, err := getGithubRemote()

if err != nil {
return "", err
}

splitRemote := strings.Split(remote, "/")
return strings.Replace(splitRemote[1], ".git", "", 1), nil
}

func GetGithubOrg() (string, error) {
remote, err := getGithubRemote()

if err != nil {
return "", err
}

return "", fmt.Errorf("cannot find any remote with github.com")
splitRemote := strings.Split(remote, "/")
return splitRemote[0], nil
}
10 changes: 10 additions & 0 deletions src/services/project/project.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"path"
"text/template"

"github.com/nearform/initium-cli/src/services/git"
"github.com/nearform/initium-cli/src/utils/defaults"
)

Expand Down Expand Up @@ -36,6 +37,15 @@ type InitOptions struct {
ProjectDirectory string
}

func GuessAppName() *string {
var name string
name, err := git.GetRepoName()
if err != nil {
return nil
}
return &name
}

func New(name string, directory string, runtimeVersion string, version string, resources fs.FS) Project {
return Project{
Name: name,
Expand Down

0 comments on commit c3935eb

Please sign in to comment.