Skip to content

Commit

Permalink
feat: init command - close #48 close #54
Browse files Browse the repository at this point in the history
  • Loading branch information
Marcel Kloubert committed May 20, 2024
1 parent 2950f76 commit 3c4c32c
Show file tree
Hide file tree
Showing 6 changed files with 171 additions and 45 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,16 @@
## 0.14.0

- **BREAKING CHANGE**: `audit` command now uses spinners and pretty tables for output
- **BREAKING CHANGE**: if `GPM_BIN_PATH` is relative, it will be mapped to `$HOME/.gpm` instead
- feat: `bump version` command, which upgrades the current version of the underlying repository by setting up a new Git tag locally
- feat: `diff` command, which displays changes between version (or the current HEAD) as pretty diff output
- feat: `init` command, which currently can initialize a `gpm.yaml` file
- feat: add `GPM_AI_CHAT_TEMPERATURE` environment variable, which defines the custom temperature value for AI chat (operations)
- feat: add `--temperature` flag to `chat` command, which can define the initial temperature value for the command
- feat: `setup updater` command, which installs a shell script called `gpm-update` in `$HOME/.gpm/bin` folder of a UNIX environment, like *BSD, Linux or MacOS
- refactor: improve prompting in `chat` command
- refactor: `pack` command now outputs progress with pretty bars
- refactor: code cleanups and improvements

## 0.13.0

Expand Down
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -527,6 +527,14 @@ The idea of an `gpm.yaml` file is very similar to `package.json` file for Node /

An [example can be found here](./gpm.yaml).

If you want to initialize an empty one, you only need to execute

```bash
gpm init
```

in your terminal.

### Files [<a href="#gpmyaml-">↑</a>]

