restic/src/cmds/restic/cmd_ls.go

102 lines
2.1 KiB
Go
Raw Normal View History

2014-10-05 12:44:59 +00:00
package main
import (
"fmt"
"os"
"path/filepath"
"restic"
2016-09-01 20:17:37 +00:00
"restic/errors"
"restic/repository"
2014-10-05 12:44:59 +00:00
)
type CmdLs struct {
Long bool `short:"l" long:"long" description:"Use a long listing format showing size and mode"`
global *GlobalOptions
}
2014-12-07 15:30:52 +00:00
2014-11-30 21:39:58 +00:00
func init() {
2014-12-07 15:30:52 +00:00
_, err := parser.AddCommand("ls",
"list files",
"The ls command lists all files and directories in a snapshot",
&CmdLs{global: &globalOpts})
2014-12-07 15:30:52 +00:00
if err != nil {
panic(err)
}
2014-11-30 21:39:58 +00:00
}
func (cmd CmdLs) printNode(prefix string, n *restic.Node) string {
if !cmd.Long {
return filepath.Join(prefix, n.Name)
}
2016-09-01 19:20:03 +00:00
switch n.Type {
2014-10-05 12:44:59 +00:00
case "file":
return fmt.Sprintf("%s %5d %5d %6d %s %s",
n.Mode, n.UID, n.GID, n.Size, n.ModTime, filepath.Join(prefix, n.Name))
case "dir":
return fmt.Sprintf("%s %5d %5d %6d %s %s",
n.Mode|os.ModeDir, n.UID, n.GID, n.Size, n.ModTime, filepath.Join(prefix, n.Name))
case "symlink":
return fmt.Sprintf("%s %5d %5d %6d %s %s -> %s",
n.Mode|os.ModeSymlink, n.UID, n.GID, n.Size, n.ModTime, filepath.Join(prefix, n.Name), n.LinkTarget)
default:
2016-09-01 19:20:03 +00:00
return fmt.Sprintf("<Node(%s) %s>", n.Type, n.Name)
2014-10-05 12:44:59 +00:00
}
}
2016-09-01 14:04:29 +00:00
func (cmd CmdLs) printTree(prefix string, repo *repository.Repository, id restic.ID) error {
tree, err := repo.LoadTree(id)
2014-10-05 12:44:59 +00:00
if err != nil {
return err
}
for _, entry := range tree.Nodes {
cmd.global.Printf(cmd.printNode(prefix, entry) + "\n")
2014-10-05 12:44:59 +00:00
2016-09-01 19:20:03 +00:00
if entry.Type == "dir" && entry.Subtree != nil {
err = cmd.printTree(filepath.Join(prefix, entry.Name), repo, *entry.Subtree)
2014-10-05 12:44:59 +00:00
if err != nil {
return err
}
}
}
return nil
}
2014-12-07 15:30:52 +00:00
func (cmd CmdLs) Usage() string {
return "snapshot-ID [DIR]"
2014-12-07 15:30:52 +00:00
}
func (cmd CmdLs) Execute(args []string) error {
2014-10-05 12:44:59 +00:00
if len(args) < 1 || len(args) > 2 {
2016-09-01 20:17:37 +00:00
return errors.Fatalf("wrong number of arguments, Usage: %s", cmd.Usage())
2014-12-07 15:30:52 +00:00
}
repo, err := cmd.global.OpenRepository()
2014-12-07 15:30:52 +00:00
if err != nil {
return err
2014-10-05 12:44:59 +00:00
}
err = repo.LoadIndex()
if err != nil {
return err
}
id, err := restic.FindSnapshot(repo, args[0])
2014-10-05 12:44:59 +00:00
if err != nil {
return err
}
sn, err := restic.LoadSnapshot(repo, id)
2014-10-05 12:44:59 +00:00
if err != nil {
return err
}
cmd.global.Verbosef("snapshot of %v at %s:\n", sn.Paths, sn.Time)
2014-10-05 12:44:59 +00:00
return cmd.printTree("", repo, *sn.Tree)
2014-10-05 12:44:59 +00:00
}