fuzzyworld

template / commit

Added support for file template strings, instead of needing to have a file template.

fe139e41cf2313ee3e0a4d6d04f606f46b632b38 · Pavel Safronov · 2022-09-25 01:26:47 -0700 · parents d1bc1307e9e8

Added support for file template strings, instead of needing to have a file template.
 .vscode/launch.json | 10 ++++++++++
 config.go           | 22 +++++++++++++++++++---
 file.go             | 31 ++++++++++++++++++++++++++++---
 profile.go          |  9 +++++++++
 4 files changed, 66 insertions(+), 6 deletions(-)

diff --git a/.vscode/launch.json b/.vscode/launch.json
index c823651..2f60e7f 100644
--- a/.vscode/launch.json
+++ b/.vscode/launch.json
@@ -28,6 +28,16 @@
                 "blog"
             ]
         },
+        {
+            "name": "Run: template daily",
+            "type": "go",
+            "request": "launch",
+            "mode": "auto",
+            "program": ".",
+            "args": [
+                "daily"
+            ]
+        },
         {
             "name": "Run: template work",
             "type": "go",
diff --git a/config.go b/config.go
index fa7cfe0..04eb025 100644
--- a/config.go
+++ b/config.go
@@ -3,6 +3,7 @@ package main
 import (
 	"fmt"
 	"os"
+	"strings"
 
 	"golang.org/x/exp/slices"
 	"gopkg.in/yaml.v3"
@@ -34,6 +35,7 @@ type Profile struct {
 	ScriptShell      string
 	OS               OSType
 	FileTemplatePath string
+	FileTemplate     string
 
 	// FileTemplatePath string
 }
@@ -53,8 +55,7 @@ func defaultConfig() Config {
 			{
 				Name:        "daily",
 				Description: "Creates a MD file in c:\\work\\daily-notes folder in the format YYYY-MM-DD[-vX].md",
-				OS:          "Windows",
-				Path:        "C:\\work\\daily-notes",
+				Path:        "~/Dropbox/DailyNotes",
 				Type:        FileType,
 				NamePatterns: []string{
 					"{{$version := getVersion}}" +
@@ -62,6 +63,18 @@ func defaultConfig() Config {
 						"{{if (gt $version 1)}}v{{$version}}{{end}}" +
 						".md",
 				},
+				FileTemplate: `# {{.Year}}-{{.Month}}-{{.Day}}
+
+Today's notes
+
+## Todo
+
+1. [ ] Check email
+2. [ ] Check chat
+3. [ ] Check calendar
+4. [ ] Check yesterday's notes
+5. [ ] Have fun!
+				`,
 				ScriptShell: "pwsh",
 				PostScripts: []string{
 					"code . \"{{.Path}}\"",
@@ -164,7 +177,7 @@ func validateConfig(config Config) error {
 			return fmt.Errorf("Profile name is required")
 		}
 		if slices.Contains(forbiddenProfileNames, profile.Name) {
-			return fmt.Errorf("Forbidden profile name '%s'", profile.Name)
+			return fmt.Errorf("forbidden profile name '%s'", profile.Name)
 		}
 		if profile.IsDefault {
 			if foundDefault {
@@ -175,6 +188,9 @@ func validateConfig(config Config) error {
 		if profile.NamePatterns == nil || len(profile.NamePatterns) == 0 {
 			return fmt.Errorf("no name patterns found for profile %s", profile.Name)
 		}
+		if profile.Path != "" && strings.Contains(profile.Path, "\\") {
+			return fmt.Errorf("invalid path for profile %s: %s", profile.Name, profile.Path)
+		}
 		if profile.Type == "" || (profile.Type != FileType && profile.Type != FolderType) {
 			return fmt.Errorf("invalid profile type %s for profile %s", profile.Type, profile.Name)
 		}
diff --git a/file.go b/file.go
index 149dd4f..bdf7952 100644
--- a/file.go
+++ b/file.go
@@ -4,14 +4,16 @@ import (
 	"fmt"
 	"os"
 	"path/filepath"
+	"strings"
 	"text/template"
 	"time"
 )
 
 type FilePatternData struct {
-	Name        string
-	ProjectName string
-	Time        string
+	Name             string
+	ProjectName      string
+	Time             string
+	Year, Month, Day string
 }
 
 func createFilePatternData(now time.Time, projectName string, name string) FilePatternData {
@@ -19,6 +21,9 @@ func createFilePatternData(now time.Time, projectName string, name string) FileP
 		Name:        name,
 		ProjectName: projectName,
 		Time:        now.Format("Monday, Jan 02, 2006 15:04:05 MST"),
+		Year:        now.Format("2006"),
+		Month:       now.Format("01"),
+		Day:         now.Format("02"),
 	}
 }
 
@@ -51,3 +56,23 @@ func createTemplateFile(srcPath string, destPath string, projectName string, nam
 
 	return nil
 }
+
+func createTemplateString(templateText string, projectName string, name string) (string, error) {
+	now := time.Now()
+	filePatternData := createFilePatternData(now, projectName, name)
+
+	// parse template
+	template, err := template.New("text-template").Parse(templateText)
+	if err != nil {
+		return "", fmt.Errorf("Error parsing template text: %v", err)
+	}
+
+	// create output string
+	sb := new(strings.Builder)
+	err = template.Execute(sb, filePatternData)
+	if err != nil {
+		return "", fmt.Errorf("Error creating templated file: %v", err)
+	}
+
+	return sb.String(), nil
+}
diff --git a/profile.go b/profile.go
index 4d6256b..7149110 100644
--- a/profile.go
+++ b/profile.go
@@ -3,6 +3,7 @@ package main
 import (
 	"errors"
 	"fmt"
+	"io/ioutil"
 	"os"
 	"os/exec"
 	"path/filepath"
@@ -115,12 +116,20 @@ func processProfile(profile Profile, projectName string) error {
 		}
 	} else {
 		useTemplateFile := profile.FileTemplatePath != ""
+		useTemplate := profile.FileTemplate != ""
 		if useTemplateFile {
 			fmt.Printf("Creating file '%v' from template: %v\n", fullPath, profile.FileTemplatePath)
 			err := createTemplateFile(profile.FileTemplatePath, fullPath, projectName, newName)
 			if err != nil {
 				return fmt.Errorf("error creating template file: %v", err)
 			}
+		} else if useTemplate {
+			fmt.Printf("Creating file '%v' from template string\n", fullPath)
+			templateString, err := createTemplateString(profile.FileTemplate, projectName, newName)
+			if err != nil {
+				return fmt.Errorf("error creating template: %v", err)
+			}
+			ioutil.WriteFile(fullPath, []byte(templateString), os.ModePerm)
 		} else {
 			fmt.Printf("Creating empty file: %v\n", fullPath)
 			os.WriteFile(fullPath, []byte{}, os.ModePerm)