repos / pico

pico services - prose.sh, pastes.sh, imgs.sh, feeds.sh, pgs.sh
git clone https://github.com/picosh/pico.git

commit
06d4bdd
parent
0ab3eda
author
Eric Bower
date
2023-08-14 13:23:32 +0000 UTC
feat: delete orphaned files when link succeeds
1 files changed,  +37, -4
M pgs/wish.go
+37, -4
 1@@ -178,7 +178,9 @@ func WishMiddleware(handler *uploadassets.UploadAssetHandler) wish.Middleware {
 2 				}
 3 
 4 				project, err := dbpool.FindProjectByName(user.ID, projectName)
 5+				projectID := ""
 6 				if err == nil {
 7+					projectID = project.ID
 8 					log.Infof("user (%s) already has project (%s), updating ...", user.Name, projectName)
 9 					err = dbpool.LinkToProject(user.ID, project.ID, projectDir)
10 					if err != nil {
11@@ -194,15 +196,46 @@ func WishMiddleware(handler *uploadassets.UploadAssetHandler) wish.Middleware {
12 						utils.ErrorHandler(session, err)
13 						return
14 					}
15+					projectID = id
16+				}
17 
18-					log.Infof("user (%s) linking (%s) to (%s) ...", user.Name, projectName, projectDir)
19-					err = dbpool.LinkToProject(user.ID, id, projectDir)
20-					if err != nil {
21+				log.Infof("user (%s) linking (%s) to (%s) ...", user.Name, projectName, projectDir)
22+				err = dbpool.LinkToProject(user.ID, projectID, projectDir)
23+				if err != nil {
24+					log.Error(err)
25+					utils.ErrorHandler(session, err)
26+					return
27+				}
28+
29+				bucketName := shared.GetAssetBucketName(user.ID)
30+				bucket, err := store.GetBucket(bucketName)
31+				if err != nil {
32+					log.Error(err)
33+					utils.ErrorHandler(session, err)
34+					return
35+				}
36+
37+				fileList, err := store.ListFiles(bucket, projectName, true)
38+				if err != nil {
39+					log.Error(err)
40+					return
41+				}
42+
43+				if len(fileList) > 0 {
44+					out := fmt.Sprintf("(%s) assets now orphaned, deleting files (%d) ...\n", projectName, len(fileList))
45+					_, _ = session.Write([]byte(out))
46+				}
47+
48+				for _, file := range fileList {
49+					err = store.DeleteFile(bucket, file.Name())
50+					if err == nil {
51+						_, _ = session.Write([]byte(fmt.Sprintf("deleted orphaned (%s)\n", file.Name())))
52+					} else {
53 						log.Error(err)
54 						utils.ErrorHandler(session, err)
55-						return
56 					}
57 				}
58+
59 				out := fmt.Sprintf("(%s) now points to (%s)\n", projectName, linkTo)
60 				_, _ = session.Write([]byte(out))
61 				return