~kornellapacz/gmnigit

ref: 59e46173f00af1ae3b5477dd79eb4bdf30e21d6e gmnigit/files.go -rw-r--r-- 2.0 KiB
59e46173Korneliusz Łapacz refactor generating browsable tree 6 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
package main

import (
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"

	gemini "git.tdem.in/tdemin/gmnhg"
	"github.com/go-git/go-git/v5"
)

func createDirectoryIndex(treeRootPath, path string) {
	files, err := ioutil.ReadDir(filepath.Join(treeRootPath, path))
	check(err)

	index, err := os.Create(filepath.Join(treeRootPath, path, "index.gmi"))
	check(err)
	defer index.Close()

	index.WriteString("# Tree\n\nPath: " + path + "/\n\n")

	for _, file := range files {
		if file.IsDir() {
			index.WriteString("=> " + file.Name() + "/\n")
			createDirectoryIndex(treeRootPath, filepath.Join(path, file.Name()))
			continue
		}

		index.WriteString("=> " + file.Name() + "\n")
	}
}

func createBrowsableTree(distPath, repositoryPath string) {
	treePath := filepath.Join(distPath, treeSubPath)

	_, err := git.PlainClone(treePath, false, &git.CloneOptions{
		URL: repositoryPath,
	})

	check(err)
	check(os.RemoveAll(filepath.Join(treePath, ".git")))

	createDirectoryIndex(treePath, "")
}

func createIndexFile(distPath, repositoryPath string) {
	// check if in bare repository is `url` file with git url for cloning
	url, err := os.ReadFile(filepath.Join(repositoryPath, "url"))

	if err != nil && !os.IsNotExist(err) {
		log.Fatal(err)
	}

	indexFile, err := os.Create(filepath.Join(distPath, "index.gmi"))
	check(err)

	if url != nil {
		indexFile.WriteString("```\ngit clone " + strings.TrimSpace(string(url)) + "\n```\n\n")
	}

	indexFile.WriteString("=> " + commitsSubPath + "/\n")
	indexFile.WriteString("=> " + treeSubPath + "/\n\n")

	// convert README.md to gemini and write it to index.gmi in repository root
	text, err := os.ReadFile(filepath.Join(distPath, treeSubPath, "README.md"))

	if err != nil {
		if os.IsNotExist(err) {
			log.Println("README.md not found in your repository")

			check(indexFile.Close())
			return
		}

		log.Fatal(err)
	}

	check(err)
	geminiContent, _, err := gemini.RenderMarkdown(text, gemini.WithMetadata)
	check(err)

	indexFile.Write(geminiContent)

	check(indexFile.Close())
}