Skip to content

Commit

Permalink
feat: add support for lazy generation (#874)
Browse files Browse the repository at this point in the history
Co-authored-by: Adrian Hesketh <[email protected]>
  • Loading branch information
Aerek-Yasa and a-h authored Aug 18, 2024
1 parent b5513b9 commit 65c2618
Show file tree
Hide file tree
Showing 7 changed files with 39 additions and 9 deletions.
2 changes: 2 additions & 0 deletions cmd/templ/generatecmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ func (cmd Generate) Run(ctx context.Context) (err error) {
cmd.Args.GenerateSourceMapVisualisations,
cmd.Args.KeepOrphanedFiles,
cmd.Args.FileWriter,
cmd.Args.Lazy,
)

// If we're processing a single file, don't bother setting up the channels/multithreaing.
Expand Down Expand Up @@ -183,6 +184,7 @@ func (cmd Generate) Run(ctx context.Context) (err error) {
cmd.Args.GenerateSourceMapVisualisations,
cmd.Args.KeepOrphanedFiles,
cmd.Args.FileWriter,
cmd.Args.Lazy,
)
errorCount.Store(0)
if err := watcher.WalkFiles(ctx, cmd.Args.Path, events); err != nil {
Expand Down
35 changes: 27 additions & 8 deletions cmd/templ/generatecmd/eventhandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ func NewFSEventHandler(
genSourceMapVis bool,
keepOrphanedFiles bool,
fileWriter FileWriterFunc,
lazy bool,
) *FSEventHandler {
if !path.IsAbs(dir) {
dir, _ = filepath.Abs(dir)
Expand All @@ -63,6 +64,7 @@ func NewFSEventHandler(
DevMode: devMode,
keepOrphanedFiles: keepOrphanedFiles,
writer: fileWriter,
lazy: lazy,
}
if devMode {
fseh.genOpts = append(fseh.genOpts, generator.WithExtractStrings())
Expand All @@ -86,6 +88,7 @@ type FSEventHandler struct {
Errors []error
keepOrphanedFiles bool
writer func(string, []byte) error
lazy bool
}

func (h *FSEventHandler) HandleEvent(ctx context.Context, event fsnotify.Event) (goUpdated, textUpdated bool, err error) {
Expand Down Expand Up @@ -125,10 +128,16 @@ func (h *FSEventHandler) HandleEvent(ctx context.Context, event fsnotify.Event)
}

// If the file hasn't been updated since the last time we processed it, ignore it.
if !h.UpsertLastModTime(event.Name) {
lastModTime, updatedModTime := h.UpsertLastModTime(event.Name)
if !updatedModTime {
h.Log.Debug("Skipping file because it wasn't updated", slog.String("file", event.Name))
return false, false, nil
}
// If the go file is newer than the templ file, skip generation, because it's up-to-date.
if h.lazy && goFileIsUpToDate(event.Name, lastModTime) {
h.Log.Debug("Skipping file because the Go file is up-to-date", slog.String("file", event.Name))
return false, false, nil
}

// Start a processor.
start := time.Now()
Expand Down Expand Up @@ -159,6 +168,15 @@ func (h *FSEventHandler) HandleEvent(ctx context.Context, event fsnotify.Event)
return goUpdated, textUpdated, nil
}

func goFileIsUpToDate(templFileName string, templFileLastMod time.Time) (upToDate bool) {
goFileName := strings.TrimSuffix(templFileName, ".templ") + "_templ.go"
goFileInfo, err := os.Stat(goFileName)
if err != nil {
return false
}
return goFileInfo.ModTime().After(templFileLastMod)
}

func (h *FSEventHandler) SetError(fileName string, hasError bool) (previouslyHadError bool, errorCount int) {
h.fileNameToErrorMutex.Lock()
defer h.fileNameToErrorMutex.Unlock()
Expand All @@ -170,19 +188,20 @@ func (h *FSEventHandler) SetError(fileName string, hasError bool) (previouslyHad
return previouslyHadError, len(h.fileNameToError)
}

func (h *FSEventHandler) UpsertLastModTime(fileName string) (updated bool) {
func (h *FSEventHandler) UpsertLastModTime(fileName string) (modTime time.Time, updated bool) {
fileInfo, err := os.Stat(fileName)
if err != nil {
return false
return modTime, false
}
h.fileNameToLastModTimeMutex.Lock()
defer h.fileNameToLastModTimeMutex.Unlock()
lastModTime := h.fileNameToLastModTime[fileName]
if !fileInfo.ModTime().After(lastModTime) {
return false
previousModTime := h.fileNameToLastModTime[fileName]
currentModTime := fileInfo.ModTime()
if !currentModTime.After(previousModTime) {
return currentModTime, false
}
h.fileNameToLastModTime[fileName] = fileInfo.ModTime()
return true
h.fileNameToLastModTime[fileName] = currentModTime
return currentModTime, true
}

func (h *FSEventHandler) UpsertHash(fileName string, hash [sha256.Size]byte) (updated bool) {
Expand Down
1 change: 1 addition & 0 deletions cmd/templ/generatecmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ type Arguments struct {
// PPROFPort is the port to run the pprof server on.
PPROFPort int
KeepOrphanedFiles bool
Lazy bool
}

func Run(ctx context.Context, log *slog.Logger, args Arguments) (err error) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func TestErrorLocationMapping(t *testing.T) {

slog := slog.New(slog.NewTextHandler(io.Discard, &slog.HandlerOptions{}))
var fw generatecmd.FileWriterFunc
fseh := generatecmd.NewFSEventHandler(slog, ".", false, []generator.GenerateOpt{}, false, false, fw)
fseh := generatecmd.NewFSEventHandler(slog, ".", false, []generator.GenerateOpt{}, false, false, fw, false)
for _, test := range tests {
// The raw files cannot end in .templ because they will cause the generator to fail. Instead,
// we create a tmp file that ends in .templ only for the duration of the test.
Expand Down
4 changes: 4 additions & 0 deletions cmd/templ/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,8 @@ Args:
If present, the command will issue a reload event to the proxy 127.0.0.1:7331, or use proxyport and proxybind to specify a different address.
-w
Number of workers to use when generating code. (default runtime.NumCPUs)
-lazy
Only generate .go files if the source .templ file is newer.
-pprof
Port to run the pprof server on.
-keep-orphaned-files
Expand Down Expand Up @@ -215,6 +217,7 @@ func generateCmd(stdout, stderr io.Writer, args []string) (code int) {
keepOrphanedFilesFlag := cmd.Bool("keep-orphaned-files", false, "")
verboseFlag := cmd.Bool("v", false, "")
logLevelFlag := cmd.String("log-level", "info", "")
lazyFlag := cmd.Bool("lazy", false, "")
helpFlag := cmd.Bool("help", false, "")
err := cmd.Parse(args)
if err != nil {
Expand Down Expand Up @@ -259,6 +262,7 @@ func generateCmd(stdout, stderr io.Writer, args []string) (code int) {
IncludeTimestamp: *includeTimestampFlag,
PPROFPort: *pprofPortFlag,
KeepOrphanedFiles: *keepOrphanedFilesFlag,
Lazy: *lazyFlag,
})
if err != nil {
color.New(color.FgRed).Fprint(stderr, "(✗) ")
Expand Down
2 changes: 2 additions & 0 deletions docs/docs/04-core-concepts/02-template-generation.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ Args:
If present, the command will issue a reload event to the proxy 127.0.0.1:7331, or use proxyport and proxybind to specify a different address.
-w
Number of workers to use when generating code. (default runtime.NumCPUs)
-lazy
Only generate .go files if the source .templ file is newer.
-pprof
Port to run the pprof server on.
-keep-orphaned-files
Expand Down
2 changes: 2 additions & 0 deletions docs/docs/09-commands-and-tools/01-cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ Args:
The address the proxy will listen on. (default 127.0.0.1)
-w
Number of workers to use when generating code. (default runtime.NumCPUs)
-lazy
Only generate .go files if the source .templ file is newer.
-pprof
Port to run the pprof server on.
-keep-orphaned-files
Expand Down

0 comments on commit 65c2618

Please sign in to comment.