From 9b8ebee972562155638e10db9771d2c8a5ff4b0f Mon Sep 17 00:00:00 2001 From: Mathias Magnusson Date: Wed, 17 Apr 2024 17:38:55 +0200 Subject: [PATCH] Clean some stuff up (#32) --- anchor/anchor.go | 32 +++++++++++--------------------- anchor/anchor_test.go | 38 ++++++++++++++++++++------------------ pages/pages.go | 29 ++++++++++------------------- pages/pages_test.go | 2 +- taitan.go | 16 +++++++++------- 5 files changed, 51 insertions(+), 66 deletions(-) diff --git a/anchor/anchor.go b/anchor/anchor.go index b55ff8c..9933aff 100644 --- a/anchor/anchor.go +++ b/anchor/anchor.go @@ -4,7 +4,6 @@ import ( "strconv" "strings" - log "github.com/sirupsen/logrus" "golang.org/x/net/html" ) @@ -29,8 +28,16 @@ func Anchors(body string) (anchs []Anchor, err error) { var findAnchors func(*html.Node) findAnchors = func(n *html.Node) { if isHNode(n) { - // Append valid anchors. - anchs = anchor(n, anchs) + id := findIDAttr(n.Attr) + val := plain(n) + if id != "" && val != "" { + headerLevel, _ := strconv.Atoi(n.Data[1:]) + anchs = append(anchs, Anchor{ + ID: id, + Value: val, + HeaderLevel: headerLevel, + }) + } } for c := n.FirstChild; c != nil; c = c.NextSibling { findAnchors(c) @@ -40,24 +47,7 @@ func Anchors(body string) (anchs []Anchor, err error) { return anchs, nil } -// anchor appends valid anchors to anchs. -func anchor(n *html.Node, anchs []Anchor) []Anchor { - log.WithField("attrs", n.Attr).Debug("Found potential anchor (

)") - id := findAttr("id", n.Attr) - val := plain(n) - if val == "" && id == "" { - return anchs - } - headerLevel, _ := strconv.Atoi(n.Data[1:]) - - return append(anchs, Anchor{ - ID: id, - Value: val, - HeaderLevel: headerLevel, - }) -} - -func findAttr(key string, attrs []html.Attribute) string { +func findIDAttr(attrs []html.Attribute) string { for _, attr := range attrs { if attr.Key == "id" { return attr.Val diff --git a/anchor/anchor_test.go b/anchor/anchor_test.go index 5ccf0cb..301ddc8 100644 --- a/anchor/anchor_test.go +++ b/anchor/anchor_test.go @@ -2,8 +2,8 @@ package anchor import ( "bytes" - "fmt" "log" + "slices" "testing" "golang.org/x/net/html" @@ -37,39 +37,41 @@ func TestPlain(t *testing.T) { } var anchortests = []struct { - in *html.Node - in2 []Anchor + in string out []Anchor }{ - {s2html(`

plain

`), []Anchor{}, []Anchor{{"asdf", "plain", 1}}}, - {s2html(``), []Anchor{{"qwerty", "asdf", 1}}, []Anchor{{"qwerty", "asdf", 1}}}, - {s2html(`asdf`), []Anchor{}, []Anchor{{"", "asdf", 1}}}, + {`

plain

`, []Anchor{{"asdf", "plain", 1}}}, + {``, []Anchor{}}, + {`asdf`, []Anchor{}}, + {`

chilling

