Skip to content
This repository has been archived by the owner on Feb 24, 2024. It is now read-only.

Add reload.FS for hot reloading during development #2180

Merged
merged 7 commits into from
Nov 28, 2021
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions reload/fs.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package reload
sio4 marked this conversation as resolved.
Show resolved Hide resolved

import (
"fmt"
"io/fs"
"os"
)

type FS struct {
embed fs.FS
dir fs.FS
}

func NewFS(embed fs.ReadDirFS, dir string) FS {
return FS{
embed: embed,
dir: os.DirFS(dir),
}
}

func (f FS) Open(name string) (fs.File, error) {
if name == "embed.go" {
return nil, fs.ErrNotExist
}
file, err := f.getFile(name)
if name != "." {
return file, err
}
return rootFile{file}, err
fasmat marked this conversation as resolved.
Show resolved Hide resolved
}

func (f FS) getFile(name string) (fs.File, error) {
cfgFile := "./.buffalo.dev.yml"
if _, err := os.Stat(cfgFile); err != nil {
return f.embed.Open(name)
}
return f.dir.Open(name)
}
fasmat marked this conversation as resolved.
Show resolved Hide resolved

type rootFile struct {
fs.File
}

func (f rootFile) ReadDir(n int) ([]fs.DirEntry, error) {
dir, ok := f.File.(fs.ReadDirFile)
if !ok {
return nil, fmt.Errorf("failed at hiding embed.go file")
fasmat marked this conversation as resolved.
Show resolved Hide resolved
}
entries, err := dir.ReadDir(n)
if err != nil {
return entries, err
}

for i, entry := range entries {
if entry.Name() == "embed.go" {
entries = append(entries[:i], entries[i+1:]...)
}
sio4 marked this conversation as resolved.
Show resolved Hide resolved
}
return entries, nil
}