Skip to content

Commit

Permalink
feat: add init command and it's actions
Browse files Browse the repository at this point in the history
  • Loading branch information
barelyhuman committed May 16, 2024
1 parent 3ffb933 commit dbd599c
Show file tree
Hide file tree
Showing 7 changed files with 206 additions and 16 deletions.
159 changes: 159 additions & 0 deletions commands/init.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
package commands

import (
"fmt"
"os"
"path/filepath"

"github.com/barelyhuman/alvu/pkg/alvu"
"github.com/barelyhuman/go/color"
"github.com/urfave/cli/v2"
)

func AlvuInit(c *cli.Context) (err error) {
basePath := c.Args().First()
forceFlag := c.Bool("force")
logger := alvu.NewLogger()
logger.LogPrefix = "[alvu]"

fileInfo, err := os.Stat(basePath)

if err == nil {
if fileInfo.IsDir() && !forceFlag {
logger.Error(fmt.Sprintf("Directory: %v , already exists, cannot overwrite, if you wish to force overwrite use the -f flag with the `init` command", basePath))
os.Exit(1)
}
}

mustCreateDir(basePath, "public")
mustCreateDir(basePath, "hooks")
mustCreateDir(basePath, "pages")
prepareBaseStyles(basePath)
preparePages(basePath)

logger.Success(
fmt.Sprintf("Alvu initialized in: %v", basePath),
)

runStr := color.ColorString{}

fmt.Println(runStr.Dim("\n> Run the following to get started").String())

commandStr := color.ColorString{}
commandStr.Cyan(
fmt.Sprintf("\n alvu -s -path %v\n", basePath),
)
fmt.Println(commandStr.String())
return
}

func mustCreateDir(root, dir string) {
pathToCreate := filepath.Join(root, dir)
err := os.MkdirAll(pathToCreate, os.ModePerm)
if err != nil {
panic(fmt.Sprintf("Failed to create %v due to error: %v\n", pathToCreate, err))
}
}

func prepareBaseStyles(root string) {
fileHandle, err := os.OpenFile(filepath.Join(root, "public", "styles.css"), os.O_CREATE|os.O_RDWR, os.ModePerm)
if err != nil {
fmt.Printf("Failed to open file public/styles.css with error: %v", err)
}
defer fileHandle.Sync()
defer fileHandle.Close()

fileHandle.WriteString(`
/* Resets */
html {
box-sizing: border-box;
font-size: 16px;
font-family: -apple-system, BlinkMacSystemFont, avenir next, avenir, segoe ui, helvetica neue, helvetica, Cantarell, Ubuntu, roboto, noto, arial, sans-serif;
}
*, *:before, *:after {
box-sizing: inherit;
}
body, h1, h2, h3, h4, h5, h6, p {
margin: 0;
padding: 0;
font-weight: normal;
}
img {
max-width: 100%;
height: auto;
}
/* Styles */
:root {
--base: #efefef;
--text: #181819;
}
@media (prefers-color-scheme: dark) {
:root {
--base: #181819;
--text: #efefef;
}
}
body {
background: var(--base);
color: var(--text);
max-width: 900px;
margin: 0 auto;
padding: 4px;
display: flex;
flex-direction: column;
justify-content: center;
min-height: 100vh;
}
ol,ul,p{
line-height: 1.7;
}
`)

}

func preparePages(root string) {
layoutHandle, _ := os.OpenFile(filepath.Join(root, "pages", "_layout.html"), os.O_CREATE|os.O_RDWR, os.ModePerm)
defer layoutHandle.Sync()
defer layoutHandle.Close()

rootPageHandle, _ := os.OpenFile(filepath.Join(root, "pages", "index.md"), os.O_CREATE|os.O_RDWR, os.ModePerm)

defer rootPageHandle.Sync()
defer rootPageHandle.Close()

layoutHandle.WriteString(`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Alvu | Minimal Starter</title>
<link href="/styles.css" rel="stylesheet">
</head>
<body>
<slot></slot>
</body>
</html>`)

rootPageHandle.WriteString(`# Alvu
- Scriptable
- Fast
- Tiny
In whatever order you'd like...
`)

}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ module github.com/barelyhuman/alvu
go 1.18

