refactor(cli): improve dump's temporary file handling

- Create temporary directory inside of a temporary directory (useful
  for a work-in-progress Landlock implementation, as we will not want
  to "whitelist" the entirety of the /tmp directory in our case,
  i.e. /tmp/forgejo-dump-133552095).
- The database is always removed after dump is complete.
- The temporary directory is removed if no temporary directory has
  been explicitly set (as in, created by Forgejo in /tmp or
  equivalent).
This commit is contained in:
Panagiotis "Ivory" Vasilopoulos 2025-03-26 20:33:30 +01:00
parent d0a5531ebc
commit 72a78e64cc

View file

@ -122,7 +122,6 @@ It can be used for backup and capture Forgejo server image to send to maintainer
&cli.StringFlag{
Name: "tempdir",
Aliases: []string{"t"},
Value: os.TempDir(),
Usage: "Temporary dir path",
},
&cli.StringFlag{
@ -288,18 +287,31 @@ func runDump(ctx *cli.Context) error {
}
tmpDir := ctx.String("tempdir")
if tmpDir == "" {
tmpDir, err = os.MkdirTemp("", "forgejo-dump-*")
if err != nil {
fatal("Failed to create temporary directory: %v", err)
}
defer func() {
if err := util.Remove(tmpDir); err != nil {
log.Warn("Failed to remove temporary directory: %s: Error: %v", tmpDir, err)
}
}()
}
if _, err := os.Stat(tmpDir); os.IsNotExist(err) {
fatal("Path does not exist: %s", tmpDir)
}
dbDump, err := os.CreateTemp(tmpDir, "forgejo-db.sql")
if err != nil {
fatal("Failed to create tmp file: %v", err)
fatal("Failed to create temporary file: %v", err)
}
defer func() {
_ = dbDump.Close()
if err := util.Remove(dbDump.Name()); err != nil {
log.Warn("Failed to remove temporary file: %s: Error: %v", dbDump.Name(), err)
log.Warn("Failed to remove temporary database file: %s: Error: %v", dbDump.Name(), err)
}
}()