fuzzyworld

template / commit

Removed pwsh dependency from both the Makefile and the default profiles.

52e9ad7cab946d8902172d201f02387172ab1ca7 · Pavel Safronov · 2022-11-07 23:51:13 -0800 · parents 10676da375cc

Removed pwsh dependency from both the Makefile and the default profiles.
 .vscode/launch.json | 28 +++++++++++++++++++++-------
 Makefile            | 13 ++++---------
 README.md           | 25 ++++++++++++-------------
 default_config.go   | 16 ++--------------
 main.go             |  4 +---
 profile.go          | 25 ++++++++++++++++---------
 profile_test.go     | 18 +-----------------
 7 files changed, 57 insertions(+), 72 deletions(-)

diff --git a/.vscode/launch.json b/.vscode/launch.json
index 60b8f44..22ee5d9 100644
--- a/.vscode/launch.json
+++ b/.vscode/launch.json
@@ -12,13 +12,6 @@
             "program": ".",
             "args": []
         },
-        {
-            "name": "Clean install",
-            "type": "PowerShell",
-            "request": "launch",
-            "script": "./scripts/clean-install.ps1",
-            "cwd": "${workspaceFolder}"
-        },
         {
             "name": "Run: template",
             "type": "go",
@@ -37,6 +30,27 @@
                 "reset",
             ]
         },
