Skip to content

Commit

Permalink
Clean some stuff up (#32)
Browse files Browse the repository at this point in the history
  • Loading branch information
foodelevator committed Apr 17, 2024
1 parent 2befb6c commit 9b8ebee
Show file tree
Hide file tree
Showing 5 changed files with 51 additions and 66 deletions.
32 changes: 11 additions & 21 deletions anchor/anchor.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"strconv"
"strings"

log "github.com/sirupsen/logrus"
"golang.org/x/net/html"
)

Expand All @@ -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)
Expand All @@ -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 (<h2>)")
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
Expand Down
38 changes: 20 additions & 18 deletions anchor/anchor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ package anchor

import (
"bytes"
"fmt"
"log"
"slices"
"testing"

"golang.org/x/net/html"
Expand Down Expand Up @@ -37,39 +37,41 @@ func TestPlain(t *testing.T) {
}

var anchortests = []struct {
in *html.Node
in2 []Anchor
in string
out []Anchor
}{
{s2html(`<h1 id="asdf"><b><b>plain</b></b></h1>`), []Anchor{}, []Anchor{{"asdf", "plain", 1}}},
{s2html(`<b><b></b></b>`), []Anchor{{"qwerty", "asdf", 1}}, []Anchor{{"qwerty", "asdf", 1}}},
{s2html(`asdf`), []Anchor{}, []Anchor{{"", "asdf", 1}}},
{`<h1 id="asdf"><b><b>plain</b></b></h1>`, []Anchor{{"asdf", "plain", 1}}},
{`<b><b></b></b>`, []Anchor{}},
{`asdf`, []Anchor{}},
{`<h2 id="bing"><span style="color: red;">chilling</h2>`, []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)
}
}
}
29 changes: 10 additions & 19 deletions pages/pages.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
2 changes: 1 addition & 1 deletion pages/pages_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
16 changes: 9 additions & 7 deletions taitan.go
Original file line number Diff line number Diff line change
Expand Up @@ -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...)
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down

0 comments on commit 9b8ebee

Please sign in to comment.