The `files` section contains a list of regular expressions of files which is used by [pack command](#pack-project-):
Expand Down
94 changes: 94 additions & 0 deletions commands/init.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
// MIT License
//
// Copyright (c) 2024 Marcel Joachim Kloubert (https://marcel.coffee)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

package commands

import (
"fmt"
"os"
"path"

"github.com/goccy/go-yaml"
"github.com/spf13/cobra"

"github.com/mkloubert/go-package-manager/constants"
"github.com/mkloubert/go-package-manager/types"
"github.com/mkloubert/go-package-manager/utils"
)

func Init_Init_Command(parentCmd *cobra.Command, app *types.AppContext) {
var force bool

var initCmd = &cobra.Command{
Use: "init [resource]",
Short: "Init project or resource",
Long: `Inits if no argument is defined the gpm.yaml, file otherwise a resource like a workflow.`,
Run: func(cmd *cobra.Command, args []string) {
gpmFilePath := path.Join(app.Cwd, "gpm.yaml")
gpmDirPath := path.Dir(gpmFilePath)
gpmFileName := path.Base(gpmFilePath)

app.Debug(fmt.Sprintf("Will initialize '%v' file in '%v' directory ...", gpmFileName, gpmDirPath))

isGpmFileExisting, err := utils.IsFileExisting(gpmFilePath)
if err != nil {
utils.CloseWithError(err)
}

if isGpmFileExisting {
app.Debug(fmt.Sprintf("Found %v file in '%v'", gpmFileName, gpmDirPath))

if !force {
utils.CloseWithError(fmt.Errorf("%v already exists in '%v'", gpmFileName, gpmDirPath))
}
}

app.Debug(fmt.Sprintf("Building content for '%v' file ...", gpmFileName))
initialGpmFile := types.GpmFile{
Files: []string{},
Scripts: map[string]string{
"test": "go test .",
},
}

app.Debug(fmt.Sprintf("Serializing content of '%v' file to YAML ...", gpmFileName))
yamlData, err := yaml.Marshal(&initialGpmFile)
if err != nil {
utils.CloseWithError(err)
}

app.Debug(fmt.Sprintf("Writing content to '%v' file of '%v' directory ...", gpmFileName, gpmDirPath))
err = os.WriteFile(gpmFilePath, yamlData, constants.DefaultFileMode)
if err != nil {
utils.CloseWithError(err)
}

fmt.Printf("✅ '%v' has been initialized%v", gpmFileName, fmt.Sprintln())
},
}

initCmd.PersistentFlags().BoolVarP(&force, "force", "f", false, "overwrite existing resource")

parentCmd.AddCommand(
initCmd,
)
}
70 changes: 44 additions & 26 deletions commands/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,41 +31,59 @@ import (
"github.com/spf13/cobra"
)

func Init_Run_Command(parentCmd *cobra.Command, app *types.AppContext) {
var runCmd = &cobra.Command{
Use: "run",
Aliases: []string{"r"},
Short: "Runs a command by name",
Long: `Runs a command by name which is defined in gpm.ya(m)l file.`,
Run: func(cmd *cobra.Command, args []string) {
scriptsToExecute := []string{}
func run_scripts(app *types.AppContext, args []string) {
scriptsToExecute := []string{}

for _, scriptName := range args {
scriptName = strings.TrimSpace(scriptName)
if scriptName == "" {
continue
}
for _, scriptName := range args {
scriptName = strings.TrimSpace(scriptName)
if scriptName == "" {
continue
}

_, ok := app.GpmFile.Scripts[scriptName]
if !ok {
utils.CloseWithError(fmt.Errorf("script '%v' not found", scriptName))
}
_, ok := app.GpmFile.Scripts[scriptName]
if !ok {
utils.CloseWithError(fmt.Errorf("script '%v' not found", scriptName))
}

scriptsToExecute = append(scriptsToExecute, scriptName)
}
scriptsToExecute = append(scriptsToExecute, scriptName)
}

if len(scriptsToExecute) == 0 {
app.RunCurrentProject()
} else {
// run scripts

for _, scriptName := range scriptsToExecute {
app.RunScript(scriptName)
}
}
}

func Init_Run_Command(parentCmd *cobra.Command, app *types.AppContext) {
var mode string

if len(scriptsToExecute) == 0 {
app.RunCurrentProject()
} else {
// run scripts
var runCmd = &cobra.Command{
Use: "run [resource]",
Aliases: []string{"r"},
Short: "Run resource",
Long: `Runs resources like scripts by name.`,
Run: func(cmd *cobra.Command, args []string) {
m := strings.TrimSpace(strings.ToLower(mode))

for _, scriptName := range scriptsToExecute {
app.RunScript(scriptName)
}
switch m {
case "":
case "s":
case "script":
case "scripts":
run_scripts(app, args)
default:
utils.CloseWithError(fmt.Errorf("invalid value '%v' for mode", m))
}
},
}

runCmd.Flags().StringVarP(&mode, "mode", "m", "", "the mode like scripts or workflows")

parentCmd.AddCommand(
runCmd,
)
Expand Down
1 change: 1 addition & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ func main() {
commands.Init_Diff_Command(rootCmd, &app)
commands.Init_Exec_Command(rootCmd, &app)
commands.Init_Import_Command(rootCmd, &app)
commands.Init_Init_Command(rootCmd, &app)
commands.Init_Install_Command(rootCmd, &app)
commands.Init_List_Command(rootCmd, &app)
commands.Init_Make_Command(rootCmd, &app)
Expand Down
40 changes: 21 additions & 19 deletions types/app_context.go
Original file line number Diff line number Diff line change
Expand Up @@ -457,24 +457,43 @@ func (app *AppContext) GetAliasesFilePath() (string, error) {
func (app *AppContext) GetBinFolderPath() (string, error) {
homeDir, err := os.UserHomeDir()
if err == nil {
gpmDirPath := path.Join(homeDir, ".gpm")

var binPath string

GPM_BIN_PATH := strings.TrimSpace(os.Getenv("GPM_BIN_PATH"))
if GPM_BIN_PATH != "" {
binPath = GPM_BIN_PATH
} else {
binPath = path.Join(homeDir, ".gpm/bin")
binPath = path.Join(gpmDirPath, "bin")
}

if !path.IsAbs(binPath) {
binPath = path.Join(app.Cwd, binPath)
binPath = path.Join(gpmDirPath, binPath)
}

return binPath, nil
}
return "", nil
}

// app.GetCurrentGitBranch() - returns the name of the current branch using git command
func (app *AppContext) GetCurrentGitBranch() (string, error) {
p := exec.Command("git", "symbolic-ref", "--short", "HEAD")
p.Dir = app.Cwd

var output bytes.Buffer
p.Stdout = &output

err := p.Run()
if err != nil {
return "", err
}
defer output.Reset()

return strings.TrimSpace(output.String()), nil
}

// app.GetEnvFilePaths() - returns possible paths of .env* files
func (app *AppContext) GetEnvFilePaths() ([]string, error) {
homeDir, err := os.UserHomeDir()
Expand Down Expand Up @@ -504,23 +523,6 @@ func (app *AppContext) GetEnvFilePaths() ([]string, error) {
}
}

// app.GetCurrentGitBranch() - returns the name of the current branch using git command
func (app *AppContext) GetCurrentGitBranch() (string, error) {
p := exec.Command("git", "symbolic-ref", "--short", "HEAD")
p.Dir = app.Cwd

var output bytes.Buffer
p.Stdout = &output

err := p.Run()
if err != nil {
return "", err
}
defer output.Reset()

return strings.TrimSpace(output.String()), nil
}

// app.GetGitBranches() - returns the list of branches using git command
func (app *AppContext) GetGitBranches() ([]string, error) {
p := exec.Command("git", "branch", "-a")
Expand Down

0 comments on commit 3c4c32c

Please sign in to comment.