Skip to content

Commit

Permalink
feat: ADD WSL route in auto open feature (#48)
Browse files Browse the repository at this point in the history
  • Loading branch information
ShortArrow authored Aug 23, 2023
1 parent 23d1a24 commit efb2fef
Show file tree
Hide file tree
Showing 2 changed files with 114 additions and 1 deletion.
39 changes: 38 additions & 1 deletion cmd/browser.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,43 @@
package cmd

import (
"os"
"os/exec"
"runtime"
"strings"
"time"
)

type FileReader interface {
ReadFile(string) (string, error)
}

type ProcVersionReader struct{}

func (r ProcVersionReader) ReadFile(filename string) (string, error) {
data, err := os.ReadFile(filename)
if err != nil {
return "", err
}
return string(data), nil
}

func isContainWSL(data string) bool {
return strings.Contains(data, "WSL")
}

func isWSLWithReader(reader FileReader) bool {
data, err := reader.ReadFile("/proc/version")
if err != nil {
return false
}
return isContainWSL(data)
}

func isWSL() bool {
return isWSLWithReader(ProcVersionReader{})
}

func openBrowser(url string) error {
<-time.After(100 * time.Millisecond)
var args []string
Expand All @@ -17,7 +49,12 @@ func openBrowser(url string) error {
case "darwin":
cmd = "open"
default: // "linux", "freebsd", "openbsd", "netbsd"
cmd = "xdg-open"
if isWSL() {
cmd = "cmd.exe"
args = []string{"/c", "start"}
} else {
cmd = "xdg-open"
}
}
args = append(args, url)
return exec.Command(cmd, args...).Start()
Expand Down
76 changes: 76 additions & 0 deletions cmd/browser_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package cmd

import (
"errors"
"testing"
)

type MockFileReader struct {
content string
err error
}

func (m MockFileReader) ReadFile(path string) (string, error) {
return m.content, m.err
}

func TestIsContainWSL(t *testing.T) {
tests := []struct {
name string
data string
expected bool
}{
{
name: "WSL Data",
data: "Linux version 4.19.128-microsoft-standard (WSL2)",
expected: true,
},
{
name: "Non-WSL Data",
data: "Linux version 4.15.0-72-generic",
expected: false,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := isContainWSL(tt.data)
if result != tt.expected {
t.Errorf("expected %v, got %v", tt.expected, result)
}
})
}
}

func TestIsWSL(t *testing.T) {
tests := []struct {
name string
reader FileReader
expected bool
}{
{
name: "WSL Data",
reader: MockFileReader{content: "Linux version 4.19.128-microsoft-standard (WSL2)"},
expected: true,
},
{
name: "Non-WSL Data",
reader: MockFileReader{content: "Linux version 4.15.0-72-generic"},
expected: false,
},
{
name: "Read error",
reader: MockFileReader{err: errors.New("read error")},
expected: false,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := isWSLWithReader(tt.reader)
if result != tt.expected {
t.Errorf("expected %v, got %v", tt.expected, result)
}
})
}
}

0 comments on commit efb2fef

Please sign in to comment.