Skip to content

Commit

Permalink
Gofumpt, staticcheck
Browse files Browse the repository at this point in the history
  • Loading branch information
baalimago committed Aug 18, 2024
1 parent ecc9954 commit 25749cc
Show file tree
Hide file tree
Showing 10 changed files with 63 additions and 75 deletions.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# (W)eb (D)evelopment-(40)
# (w)eb (d)evelopment-(40)
[![Go Report Card](https://goreportcard.com/badge/github.com/baalimago/wd-40)](https://goreportcard.com/report/github.com/baalimago/wd-40)
[![wakatime](https://wakatime.com/badge/user/018cc8d2-3fd9-47ef-81dc-e4ad645d5f34/project/3bc921ec-dc23-4222-bf00-578f2eda0cbd.svg)](https://wakatime.com/badge/user/018cc8d2-3fd9-47ef-81dc-e4ad645d5f34/project/3bc921ec-dc23-4222-bf00-578f2eda0cbd)

Expand All @@ -15,9 +15,9 @@ This is a static webserver which hot-reloads your web-browser on any local filec
1. The web server is started, hosting the _mirrored_ content
1. The `delta-streamer.js` in turn sets up a websocket connection to wd-40
1. The original file system is monitored, on any file changes:
1. the new file is copied to the mirror
1. the file name is propagated to the browser via the websocket
1. if the browser's origin matches the recently updated file, the browser is told to reload via javascript
1. the new file is copied to the mirror
1. the file name is propagated to the browser via the websocket
1. if the browser's origin matches the recently updated file, the browser is told to reload via javascript

```
┌───────────────┐
Expand Down
2 changes: 1 addition & 1 deletion cmd/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ var commands = map[string]Command{

func Parse(args []string) (Command, error) {
if len(args) == 1 {
return nil, NoArgsError
return nil, ErrNoArgs
}
cmdCandidate := ""
for _, arg := range args[1:] {
Expand Down
3 changes: 1 addition & 2 deletions cmd/setup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,10 @@ func Test_Parse(t *testing.T) {

t.Run("it should return NoArgsError on lack of second argument", func(t *testing.T) {
_, gotErr := Parse([]string{"/some/cli/path"})
if !errors.Is(gotErr, NoArgsError) {
if !errors.Is(gotErr, ErrNoArgs) {
t.Fatalf("expected to get HelpfulError, got: %v", gotErr)
}
})

}

func TestFormatCommandDescriptions(t *testing.T) {
Expand Down
12 changes: 8 additions & 4 deletions cmd/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,18 @@ type Command interface {
Flagset() *flag.FlagSet
}

type ArgParser func([]string) (Command, error)
type UsagePrinter func()
type (
ArgParser func([]string) (Command, error)
UsagePrinter func()
)

type ArgNotFoundError string

func (e ArgNotFoundError) Error() string {
return fmt.Sprintf("'%v' is not a valid argument\n", string(e))
}

var HelpfulError = errors.New("user needs help")
var NoArgsError = errors.New("no arguments found")
var (
ErrHelpful = errors.New("user needs help")
ErrNoArgs = errors.New("no arguments found")
)
74 changes: 32 additions & 42 deletions internal/wsinject/delta_streamer.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,39 +18,31 @@ func (fs *Fileserver) WsHandler(ws *websocket.Conn) {
go func() {
ancli.PrintfOK("new websocket connection: '%v'", ws.Config().Origin)
for {
select {
case pageToReload, ok := <-reloadChan:
if !ok {
killChan <- struct{}{}
}
err := websocket.Message.Send(ws, pageToReload)
if err != nil {
// Exit on error
ancli.PrintfErr("ws: failed to send message via ws: %v", err)
killChan <- struct{}{}
}
pageToReload, ok := <-reloadChan
if !ok {
killChan <- struct{}{}
}
err := websocket.Message.Send(ws, pageToReload)
if err != nil {
// Exit on error
ancli.PrintfErr("ws: failed to send message via ws: %v", err)
killChan <- struct{}{}
}
}
}()

ancli.PrintOK("Listening to file changes on pageReloadChan")
fs.registerWs(name, reloadChan)
for {
select {
case <-killChan:
ancli.PrintOK("websocket disconnected")
fs.deregisterWs(name)
err := ws.WriteClose(1005)
if err != nil {
ancli.PrintfErr("ws-listener: '%v' got err when writeclosing: %v", name, err)
}
err = ws.Close()
if err != nil {
ancli.PrintfErr("ws-listener: '%v' got err when closing: %v", name, err)
}

return
}
<-killChan
ancli.PrintOK("websocket disconnected")
fs.deregisterWs(name)
err := ws.WriteClose(1005)
if err != nil {
ancli.PrintfErr("ws-listener: '%v' got err when writeclosing: %v", name, err)
}
err = ws.Close()
if err != nil {
ancli.PrintfErr("ws-listener: '%v' got err when closing: %v", name, err)
}
}

Expand All @@ -69,26 +61,24 @@ func (fs *Fileserver) deregisterWs(name string) {

func (fs *Fileserver) wsDispatcherStart() {
for {
select {
case pageToReload, ok := <-fs.pageReloadChan:
if !ok {
ancli.PrintNotice("stopping wsDispatcher")
fs.wsDispatcher.Range(func(key, value any) bool {
ancli.PrintfNotice("sending to: '%v'", key)
wsWriterChan := value.(chan string)
// Close chan to stop the wsRoutine
close(wsWriterChan)
return true
})
return
}
ancli.PrintfNotice("got update: '%v'", pageToReload)
pageToReload, ok := <-fs.pageReloadChan
if !ok {
ancli.PrintNotice("stopping wsDispatcher")
fs.wsDispatcher.Range(func(key, value any) bool {
ancli.PrintfNotice("sending to: '%v'", key)
wsWriterChan := value.(chan string)
wsWriterChan <- pageToReload
// Close chan to stop the wsRoutine
close(wsWriterChan)
return true
})
return
}
ancli.PrintfNotice("got update: '%v'", pageToReload)
fs.wsDispatcher.Range(func(key, value any) bool {
ancli.PrintfNotice("sending to: '%v'", key)
wsWriterChan := value.(chan string)
wsWriterChan <- pageToReload
return true
})
}
}
4 changes: 1 addition & 3 deletions internal/wsinject/delta_streamer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import (
)

func TestWsHandler(t *testing.T) {

ancli.Newline = true
setup := func(t *testing.T) (*Fileserver, *websocket.Config, *httptest.Server) {
t.Helper()
Expand Down Expand Up @@ -110,7 +109,7 @@ func TestWsHandler(t *testing.T) {
for want != 2 {
select {
case <-time.After(time.Second):
t.Fatal("failed to recieve data from websocket")
t.Fatal("failed to receive data from websocket")
case got := <-gotMsgChan:
want += 1
t.Logf("got message from mocked ws client: %v", got)
Expand All @@ -121,5 +120,4 @@ func TestWsHandler(t *testing.T) {
close(fs.pageReloadChan)
mu.Unlock()
})

}
8 changes: 3 additions & 5 deletions internal/wsinject/wsinject.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,11 +66,11 @@ func (fs *Fileserver) mirrorFile(origPath string) error {
}
mirroredPath := path.Join(fs.mirrorPath, relativePath)
relativePathDir := path.Dir(mirroredPath)
err = os.MkdirAll(relativePathDir, 0755)
err = os.MkdirAll(relativePathDir, 0o755)
if err != nil {
return fmt.Errorf("failed to create relative dir: '%v', error: %v", relativePathDir, err)
}
err = os.WriteFile(mirroredPath, injectedBytes, 0755)
err = os.WriteFile(mirroredPath, injectedBytes, 0o755)
if err != nil {
return fmt.Errorf("failed to write mirrored file: %w", err)
}
Expand All @@ -89,7 +89,7 @@ func (fs *Fileserver) mirrorMaker(p string, info os.DirEntry, err error) error {
}

func (fs *Fileserver) writeDeltaStreamerScript() error {
err := os.WriteFile(path.Join(fs.mirrorPath, "delta-streamer.js"), []byte(fmt.Sprintf(DeltaStreamerSourceCode, fs.wsPort, fs.wsPath)), 0755)
err := os.WriteFile(path.Join(fs.mirrorPath, "delta-streamer.js"), []byte(fmt.Sprintf(DeltaStreamerSourceCode, fs.wsPort, fs.wsPath)), 0o755)
if err != nil {
return fmt.Errorf("failed to write delta-streamer.js: %w", err)
}
Expand Down Expand Up @@ -179,13 +179,11 @@ func injectScript(html []byte, scriptTag string) ([]byte, error) {
}

_, err = buf.WriteString(scriptTag)

if err != nil {
return nil, fmt.Errorf("failed to write script tag: %w", err)
}

_, err = buf.WriteString(htmlStr[idx:])

if err != nil {
return nil, fmt.Errorf("failed to write post: %w", err)
}
Expand Down
18 changes: 9 additions & 9 deletions internal/wsinject/wsinject_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,18 @@ func Test_walkDir(t *testing.T) {
var got []string
want := []string{"t0", "t1", "t2"}
tmpDir := t.TempDir()
os.WriteFile(path.Join(tmpDir, "t0"), []byte("t0"), 0644)
os.WriteFile(path.Join(tmpDir, "t1"), []byte("t1"), 0644)
os.WriteFile(path.Join(tmpDir, "t0"), []byte("t0"), 0o644)
os.WriteFile(path.Join(tmpDir, "t1"), []byte("t1"), 0o644)
nestedDir, err := os.MkdirTemp(tmpDir, "dir0_*")
if err != nil {
t.Fatalf("failed to create temp dir: %v", err)
}
os.WriteFile(path.Join(nestedDir, "t2"), []byte("t2"), 0644)
os.WriteFile(path.Join(nestedDir, "t2"), []byte("t2"), 0o644)

wsInjectMaster(tmpDir, func(path string, d os.DirEntry, err error) error {
if err != nil {
t.Fatalf("got err during traversal: %v", err)
}
if d.IsDir() {
return nil
}
Expand All @@ -33,15 +36,13 @@ func Test_walkDir(t *testing.T) {
}
got = append(got, string(b))
return nil

})

slices.Sort(got)
slices.Sort(want)
if !slices.Equal(got, want) {
t.Fatalf("expected: %v, got: %v", want, got)
}

})
}

Expand All @@ -62,14 +63,14 @@ func Test_Setup(t *testing.T) {
tmpDir := t.TempDir()
ancli.Newline = true
fileName := "t0.html"
os.WriteFile(path.Join(tmpDir, fileName), []byte(mockHtml), 0777)
os.WriteFile(path.Join(tmpDir, fileName), []byte(mockHtml), 0o777)
nestedDir := path.Join(tmpDir, "nested")
err := os.MkdirAll(nestedDir, 0777)
err := os.MkdirAll(nestedDir, 0o777)
if err != nil {
t.Fatalf("failed to create temp dir: %v", err)
}
nestedFile := path.Join(nestedDir, "nested.html")
os.WriteFile(nestedFile, []byte(mockHtml), 0777)
os.WriteFile(nestedFile, []byte(mockHtml), 0o777)
fs := NewFileServer(8080, "/delta-streamer-ws.js")
_, err = fs.Setup(tmpDir)
if err != nil {
Expand Down Expand Up @@ -109,5 +110,4 @@ func Test_Setup(t *testing.T) {
mirrorFilePath := path.Join(fs.mirrorPath, "delta-streamer.js")
checkIfDeltaStreamerExists(t, mirrorFilePath)
})

}
4 changes: 2 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ func printHelp(command cmd.Command, err error, printUsage cmd.UsagePrinter) int
if errors.As(err, &notValidArg) {
ancli.PrintErr(err.Error())
printUsage()
} else if errors.Is(err, cmd.NoArgsError) {
} else if errors.Is(err, cmd.ErrNoArgs) {
printUsage()
} else if errors.Is(err, cmd.HelpfulError) {
} else if errors.Is(err, cmd.ErrHelpful) {
fmt.Println(command.Help())
return 0
} else {
Expand Down
5 changes: 2 additions & 3 deletions main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func Test_printHelp_ExitCodes(t *testing.T) {
{
name: "it should exit with code 0 on HelpfulError",
command: mCmd,
err: cmd.HelpfulError,
err: cmd.ErrHelpful,
expected: 0,
},
{
Expand Down Expand Up @@ -86,7 +86,7 @@ func Test_printHelp_output(t *testing.T) {
}
got := testboil.CaptureStdout(t, func(t *testing.T) {
t.Helper()
printHelp(mCmd, cmd.HelpfulError, func() {})
printHelp(mCmd, cmd.ErrHelpful, func() {})
})
// add the printline since we actually want a newline at end
want = want + "\n"
Expand Down Expand Up @@ -118,7 +118,6 @@ func Test_printHelp_output(t *testing.T) {
t.Fatalf("expected stdout to contain: '%v', got out: '%v'", wantErr, gotStdErr)
}
})

}

func Test_Run_ExitCodes(t *testing.T) {
Expand Down

0 comments on commit 25749cc

Please sign in to comment.