Add restoring config file

This commit is contained in:
kolaente 2020-06-21 13:03:35 +02:00
parent eb0fed1aa6
commit 04e02e83a1
Signed by: konrad
GPG Key ID: F40E70337AB24C9B
1 changed files with 61 additions and 0 deletions

View File

@ -16,7 +16,68 @@
package dump
import (
"archive/zip"
"bufio"
"code.vikunja.io/api/pkg/log"
"fmt"
"io"
"os"
"strings"
)
// Restore takes a zip file name and restores it
func Restore(filename string) error {
r, err := zip.OpenReader(filename)
if err != nil {
return fmt.Errorf("could not open zip file: %s", err)
}
log.Warning("Restoring a dump will wipe your current installation!")
log.Warning("To confirm, please type 'Yes, I understand' and confirm with enter:")
cr := bufio.NewReader(os.Stdin)
text, err := cr.ReadString('\n')
if err != nil {
return fmt.Errorf("could not read confirmation message: %s", err)
}
if text != "Yes, I understand\n" {
return fmt.Errorf("invalid confirmation message")
}
// Find the config file
var config *zip.File
for _, file := range r.File {
if strings.HasPrefix(file.Name, "config") {
config = file
break
}
}
if config == nil {
return fmt.Errorf("dump does not contain a config file")
}
if err := writeFile(config, config.Name); err != nil {
return fmt.Errorf("could not create config file: %s", err)
}
return nil
}
func writeFile(file *zip.File, path string) error {
outFile, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, file.Mode())
if err != nil {
return err
}
defer outFile.Close()
rc, err := file.Open()
if err != nil {
return err
}
defer rc.Close()
_, err = io.Copy(outFile, rc)
return err
}