dashboard / erock/pico / feat(pgs): show dir listing when no index.html present #91 rss

accepted · opened on 2025-12-16T01:38:45Z by erock
Help
checkout latest patchset:
ssh pr.pico.sh print pr-91 | git am -3
checkout any patchset in a patch request:
ssh pr.pico.sh print ps-X | git am -3
add changes to patch request:
git format-patch main --stdout | ssh pr.pico.sh pr add 91
add review to patch request:
git format-patch main --stdout | ssh pr.pico.sh pr add --review 91
accept PR:
ssh pr.pico.sh pr accept 91
close PR:
ssh pr.pico.sh pr close 91
Timeline Patchsets
+120 -0 pkg/apps/pgs/gen_dir_listing.go link
  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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
diff --git a/pkg/apps/pgs/gen_dir_listing.go b/pkg/apps/pgs/gen_dir_listing.go
new file mode 100644
index 0000000..fc1889e
--- /dev/null
+++ b/pkg/apps/pgs/gen_dir_listing.go
@@ -0,0 +1,120 @@
+package pgs
+
+import (
+	"bytes"
+	"embed"
+	"fmt"
+	"html/template"
+	"os"
+	"sort"
+
+	sst "github.com/picosh/pico/pkg/pobj/storage"
+)
+
+//go:embed html/*
+var dirListingFS embed.FS
+
+var dirListingTmpl = template.Must(
+	template.New("base").ParseFS(
+		dirListingFS,
+		"html/base.layout.tmpl",
+		"html/marketing-footer.partial.tmpl",
+		"html/directory_listing.page.tmpl",
+	),
+)
+
+type dirEntryDisplay struct {
+	Href    string
+	Display string
+	Size    string
+	ModTime string
+}
+
+type DirectoryListingData struct {
+	Path       string
+	ShowParent bool
+	Entries    []dirEntryDisplay
+}
+
+func formatFileSize(size int64) string {
+	const (
+		KB = 1024
+		MB = KB * 1024
+		GB = MB * 1024
+	)
+
+	switch {
+	case size >= GB:
+		return fmt.Sprintf("%.1f GB", float64(size)/float64(GB))
+	case size >= MB:
+		return fmt.Sprintf("%.1f MB", float64(size)/float64(MB))
+	case size >= KB:
+		return fmt.Sprintf("%.1f KB", float64(size)/float64(KB))
+	default:
+		return fmt.Sprintf("%d B", size)
+	}
+}
+
+func sortEntries(entries []os.FileInfo) {
+	sort.Slice(entries, func(i, j int) bool {
+		if entries[i].IsDir() != entries[j].IsDir() {
+			return entries[i].IsDir()
+		}
+		return entries[i].Name() < entries[j].Name()
+	})
+}
+
+func toDisplayEntries(entries []os.FileInfo) []dirEntryDisplay {
+	sortEntries(entries)
+	displayEntries := make([]dirEntryDisplay, 0, len(entries))
+
+	for _, entry := range entries {
+		display := dirEntryDisplay{
+			Href:    entry.Name(),
+			Display: entry.Name(),
+			Size:    formatFileSize(entry.Size()),
+			ModTime: entry.ModTime().Format("2006-01-02 15:04"),
+		}
+
+		if entry.IsDir() {
+			display.Href += "/"
+			display.Display += "/"
+			display.Size = "-"
+		}
+
+		displayEntries = append(displayEntries, display)
+	}
+
+	return displayEntries
+}
+
+func shouldGenerateListing(st sst.ObjectStorage, bucket sst.Bucket, projectDir string, path string) bool {
+	dirPath := projectDir + path
+	if path == "/" {
+		dirPath = projectDir + "/"
+	}
+
+	entries, err := st.ListObjects(bucket, dirPath, false)
+	if err != nil || len(entries) == 0 {
+		return false
+	}
+
+	indexPath := dirPath + "index.html"
+	_, _, err = st.GetObject(bucket, indexPath)
+	return err != nil
+}
+
+func generateDirectoryHTML(path string, entries []os.FileInfo) string {
+	data := DirectoryListingData{
+		Path:       path,
+		ShowParent: path != "/",
+		Entries:    toDisplayEntries(entries),
+	}
+
+	var buf bytes.Buffer
+	if err := dirListingTmpl.Execute(&buf, data); err != nil {
+		return fmt.Sprintf("Error rendering directory listing: %s", err)
+	}
+
+	return buf.String()
+}
+200 -0 pkg/apps/pgs/gen_dir_listing_test.go link
  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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