require (
github.com/barelyhuman/go v0.2.2
github.com/barelyhuman/go v0.2.3-0.20240516192751-30a6c804e4e5
github.com/cjoudrey/gluahttp v0.0.0-20201111170219-25003d9adfa9
github.com/joho/godotenv v1.5.1
github.com/urfave/cli/v2 v2.27.1
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRF
github.com/alecthomas/units v0.0.0-20190924025748-f65c72e2690d/go.mod h1:rBZYJk541a8SKzHPHnH3zbiI+7dagKZ0cgpgrD7Fyho=
github.com/alessio/shellescape v1.4.1/go.mod h1:PZAiSCk0LJaZkiCSkPv8qIobYglO3FPpyFjDCtHLS30=
github.com/aws/aws-sdk-go v1.34.0/go.mod h1:5zCpMtNQVjRREroY7sYe8lOMRSxkhG6MZveU8YkpAk0=
github.com/barelyhuman/go v0.2.2 h1:Lpk1XrlP40F3II8BibVzViZUOJ1GgDdzXUBb8ENwb0U=
github.com/barelyhuman/go v0.2.2/go.mod h1:hox2iDYZAarjpS7jKQeYIi2F+qMA8KLMtCws++L2sSY=
github.com/barelyhuman/go v0.2.3-0.20240516192751-30a6c804e4e5 h1:AbJ6ZaRkEc6CguQ6rXe0epKmFe/TmwSSFX5N6hsNO+A=
github.com/barelyhuman/go v0.2.3-0.20240516192751-30a6c804e4e5/go.mod h1:hox2iDYZAarjpS7jKQeYIi2F+qMA8KLMtCws++L2sSY=
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
Expand Down
18 changes: 18 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,24 @@ func main() {
Version: version,
Compiled: time.Now(),
HideVersion: false,
Commands: []*cli.Command{
{
Name: "init",
Description: "Initialise a new alvu Project",
Args: true,
ArgsUsage: "<directory>",
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "force",
Aliases: []string{"f"},
Usage: "Force create in the directory even overwriting any files that exist",
},
},
Action: func(ctx *cli.Context) error {
return commands.AlvuInit(ctx)
},
},
},
}

err := app.Run(os.Args)
Expand Down
13 changes: 7 additions & 6 deletions pkg/alvu/alvu.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,8 @@ func (ac *AlvuConfig) Rebuild(path string) {
}

func (ac *AlvuConfig) Run() error {
ac.logger = Logger{
logPrefix: "[alvu]",
}
ac.logger = NewLogger()
ac.logger.LogPrefix = "[alvu]"

ac.rebuildCond = sync.NewCond(&ac.rebuildLock)
ac.connections = make(map[*websocket.Conn]struct{})
Expand Down Expand Up @@ -158,9 +157,11 @@ func (ac *AlvuConfig) Build() error {
return err
}

ac.watcher.AddDir(pageDir)
ac.watcher.AddDir(publicDir)
ac.watcher.AddDir(hooksDir)
if ac.Serve {
ac.watcher.AddDir(pageDir)
ac.watcher.AddDir(publicDir)
ac.watcher.AddDir(hooksDir)
}

normalizedFiles, err := runTransfomers(filesToProcess, ac)
if err != nil {
Expand Down
10 changes: 9 additions & 1 deletion pkg/alvu/hooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package alvu
import (
"encoding/json"
"fmt"
"io"
"io/fs"
"net/http"
"os"
Expand Down Expand Up @@ -52,13 +53,20 @@ func (h *Hooks) Load() {
if os.IsNotExist(err) {
return
}

readHookDirError(err, hookDir, h.ac.logger)
}

file, err := os.Open(hookDir)
readHookDirError(err, hookDir, h.ac.logger)
childs, err := file.Readdirnames(1)
readHookDirError(err, hookDir, h.ac.logger)
if err != nil {
if err == io.EOF {
return
}
readHookDirError(err, hookDir, h.ac.logger)
}

if len(childs) == 0 {
return
}
Expand Down
16 changes: 10 additions & 6 deletions pkg/alvu/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,11 @@ import (
)

type Logger struct {
logPrefix string
LogPrefix string
}

func NewLogger() Logger {
return Logger{}
}

func (l *Logger) Debug(msg string) {
Expand All @@ -17,30 +21,30 @@ func (l *Logger) Debug(msg string) {
return
}
cs := color.ColorString{}
cs.Gray(l.logPrefix).Reset(" ").Gray("-").Reset(" ").Gray(msg)
cs.Gray(l.LogPrefix).Reset(" ").Gray("-").Reset(" ").Gray(msg)
fmt.Println(cs.String())
}

func (l *Logger) Success(msg string) {
cs := color.ColorString{}
cs.Gray(l.logPrefix).Reset(" ").Green("✔").Reset(" ").Green(msg)
cs.Gray(l.LogPrefix).Reset(" ").Green("✔").Reset(" ").Green(msg)
fmt.Println(cs.String())
}

func (l *Logger) Info(msg string) {
cs := color.ColorString{}
cs.Gray(l.logPrefix).Reset(" ").Cyan("ℹ").Reset(" ").Cyan(msg)
cs.Gray(l.LogPrefix).Reset(" ").Cyan("ℹ").Reset(" ").Cyan(msg)
fmt.Println(cs.String())
}

func (l *Logger) Warning(msg string) {
cs := color.ColorString{}
cs.Gray(l.logPrefix).Reset(" ").Yellow(msg)
cs.Gray(l.LogPrefix).Reset(" ").Yellow(msg)
fmt.Println(cs.String())
}

func (l *Logger) Error(msg string) {
cs := color.ColorString{}
cs.Gray(l.logPrefix).Reset(" ").Red(msg)
cs.Gray(l.LogPrefix).Reset(" ").Red(msg)
fmt.Println(cs.String())
}

0 comments on commit dbd599c

Please sign in to comment.