Copy over environment.go and generate .env file in starter

This commit is contained in:
Achim Rohn
2025-09-03 00:32:45 +02:00
parent 5f0a1872a5
commit 7c41bd3d35
5 changed files with 118 additions and 99 deletions
+32 -15
View File
@@ -2,6 +2,8 @@ package create
import (
. "ersteller-lib"
"ersteller-lib/starter/env"
"fmt"
"log"
"os"
"os/exec"
@@ -18,10 +20,11 @@ const (
)
type Params struct {
DbType DatabaseType
ProjectDir string
ModuleName string
GoPath string
DbType DatabaseType
ProjectDir string
ModuleName string
GoPath string
OverwriteEnv bool
}
type StarterCreator struct {
@@ -71,6 +74,7 @@ func (s StarterCreator) Create() {
// Write to <ProjectDir>/main.go
targetPath := filepath.Join(s.params.ProjectDir, "main.go")
content = s.replaceImports(content)
must(os.WriteFile(targetPath, content, 0o644))
log.Printf("StarterCreator.Create: wrote starter main.go to %s", targetPath)
@@ -91,6 +95,24 @@ func (s StarterCreator) Create() {
if s.params.DbType == DataBaseTypeSqlite {
s.executeDbPush()
}
s.copyFile("../.gitignore", ".gitignore")
s.createEnvironment()
}
func (s StarterCreator) createEnvironment() {
if err := os.MkdirAll(s.params.ProjectDir+"/env", 0o755); err != nil {
log.Printf("StarterCreator.Create: failed to create env target directory%v", err)
return
}
//s.copyFile("../env/environment.go", "env/environment.go")
content, err := os.ReadFile(filepath.Join(s.thisDir, "../env/environment.go"))
must(err)
must(os.WriteFile(filepath.Join(s.params.ProjectDir, "env/environment.go"), content, 0o644))
must(env.GenerateEnvFile(s.params.ProjectDir, s.params.OverwriteEnv))
}
func (s StarterCreator) executeDbPush() {
@@ -119,17 +141,6 @@ func (s StarterCreator) executeDbPush() {
func (s StarterCreator) copyFile(src string, dst string) {
content, err := os.ReadFile(filepath.Join(s.thisDir, src))
must(err)
// If we are copying the Prisma schema and the target DB is sqlite,
// replace the datasource block accordingly.
if dst == "schema.prisma" && s.params.DbType == DataBaseTypeSqlite {
pgBlock := "datasource db {\n provider = \"postgresql\"\n url = env(\"DATABASE_URL\")\n}\n"
sqliteBlock := "datasource db {\n provider = \"sqlite\"\n url = \"file:./db/sqlite.db\"\n}\n"
contentStr := string(content)
contentStr = strings.Replace(contentStr, pgBlock, sqliteBlock, 1)
content = []byte(contentStr)
}
must(os.WriteFile(filepath.Join(s.params.ProjectDir, dst), content, 0o644))
}
@@ -187,6 +198,12 @@ func (s StarterCreator) executeGetPrismaClient() {
must(cmd.Run())
}
func (s StarterCreator) replaceImports(content []byte) []byte {
contentString := string(content)
contentString = strings.ReplaceAll(contentString, "\"ersteller-lib/starter/env\"", fmt.Sprint("\"", s.params.ModuleName, "/env\""))
return []byte(contentString)
}
func must(err error) {
if err != nil {
panic(err)