From 7e5665f249a795ca67ff14766a9f3f93d6c62d40 Mon Sep 17 00:00:00 2001 From: early Date: Wed, 6 Nov 2024 19:15:45 -0700 Subject: [PATCH] add database support --- .gitignore | 1 + app/app.go | 2 +- database/database.go | 166 +++++++++++++++ database/database_test.go | 54 +++++ database/migrate.go | 200 ++++++++++++++++++ database/test/.gitignore | 1 + database/test/file-init/init.sql | 6 + .../named-versions-init/v0.10/migrate.sql | 2 + .../test/named-versions-init/v0.2/init.sql | 4 + .../test/named-versions-init/v0.2/migrate.sql | 1 + database/test/named-versions-init/v0/init.sql | 4 + database/test/raw-init/.ignoreme | 1 + database/test/versions-init/v0.10/migrate.sql | 2 + database/test/versions-init/v0.2/init.sql | 4 + database/test/versions-init/v0.2/migrate.sql | 1 + database/test/versions-init/v0/init.sql | 4 + go.mod | 18 +- go.sum | 55 ++++- include/callstack.go | 4 + include/include.go | 16 ++ web/cmd/standard-test/main.go | 54 ----- web/cmd/standard-test/pages/index.html | 22 -- web/cmd/standard-test/pages/static.html | 16 -- web/cmd/standard-test/public/style.css | 51 ----- web/cmd/standard-test/test_thing.html | 3 - 25 files changed, 539 insertions(+), 153 deletions(-) create mode 100644 .gitignore create mode 100644 database/database.go create mode 100644 database/database_test.go create mode 100644 database/migrate.go create mode 100644 database/test/.gitignore create mode 100644 database/test/file-init/init.sql create mode 100644 database/test/named-versions-init/v0.10/migrate.sql create mode 100644 database/test/named-versions-init/v0.2/init.sql create mode 100644 database/test/named-versions-init/v0.2/migrate.sql create mode 100644 database/test/named-versions-init/v0/init.sql create mode 100644 database/test/raw-init/.ignoreme create mode 100644 database/test/versions-init/v0.10/migrate.sql create mode 100644 database/test/versions-init/v0.2/init.sql create mode 100644 database/test/versions-init/v0.2/migrate.sql create mode 100644 database/test/versions-init/v0/init.sql delete mode 100644 web/cmd/standard-test/main.go delete mode 100644 web/cmd/standard-test/pages/index.html delete mode 100644 web/cmd/standard-test/pages/static.html delete mode 100644 web/cmd/standard-test/public/style.css delete mode 100644 web/cmd/standard-test/test_thing.html diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3997bea --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +*.db \ No newline at end of file diff --git a/app/app.go b/app/app.go index 9bcace5..8d82812 100644 --- a/app/app.go +++ b/app/app.go @@ -23,7 +23,7 @@ import ( ) func init() { - include.SetNotEligible("git.earlybird.gay/today-app/app") + include.SetNotEligible("git.earlybird.gay/today/app") } type App struct { diff --git a/database/database.go b/database/database.go new file mode 100644 index 0000000..f197acc --- /dev/null +++ b/database/database.go @@ -0,0 +1,166 @@ +package database + +import ( + "database/sql" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path/filepath" + "regexp" + "slices" + + "git.earlybird.gay/today/include" + + _ "modernc.org/sqlite" +) + +var versionRegexp = regexp.MustCompile(`^(\w*?)-?v?((?:\d\.?)*\d)$`) +var definedByDir = map[string][]string{} + +type Database struct { + *sql.DB + name string + rootDir string + liveFile string + + initSql string + + err error +} + +type Config func(db *Database) error + +// Init sets a sql statement to call when the database is initialized. +// If initSql is a valid file, relative to the Database, it is read as a SQL +// script. Otherwise, initSql is interpreted as sql. +func Init(initSql string) Config { + return func(db *Database) error { + initFilename := filepath.Join(db.rootDir, initSql) + if _, err := os.Stat(initFilename); err == nil { + r, err := os.Open(initFilename) + if err != nil { + return err + } + raw, err := io.ReadAll(r) + if err != nil { + return err + } + db.initSql = string(raw) + } else { + db.initSql = initSql + } + return nil + } +} + +func Subdirectory(dir string) Config { + return func(db *Database) error { + db.rootDir = filepath.Join(db.rootDir, dir) + return nil + } +} + +func New(name string, confs ...Config) *Database { + db := &Database{ + name: name, + } + db.rootDir, _ = include.Dir("git.earlybird.gay/today/database") + + for _, conf := range confs { + db.err = errors.Join(db.err, conf(db)) + } + if db.err != nil { + return db + } + + // Migration + // If db.initSql has content, just use that. + if db.initSql != "" { + liveFile := filepath.Join(db.rootDir, db.name+".db") + shouldInit := false + if _, err := os.Stat(liveFile); errors.Is(err, os.ErrNotExist) { + shouldInit = true + } + db.DB, db.err = sql.Open("sqlite", liveFile) + if db.err != nil { + return db + } + if shouldInit { + _, db.err = db.Exec(db.initSql) + if db.err != nil { + return db + } + } + db.liveFile = liveFile + return db + } + // If the user hasn't *explicitly* defined a migration method, make a choice + // based on the filesystem structure. + dbsInThisDir := definedByDir[db.rootDir] + if len(dbsInThisDir) > 0 { + if slices.Contains(dbsInThisDir, name) { + db.err = errors.New("cannot have two databases " + name + " in the same directory") + return db + } + } + dbsInThisDir = append(dbsInThisDir, name) + entries, err := os.ReadDir(db.rootDir) + if err != nil { + db.err = err + return db + } + versions := make([]string, 0) + if slices.ContainsFunc(entries, func(entry fs.DirEntry) bool { + return entry.IsDir() && entry.Name() == db.name + }) { + db.rootDir = filepath.Join(db.rootDir, db.name) + entries, err = os.ReadDir(db.rootDir) + if err != nil { + db.err = err + return db + } + } + for _, entry := range entries { + if !entry.IsDir() { + continue + } + fmt.Println("entry", entry.Name()) + if submatches := versionRegexp.FindAllStringSubmatch(entry.Name(), -1); len(submatches) == 1 { + dbFolder := submatches[0] + dbf, dbfName := dbFolder[0], dbFolder[1] + if dbfName == "" && len(dbsInThisDir) > 1 { + // Resolve ambiguity when two databases fight over unnamed version folder + db.err = errors.New("can't use unnamed version folders with multiple databases; use name-vX.Y.Z") + return db + } else if dbfName != "" && dbfName != name { + // Don't use A-vN for database B + continue + } + versions = append(versions, dbf) + } + } + if len(versions) > 0 { + liveFile, err := migrateVersions(db, versions) + if err != nil { + db.err = err + return db + } + db.liveFile = liveFile + } + definedByDir[db.rootDir] = dbsInThisDir + return db +} + +func (db *Database) Filename() string { + return db.liveFile +} + +func (db *Database) ConnString() string { + return "" +} + +func (db *Database) Error() error { + return db.err +} diff --git a/database/database_test.go b/database/database_test.go new file mode 100644 index 0000000..d4c3145 --- /dev/null +++ b/database/database_test.go @@ -0,0 +1,54 @@ +package database + +import ( + "os" + "testing" +) + +func TestRawInit(t *testing.T) { + db := New("raw-init", + Subdirectory("test/raw-init"), + Init(` +CREATE TABLE messages ( + user TEXT, + msg TEXT, + likes INTEGER +); +INSERT INTO messages (user, msg, likes) VALUES ('test-user', 'hello, world', 5);`), + ) + if db.Error() != nil { + t.Fatal(db.Error()) + } + os.Remove(db.Filename()) +} + +func TestFileInit(t *testing.T) { + db := New("file-init", + Subdirectory("test/file-init"), + Init(`init.sql`), + ) + if db.Error() != nil { + t.Fatal(db.Error()) + } + os.Remove(db.Filename()) +} + +func TestVersionsInit(t *testing.T) { + db := New("versions-init", + Subdirectory("test/versions-init"), + ) + if db.Error() != nil { + t.Fatal(db.Error()) + } + // os.Remove(db.Filename()) +} + +func TestNamedVersionsInit(t *testing.T) { + db := New("named-versions-init", + Subdirectory("test"), + ) + if db.Error() != nil { + t.Fatal(db.Error()) + } + os.Remove(db.Filename()) +} diff --git a/database/migrate.go b/database/migrate.go new file mode 100644 index 0000000..18a0522 --- /dev/null +++ b/database/migrate.go @@ -0,0 +1,200 @@ +package database + +import ( + "database/sql" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "slices" + "strconv" + "strings" + + _ "modernc.org/sqlite" +) + +type migrateStep struct { + dir string + isActive bool + init string + migrate string +} + +func quickRead(filepath string) (string, error) { + reader, err := os.Open(filepath) + if err != nil { + return "", err + } + raw, err := io.ReadAll(reader) + if err != nil { + return "", err + } + return string(raw), nil +} + +func quickCopy(src, dst string) error { + r, err := os.Open(src) + if err != nil { + return err + } + w, err := os.Create(dst) + if err != nil { + return err + } + _, err = io.Copy(w, r) + return err +} + +// migrateVersions updates a database to the latest version in versions. +// Versions are sorted by +func migrateVersions(db *Database, versions []string) (string, error) { + if db == nil || len(versions) == 0 { + return "", nil + } + fmt.Println(db.name, versions) + slices.SortFunc(versions, func(a, b string) int { + // if pos a after b + as, bs := strings.Split(a, "."), strings.Split(b, ".") + for i := range min(len(as), len(bs)) { + av := as[i] + bv := bs[i] + if i == 0 { + if len(av) > 0 && av[0] == 'v' { + av = av[1:] + } + if len(bv) > 0 && bv[0] == 'v' { + bv = bv[1:] + } + } + an, _ := strconv.Atoi(av) + bn, _ := strconv.Atoi(bv) + fmt.Println(an, bn) + if an > bn { + return 1 + } else if an < bn { + return -1 + } + } + return 0 + }) + + steps := make([]migrateStep, len(versions)) + lastActive := -1 + firstInit := -1 + for i, version := range versions { + step := migrateStep{ + dir: filepath.Join(db.rootDir, version), + } + var err error + entries, _ := os.ReadDir(step.dir) + for _, entry := range entries { + switch entry.Name() { + case "init.sql": + step.init, err = quickRead(filepath.Join(step.dir, entry.Name())) + if firstInit == -1 { + firstInit = i + } + case "migrate.sql": + step.migrate, err = quickRead(filepath.Join(step.dir, entry.Name())) + case db.name + ".db": + step.isActive = true + } + if err != nil { + return "", err + } + + // Store the index of the last active step (has a live db) + if step.isActive { + fmt.Println(i, "is active") + lastActive = i + } + } + steps[i] = step + } + + if lastActive == len(steps)-1 { + fmt.Println("already up to date") + return "", nil + } + start := lastActive + if start == -1 { + start = firstInit + } + + if start == -1 { + return "", errors.New("can't determine a starting point for migration") + } + + var oldPath, currentPath string + var old, current *sql.DB + for i := start; i < len(steps); i++ { + var err error + step := steps[i] + fmt.Println("migrating to", filepath.Base(step.dir)) + + currentPath = filepath.Join(step.dir, "migration.db") + if step.init != "" { + if i != lastActive { + fmt.Println("has init; opening and running") + current, err = sql.Open("sqlite", currentPath) + if err != nil { + return "", err + } + _, err = current.Exec(step.init) + if err != nil { + return "", err + } + } else { + fmt.Println("has init, but is the last active database; using as source-of-truth") + sotPath := strings.Replace(currentPath, "migration", db.name, 1) + err = quickCopy(sotPath, currentPath) + if err != nil { + return "", err + } + current, err = sql.Open("sqlite", currentPath) + if err != nil { + return "", err + } + } + if step.migrate != "" && old != nil { + fmt.Println("has migrate; running with old attached") + current.Exec("ATTACH DATABASE ? AS old", oldPath) + _, err := current.Exec(step.migrate) + if err != nil { + return "", err + } + } + } else { + fmt.Println("has no init; moving old to current") + old.Close() + old = nil + os.Rename(oldPath, currentPath) + current, err = sql.Open("sqlite", currentPath) + if err != nil { + return "", err + } + if step.migrate != "" { + fmt.Println("has migrate; running on old database") + _, err := current.Exec(step.migrate) + if err != nil { + return "", err + } + } + } + + if old != nil { + old.Close() + old = nil + os.Remove(oldPath) + } + oldPath = currentPath + old = current + current = nil + } + old.Close() + old = nil + newPath := strings.Replace(oldPath, "migration", db.name, 1) + err := os.Rename(oldPath, newPath) + return newPath, err +} diff --git a/database/test/.gitignore b/database/test/.gitignore new file mode 100644 index 0000000..3997bea --- /dev/null +++ b/database/test/.gitignore @@ -0,0 +1 @@ +*.db \ No newline at end of file diff --git a/database/test/file-init/init.sql b/database/test/file-init/init.sql new file mode 100644 index 0000000..bb850ff --- /dev/null +++ b/database/test/file-init/init.sql @@ -0,0 +1,6 @@ +CREATE TABLE messages ( + user TEXT, + msg TEXT, + likes INTEGER +); +INSERT INTO messages (user, msg, likes) VALUES ('test-user', 'hello, world', 5); \ No newline at end of file diff --git a/database/test/named-versions-init/v0.10/migrate.sql b/database/test/named-versions-init/v0.10/migrate.sql new file mode 100644 index 0000000..95c8d19 --- /dev/null +++ b/database/test/named-versions-init/v0.10/migrate.sql @@ -0,0 +1,2 @@ +ALTER TABLE messages ADD likes INTEGER; +UPDATE messages SET likes = 5; \ No newline at end of file diff --git a/database/test/named-versions-init/v0.2/init.sql b/database/test/named-versions-init/v0.2/init.sql new file mode 100644 index 0000000..646d20c --- /dev/null +++ b/database/test/named-versions-init/v0.2/init.sql @@ -0,0 +1,4 @@ +CREATE TABLE messages ( + user TEXT, + msg TEXT +); \ No newline at end of file diff --git a/database/test/named-versions-init/v0.2/migrate.sql b/database/test/named-versions-init/v0.2/migrate.sql new file mode 100644 index 0000000..48adf09 --- /dev/null +++ b/database/test/named-versions-init/v0.2/migrate.sql @@ -0,0 +1 @@ +INSERT INTO messages (user, msg) SELECT 'test-user', msg FROM old.messages; \ No newline at end of file diff --git a/database/test/named-versions-init/v0/init.sql b/database/test/named-versions-init/v0/init.sql new file mode 100644 index 0000000..1bcf722 --- /dev/null +++ b/database/test/named-versions-init/v0/init.sql @@ -0,0 +1,4 @@ +CREATE TABLE messages ( + msg TEXT +); +INSERT INTO messages (msg) VALUES ('hello, world'); \ No newline at end of file diff --git a/database/test/raw-init/.ignoreme b/database/test/raw-init/.ignoreme new file mode 100644 index 0000000..99d1197 --- /dev/null +++ b/database/test/raw-init/.ignoreme @@ -0,0 +1 @@ +I'm here so this folder is included in Git commits! \ No newline at end of file diff --git a/database/test/versions-init/v0.10/migrate.sql b/database/test/versions-init/v0.10/migrate.sql new file mode 100644 index 0000000..95c8d19 --- /dev/null +++ b/database/test/versions-init/v0.10/migrate.sql @@ -0,0 +1,2 @@ +ALTER TABLE messages ADD likes INTEGER; +UPDATE messages SET likes = 5; \ No newline at end of file diff --git a/database/test/versions-init/v0.2/init.sql b/database/test/versions-init/v0.2/init.sql new file mode 100644 index 0000000..646d20c --- /dev/null +++ b/database/test/versions-init/v0.2/init.sql @@ -0,0 +1,4 @@ +CREATE TABLE messages ( + user TEXT, + msg TEXT +); \ No newline at end of file diff --git a/database/test/versions-init/v0.2/migrate.sql b/database/test/versions-init/v0.2/migrate.sql new file mode 100644 index 0000000..48adf09 --- /dev/null +++ b/database/test/versions-init/v0.2/migrate.sql @@ -0,0 +1 @@ +INSERT INTO messages (user, msg) SELECT 'test-user', msg FROM old.messages; \ No newline at end of file diff --git a/database/test/versions-init/v0/init.sql b/database/test/versions-init/v0/init.sql new file mode 100644 index 0000000..1bcf722 --- /dev/null +++ b/database/test/versions-init/v0/init.sql @@ -0,0 +1,4 @@ +CREATE TABLE messages ( + msg TEXT +); +INSERT INTO messages (msg) VALUES ('hello, world'); \ No newline at end of file diff --git a/go.mod b/go.mod index 41e9760..707489b 100644 --- a/go.mod +++ b/go.mod @@ -3,8 +3,22 @@ module git.earlybird.gay/today go 1.22.4 require ( - git.earlybird.gay/today-app v0.0.0-20241023050205-d1c3413a0e12 golang.org/x/text v0.19.0 + modernc.org/sqlite v1.33.1 ) -require git.earlybird.gay/today-engine v0.0.0-20240911045033-55d49a64189f // indirect +require ( + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/ncruces/go-strftime v0.1.9 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + golang.org/x/sys v0.22.0 // indirect + modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 // indirect + modernc.org/libc v1.55.3 // indirect + modernc.org/mathutil v1.6.0 // indirect + modernc.org/memory v1.8.0 // indirect + modernc.org/strutil v1.2.0 // indirect + modernc.org/token v1.1.0 // indirect +) diff --git a/go.sum b/go.sum index f849da5..93d587f 100644 --- a/go.sum +++ b/go.sum @@ -1,6 +1,53 @@ -git.earlybird.gay/today-app v0.0.0-20241023050205-d1c3413a0e12 h1:I4PpIONymTb+ti3at+5+Rixs7uApzVWpY9YoGP10b0s= -git.earlybird.gay/today-app v0.0.0-20241023050205-d1c3413a0e12/go.mod h1:ua0E6veNXtTRAXXJPsJP4hzQohFW+0Ogy6PZoX7pHCU= -git.earlybird.gay/today-engine v0.0.0-20240911045033-55d49a64189f h1:vyQTIzkDUvqO3coZArw+jiERQ0xzLVjaZx6n6lIpOxQ= -git.earlybird.gay/today-engine v0.0.0-20240911045033-55d49a64189f/go.mod h1:9w8xpAPxs1QvT//ph/jgAuRIoWyqdi2QEifwsKWOKns= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo= +github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= +github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4= +github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA= +golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ= +golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI= +golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/text v0.19.0 h1:kTxAhCbGbxhK0IwgSKiMO5awPoDQ0RpfiVYBfK860YM= golang.org/x/text v0.19.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= +golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d h1:vU5i/LfpvrRCpgM/VPfJLg5KjxD3E+hfT1SH+d9zLwg= +golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk= +modernc.org/cc/v4 v4.21.4 h1:3Be/Rdo1fpr8GrQ7IVw9OHtplU4gWbb+wNgeoBMmGLQ= +modernc.org/cc/v4 v4.21.4/go.mod h1:HM7VJTZbUCR3rV8EYBi9wxnJ0ZBRiGE5OeGXNA0IsLQ= +modernc.org/ccgo/v4 v4.19.2 h1:lwQZgvboKD0jBwdaeVCTouxhxAyN6iawF3STraAal8Y= +modernc.org/ccgo/v4 v4.19.2/go.mod h1:ysS3mxiMV38XGRTTcgo0DQTeTmAO4oCmJl1nX9VFI3s= +modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE= +modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ= +modernc.org/gc/v2 v2.4.1 h1:9cNzOqPyMJBvrUipmynX0ZohMhcxPtMccYgGOJdOiBw= +modernc.org/gc/v2 v2.4.1/go.mod h1:wzN5dK1AzVGoH6XOzc3YZ+ey/jPgYHLuVckd62P0GYU= +modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 h1:5D53IMaUuA5InSeMu9eJtlQXS2NxAhyWQvkKEgXZhHI= +modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6/go.mod h1:Qz0X07sNOR1jWYCrJMEnbW/X55x206Q7Vt4mz6/wHp4= +modernc.org/libc v1.55.3 h1:AzcW1mhlPNrRtjS5sS+eW2ISCgSOLLNyFzRh/V3Qj/U= +modernc.org/libc v1.55.3/go.mod h1:qFXepLhz+JjFThQ4kzwzOjA/y/artDeg+pcYnY+Q83w= +modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4= +modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo= +modernc.org/memory v1.8.0 h1:IqGTL6eFMaDZZhEWwcREgeMXYwmW83LYW8cROZYkg+E= +modernc.org/memory v1.8.0/go.mod h1:XPZ936zp5OMKGWPqbD3JShgd/ZoQ7899TUuQqxY+peU= +modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4= +modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0= +modernc.org/sortutil v1.2.0 h1:jQiD3PfS2REGJNzNCMMaLSp/wdMNieTbKX920Cqdgqc= +modernc.org/sortutil v1.2.0/go.mod h1:TKU2s7kJMf1AE84OoiGppNHJwvB753OYfNl2WRb++Ss= +modernc.org/sqlite v1.33.1 h1:trb6Z3YYoeM9eDL1O8do81kP+0ejv+YzgyFo+Gwy0nM= +modernc.org/sqlite v1.33.1/go.mod h1:pXV2xHxhzXZsgT/RtTFAPY6JJDEvOTcTdwADQCCWD4k= +modernc.org/strutil v1.2.0 h1:agBi9dp1I+eOnxXeiZawM8F4LawKv4NzGWSaLfyeNZA= +modernc.org/strutil v1.2.0/go.mod h1:/mdcBmfOibveCTBxUl5B5l6W+TTH1FXPLHZE6bTosX0= +modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= +modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= diff --git a/include/callstack.go b/include/callstack.go index 94f53b2..53afd13 100644 --- a/include/callstack.go +++ b/include/callstack.go @@ -42,6 +42,7 @@ func getCallStackButt(ignorePackages []string) (string, error) { count := runtime.Callers(skip, callers) frames := runtime.CallersFrames(callers) + var prev runtime.Frame frame, more := frames.Next() for { // If getCallStackButt gets called from main, use the runtime to @@ -50,7 +51,10 @@ func getCallStackButt(ignorePackages []string) (string, error) { if !more { break } + prev = frame frame, more = frames.Next() + } else if strings.HasPrefix(frame.Function, "testing.") { + return prev.File, nil } else { return frame.File, nil } diff --git a/include/include.go b/include/include.go index 800fc2c..ac34fd4 100644 --- a/include/include.go +++ b/include/include.go @@ -38,6 +38,20 @@ func (fopener *fileOpener) FileName() string { return fopener.absPath } +// Dir gets the directory of the calling file. +func Dir(ignorePackages ...string) (string, error) { + caller, err := getCallStackButt(ignorePackages) + if err != nil { + return "", err + } else { + return path.Dir(caller), nil + } +} + +// Abs gets an absolute path to a file, relative to the caller. +// If you're going to use this to open a file, it's suggested you use +// include.File instead; this is here for when you need to know a path to pass +// to a different package. func Abs(filename string, ignorePackages ...string) (string, error) { if path.IsAbs(filename) { return filename, nil @@ -55,6 +69,8 @@ func Abs(filename string, ignorePackages ...string) (string, error) { // If filename is a relative path, it is considered relative to the *calling // file*, not the working directory. // If ignorePackages is nonempty, callers in any package specified are ignored. +// If there's an error accessing the file, it will be returned when calling +// Open() (Reader, error). func File(filename string, ignorePackages ...string) FileOpener { opener := new(fileOpener) if path.IsAbs(filename) { diff --git a/web/cmd/standard-test/main.go b/web/cmd/standard-test/main.go deleted file mode 100644 index 776abd0..0000000 --- a/web/cmd/standard-test/main.go +++ /dev/null @@ -1,54 +0,0 @@ -package main - -import ( - "context" - "net/http" - "syscall" - "text/template" - - tapp "git.earlybird.gay/today-app/app" - "git.earlybird.gay/today/web/page" - "git.earlybird.gay/today/web/part" - "git.earlybird.gay/today/web/render" - stdpart "git.earlybird.gay/today/web/standard/part" -) - -var Thing = part.New("test-thing", "test_thing.html", - part.OnLoad(func(ctx context.Context, data render.Data) error { - // fmt.Println(data.Get("value")) - return nil - }), -) - -var Page = page.New("index", "pages/index.html", - page.Includes( - stdpart.ContactForm([]string{"Feedback"}), Thing, - ), - page.Funcs(template.FuncMap{ - "SliceOfLen": func(i int) []int { - out := make([]int, i) - for i := range i { - out[i] = i - } - return out - }, - }), -) - -var Static = page.Static("pages/static.html") - -func main() { - app := tapp.New() - tapp.GetEnv().Apply(app) - app.ShutdownOnSignal(syscall.SIGINT, syscall.SIGTERM) - - app.Handle("GET /{$}", Page) - app.Handle("GET /static", Static) - app.Handle("GET /", http.FileServer(http.Dir("public"))) - app.Handle("GET /contact", stdpart.HandleContactForm(nil, stdpart.PrintContact)) - app.Handle("POST /contact", stdpart.HandleContactForm(nil, stdpart.PrintContact)) - - // fmt.Println(Page.Raw()) - - app.ListenAndServe() -} diff --git a/web/cmd/standard-test/pages/index.html b/web/cmd/standard-test/pages/index.html deleted file mode 100644 index b7a2f80..0000000 --- a/web/cmd/standard-test/pages/index.html +++ /dev/null @@ -1,22 +0,0 @@ - - - - - Today Engine Examples - - - - -
- - - - {{- range $i, $v := SliceOfLen 5 }} - - {{ end -}} - - Link to static page -
- - - \ No newline at end of file diff --git a/web/cmd/standard-test/pages/static.html b/web/cmd/standard-test/pages/static.html deleted file mode 100644 index e03b202..0000000 --- a/web/cmd/standard-test/pages/static.html +++ /dev/null @@ -1,16 +0,0 @@ - - - - - Today Engine Examples - - - - -
-

This is a normal static page.

-

It doesn't do anything except exist. Neat.

-
- - - \ No newline at end of file diff --git a/web/cmd/standard-test/public/style.css b/web/cmd/standard-test/public/style.css deleted file mode 100644 index c0a3157..0000000 --- a/web/cmd/standard-test/public/style.css +++ /dev/null @@ -1,51 +0,0 @@ -/* The Great Reset */ -* { - padding: 0; - margin: 0; -} - -/* Containers */ - -html { - font-family: sans-serif; -} - -main, section, nav { - display: flex; - flex-direction: column; - gap: 1rem; -} - -main { - margin: 2rem 25%; -} - -span { - display: inline; -} - -span + span { - margin-left: .5rem; -} - -/* Forms */ - -form { - display: grid; - grid-template-columns: 1fr 3fr; - gap: .5rem; -} - -form > input[type="submit"] { - grid-column: span 2; -} - -/* Typography */ - -:not(pre) > code { - font-size: 1rem; -} - -li { - margin-left: 20px; -} \ No newline at end of file diff --git a/web/cmd/standard-test/test_thing.html b/web/cmd/standard-test/test_thing.html deleted file mode 100644 index 5988d75..0000000 --- a/web/cmd/standard-test/test_thing.html +++ /dev/null @@ -1,3 +0,0 @@ - \ No newline at end of file -- 2.39.5