+        {
+            "name": "Run: template list",
+            "type": "go",
+            "request": "launch",
+            "mode": "auto",
+            "program": ".",
+            "args": [
+                "list",
+            ]
+        },
+        {
+            "name": "Run: template get work",
+            "type": "go",
+            "request": "launch",
+            "mode": "auto",
+            "program": ".",
+            "args": [
+                "get",
+                "work"
+            ]
+        },
         {
             "name": "Run: template blog",
             "type": "go",
diff --git a/Makefile b/Makefile
index 7163fb6..21e7111 100644
--- a/Makefile
+++ b/Makefile
@@ -1,9 +1,3 @@
-ifeq ($(OS),Windows_NT)
-    SHELL := pwsh.exe
-else
-    SHELL := pwsh
-endif
-
 .SHELLFLAGS := -Command
 BINARY_NAME := template
 
@@ -18,7 +12,8 @@ build:
 	go build .
 
 install: build
-	./scripts/clean-install.ps1
+	go install
+	template reset
 
 uninstall:
 	go clean -i gitlab.com/fuzzy-rp/template...
@@ -39,14 +34,14 @@ endif
 endif
 
 test: build
-	New-Item -ItemType Directory -Force -Path ./test | out-null
+	mkdir -p test
 	go test -v ./... -coverprofile="./test/coverage.out"
 
 test_coverage: test
 	go tool cover -html="./test/coverage.out" -o "./test/coverage.html"
 
 test_coverage_html: test_coverage
-	Invoke-Item "./test/coverage.html"
+	open "./test/coverage.html"
 
 clean:
 	go clean
diff --git a/README.md b/README.md
index 5310c5e..50959c4 100644
--- a/README.md
+++ b/README.md
@@ -27,7 +27,6 @@ This is one of the profiles that comes with the tool.
       path: ~/DailyNotes
       namepatterns:
         - '{{.Year}}-{{.Month}}-{{.Day}}.md'
-      scriptshell: pwsh
       runpostscriptonfailure: true
       postscripts:
         - code . {{ if .FullPath }}"{{.FullPath}}"{{else}}(gci . | select -last 1){{ end }}
@@ -48,13 +47,14 @@ This is one of the profiles that comes with the tool.
 ```
 
 Using the above configuration:
-```pwsh
-> template daily               
+```sh
+> template daily
 Profile: daily
 Project name: 
 Loaded config from /Users/fuzzy/.template.yaml
-Creating file: /Users/fuzzy/DailyNotes/2022-11-02.md
-Executing post script: pwsh -c code . "/Users/fuzzy/DailyNotes/2022-11-02.md"
+Loaded user config from /Users/fuzzy/.template.user.yaml, combining with global config
+Creating file: /Users/fuzzy/DailyNotes/2022-11-07.md
+Executing post script: sh -c code . "/Users/fuzzy/DailyNotes/2022-11-07.md"
 Post script had no output
 ```
 
@@ -64,9 +64,9 @@ This will cause VSCode to open the `~\DailyNotes` folder as a workspace, and the
 
 The application requires [go](https://en.wikipedia.org/wiki/Go_(programming_language)). You can download the installer [here](https://go.dev/doc/install).
 
-The build is managed by [make](https://www.gnu.org/software/make/) and uses [PowerShell Core](https://github.com/PowerShell/PowerShell).
+The build is managed by [make](https://www.gnu.org/software/make/).
 
-The default profiles use [PowerShell Core](https://github.com/PowerShell/PowerShell) and [Visual Studio Code](https://code.visualstudio.com/).
+The default profiles use [Visual Studio Code](https://code.visualstudio.com/).
 
 ## Package and installation
 
@@ -93,7 +93,7 @@ To uninstall, run this command from the repo directory:
 
 template currently refers to paths under `~`. This is to ensure that it works on all systems.
 
-But I personally keep files in Dropbox, so I usually create symbolic links from (for example) `~/Blog` -> `~/Dropbox/Blog`. Here are the Powershell commands that I use, maybe they will be helpful for you. :)
+But I personally keep files in Dropbox, so I usually create symbolic links from (for example) `~/Blog` -> `~/Dropbox/Blog`. Here are the shell commands that I use, maybe they will be helpful for you. :)
 
 ```powershell
 New-Item -ItemType Junction -Path "~\Blog\" -Target (Resolve-Path "~\Dropbox\Blog")
@@ -145,16 +145,15 @@ Here are the basic features of the CLI that I want to keep:
 
 I want to keep this CLI simple. To that extent, I'm not interested in adding too many features. My main requirement right now is: `template blog topic` should do the same thing as `template --profile blog --name topic`.
 
-The CLI should also not be too opinionated. Aside from `go`, there are no other requirements. Default profiles might need VSCode and/or pwsh, but the user can always override that.
+The CLI should also not be too opinionated. Aside from `go`, there are no other requirements. Default profiles use need VSCode, but the user can always override that.
 
 ### Future Features
 
 Here is the future feature list:
 
-1. Remove dependency on pwsh - is there a better approach to making `template` a cross-platform CLI?
-2. Publish Homebrew version of app
-3. Publish Chocolatey version of app
-4. Support for passing in a list of template values for custom values in the template. Use might look like this: `template work form123 --id=456 --corpOffice=SEA`. The passed-in extra values will be placed somewhere inside the template. Some value keys will not be allowed, like "time".
+1. Publish Homebrew version of app
+2. Publish Chocolatey version of app
+3. Support for passing in a list of template values for custom values in the template. Use might look like this: `template work form123 --id=456 --corpOffice=SEA`. The passed-in extra values will be placed somewhere inside the template. Some value keys will not be allowed, like "time".
 
 ## Contributing
 
diff --git a/default_config.go b/default_config.go
index a27885a..6c9dc88 100644
--- a/default_config.go
+++ b/default_config.go
@@ -23,9 +23,8 @@ Today's notes for {{.Year}}-{{.Month}}-{{.Day}}.
 5. Have fun!
 6. ADD MORE ITEMS HERE`,
 				},
-				ScriptShell: "pwsh",
 				PostScripts: []ParameterizedText{
-					"code . {{ if .FullPath }}\"{{.FullPath}}\"{{else}}(gci . | select -last 1){{ end }}",
+					"code . {{ if .FullPath }}\"{{.FullPath}}\"{{else}}(ls -t | head -n1){{ end }}",
 				},
 				RunPostscriptOnFailure: true,
 			},
@@ -42,7 +41,6 @@ Today's notes for {{.Year}}-{{.Month}}-{{.Day}}.
 						"{{if (gt $version 1)}}n{{$version}}{{end}}" +
 						".md",
 				},
-				ScriptShell: "pwsh",
 				PostScripts: []ParameterizedText{
 					"code \"{{.FullPath}}\"",
 				},
@@ -71,7 +69,6 @@ Today's notes for {{.Year}}-{{.Month}}-{{.Day}}.
 						"{{if (gt $version 1)}}n{{$version}}{{end}}" +
 						".md",
 				},
-				ScriptShell: "pwsh",
 				PostScripts: []ParameterizedText{
 					"code \"{{.FullPath}}\"",
 				},
@@ -103,7 +100,6 @@ cspell:words nanite
 						"{{if (gt $version 1)}}v{{$version}}{{end}}" +
 						".md",
 				},
-				ScriptShell: "pwsh",
 				PostScripts: []ParameterizedText{
 					"code . \"{{.FileName}}\"",
 				},
@@ -120,7 +116,6 @@ cspell:words nanite
 					"{{.Year}}-{{.Month}}-{{.Day}}-{{.Hour}}-{{.Minute}}{{if .ProjectName}}-{{.ProjectName}}{{end}}",
 					"{{.Year}}-{{.Month}}-{{.Day}}-{{.Hour}}-{{.Minute}}-{{.Second}}{{if .ProjectName}}-{{.ProjectName}}{{end}}",
 				},
