~kornellapacz/gmnigit

59e46173f00af1ae3b5477dd79eb4bdf30e21d6e — Korneliusz Łapacz 5 months ago 96a1d84
refactor generating browsable tree
1 files changed, 17 insertions(+), 51 deletions(-)

M files.go
M files.go => files.go +17 -51
@@ 1,6 1,7 @@
package main

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


@@ 8,75 9,40 @@ import (

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

var directoryIndexingFiles = make(map[string]*os.File)

func registerDirectory(toRegister, toRegisterOriginal string) {
	if toRegister == "." {
		return
	}

	parentPath := filepath.Dir(toRegister)
	parentIndex, ok := directoryIndexingFiles[parentPath]

	if !ok {
		// if directory below doesn't have index.gmi (empty directory) search even below
		registerDirectory(filepath.Dir(toRegister), toRegisterOriginal)
		return
	}

	parentIndex.WriteString("=> " + toRegisterOriginal + "/\n")
}

func createDirectoriesIndexes(treePath string, tree *object.Tree) {
	tree.Files().ForEach(func(f *object.File) error {
		dir := filepath.Dir(f.Name)

		val, ok := directoryIndexingFiles[dir]
		// if directory doesn't have index.gmi create one
		if !ok {
			// TODO do something if index.gmi is already in directory (as repository file)
			index, err := os.Create(filepath.Join(treePath, dir, "index.gmi"))
			check(err)
func createDirectoryIndex(treeRootPath, path string) {
	files, err := ioutil.ReadDir(filepath.Join(treeRootPath, path))
	check(err)

			index.WriteString("# directory " + filepath.Join("/", dir) + "\n\n")
	index, err := os.Create(filepath.Join(treeRootPath, path, "index.gmi"))
	check(err)
	defer index.Close()

			// register directory in folder below
			registerDirectory(dir, dir)
	index.WriteString("# Tree\n\nPath: " + path + "/\n\n")

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

		val.WriteString("=> " + filepath.Base(f.Name) + "\n")
		return nil
	})

	for _, file := range directoryIndexingFiles {
		check(file.Close())
		index.WriteString("=> " + file.Name() + "\n")
	}
}

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

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

	check(err)
	ref, err := repository.Head()
	check(err)
	commit, err := repository.CommitObject(ref.Hash())
	check(err)
	tree, err := commit.Tree()
	check(err)

	createDirectoriesIndexes(treePath, tree)

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

	createDirectoryIndex(treePath, "")
}

func createIndexFile(distPath, repositoryPath string) {