Add a tool to manage modules

This commit is contained in:
Sasha Koshka 2024-02-23 01:41:36 -05:00
parent 3297f6671e
commit 14b36bba1a
2 changed files with 109 additions and 0 deletions

2
cmd/fsplmod/doc.go Normal file
View File

@ -0,0 +1,2 @@
// fsplmod manages FSPL modules.
package main

107
cmd/fsplmod/main.go Normal file
View File

@ -0,0 +1,107 @@
package main
import "io"
import "os"
import "path/filepath"
import "github.com/google/uuid"
import "git.tebibyte.media/fspl/fspl/cli"
import "git.tebibyte.media/fspl/fspl/lexer"
import "git.tebibyte.media/fspl/fspl/entity"
import "git.tebibyte.media/fspl/fspl/parser/meta"
import ferrors "git.tebibyte.media/fspl/fspl/errors"
func main () {
// CLI: application
applicationCli := cli.New (
"Manage FSPL modules",
cli.NewHelp())
// CLI: new
newCli := cli.New (
"Create a new module in the specified directory",
cli.NewHelp())
newCli.Syntax = "[OPTION]... DIRECTORY"
applicationCli.AddSub("new", newCli)
// CLI: bump
bumpCli := cli.New (
"Re-generate the UUID of a module",
cli.NewHelp())
newCli.Syntax = "[OPTION]... DIRECTORY"
applicationCli.AddSub("bump", bumpCli)
handleErr := func (cli *cli.Cli, err error, code int) {
if err == nil { return }
cli.Errorln(ferrors.Format(err))
os.Exit(code)
}
switch cli := applicationCli.ParseOrExit(os.Args); cli {
case newCli:
// Create a new module in the specified directory
if len(cli.Args) != 1 {
cli.Errorln("please specify one module directory")
cli.Usage()
os.Exit(2)
}
dir := cli.Args[0]
_, err := os.Stat(dir)
if err != nil {
err := os.Mkdir(dir, 0755)
handleErr(cli, err, 1)
}
moduleId, err := uuid.NewRandom()
handleErr(cli, err, 1)
cli.Println("creating module", moduleId, "in", dir)
metadataPath := filepath.Join(dir, "fspl.mod")
file, err := os.OpenFile (
metadataPath,
os.O_CREATE | os.O_WRONLY | os.O_TRUNC,
0644)
handleErr(cli, err, 1)
defer file.Close()
meta := entity.Metadata {
UUID: moduleId,
}
_, err = io.WriteString(file, meta.String() + "\n")
handleErr(cli, err, 1)
case bumpCli:
// Re-generate the UUID of a module
if len(cli.Args) != 1 {
cli.Errorln("please specify one module directory")
cli.Usage()
os.Exit(2)
}
dir := cli.Args[0]
metadataPath := filepath.Join(dir, "fspl.mod")
file, err := os.OpenFile(metadataPath, os.O_RDWR, 0644)
handleErr(cli, err, 1)
defer file.Close()
lx, err := lexer.LexReader(metadataPath, file)
handleErr(cli, err, 1)
meta := metaParser.Tree { }
err = meta.Parse(lx)
handleErr(cli, err, 1)
newModuleId, err := uuid.NewRandom()
handleErr(cli, err, 1)
cli.Println("changing uuid of", dir + ":", meta.UUID, "->", newModuleId)
meta.UUID = newModuleId
file.Truncate(0)
file.Seek(0, 0)
_, err = io.WriteString(file, meta.String() + "\n")
handleErr(cli, err, 1)
default:
applicationCli.Usage()
os.Exit(2)
}
}