diff --git a/pkg/apps/pgs/gen_dir_listing_test.go b/pkg/apps/pgs/gen_dir_listing_test.go
new file mode 100644
index 0000000..8825c25
--- /dev/null
+++ b/pkg/apps/pgs/gen_dir_listing_test.go
@@ -0,0 +1,200 @@
+package pgs
+
+import (
+	"os"
+	"strings"
+	"testing"
+	"time"
+
+	sst "github.com/picosh/pico/pkg/pobj/storage"
+	"github.com/picosh/pico/pkg/send/utils"
+)
+
+func TestGenerateDirectoryHTML(t *testing.T) {
+	fixtures := []struct {
+		Name     string
+		Path     string
+		Entries  []os.FileInfo
+		Contains []string
+	}{
+		{
+			Name:    "empty-directory",
+			Path:    "/",
+			Entries: []os.FileInfo{},
+			Contains: []string{
+				"<title>Index of /</title>",
+				"Index of /",
+			},
+		},
+		{
+			Name: "single-file",
+			Path: "/",
+			Entries: []os.FileInfo{
+				&utils.VirtualFile{FName: "hello.txt", FSize: 1024, FIsDir: false, FModTime: time.Date(2025, 1, 15, 10, 30, 0, 0, time.UTC)},
+			},
+			Contains: []string{
+				"<title>Index of /</title>",
+				`href="hello.txt"`,
+				"hello.txt",
+				"1.0 KB",
+			},
+		},
+		{
+			Name: "single-folder",
+			Path: "/",
+			Entries: []os.FileInfo{
+				&utils.VirtualFile{FName: "docs", FSize: 0, FIsDir: true, FModTime: time.Date(2025, 1, 15, 10, 30, 0, 0, time.UTC)},
+			},
+			Contains: []string{
+				`href="docs/"`,
+				"docs/",
+			},
+		},
+		{
+			Name: "mixed-entries",
+			Path: "/assets/",
+			Entries: []os.FileInfo{
+				&utils.VirtualFile{FName: "images", FSize: 0, FIsDir: true, FModTime: time.Date(2025, 1, 15, 10, 30, 0, 0, time.UTC)},
+				&utils.VirtualFile{FName: "style.css", FSize: 2048, FIsDir: false, FModTime: time.Date(2025, 1, 14, 8, 0, 0, 0, time.UTC)},
+				&utils.VirtualFile{FName: "app.js", FSize: 512, FIsDir: false, FModTime: time.Date(2025, 1, 13, 12, 0, 0, 0, time.UTC)},
+			},
+			Contains: []string{
+				"<title>Index of /assets/</title>",
+				`href="images/"`,
+				`href="style.css"`,
+				`href="app.js"`,
+				"images/",
+				"2.0 KB",
+			},
+		},
+		{
+			Name: "subdirectory-with-parent-link",
+			Path: "/docs/api/",
+			Entries: []os.FileInfo{
+				&utils.VirtualFile{FName: "readme.md", FSize: 256, FIsDir: false, FModTime: time.Date(2025, 1, 15, 10, 30, 0, 0, time.UTC)},
+			},
+			Contains: []string{
+				"<title>Index of /docs/api/</title>",
+				`href="../"`,
+				"../",
+			},
+		},
+	}
+
+	for _, fixture := range fixtures {
+		t.Run(fixture.Name, func(t *testing.T) {
+			html := generateDirectoryHTML(fixture.Path, fixture.Entries)
+
+			for _, expected := range fixture.Contains {
+				if !strings.Contains(html, expected) {
+					t.Errorf("expected HTML to contain %q, got:\n%s", expected, html)
+				}
+			}
+		})
+	}
+}
+
+func TestSortEntries(t *testing.T) {
+	entries := []os.FileInfo{
+		&utils.VirtualFile{FName: "zebra.txt", FIsDir: false},
+		&utils.VirtualFile{FName: "alpha", FIsDir: true},
+		&utils.VirtualFile{FName: "beta.md", FIsDir: false},
+		&utils.VirtualFile{FName: "zulu", FIsDir: true},
+		&utils.VirtualFile{FName: "apple.js", FIsDir: false},
+	}
+
+	sortEntries(entries)
+
+	expected := []string{"alpha", "zulu", "apple.js", "beta.md", "zebra.txt"}
+	for i, entry := range entries {
+		if entry.Name() != expected[i] {
+			t.Errorf("position %d: expected %q, got %q", i, expected[i], entry.Name())
+		}
+	}
+}
+
+func TestShouldGenerateListing(t *testing.T) {
+	fixtures := []struct {
+		Name     string
+		Path     string
+		Storage  map[string]map[string]string
+		Expected bool
+	}{
+		{
+			Name: "directory-with-index-html",
+			Path: "/docs/",
+			Storage: map[string]map[string]string{
+				"testbucket": {
+					"/project/docs/index.html": "<html>hello</html>",
+				},
+			},
+			Expected: false,
+		},
+		{
+			Name: "directory-without-index-html",
+			Path: "/docs/",
+			Storage: map[string]map[string]string{
+				"testbucket": {
+					"/project/docs/readme.md": "# Readme",
+					"/project/docs/guide.md":  "# Guide",
+				},
+			},
+			Expected: true,
+		},
+		{
+			Name: "empty-directory",
+			Path: "/empty/",
+			Storage: map[string]map[string]string{
+				"testbucket": {
+					"/project/other/file.txt": "content",
+				},
+			},
+			Expected: false,
+		},
+		{
+			Name: "root-directory-without-index",
+			Path: "/",
+			Storage: map[string]map[string]string{
+				"testbucket": {
+					"/project/style.css": "body {}",
+					"/project/app.js":    "console.log('hi')",
+				},
+			},
+			Expected: true,
+		},
+		{
+			Name: "root-directory-with-index",
+			Path: "/",
+			Storage: map[string]map[string]string{
+				"testbucket": {
+					"/project/index.html": "<html>home</html>",
+				},
+			},
+			Expected: false,
+		},
+		{
+			Name: "nested-directory-without-index",
+			Path: "/assets/images/",
+			Storage: map[string]map[string]string{
+				"testbucket": {
+					"/project/assets/images/logo.png":   "png data",
+					"/project/assets/images/banner.jpg": "jpg data",
+				},
+			},
+			Expected: true,
+		},
+	}
+
+	for _, fixture := range fixtures {
+		t.Run(fixture.Name, func(t *testing.T) {
+			st, _ := sst.NewStorageMemory(fixture.Storage)
+			bucket := sst.Bucket{Name: "testbucket", Path: "testbucket"}
+
+			result := shouldGenerateListing(st, bucket, "project", fixture.Path)
+
+			if result != fixture.Expected {
+				t.Errorf("shouldGenerateListing(%q) = %v, want %v", fixture.Path, result, fixture.Expected)
+			}
+		})
+	}
+}
+30 -0 pkg/apps/pgs/html/directory_listing.page.tmpl link
 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
