index.json
This commit is contained in:
@@ -1,9 +1,11 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"flag"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
@@ -17,8 +19,8 @@ type IndexData struct {
|
||||
}
|
||||
|
||||
type FileEntry struct {
|
||||
Name string
|
||||
URL string
|
||||
Name string `json:"name"`
|
||||
URL string `json:"url"`
|
||||
}
|
||||
|
||||
func generateIndex(dir string, rootURL string) error {
|
||||
@@ -33,8 +35,8 @@ func generateIndex(dir string, rootURL string) error {
|
||||
var fileNames []string
|
||||
for _, entry := range entries {
|
||||
name := entry.Name()
|
||||
// Skip the index.html itself and hidden files
|
||||
if name != "index.html" && !filepath.HasPrefix(name, ".") {
|
||||
// Skip the index files themselves and hidden files
|
||||
if name != "index.html" && name != "index.json" && !filepath.HasPrefix(name, ".") {
|
||||
fileNames = append(fileNames, name)
|
||||
}
|
||||
}
|
||||
@@ -44,7 +46,6 @@ func generateIndex(dir string, rootURL string) error {
|
||||
var files []FileEntry
|
||||
dirName := filepath.Base(dir)
|
||||
for _, name := range fileNames {
|
||||
// URL encode the filename for the path
|
||||
url := fmt.Sprintf("%s/%s/%s", rootURL, dirName, name)
|
||||
files = append(files, FileEntry{
|
||||
Name: name,
|
||||
@@ -74,8 +75,24 @@ func generateIndex(dir string, rootURL string) error {
|
||||
if err := tmpl.Execute(f, data); err != nil {
|
||||
return fmt.Errorf("failed to execute template: %w", err)
|
||||
}
|
||||
log.Println(indexPath)
|
||||
|
||||
// Generate index.json
|
||||
jsonPath := filepath.Join(dir, "index.json")
|
||||
jsonFile, err := os.Create(jsonPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create index.json: %w", err)
|
||||
}
|
||||
defer jsonFile.Close()
|
||||
|
||||
encoder := json.NewEncoder(jsonFile)
|
||||
encoder.SetIndent("", " ")
|
||||
encoder.SetEscapeHTML(false)
|
||||
if err := encoder.Encode(files); err != nil {
|
||||
return fmt.Errorf("failed to encode JSON: %w", err)
|
||||
}
|
||||
log.Println(jsonPath)
|
||||
|
||||
fmt.Printf("Generated index.html in %s\n", dir)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -93,8 +110,7 @@ func main() {
|
||||
|
||||
for _, dir := range dirs {
|
||||
if err := generateIndex(dir, *rootURL); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error processing %s: %v\n", dir, err)
|
||||
os.Exit(1)
|
||||
log.Fatalf("Error processing %s: %v", dir, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user