1package backend
2
3import (
4	"encoding/hex"
5
6	"github.com/restic/restic/internal/restic"
7)
8
9// DefaultLayout implements the default layout for local and sftp backends, as
10// described in the Design document. The `data` directory has one level of
11// subdirs, two characters each (taken from the first two characters of the
12// file name).
13type DefaultLayout struct {
14	Path string
15	Join func(...string) string
16}
17
18var defaultLayoutPaths = map[restic.FileType]string{
19	restic.PackFile:     "data",
20	restic.SnapshotFile: "snapshots",
21	restic.IndexFile:    "index",
22	restic.LockFile:     "locks",
23	restic.KeyFile:      "keys",
24}
25
26func (l *DefaultLayout) String() string {
27	return "<DefaultLayout>"
28}
29
30// Name returns the name for this layout.
31func (l *DefaultLayout) Name() string {
32	return "default"
33}
34
35// Dirname returns the directory path for a given file type and name.
36func (l *DefaultLayout) Dirname(h restic.Handle) string {
37	p := defaultLayoutPaths[h.Type]
38
39	if h.Type == restic.PackFile && len(h.Name) > 2 {
40		p = l.Join(p, h.Name[:2]) + "/"
41	}
42
43	return l.Join(l.Path, p) + "/"
44}
45
46// Filename returns a path to a file, including its name.
47func (l *DefaultLayout) Filename(h restic.Handle) string {
48	name := h.Name
49	if h.Type == restic.ConfigFile {
50		return l.Join(l.Path, "config")
51	}
52
53	return l.Join(l.Dirname(h), name)
54}
55
56// Paths returns all directory names needed for a repo.
57func (l *DefaultLayout) Paths() (dirs []string) {
58	for _, p := range defaultLayoutPaths {
59		dirs = append(dirs, l.Join(l.Path, p))
60	}
61
62	// also add subdirs
63	for i := 0; i < 256; i++ {
64		subdir := hex.EncodeToString([]byte{byte(i)})
65		dirs = append(dirs, l.Join(l.Path, defaultLayoutPaths[restic.PackFile], subdir))
66	}
67
68	return dirs
69}
70
71// Basedir returns the base dir name for type t.
72func (l *DefaultLayout) Basedir(t restic.FileType) (dirname string, subdirs bool) {
73	if t == restic.PackFile {
74		subdirs = true
75	}
76
77	dirname = l.Join(l.Path, defaultLayoutPaths[t])
78	return
79}
80