diff --git a/pkg/apps/pgs/html/directory_listing.page.tmpl b/pkg/apps/pgs/html/directory_listing.page.tmpl
new file mode 100644
index 0000000..d6e151b
--- /dev/null
+++ b/pkg/apps/pgs/html/directory_listing.page.tmpl
@@ -0,0 +1,30 @@
+{{template "base" .}}
+
+{{define "title"}}Index of {{.Path}}{{end}}
+
+{{define "meta"}}{{end}}
+
+{{define "attrs"}}class="container"{{end}}
+
+{{define "body"}}
+<header>
+  <h1 class="text-2xl">Index of {{.Path}}</h1>
+  <hr />
+</header>
+<main>
+  <table>
+    <thead>
+      <tr><th>Name</th><th>Size</th><th>Modified</th></tr>
+    </thead>
+    <tbody>
+{{- if .ShowParent}}
+      <tr><td><a href="../">../</a></td><td>-</td><td>-</td></tr>
+{{- end}}
+{{- range .Entries}}
+      <tr><td><a href="{{.Href}}">{{.Display}}</a></td><td>{{.Size}}</td><td>{{.ModTime}}</td></tr>
+{{- end}}
+    </tbody>
+  </table>
+</main>
+{{template "marketing-footer" .}}
+{{end}}
+21 -0 pkg/apps/pgs/web_asset_handler.go link
 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
