~kaction/fix-links

ref: bb9df800d764d77c23a4fed0374f8bae45afd505 fix-links/main.go -rw-r--r-- 2.0 KiB
bb9df800 — Dmitry Bogatov Work-around fs.Stat beeing too picky 7 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package main

import (
	"fmt"
	"golang.org/x/net/html"
	"golang.org/x/net/html/atom"
	"io/fs"
	"log"
	"os"
	"path"
	"strings"
)

func fixNode(s fs.FS, n *html.Node, fixed *bool) {
	if n.Type != html.ElementNode || n.DataAtom != atom.A {
		goto recurse
	}

	for ix := range n.Attr {
		a := n.Attr[ix]
		if a.Key != "href" {
			continue
		}
		if strings.HasPrefix(a.Val, "/") || strings.Contains(a.Val, "://") {
			break
		}

		info, err := fs.Stat(s, strings.TrimSuffix(a.Val, "/"))
		if err != nil {
			break
		}
		if !info.IsDir() {
			break
		}
		*fixed = true
		if strings.HasSuffix(a.Val, "/") {
			n.Attr[ix].Val = fmt.Sprintf("%vindex.html", a.Val)
		} else {
			n.Attr[ix].Val = fmt.Sprintf("%v/index.html", a.Val)
		}
		break
	}

recurse:
	for c := n.FirstChild; c != nil; c = c.NextSibling {
		fixNode(s, c, fixed)
	}
}

func main() {
	start := "."
	here := os.DirFS(start)

	err := fs.WalkDir(here, ".", func(p string, d fs.DirEntry, err error) error {
		if d.IsDir() && d.Name() == ".git" {
			return fs.SkipDir
		}

		if d.IsDir() {
			return nil
		}

		if !strings.HasSuffix(d.Name(), ".html") && !strings.HasSuffix(d.Name(), ".htm") {
			return nil
		}

		parent := here
		if p != d.Name() {
			pname := strings.TrimSuffix(p, "/" + d.Name())
			parent, err = fs.Sub(here, pname)
			if err != nil {
				return err
			}
		}

		realPath := path.Join(start, p)
		file, err := os.Open(realPath)
		if err != nil {
			return err
		}
		defer file.Close()


		node, err := html.Parse(file)
		if err != nil {
			log.Printf("warning: failed to parse %v\n", realPath)
			return nil
		}
		fixed := false
		fixNode(parent, node, &fixed)
		if fixed {
			log.Printf("fixed %v", p)
		}

		// This code is mainly intended for build process, so no write/rename dance.
		fileW, err := os.OpenFile(realPath, os.O_RDWR|os.O_CREATE, 0755)
		if err != nil {
			return nil
		}
		defer fileW.Close()
		html.Render(fileW, node)

		return nil
	})

	if err != nil {
		log.Fatalf("failed to walk directory: %v", err)
	}
}