handler_file.go 1.64 KB
Newer Older
ale's avatar
ale committed
1 2 3 4 5
package tabacco

import (
	"context"
	"path/filepath"
ale's avatar
ale committed
6

ale's avatar
ale committed
7
	"git.autistici.org/ai3/tools/tabacco/jobs"
ale's avatar
ale committed
8 9 10 11 12 13
)

type fileHandler struct {
	path string
}

ale's avatar
ale committed
14
func newFileHandler(name string, params Params) (Handler, error) {
15
	return &fileHandler{path: params.Get("path")}, nil
16 17
}

ale's avatar
ale committed
18 19 20 21 22 23 24
// Convert the atom to a path.
func atomPath(a Atom, root string) string {
	// If the atom has a path, use that.
	if a.Path != "" {
		// If it's an absolute path, just use it.
		if a.Path[0] == '/' {
			return a.Path
ale's avatar
ale committed
25
		}
ale's avatar
ale committed
26 27
		// Otherwise join it with the root path.
		return filepath.Join(root, a.Path)
ale's avatar
ale committed
28
	}
ale's avatar
ale committed
29 30
	// Join the name with the root path by default.
	return filepath.Join(root, a.Name)
ale's avatar
ale committed
31 32
}

ale's avatar
ale committed
33 34 35 36 37 38 39 40 41 42
func (h *fileHandler) BackupJob(rctx RuntimeContext, repo Repository, backup *Backup, ds *Dataset) jobs.Job {
	// Build the list of filesystem paths to pass to the
	// Repository.Backup method.
	var paths []string
	for _, a := range ds.Atoms {
		paths = append(paths, atomPath(a, h.path))
	}
	cmd := repo.BackupCmd(backup, ds, paths)

	// Now pass those paths to the Backup method.
ale's avatar
ale committed
43
	return jobs.JobFunc(func(ctx context.Context) error {
ale's avatar
ale committed
44
		return rctx.Shell().Run(ctx, cmd)
ale's avatar
ale committed
45 46 47
	})
}

ale's avatar
ale committed
48 49 50 51 52 53 54
func (h *fileHandler) RestoreJob(rctx RuntimeContext, repo Repository, backup *Backup, ds *Dataset, target string) jobs.Job {
	// Build the list of filesystem paths to pass to the
	// Repository.Backup method.
	var paths []string
	for _, a := range ds.Atoms {
		paths = append(paths, atomPath(a, h.path))
	}
ale's avatar
ale committed
55

ale's avatar
ale committed
56
	// Call the repo Restore method.
ale's avatar
ale committed
57
	return jobs.JobFunc(func(ctx context.Context) error {
ale's avatar
ale committed
58 59 60 61 62
		cmd, err := repo.RestoreCmd(ctx, rctx, backup, ds, paths, target)
		if err != nil {
			return err
		}
		return rctx.Shell().Run(ctx, cmd)
ale's avatar
ale committed
63
	})
ale's avatar
ale committed
64
}