Eric Bower
·
2026-08-17
1package pgs
2
3import (
4 "encoding/json"
5 "errors"
6 "fmt"
7 "io"
8 "log/slog"
9 "path/filepath"
10 "strings"
11 "text/tabwriter"
12 "time"
13
14 pgsdb "github.com/picosh/pico/pkg/apps/pgs/db"
15 "github.com/picosh/pico/pkg/db"
16 "github.com/picosh/pico/pkg/shared"
17 "github.com/picosh/pico/pkg/storage"
18)
19
20func NewTabWriter(out io.Writer) *tabwriter.Writer {
21 return tabwriter.NewWriter(out, 0, 0, 2, ' ', tabwriter.TabIndent)
22}
23
24func projectTable(sesh io.Writer, projects []*db.Project) {
25 writer := NewTabWriter(sesh)
26 _, _ = fmt.Fprintln(writer, "Name\tLast Updated\tLinks To\tACL Type\tACL\tBlocked")
27
28 for _, project := range projects {
29 links := ""
30 if project.ProjectDir != project.Name {
31 links = project.ProjectDir
32 }
33 _, _ = fmt.Fprintf(
34 writer,
35 "%s\t%s\t%s\t%s\t%s\t%s\r\n",
36 project.Name,
37 project.UpdatedAt.Format("2006-01-02 15:04:05"),
38 links,
39 project.Acl.Type,
40 strings.Join(project.Acl.Data, " "),
41 project.Blocked,
42 )
43 }
44 _ = writer.Flush()
45}
46
47type Cmd struct {
48 User *db.User
49 Session shared.CmdSession
50 Log *slog.Logger
51 Store storage.StorageServe
52 Dbpool pgsdb.PgsDB
53 Write bool
54 Width int
55 Height int
56 Cfg *PgsConfig
57}
58
59func (c *Cmd) output(out string) {
60 _, _ = c.Session.Write([]byte(out + "\r\n"))
61}
62
63func (c *Cmd) error(err error) {
64 _, _ = fmt.Fprint(c.Session.Stderr(), err, "\r\n")
65 _ = c.Session.Exit(1)
66 _ = c.Session.Close()
67}
68
69func (c *Cmd) bail(err error) {
70 if err == nil {
71 return
72 }
73 c.Log.Error(err.Error())
74 c.error(err)
75}
76
77func (c *Cmd) notice() {
78 if !c.Write {
79 c.output("\nNOTICE: changes not commited, use `--write` to save operation")
80 }
81}
82
83func (c *Cmd) RmProjectAssets(projectName string) error {
84 bucketName := shared.GetAssetBucketName(c.User.ID)
85 bucket, err := c.Store.GetBucket(bucketName)
86 if err != nil {
87 return err
88 }
89 c.output(fmt.Sprintf("removing project assets (%s)", projectName))
90
91 fileList, err := c.Store.ListObjects(bucket, projectName+"/", true)
92 if err != nil {
93 return err
94 }
95
96 if len(fileList) == 0 {
97 c.output(fmt.Sprintf("no assets found for project (%s)", projectName))
98 return nil
99 }
100 c.output(fmt.Sprintf("found (%d) assets for project (%s), removing", len(fileList), projectName))
101
102 for _, file := range fileList {
103 if file.IsDir() {
104 continue
105 }
106 intent := fmt.Sprintf("deleted (%s)", file.Name())
107 c.Log.Info(
108 "attempting to delete file",
109 "user", c.User.Name,
110 "bucket", bucket.Name,
111 "filename", file.Name(),
112 )
113 if c.Write {
114 err = c.Store.DeleteObject(
115 bucket,
116 filepath.Join(projectName, file.Name()),
117 )
118 if err == nil {
119 c.output(intent)
120 } else {
121 return err
122 }
123 } else {
124 c.output(intent)
125 }
126 }
127 return nil
128}
129
130func (c *Cmd) help() {
131 helpStr := `pgs.sh
132======
133
134Deploy static sites with a single command. No passwords. No config files. No CI setup. Just your SSH key and rsync.
135
136 rsync --delete -rv ./public/ pgs.sh:/mysite
137 # => https://erock-mysite.pgs.sh
138
139That's the entire workflow. Your SSH key is your identity and every deploy is instant.
140
141You can fetch project assets with the same command in reverse:
142
143 rsync -rv pgs.sh:/mysite/ ./public/
144
145You can also use unix pipes to directly upload files by providing the project name as part of the path:
146
147 echo "<body>hello world!</body>" | ssh pgs.sh /mysite/index.html
148 # => https://erock-mysite.pgs.sh/index.html
149
150The leading "/" is important.
151
152You can also create private projects when you prefix the project name with 'private':
153
154 rsync -rv ./public/ pgs.sh:/private-site/
155
156This means only you can access the site through a web tunnel or by downloading the files.
157`
158 helpStr += "\r\nCommands: [help, stats, ls, fzf, rm, link, unlink, prune, retain, depends, acl, cache, forms]\r\n"
159 helpStr += "For most of these commands you can provide a `-h` to learn about its usage.\r\n"
160 helpStr += "\r\n> NOTICE:" + " *must* append with `--write` for the changes to persist.\r\n"
161 c.output(helpStr)
162 projectName := "{project}"
163
164 data := [][]string{
165 {
166 "help",
167 "Prints this screen",
168 },
169 {
170 "stats",
171 "Usage statistics (quota, % quota used, number of projects)",
172 },
173 {
174 "ls",
175 "Lists all projects and meta data",
176 },
177 {
178 fmt.Sprintf("fzf %s", projectName),
179 "Lists urls of all assets in project",
180 },
181 {
182 fmt.Sprintf("rm %s", projectName),
183 "Removes all files in project and then deletes the project",
184 },
185 {
186 fmt.Sprintf("link %s --to projB", projectName),
187 fmt.Sprintf("Instant promotion and rollback mechanism that symbolic links %s to `projB`", projectName),
188 },
189 {
190 fmt.Sprintf("unlink %s", projectName),
191 "Removes symbolic link",
192 },
193 {
194 fmt.Sprintf("prune %s", projectName),
195 "Delete all projects matching a prefix (except projects with linked projects)",
196 },
197 {
198 fmt.Sprintf("retain %s", projectName),
199 "Delete all projects matching a prefix except the last N recently updated projects.",
200 },
201 {
202 fmt.Sprintf("depends %s", projectName),
203 "Lists all projects linked to project",
204 },
205 {
206 fmt.Sprintf("acl %s", projectName),
207 "Access control for project",
208 },
209 {
210 fmt.Sprintf("cache %s", projectName),
211 "Clear http cache",
212 },
213 {
214 "forms ls",
215 "Print list of forms",
216 },
217 {
218 fmt.Sprintf("forms %s", projectName),
219 "Print form submissions in json",
220 },
221 }
222
223 writer := NewTabWriter(c.Session)
224 _, _ = fmt.Fprintln(writer, "Cmd\tDescription")
225 _, _ = fmt.Fprintf(writer, "===\t===========\r\n")
226 for _, dat := range data {
227 _, _ = fmt.Fprintf(writer, "%s\t%s\r\n", dat[0], dat[1])
228 }
229 _ = writer.Flush()
230}
231
232func (c *Cmd) stats(cfgMaxSize uint64) error {
233 ff, err := findFeatureFlag(c.Dbpool, c.Cfg, c.User.ID)
234 if err != nil {
235 ff = db.NewFeatureFlag(c.User.ID, "pgs", cfgMaxSize, 0, 0)
236 }
237 storageMax := ff.FindStorageMax(cfgMaxSize)
238
239 bucketName := shared.GetAssetBucketName(c.User.ID)
240 bucket, err := c.Store.GetBucket(bucketName)
241 if err != nil {
242 return err
243 }
244
245 totalFileSize, err := c.Store.GetBucketQuota(bucket)
246 if err != nil {
247 return err
248 }
249
250 projects, err := c.Dbpool.FindProjectsByUser(c.User.ID)
251 if err != nil {
252 return err
253 }
254
255 writer := NewTabWriter(c.Session)
256 _, _ = fmt.Fprintln(writer, "Used (GB)\tQuota (GB)\tUsed (%)\tProjects (#)")
257 _, _ = fmt.Fprintf(
258 writer,
259 "%.4f\t%.4f\t%.4f\t%d\r\n",
260 shared.BytesToGB(int(totalFileSize)),
261 shared.BytesToGB(int(storageMax)),
262 (float32(totalFileSize)/float32(storageMax))*100,
263 len(projects),
264 )
265 return writer.Flush()
266}
267
268func (c *Cmd) ls() error {
269 projects, err := c.Dbpool.FindProjectsByUser(c.User.ID)
270 if err != nil {
271 return err
272 }
273
274 if len(projects) == 0 {
275 c.output("no projects found")
276 }
277
278 projectTable(c.Session, projects)
279
280 return nil
281}
282
283func (c *Cmd) unlink(projectName string) error {
284 c.Log.Info("user running `unlink` command", "user", c.User.Name, "project", projectName)
285 project, err := c.Dbpool.FindProjectByName(c.User.ID, projectName)
286 if err != nil {
287 return errors.Join(err, fmt.Errorf("project (%s) does not exit", projectName))
288 }
289
290 err = c.Dbpool.LinkToProject(c.User.ID, project.ID, project.Name, c.Write)
291 if err != nil {
292 return err
293 }
294 c.output(fmt.Sprintf("(%s) unlinked", project.Name))
295
296 return nil
297}
298
299func (c *Cmd) fzf(projectName string) error {
300 project, err := c.Dbpool.FindProjectByName(c.User.ID, projectName)
301 if err != nil {
302 return err
303 }
304
305 bucket, err := c.Store.GetBucket(shared.GetAssetBucketName(c.User.ID))
306 if err != nil {
307 return err
308 }
309
310 objs, err := c.Store.ListObjects(bucket, project.ProjectDir+"/", true)
311 if err != nil {
312 return err
313 }
314
315 for _, obj := range objs {
316 if strings.Contains(obj.Name(), "._pico_keep_dir") {
317 continue
318 }
319 url := c.Cfg.AssetURL(
320 c.User.Name,
321 project.Name,
322 strings.TrimPrefix(obj.Name(), "/"),
323 )
324 c.output(url)
325 }
326
327 return nil
328}
329
330func (c *Cmd) link(projectName, linkTo string) error {
331 c.Log.Info("user running `link` command", "user", c.User.Name, "project", projectName, "link", linkTo)
332
333 projectDir := linkTo
334 _, err := c.Dbpool.FindProjectByName(c.User.ID, linkTo)
335 if err != nil {
336 e := fmt.Errorf("(%s) project doesn't exist", linkTo)
337 return e
338 }
339
340 project, err := c.Dbpool.FindProjectByName(c.User.ID, projectName)
341 projectID := ""
342 if err == nil {
343 projectID = project.ID
344 c.Log.Info("user already has project, updating", "user", c.User.Name, "project", projectName)
345 err = c.Dbpool.LinkToProject(c.User.ID, project.ID, projectDir, c.Write)
346 if err != nil {
347 return err
348 }
349 } else {
350 c.Log.Info("user has no project record, creating", "user", c.User.Name, "project", projectName)
351 if !c.Write {
352 out := fmt.Sprintf("(%s) cannot create a new project without `--write` permission, aborting", projectName)
353 c.output(out)
354 return nil
355 }
356 id, err := c.Dbpool.InsertProject(c.User.ID, projectName, projectName)
357 if err != nil {
358 return err
359 }
360 projectID = id
361 }
362
363 c.Log.Info("user linking", "user", c.User.Name, "project", projectName, "projectDir", projectDir)
364 err = c.Dbpool.LinkToProject(c.User.ID, projectID, projectDir, c.Write)
365 if err != nil {
366 return err
367 }
368
369 out := fmt.Sprintf("(%s) might have orphaned assets, removing", projectName)
370 c.output(out)
371
372 err = c.RmProjectAssets(projectName)
373 if err != nil {
374 return err
375 }
376
377 out = fmt.Sprintf("(%s) now points to (%s)", projectName, linkTo)
378 c.output(out)
379 return nil
380}
381
382func (c *Cmd) depends(projectName string) error {
383 projects, err := c.Dbpool.FindProjectLinks(c.User.ID, projectName)
384 if err != nil {
385 return err
386 }
387
388 if len(projects) == 0 {
389 out := fmt.Sprintf("no projects linked to (%s)", projectName)
390 c.output(out)
391 return nil
392 }
393
394 projectTable(c.Session, projects)
395 return nil
396}
397
398// delete all the projects and associated assets matching prefix
399// but keep the latest N records.
400func (c *Cmd) prune(prefix string, keepNumLatest int) error {
401 c.Log.Info("user running `clean` command", "user", c.User.Name, "prefix", prefix)
402 c.output(fmt.Sprintf("searching for projects that match prefix (%s) and are not linked to other projects", prefix))
403
404 if prefix == "" || prefix == "*" {
405 e := fmt.Errorf("must provide valid prefix")
406 return e
407 }
408
409 projects, err := c.Dbpool.FindProjectsByPrefix(c.User.ID, prefix)
410 if err != nil {
411 return err
412 }
413
414 if len(projects) == 0 {
415 c.output(fmt.Sprintf("no projects found matching prefix (%s)", prefix))
416 return nil
417 }
418
419 rmProjects := []*db.Project{}
420 for _, project := range projects {
421 links, err := c.Dbpool.FindProjectLinks(c.User.ID, project.Name)
422 if err != nil {
423 return err
424 }
425
426 if len(links) == 0 {
427 rmProjects = append(rmProjects, project)
428 } else {
429 out := fmt.Sprintf("project (%s) has (%d) projects linked to it, cannot prune", project.Name, len(links))
430 c.output(out)
431 }
432 }
433
434 goodbye := rmProjects
435 if keepNumLatest > 0 {
436 pmax := len(rmProjects) - (keepNumLatest)
437 if pmax <= 0 {
438 out := fmt.Sprintf(
439 "no projects available to prune (retention policy: %d, total: %d)",
440 keepNumLatest,
441 len(rmProjects),
442 )
443 c.output(out)
444 return nil
445 }
446 goodbye = rmProjects[:pmax]
447 }
448
449 for _, project := range goodbye {
450 out := fmt.Sprintf("project (%s) is available to be pruned", project.Name)
451 c.output(out)
452 err = c.RmProjectAssets(project.Name)
453 if err != nil {
454 return err
455 }
456
457 out = fmt.Sprintf("(%s) removing", project.Name)
458 c.output(out)
459
460 if c.Write {
461 c.Log.Info("removing project", "project", project.Name)
462 err = c.Dbpool.RemoveProject(project.ID)
463 if err != nil {
464 return err
465 }
466 }
467 }
468
469 c.output("\r\nsummary")
470 c.output("=======")
471 for _, project := range goodbye {
472 c.output(fmt.Sprintf("project (%s) removed", project.Name))
473 }
474
475 return nil
476}
477
478func (c *Cmd) rm(projectName string) error {
479 c.Log.Info("user running `rm` command", "user", c.User.Name, "project", projectName)
480
481 project, err := c.Dbpool.FindProjectByName(c.User.ID, projectName)
482 if err == nil {
483 c.Log.Info("found project, checking dependencies", "project", projectName, "projectID", project.ID)
484
485 links, err := c.Dbpool.FindProjectLinks(c.User.ID, projectName)
486 if err != nil {
487 return err
488 }
489
490 if len(links) > 0 {
491 e := fmt.Errorf("project (%s) has (%d) projects linking to it, cannot delete project until they have been unlinked or removed, aborting", projectName, len(links))
492 return e
493 }
494
495 out := fmt.Sprintf("(%s) removing", project.Name)
496 c.output(out)
497 if c.Write {
498 c.Log.Info("removing project", "project", project.Name)
499 err = c.Dbpool.RemoveProject(project.ID)
500 if err != nil {
501 return err
502 }
503 }
504 } else {
505 msg := fmt.Sprintf("(%s) project record not found for user (%s)", projectName, c.User.Name)
506 c.output(msg)
507 }
508
509 err = c.RmProjectAssets(projectName)
510 return err
511}
512
513func (c *Cmd) acl(projectName, aclType string, acls []string) error {
514 c.Log.Info(
515 "user running `acl` command",
516 "user", c.User.Name,
517 "project", projectName,
518 "actType", aclType,
519 "acls", acls,
520 )
521 c.output(fmt.Sprintf("setting acl for %s to %s (%s)", projectName, aclType, strings.Join(acls, ",")))
522 acl := db.ProjectAcl{
523 Type: aclType,
524 Data: acls,
525 }
526 if c.Write {
527 return c.Dbpool.UpdateProjectAcl(c.User.ID, projectName, acl)
528 }
529 return nil
530}
531
532func (c *Cmd) cache(projectName string) error {
533 c.Log.Info(
534 "user running `cache` command",
535 "user", c.User.Name,
536 "project", projectName,
537 )
538
539 c.output(fmt.Sprintf("clearing http cache for %s", projectName))
540
541 if c.Write {
542 surrogate := getSurrogateKey(c.User.Name, projectName)
543 return purgeCache(c.Cfg, c.Cfg.Pubsub, surrogate)
544 }
545 return nil
546}
547
548func (c *Cmd) cacheAll() error {
549 isAdmin := false
550 ff, _ := c.Dbpool.FindFeature(c.User.ID, "admin")
551 if ff != nil {
552 if ff.ExpiresAt.After(time.Now()) {
553 isAdmin = true
554 }
555 }
556
557 if !isAdmin {
558 return fmt.Errorf("must be admin to use this command")
559 }
560
561 c.Log.Info(
562 "admin running `cache-all` command",
563 "user", c.User.Name,
564 )
565 c.output("clearing http cache for all sites")
566 if c.Write {
567 return purgeAllCache(c.Cfg, c.Cfg.Pubsub)
568 }
569 return nil
570}
571
572func (c *Cmd) formsLs() error {
573 forms, err := c.Dbpool.FindFormNamesByUser(c.User.ID)
574 if err != nil {
575 return err
576 }
577 if len(forms) == 0 {
578 c.output("no forms found")
579 return nil
580 }
581 for _, name := range forms {
582 c.output(name)
583 }
584 return nil
585}
586
587func (c *Cmd) formData(formName string) error {
588 formData, err := c.Dbpool.FindFormEntriesByUserAndName(c.User.ID, formName)
589 if err != nil {
590 return err
591 }
592 data, err := json.Marshal(formData)
593 if err != nil {
594 return err
595 }
596 c.output(string(data))
597 return nil
598}
599
600func (c *Cmd) formRm(formName string) error {
601 c.output(fmt.Sprintf("removing all data associated with form: %s", formName))
602 if c.Write {
603 return c.Dbpool.RemoveFormEntriesByUserAndName(c.User.ID, formName)
604 }
605 return nil
606}