-				ScriptShell: "pwsh",
 				PostScripts: []ParameterizedText{
 					"explorer \"{{.Path}}\"",
 				},
@@ -151,10 +146,8 @@ Sincerely, me
 						"{{if (gt $version 1)}}v{{$version}}{{end}}" +
 						".md",
 				},
-				ScriptShell: "pwsh",
 				PostScripts: []ParameterizedText{
-					"code . \"{{.FileName}}\"",
-					"code .",
+					"code . {{.FullPath}}",
 				},
 			},
 			{
@@ -168,7 +161,6 @@ Sincerely, me
 					"{{.Year}}-{{.Month}}-{{.Day}}-{{.Hour}}-{{.Minute}}{{if .ProjectName}}-{{.ProjectName}}{{end}}",
 					"{{.Year}}-{{.Month}}-{{.Day}}-{{.Hour}}-{{.Minute}}-{{.Second}}{{if .ProjectName}}-{{.ProjectName}}{{end}}",
 				},
-				ScriptShell: "pwsh",
 				PostScripts: []ParameterizedText{
 					"code .",
 					"chmod +x repro.sh",
@@ -198,7 +190,6 @@ echo "Let's test {{.ProjectName}}!"`,
 				Description: "Creates a folder in the current folder in the format YYYY-MM-DD[-ProjectName][-vVersion]",
 				Type:        FolderType,
 				Path:        ".", // current folder
-				ScriptShell: "pwsh",
 				PostScripts: []ParameterizedText{},
 				NamePatterns: []ParameterizedText{
 					"{{$version := getVersion}}" +
@@ -211,7 +202,6 @@ echo "Let's test {{.ProjectName}}!"`,
 				Name:        "create-react-app",
 				Type:        FolderType,
 				Description: "Creates a folder in the current folder in the format create-react-app[-ProjectName][-vVersion], runs `npx create-react-app` to initialize the folder, and opens the folder in VSCode",
-				ScriptShell: "pwsh",
 				Path:        ".", // current folder
 				NamePatterns: []ParameterizedText{
 					"{{$version := getVersion}}" +
@@ -235,7 +225,6 @@ echo "Let's test {{.ProjectName}}!"`,
 					"{{.Year}}-{{.Month}}-{{.Day}}-{{.Hour}}-{{.Minute}}{{if .ProjectName}}-{{.ProjectName}}{{end}}",
 					"{{.Year}}-{{.Month}}-{{.Day}}-{{.Hour}}-{{.Minute}}-{{.Second}}{{if .ProjectName}}-{{.ProjectName}}{{end}}",
 				},
-				ScriptShell: "pwsh",
 				PostScripts: []ParameterizedText{
 					"git init",
 					"code .",
@@ -253,7 +242,6 @@ echo "Let's test {{.ProjectName}}!"`,
 					"{{.Year}}-{{.Month}}-{{.Day}}-{{.Hour}}-{{.Minute}}{{if .ProjectName}}-{{.ProjectName}}{{end}}",
 					"{{.Year}}-{{.Month}}-{{.Day}}-{{.Hour}}-{{.Minute}}-{{.Second}}{{if .ProjectName}}-{{.ProjectName}}{{end}}",
 				},
-				ScriptShell: "pwsh",
 				PostScripts: []ParameterizedText{
 					"git clone {{.Url}} .",
 					"code .",
diff --git a/main.go b/main.go
index 485b68f..b033a45 100644
--- a/main.go
+++ b/main.go
@@ -278,9 +278,7 @@ func setConfig(settings *Settings) error {
 		if err != nil {
 			return fmt.Errorf("error loading user config from %v: %w", fullUserConfigPath, err)
 		} else {
-			log.WithFields(log.Fields{
-				"fullUserConfigPath": fullUserConfigPath,
-			}).Debug("loaded user config, combining with global config")
+			fmt.Printf("Loaded user config from %v, combining with global config\n", fullUserConfigPath)
 			config, err = mergeConfigs(config, userConfig)
 			if err != nil {
 				return fmt.Errorf("error merging configs: %w", err)
diff --git a/profile.go b/profile.go
index af933e4..e1faa57 100644
--- a/profile.go
+++ b/profile.go
@@ -49,7 +49,6 @@ type Profile struct {
 	Path                   string `yaml:"path,omitempty"`
 	OS                     OSType `yaml:"os,omitempty"`
 	NamePatterns           []ParameterizedText
-	ScriptShell            string              `yaml:"scriptshell,omitempty"`
 	Files                  []FileInFolder      `yaml:"files,omitempty"`
 	RunPostscriptOnFailure bool                `yaml:"runpostscriptonfailure,omitempty"`
 	PostScripts            []ParameterizedText `yaml:"postscripts,omitempty"`
@@ -155,12 +154,11 @@ func processProfile(profile Profile, projectName string, extras map[string]strin
 		return errors
 	}
 	for _, postScript := range postScripts {
-		allArgs := []string{"-c", postScript}
-		shell := profile.ScriptShell
 
+		shell, args := shellCommandAndArgs(postScript)
 		var out bytes.Buffer
-		fmt.Printf("Executing post script: %v %v\n", shell, strings.Join(allArgs, " "))
-		cmd := monkey.ExecCommand(shell, allArgs...)
+		fmt.Printf("Executing post script: %v %v\n", shell, strings.Join(args, " "))
+		cmd := monkey.ExecCommand(shell, args...)
 		cmd.Stdout = &out
 		err := cmd.Run()
 		output := out.String()
@@ -173,13 +171,25 @@ func processProfile(profile Profile, projectName string, extras map[string]strin
 			// post scripts can fail (TODO: investigate why), so for now we'll just log the error
 
 			fmt.Printf("Error executing post script '%v': %v\n",
-				fmt.Sprintf("%v %v", shell, strings.Trim(fmt.Sprint(allArgs), "[]")), err)
+				fmt.Sprintf("%v %v", shell, strings.Trim(fmt.Sprint(args), "[]")), err)
 		}
 	}
 
 	return nil
 }
 
+func shellCommandAndArgs(command string) (shell string, args []string) {
+	if runtime.GOOS == "windows" {
+		shell = "cmd"
+		args = []string{"/c", command}
+		return
+	} else {
+		shell = "sh"
+		args = []string{"-c", command}
+		return
+	}
+}
+
 func createPrePatternData(now time.Time, projectName string, extras map[string]string) PrePatternData {
 	prePatternData := PrePatternData{
 		Year:        now.Format("2006"),
@@ -278,9 +288,6 @@ func validateProfile(profile *Profile) error {
 	if profile.Type == ScriptType && profile.NamePatterns != nil && len(profile.NamePatterns) > 1 {
 		return fmt.Errorf("multiple name patterns are not supported for profile %s, which has Type=%s", profile.Name, profile.Type)
 	}
-	if profile.ScriptShell == "" && profile.PostScripts != nil && len(profile.PostScripts) > 0 {
-		return fmt.Errorf("script shell is required for profile %s", profile.Name)
-	}
 	if profile.Files == nil {
 		profile.Files = []FileInFolder{}
 	}
diff --git a/profile_test.go b/profile_test.go
index fa6d41b..7d27ac0 100644
--- a/profile_test.go
+++ b/profile_test.go
@@ -5,7 +5,6 @@ import (
 	"os/exec"
 	"os/user"
 	"path/filepath"
-	"runtime"
 	"testing"
 
 	"github.com/stretchr/testify/assert"
@@ -72,13 +71,6 @@ func TestValidateProfile(t *testing.T) {
 		Name:         "daily",
 		NamePatterns: []ParameterizedText{"test", "test2"},
 	}, "multiple name patterns")
-	testFailure(Profile{
-		Type:         ScriptType,
-		Name:         "daily",
-		NamePatterns: []ParameterizedText{"test"},
-		PostScripts:  []ParameterizedText{"test"},
-		ScriptShell:  "",
-	}, "missing script shell")
 
 	for _, profile := range defaultConfig().Profiles {
 		testSuccess(profile)
@@ -240,12 +232,6 @@ func TestProcessProfile(t *testing.T) {
 	})
 
 	projectName := "project-name"
-	var shell string
-	if runtime.GOOS == "windows" {
-		shell = "cmd"
-	} else {
-		shell = "bash"
-	}
 	extras := map[string]string{
 		"foo": "bar",
 	}
@@ -260,7 +246,6 @@ func TestProcessProfile(t *testing.T) {
 			PostScripts: []ParameterizedText{
 				"echo 'hi'",
 			},
-			ScriptShell: shell,
 		}
 
 		usr, err := user.Current()
@@ -283,8 +268,7 @@ func TestProcessProfile(t *testing.T) {
 			PostScripts: []ParameterizedText{
 				"echo 'hi'",
 			},
-			ScriptShell: shell,
-			Type:        FileType,
+			Type: FileType,
 		}
 
 		usr, err := user.Current()