restic/cmd/restic/cmd_restore.go

99 lines
2.0 KiB
Go
Raw Normal View History

2014-04-28 00:00:15 +02:00
package main
import (
"errors"
2014-09-23 22:39:12 +02:00
"fmt"
2014-04-28 00:00:15 +02:00
2014-12-05 21:45:49 +01:00
"github.com/restic/restic"
"github.com/restic/restic/debug"
"github.com/restic/restic/filter"
2014-04-28 00:00:15 +02:00
)
type CmdRestore struct {
Exclude []string `short:"e" long:"exclude" description:"Exclude a pattern (can be specified multiple times)"`
Target string `short:"t" long:"target" description:"Directory to restore to"`
global *GlobalOptions
}
2014-12-07 16:30:52 +01:00
2014-11-30 22:39:58 +01:00
func init() {
2014-12-07 16:30:52 +01:00
_, err := parser.AddCommand("restore",
"restore a snapshot",
"The restore command restores a snapshot to a directory",
&CmdRestore{global: &globalOpts})
2014-12-07 16:30:52 +01:00
if err != nil {
panic(err)
}
}
func (cmd CmdRestore) Usage() string {
return "snapshot-ID"
2014-11-30 22:39:58 +01:00
}
2014-12-07 16:30:52 +01:00
func (cmd CmdRestore) Execute(args []string) error {
if len(args) != 1 {
2014-12-07 16:30:52 +01:00
return fmt.Errorf("wrong number of arguments, Usage: %s", cmd.Usage())
}
if cmd.Target == "" {
return errors.New("please specify a directory to restore to (--target)")
}
snapshotIDString := args[0]
debug.Log("restore", "restore %v to %v", snapshotIDString, cmd.Target)
repo, err := cmd.global.OpenRepository()
2014-12-07 16:30:52 +01:00
if err != nil {
return err
2014-04-28 00:00:15 +02:00
}
lock, err := lockRepo(repo)
defer unlockRepo(lock)
2015-06-27 14:40:18 +02:00
if err != nil {
return err
}
err = repo.LoadIndex()
if err != nil {
return err
}
id, err := restic.FindSnapshot(repo, snapshotIDString)
2014-04-28 00:00:15 +02:00
if err != nil {
cmd.global.Exitf(1, "invalid id %q: %v", snapshotIDString, err)
2014-04-28 00:00:15 +02:00
}
res, err := restic.NewRestorer(repo, id)
2014-08-04 22:46:14 +02:00
if err != nil {
cmd.global.Exitf(2, "creating restorer failed: %v\n", err)
2014-08-04 22:46:14 +02:00
}
2014-12-05 21:45:49 +01:00
res.Error = func(dir string, node *restic.Node, err error) error {
cmd.global.Warnf("error for %s: %+v\n", dir, err)
2014-09-23 22:39:12 +02:00
return err
2014-04-28 00:00:15 +02:00
}
selectFilter := func(item string, dstpath string, node *restic.Node) bool {
matched, err := filter.List(cmd.Exclude, item)
if err != nil {
cmd.global.Warnf("error for exclude pattern: %v", err)
}
return !matched
}
if len(cmd.Exclude) > 0 {
res.SelectFilter = selectFilter
}
cmd.global.Verbosef("restoring %s to %s\n", res.Snapshot(), cmd.Target)
2014-09-23 22:39:12 +02:00
err = res.RestoreTo(cmd.Target)
2014-09-23 22:39:12 +02:00
if err != nil {
return err
}
2014-04-28 00:00:15 +02:00
return nil
}