Skip to content

Commit

Permalink
feat: determine package name, ci, etc
Browse files Browse the repository at this point in the history
  • Loading branch information
garrettladley committed Nov 4, 2024
1 parent 3c2c97d commit 1fd1582
Show file tree
Hide file tree
Showing 9 changed files with 247 additions and 9 deletions.
114 changes: 114 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
name: CI

permissions: read-all

on:
push:
paths:
- **/*.go
- .github/workflows/ci.yml

concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

jobs:
format:
name: Format
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: "1.23"
- name: Get Go Cache Paths
id: go-cache-paths
run: |
echo "go-build=$(go env GOCACHE)" >> $GITHUB_OUTPUT
echo "go-mod=$(go env GOMODCACHE)" >> $GITHUB_OUTPUT
- name: Install gofumpt
run: go install mvdan.cc/gofumpt@latest
- name: Go Build Cache
uses: actions/cache@v4
with:
path: ${{ steps.go-cache-paths.outputs.go-build }}
key: ${{ runner.os }}-go-build-${{ hashFiles('**/go.sum') }}
- name: Go Mod Cache
uses: actions/cache@v4
with:
path: ${{ steps.go-cache-paths.outputs.go-mod }}
key: ${{ runner.os }}-go-mod-${{ hashFiles('**/go.sum') }}
- name: Check Code Formatting
run: |
unformatted_files=$(gofumpt -l .)
if [ -n "$unformatted_files" ]; then
echo "Files not formatted:"
echo "$unformatted_files"
exit 1
fi
lint:
name: Lint
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: read
checks: write
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: "1.23"
- name: Get Go Cache Paths
id: go-cache-paths
run: |
echo "go-build=$(go env GOCACHE)" >> $GITHUB_OUTPUT
echo "go-mod=$(go env GOMODCACHE)" >> $GITHUB_OUTPUT
- name: Go Build Cache
uses: actions/cache@v4
with:
path: ${{ steps.go-cache-paths.outputs.go-build }}
key: ${{ runner.os }}-go-build-${{ hashFiles('**/go.sum') }}
- name: Go Mod Cache
uses: actions/cache@v4
with:
path: ${{ steps.go-cache-paths.outputs.go-mod }}
key: ${{ runner.os }}-go-mod-${{ hashFiles('**/go.sum') }}
- name: golangci-lint
uses: golangci/golangci-lint-action@v5
with:
version: latest
working-directory: ./
args: --timeout=5m

test:
name: Test
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: "1.23"
- name: Get Go Cache Paths
id: go-cache-paths
run: |
echo "go-build=$(go env GOCACHE)" >> $GITHUB_OUTPUT
echo "go-mod=$(go env GOMODCACHE)" >> $GITHUB_OUTPUT
- name: Go Build Cache
uses: actions/cache@v4
with:
path: ${{ steps.go-cache-paths.outputs.go-build }}
key: ${{ runner.os }}-go-build-${{ hashFiles('**/go.sum') }}
- name: Go Mod Cache
uses: actions/cache@v4
with:
path: ${{ steps.go-cache-paths.outputs.go-mod }}
key: ${{ runner.os }}-go-mod-${{ hashFiles('**/go.sum') }}
- name: Run Tests with Coverage
run: go test -v -race -coverprofile=coverage.txt ./...
- name: Print Coverage
run: go tool cover -func=coverage.txt
2 changes: 1 addition & 1 deletion TODO.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
- [ ] Determine package name to be generated
- [ X ] Determine package name to be generated
- [ ] Determine language to be used in lexer
- [ ] Drill down style
- [ ] Flag for with version
Expand Down
2 changes: 1 addition & 1 deletion cmd/snips/generatecmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ import (
"sync/atomic"
"time"

"github.com/a-h/templ/cmd/templ/generatecmd/watcher"
"github.com/alecthomas/chroma/v2/formatters/html"
"github.com/fsnotify/fsnotify"
"github.com/garrettladley/snips/cmd/snips/generatecmd/modcheck"
"github.com/garrettladley/snips/cmd/snips/generatecmd/watcher"
)

func NewGenerate(log *slog.Logger, args Arguments) (g *Generate) {
Expand Down
6 changes: 5 additions & 1 deletion cmd/snips/generatecmd/eventhandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (

"github.com/alecthomas/chroma/v2/formatters/html"
"github.com/fsnotify/fsnotify"
"github.com/garrettladley/snips"
"github.com/garrettladley/snips/generator"
)

Expand Down Expand Up @@ -101,7 +102,7 @@ func (h *FSEventHandler) HandleEvent(ctx context.Context, event fsnotify.Event)
}

