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

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

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

type fileHandler struct {
	path string
}

ale's avatar
ale committed
15 16 17 18
func newFileHandler(name string, params Params) (Handler, error) {
	path := params.Get("path")
	if path == "" {
		return nil, errors.New("path not set")
ale's avatar
ale committed
19
	}
ale's avatar
ale committed
20
	return &fileHandler{path: path}, nil
21 22
}

ale's avatar
ale committed
23 24 25 26 27 28 29
// 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
30
		}
ale's avatar
ale committed
31 32
		// Otherwise join it with the root path.
		return filepath.Join(root, a.Path)
ale's avatar
ale committed
33
	}
ale's avatar
ale committed
34 35
	// Join the name with the root path by default.
	return filepath.Join(root, a.Name)
ale's avatar
ale committed
36 37
}

ale's avatar
ale committed
38 39 40 41 42 43 44 45 46 47
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
48
	return jobs.JobFunc(func(ctx context.Context) error {
ale's avatar
ale committed
49
		return rctx.Shell().Run(ctx, cmd)
ale's avatar
ale committed
50 51 52
	})
}

ale's avatar
ale committed
53 54 55 56 57 58 59
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
60

ale's avatar
ale committed
61
	// Call the repo Restore method.
ale's avatar
ale committed
62
	return jobs.JobFunc(func(ctx context.Context) error {
ale's avatar
ale committed
63 64 65 66 67
		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
68
	})
ale's avatar
ale committed
69
}