`, []Anchor{{"bing", "chilling", 2}}}, } -func TestAnchor(t *testing.T) { +func TestAnchors(t *testing.T) { for _, tt := range anchortests { - got := anchor(tt.in, tt.in2) - if fmt.Sprintf("%#v\n", got) != fmt.Sprintf("%#v\n", tt.out) { - t.Errorf("anchor(%v, []Anchor{}) => %q, want %q", tt.in, got, tt.out) + got, err := Anchors(tt.in) + if err != nil { + t.Errorf("anchor(%v) returned error %q", tt.in, err) + } + if !slices.Equal(got, tt.out) { + t.Errorf("anchor(%v) => %q, want %q", tt.in, got, tt.out) } } } var findattrtests = []struct { - in string - in2 []html.Attribute + in []html.Attribute out string }{ - {"id", []html.Attribute{}, ""}, - {"id", []html.Attribute{{Key: "id", Val: "asdf"}}, "asdf"}, - {"id", []html.Attribute{{Key: "class", Val: "qwerty"}, {Key: "id", Val: "asdf"}}, "asdf"}, + {[]html.Attribute{}, ""}, + {[]html.Attribute{{Key: "id", Val: "asdf"}}, "asdf"}, + {[]html.Attribute{{Key: "class", Val: "qwerty"}, {Key: "id", Val: "asdf"}}, "asdf"}, } -func TestFindAttr(t *testing.T) { +func TestFindIDAttr(t *testing.T) { for _, tt := range findattrtests { - got := findAttr(tt.in, tt.in2) + got := findIDAttr(tt.in) if got != tt.out { - t.Errorf("findAttr(%v, %v) => %q, want %q", tt.in, tt.in2, got, tt.out) + t.Errorf("findAttr(%v) => %q, want %q", tt.in, got, tt.out) } } } diff --git a/pages/pages.go b/pages/pages.go index ac6cb98..a42c2ef 100644 --- a/pages/pages.go +++ b/pages/pages.go @@ -273,32 +273,23 @@ func parseDir(isReception bool, root, dir string) (*Resp, error) { // getCommitTime returns last commit time for a file. func getCommitTime(root string, filePath string) (time.Time, error) { - // root/feature/main.md => feature/main.md - gitDir := " " - if root != "" { - gitDir = fmt.Sprintf("--git-dir=%s/.git", root) - filePath = filepath.Clean(strings.Replace(filePath, root+"/", "", 1)) - } + gitDir := fmt.Sprintf("--git-dir=%s/.git", root) + // root/page/body.md => page/body.md + filePath = filepath.Clean(strings.TrimPrefix(filePath, root+"/")) - // Execute git log - cmd := exec.Command("git", "log", "-n 1", "--format=%at", "--", filePath) - if root != "" { - cmd = exec.Command("git", gitDir, "log", "-n 1", "--format=%at", "--", filePath) - } + cmd := exec.Command("git", gitDir, "log", "-n1", "--format=%at", "--", filePath) - var out bytes.Buffer - cmd.Stdout = &out + var stdout bytes.Buffer + var stderr bytes.Buffer + cmd.Stdout = &stdout + cmd.Stderr = &stderr err := cmd.Run() if err != nil { + log.Printf("Git failed. Stderr: %s", strings.TrimSpace(stderr.String())) return time.Time{}, err } - // Split the output into individual lines - lines := strings.Split(strings.TrimSpace(out.String()), "\n") - - // Get the latest commit timestamp - lastCommitTimestamp, err := strconv.ParseInt(lines[0], 10, 64) - + lastCommitTimestamp, err := strconv.ParseInt(strings.TrimSpace(stdout.String()), 10, 64) if err != nil { return time.Time{}, err } diff --git a/pages/pages_test.go b/pages/pages_test.go index c173869..f7dbdbe 100644 --- a/pages/pages_test.go +++ b/pages/pages_test.go @@ -29,7 +29,7 @@ var getCommitTimetests = []struct { in, in2 string out time.Time }{ - {"", "test/body.md", time.Unix(1447024470, 0)}, + {"..", "pages/test/body.md", time.Unix(1447024470, 0)}, } func TestGetCommitTime(t *testing.T) { diff --git a/taitan.go b/taitan.go index 9054d14..797cac9 100644 --- a/taitan.go +++ b/taitan.go @@ -80,27 +80,27 @@ func getContent() error { root := getRoot() if _, err = os.Stat(root); os.IsNotExist(err) { - if err := runGit("clone", []string{"clone", u.String()}); err != nil { + if err := runGit("clone", "clone", u.String()); err != nil { return err } - if err := runGit("submodule init", []string{"-C", root, "submodule", "init"}); err != nil { + if err := runGit("submodule init", "-C", root, "submodule", "init"); err != nil { return err } - if err := runGit("submodule update", []string{"-C", root, "submodule", "update"}); err != nil { + if err := runGit("submodule update", "-C", root, "submodule", "update"); err != nil { return err } } else { - if err := runGit("pull", []string{"-C", root, "pull"}); err != nil { + if err := runGit("pull", "-C", root, "pull"); err != nil { return err } - if err := runGit("submodule update", []string{"-C", root, "submodule", "update"}); err != nil { + if err := runGit("submodule update", "-C", root, "submodule", "update"); err != nil { return err } } return nil } -func runGit(action string, args []string) error { +func runGit(action string, args ...string) error { log.Infof("Found root directory - %sing updates!", action) log.Debugf("Commands %#v!", args) cmd := exec.Command("git", args...) @@ -245,7 +245,9 @@ func handler(res http.ResponseWriter, req *http.Request) { } if req.URL.Path == "/fuzzyfile" { log.Info("Fuzzyfile") + responses.Lock() buf, err := json.Marshal(fuzz.NewFile(responses.Resps)) + responses.Unlock() if err != nil { log.Warnf("handler: unexpected error: %#v\n", err) res.WriteHeader(http.StatusInternalServerError) @@ -289,8 +291,8 @@ func handler(res http.ResponseWriter, req *http.Request) { log.WithField("clean", clean).Info("Sanitized path") log.Println(rootDir(clean)) responses.Lock() + defer responses.Unlock() r, ok := responses.Resps[clean] - responses.Unlock() if !ok { log.WithField("page", clean).Warn("Page doesn't exist") res.WriteHeader(http.StatusNotFound)