diff --git a/pkg/apps/pgs/web_asset_handler.go b/pkg/apps/pgs/web_asset_handler.go
index 0952e72..aba0ce2 100644
--- a/pkg/apps/pgs/web_asset_handler.go
+++ b/pkg/apps/pgs/web_asset_handler.go
@@ -175,6 +175,27 @@ func (h *ApiAssetHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
 	}
 
 	if assetFilepath == "" {
+		if shouldGenerateListing(h.Cfg.Storage, h.Bucket, h.ProjectDir, "/"+fpath) {
+			logger.Info(
+				"generating directory listing",
+				"path", fpath,
+			)
+			dirPath := h.ProjectDir + "/" + fpath
+			entries, err := h.Cfg.Storage.ListObjects(h.Bucket, dirPath, false)
+			if err == nil {
+				requestPath := "/" + fpath
+				if !strings.HasSuffix(requestPath, "/") {
+					requestPath += "/"
+				}
+
+				html := generateDirectoryHTML(requestPath, entries)
+				w.Header().Set("content-type", "text/html")
+				w.WriteHeader(http.StatusOK)
+				_, _ = w.Write([]byte(html))
+				return
+			}
+		}
+
 		logger.Info(
 			"asset not found in bucket",
 			"routes", strings.Join(attempts, ", "),
+117 -0 pkg/apps/pgs/web_test.go link
  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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
diff --git a/pkg/apps/pgs/web_test.go b/pkg/apps/pgs/web_test.go
index a2a4004..7f0de4f 100644
--- a/pkg/apps/pgs/web_test.go
+++ b/pkg/apps/pgs/web_test.go
@@ -358,6 +358,123 @@ func TestApiBasic(t *testing.T) {
 	}
 }
 
+func TestDirectoryListing(t *testing.T) {
+	logger := slog.Default()
+	dbpool := NewPgsDb(logger)
+	bucketName := shared.GetAssetBucketName(dbpool.Users[0].ID)
+
+	tt := []struct {
+		name        string
+		path        string
+		status      int
+		contentType string
+		contains    []string
+		notContains []string
+		storage     map[string]map[string]string
+	}{
+		{
+			name:        "directory-without-index-shows-listing",
+			path:        "/docs/",
+			status:      http.StatusOK,
+			contentType: "text/html",
+			contains: []string{
+				"Index of /docs/",
+				"readme.md",
+				"guide.md",
+			},
+			storage: map[string]map[string]string{
+				bucketName: {
+					"/test/docs/readme.md": "# Readme",
+					"/test/docs/guide.md":  "# Guide",
+				},
+			},
+		},
+		{
+			name:        "directory-with-index-serves-index",
+			path:        "/docs/",
+			status:      http.StatusOK,
+			contentType: "text/html",
+			contains:    []string{"hello world!"},
+			notContains: []string{"Index of"},
+			storage: map[string]map[string]string{
+				bucketName: {
+					"/test/docs/index.html": "hello world!",
+					"/test/docs/readme.md":  "# Readme",
+				},
+			},
+		},
+		{
+			name:        "root-directory-without-index-shows-listing",
+			path:        "/",
+			status:      http.StatusOK,
+			contentType: "text/html",
+			contains: []string{
+				"Index of /",
+				"style.css",
+			},
+			storage: map[string]map[string]string{
+				bucketName: {
+					"/test/style.css": "body {}",
+				},
+			},
+		},
+		{
+			name:        "nested-directory-shows-parent-link",
+			path:        "/assets/images/",
+			status:      http.StatusOK,
+			contentType: "text/html",
+			contains: []string{
+				"Index of /assets/images/",
+				`href="../"`,
+				"logo.png",
+			},
+			storage: map[string]map[string]string{
+				bucketName: {
+					"/test/assets/images/logo.png": "png data",
+				},
+			},
+		},
+	}
+
+	for _, tc := range tt {
+		t.Run(tc.name, func(t *testing.T) {
+			request := httptest.NewRequest("GET", dbpool.mkpath(tc.path), strings.NewReader(""))
+			responseRecorder := httptest.NewRecorder()
+
+			st, _ := storage.NewStorageMemory(tc.storage)
+			pubsub := NewPubsubChan()
+			defer func() {
+				_ = pubsub.Close()
+			}()
+			cfg := NewPgsConfig(logger, dbpool, st, pubsub)
+			cfg.Domain = "pgs.test"
+			router := NewWebRouter(cfg)
+			router.ServeHTTP(responseRecorder, request)
+
+			if responseRecorder.Code != tc.status {
+				t.Errorf("Want status '%d', got '%d'", tc.status, responseRecorder.Code)
+			}
+
+			ct := responseRecorder.Header().Get("content-type")
+			if ct != tc.contentType {
+				t.Errorf("Want content type '%s', got '%s'", tc.contentType, ct)
+			}
+
+			body := responseRecorder.Body.String()
+			for _, want := range tc.contains {
+				if !strings.Contains(body, want) {
+					t.Errorf("Want body to contain '%s', got '%s'", want, body)
+				}
+			}
+			for _, notWant := range tc.notContains {
+				if strings.Contains(body, notWant) {
+					t.Errorf("Want body to NOT contain '%s', got '%s'", notWant, body)
+				}
+			}
+		})
+	}
+}
+
 type ImageStorageMemory struct {
 	*storage.StorageMemory
 	Opts  *storage.ImgProcessOpts