// Handle .code.* files.
if !IsCodeFile(event.Name) {
if !snips.ContainsDotCodeDot(event.Name) {
return false, false, nil
}

Expand Down Expand Up @@ -174,6 +175,9 @@ func (h *FSEventHandler) UpsertHash(fileName string, hash [sha256.Size]byte) (up
// generate Go code for a single template.
// If a basePath is provided, the filename included in error messages is relative to it.
func (h *FSEventHandler) generate(fileName string) (goUpdated, textUpdated bool, err error) {
fmt.Println(fileName, snips.PackageName(fileName))

// remove .code. from the filename
targetFileName := fileName + ".templ"

// Only use relative filenames to the basepath for filenames in runtime error messages.
Expand Down
6 changes: 2 additions & 4 deletions cmd/snips/generatecmd/watcher/watch.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package watcher

import (
"context"
"fmt"
"io/fs"
"os"
"path"
Expand All @@ -12,7 +11,7 @@ import (
"time"

"github.com/fsnotify/fsnotify"
"github.com/garrettladley/snips/cmd/snips/generatecmd"
"github.com/garrettladley/snips"
)

func Recursive(
Expand Down Expand Up @@ -73,8 +72,7 @@ type RecursiveWatcher struct {
}

func shouldIncludeFile(name string) bool {
fmt.Println(name, generatecmd.IsCodeFile(name))
return generatecmd.IsCodeFile(name)
return snips.ContainsDotCodeDot(name)
}

type timerKey struct {
Expand Down
4 changes: 2 additions & 2 deletions cmd/snips/generatecmd/ext.go → code.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package generatecmd
package snips

import "strings"

func IsCodeFile(name string) bool {
func ContainsDotCodeDot(name string) bool {
index := strings.LastIndex(name, ".code.")
return index != -1 && index < len(name)-6
}
10 changes: 10 additions & 0 deletions generator/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package generator
import (
"io"
"path/filepath"
"strings"
"time"

"github.com/alecthomas/chroma/v2"
Expand Down Expand Up @@ -39,6 +40,15 @@ func WithFileName(name string) GenerateOpt {
}
}

func WithExtractStrings() GenerateOpt {
return func(g *generator) error {
g.w.literalWriter = &watchLiteralWriter{
builder: &strings.Builder{},
}
return nil
}
}

type generator struct {
f chroma.Formatter
w *RangeWriter
Expand Down
48 changes: 48 additions & 0 deletions package.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package snips

import (
"os"
"path/filepath"
"strings"
)

func PackageName(dir string) (name string) {
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() && strings.HasSuffix(info.Name(), ".templ") {
content, err := os.ReadFile(path)
if err != nil {
return err
}
lines := strings.Split(string(content), "\n")
for _, line := range lines {
if strings.HasPrefix(strings.TrimSpace(line), "package ") {
name = strings.TrimSpace(strings.TrimPrefix(line, "package"))
return filepath.SkipAll // stop walking, we found a package name
}
}
}
return nil
})

if err != nil || name == "" {
return fallback(dir)
}

return name
}

func fallback(dir string) (name string) {
var (
parts = strings.Split(filepath.ToSlash(dir), "/")
n = len(parts)
)

if n > 1 {
return parts[n-1]
}

return ""
}
64 changes: 64 additions & 0 deletions package_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package snips_test

import (
"os"
"path/filepath"
"testing"

"github.com/garrettladley/snips"
)

func TestPackageNameSameAsDirectory(t *testing.T) {
dir := createTempDir(t)
filePath := filepath.Join(dir, "views", "foo", "bar.templ")
createTempFile(t, filePath, "package foo\n\ntempl Hello(name string) {\n <div>Hello, { name }</div>\n}")

pkg := snips.PackageName(filepath.Join(dir, "views", "foo"))
if pkg != "foo" {
t.Fatalf("expected package name to be 'foo', got '%s'", pkg)
}
}

func TestPackageNameDifferentFromDirectory(t *testing.T) {
dir := createTempDir(t)
filePath := filepath.Join(dir, "views", "foo", "bar.templ")
createTempFile(t, filePath, "package bar\n\ntempl Hello(name string) {\n <div>Hello, { name }</div>\n}")

pkg := snips.PackageName(filepath.Join(dir, "views", "foo"))
if pkg != "bar" {
t.Fatalf("expected package name to be 'bar', got '%s'", pkg)
}
}

func TestPackageNameFallback(t *testing.T) {
dir := createTempDir(t)
filePath := filepath.Join(dir, "views", "foo", "ex.rs")
createTempFile(t, filePath, "fn main() {\n println!(\"Hello World!\");\n}")

pkg := snips.PackageName(filepath.Join(dir, "views", "foo"))
if pkg != "foo" {
t.Fatalf("expected package name to be 'foo', got '%s'", pkg)
}
}

func createTempDir(t *testing.T) string {
t.Helper()
dir, err := os.MkdirTemp("", "snips")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_ = os.RemoveAll(dir)
})
return dir
}

func createTempFile(t *testing.T, path, content string) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(content), 0644); err != nil {
t.Fatal(err)
}
}

0 comments on commit 1fd1582

Please sign in to comment.