- The type comes from --type or the extension; a contradiction is an error, and the output is never renamed. - Each input is stored under its own resolved name. - An existing output, an output inside an input, the output as an input, duplicate names and the root directory are refused before any work. - Backends: GNU tar piped into the compressor, Info-ZIP zip once per input, and 7-Zip. - --exclude matches names at any depth, translated so the three backends behave alike. - The archive is built beside the output and renamed into place only when complete.
406 lines
12 KiB
Go
406 lines
12 KiB
Go
// Package create implements c, which creates archives.
|
|
//
|
|
// The archive is written into a private temporary directory next to the
|
|
// output and renamed into place only after the backend has succeeded, so a
|
|
// failed or interrupted run never leaves a partial archive and never damages
|
|
// an existing file.
|
|
//
|
|
// Every input is stored under its own name, the last component of its
|
|
// resolved path: `c out.tar.gz ../src /tmp/notes.txt` stores "src/..." and
|
|
// "notes.txt". Inputs are never modified.
|
|
package create
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"io/fs"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"src.panahifar.ir/ahp/archive-utils/internal/cli"
|
|
"src.panahifar.ir/ahp/archive-utils/internal/fsx"
|
|
"src.panahifar.ir/ahp/archive-utils/internal/proc"
|
|
"src.panahifar.ir/ahp/archive-utils/internal/progress"
|
|
|
|
"golang.org/x/sys/unix"
|
|
)
|
|
|
|
var usage = `Usage: c [options] <output> <input> [input ...]
|
|
|
|
Create an archive. The format is taken from the output name's extension,
|
|
or from --type. Each input is stored under its own name.
|
|
|
|
Options:
|
|
-t, --type TYPE archive type: ` + typeList() + `
|
|
-f, --fast favour speed over size
|
|
-b, --best favour size over speed (highest standard level)
|
|
-q, --quiet print errors only
|
|
-v, --verbose list archived entries
|
|
--force replace an existing output file
|
|
--exclude NAME skip files and directories whose name matches the
|
|
glob NAME at any depth (repeatable; no '/')
|
|
-h, --help show this help and exit
|
|
--version show version and exit
|
|
|
|
Extensions:
|
|
.tar .tar.gz .tgz .tar.bz2 .tbz2 .tbz .tar.xz .txz .tar.zst .tzst
|
|
.zip .7z
|
|
|
|
Exit status:
|
|
0 success, 1 failure or output exists, 2 usage error,
|
|
3 bad input or output path, 4 missing dependency
|
|
`
|
|
|
|
var options = []cli.Option{
|
|
{Name: "type", Short: 't', Long: "type", Value: true},
|
|
{Name: "fast", Short: 'f', Long: "fast"},
|
|
{Name: "best", Short: 'b', Long: "best"},
|
|
{Name: "force", Long: "force"}, // long form only: in x, -f means --force
|
|
{Name: "quiet", Short: 'q', Long: "quiet"},
|
|
{Name: "verbose", Short: 'v', Long: "verbose"},
|
|
{Name: "exclude", Long: "exclude", Value: true},
|
|
{Name: "help", Short: 'h', Long: "help"},
|
|
{Name: "version", Long: "version"},
|
|
}
|
|
|
|
type creator struct {
|
|
log *cli.Logger
|
|
typ Type
|
|
profile Profile
|
|
force bool
|
|
verbose bool
|
|
excludes []string
|
|
inputs []input
|
|
output string // as given
|
|
outDir string // resolved directory of the output
|
|
outPath string // outDir + output file name
|
|
sevenZip string // 7-Zip executable
|
|
progress bool // show a live progress display
|
|
}
|
|
|
|
// Run is c's main function.
|
|
func Run(ctx context.Context, stdout io.Writer, log *cli.Logger, args []string) error {
|
|
parsed, operands, err := cli.Parse(options, args)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
c := &creator{log: log}
|
|
typeName := ""
|
|
for _, a := range parsed {
|
|
switch a.Name {
|
|
case "type":
|
|
typeName = a.Value
|
|
case "fast":
|
|
c.profile = Fast
|
|
case "best":
|
|
c.profile = Best
|
|
case "force":
|
|
c.force = true
|
|
case "quiet":
|
|
log.Level = cli.Quiet
|
|
case "verbose":
|
|
log.Level = cli.Verbose
|
|
case "exclude":
|
|
c.excludes = append(c.excludes, a.Value)
|
|
case "help":
|
|
_, err := io.WriteString(stdout, usage)
|
|
return err
|
|
case "version":
|
|
_, err := fmt.Fprintln(stdout, "c", cli.Version)
|
|
return err
|
|
}
|
|
}
|
|
c.verbose = log.Level >= cli.Verbose
|
|
// Shown only at normal verbosity: -q wants silence, -v lists entries.
|
|
c.progress = log.Level == cli.Normal && progress.Enabled(os.Stderr)
|
|
switch len(operands) {
|
|
case 0:
|
|
return cli.UsageErrorf("missing output operand")
|
|
case 1:
|
|
return cli.UsageErrorf("missing input operand")
|
|
}
|
|
c.output = operands[0]
|
|
if err := checkExcludes(c.excludes); err != nil {
|
|
return err
|
|
}
|
|
if c.typ, err = resolveType(typeName, c.output); err != nil {
|
|
return err
|
|
}
|
|
if c.typ == Tar && c.profile != Default {
|
|
log.Warn("--fast/--best have no effect on an uncompressed tar archive")
|
|
}
|
|
|
|
// Validate the output, every input and the backends before writing.
|
|
problems := cli.NewProblems(log)
|
|
c.checkOutput(problems)
|
|
c.checkInputs(operands[1:], problems)
|
|
c.checkDependencies(ctx, problems)
|
|
if err := problems.Err(); err != nil {
|
|
return err
|
|
}
|
|
return c.create(ctx)
|
|
}
|
|
|
|
func checkExcludes(excludes []string) error {
|
|
for _, e := range excludes {
|
|
switch {
|
|
case e == "":
|
|
return cli.UsageErrorf("--exclude pattern must not be empty")
|
|
case strings.Contains(e, "/"):
|
|
return cli.UsageErrorf("--exclude pattern '%s' must not contain '/'; it matches names, not paths", e)
|
|
case strings.Contains(e, "\n"):
|
|
return cli.UsageErrorf("--exclude pattern must not contain a newline")
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// resolveType returns the explicit type if given, else the type implied by
|
|
// the output name. A contradiction between the two is an error; the output
|
|
// name is never changed.
|
|
func resolveType(name, output string) (Type, error) {
|
|
implied, known := TypeFromName(filepath.Base(output))
|
|
if name == "" {
|
|
if !known {
|
|
return "", cli.UsageErrorf("cannot infer the archive type from '%s'; use a known extension or --type", output)
|
|
}
|
|
return implied, nil
|
|
}
|
|
t, ok := ParseType(name)
|
|
if !ok {
|
|
return "", cli.UsageErrorf("unknown type '%s' (choose from: %s)", name, typeList())
|
|
}
|
|
if known && implied != t {
|
|
return "", cli.UsageErrorf("output name '%s' implies type '%s', but --type '%s' was given", output, implied, t)
|
|
}
|
|
return t, nil
|
|
}
|
|
|
|
func (c *creator) checkOutput(p *cli.Problems) {
|
|
name, dir := filepath.Base(c.output), filepath.Dir(c.output)
|
|
if strings.HasSuffix(c.output, "/") || name == "." || name == ".." || name == "/" {
|
|
p.Add(cli.ExitInput, "'%s': not a valid output file name", c.output)
|
|
return
|
|
}
|
|
info, err := os.Stat(dir)
|
|
switch {
|
|
case errors.Is(err, fs.ErrNotExist):
|
|
p.Add(cli.ExitInput, "'%s': directory '%s' does not exist", c.output, dir)
|
|
return
|
|
case err != nil:
|
|
p.Add(cli.ExitInput, "'%s': %v", c.output, unwrapPath(err))
|
|
return
|
|
case !info.IsDir():
|
|
p.Add(cli.ExitInput, "'%s': '%s' is not a directory", c.output, dir)
|
|
return
|
|
case unix.Access(dir, unix.W_OK|unix.X_OK) != nil:
|
|
p.Add(cli.ExitInput, "'%s': directory '%s' is not writable", c.output, dir)
|
|
return
|
|
}
|
|
resolved, err := resolve(dir)
|
|
if err != nil {
|
|
p.Add(cli.ExitInput, "'%s': %v", c.output, unwrapPath(err))
|
|
return
|
|
}
|
|
c.outDir, c.outPath = resolved, filepath.Join(resolved, name)
|
|
|
|
if _, err := os.Lstat(c.outPath); err == nil {
|
|
if info, err := os.Stat(c.outPath); err == nil && info.IsDir() {
|
|
p.Add(cli.ExitInput, "'%s' is a directory", c.output)
|
|
} else if !c.force {
|
|
p.Add(cli.ExitFailure, "'%s' already exists (use --force to replace it)", c.output)
|
|
}
|
|
}
|
|
}
|
|
|
|
func (c *creator) checkInputs(labels []string, p *cli.Problems) {
|
|
stored := map[string]string{} // stored name -> input label
|
|
for _, label := range labels {
|
|
info, err := os.Stat(label)
|
|
switch {
|
|
case errors.Is(err, fs.ErrNotExist):
|
|
p.Add(cli.ExitInput, "'%s': no such file or directory", label)
|
|
continue
|
|
case err != nil:
|
|
p.Add(cli.ExitInput, "'%s': %v", label, unwrapPath(err))
|
|
continue
|
|
}
|
|
mode := uint32(unix.R_OK)
|
|
if info.IsDir() {
|
|
mode |= unix.X_OK
|
|
}
|
|
if unix.Access(label, mode) != nil {
|
|
p.Add(cli.ExitInput, "'%s': permission denied", label)
|
|
continue
|
|
}
|
|
resolved, err := resolve(label)
|
|
if err != nil {
|
|
p.Add(cli.ExitInput, "'%s': %v", label, unwrapPath(err))
|
|
continue
|
|
}
|
|
if resolved == "/" {
|
|
p.Add(cli.ExitInput, "'%s': refusing to archive the root directory", label)
|
|
continue
|
|
}
|
|
in := input{label: label, parent: filepath.Dir(resolved), name: filepath.Base(resolved)}
|
|
if other, dup := stored[in.name]; dup {
|
|
p.Add(cli.ExitInput, "'%s': name '%s' is already used by '%s'; both would be stored as '%s'",
|
|
label, in.name, other, in.name)
|
|
continue
|
|
}
|
|
stored[in.name] = label
|
|
|
|
if c.outPath != "" {
|
|
if out, err := os.Stat(c.outPath); err == nil && os.SameFile(out, info) {
|
|
p.Add(cli.ExitInput, "'%s' is the output file itself", label)
|
|
continue
|
|
}
|
|
if info.IsDir() && (c.outDir == resolved || strings.HasPrefix(c.outDir, resolved+"/")) {
|
|
p.Add(cli.ExitInput, "output '%s' is inside input '%s' and would include itself; write it elsewhere",
|
|
c.output, label)
|
|
continue
|
|
}
|
|
}
|
|
c.inputs = append(c.inputs, in)
|
|
}
|
|
}
|
|
|
|
func (c *creator) checkDependencies(ctx context.Context, p *cli.Problems) {
|
|
var needed []string
|
|
switch {
|
|
case c.typ.isTar():
|
|
needed = append(needed, "tar")
|
|
if comp := compressorArgs(c.typ, c.profile); comp != nil {
|
|
needed = append(needed, comp[0])
|
|
}
|
|
case c.typ == Zip:
|
|
needed = append(needed, "zip")
|
|
case c.typ == SevenZ:
|
|
var ok bool
|
|
if c.sevenZip, ok = proc.SevenZip(); !ok {
|
|
p.Add(cli.ExitDependency, "creating %s archives requires '7z', which is not installed", c.typ)
|
|
}
|
|
}
|
|
for _, program := range needed {
|
|
if !proc.Have(program) {
|
|
p.Add(cli.ExitDependency, "creating %s archives requires '%s', which is not installed", c.typ, program)
|
|
return
|
|
}
|
|
}
|
|
if c.typ.isTar() {
|
|
var version bytes.Buffer
|
|
err := proc.Run(ctx, nil, &version, proc.Cmd{Args: []string{"tar", "--version"}})
|
|
if err != nil || !strings.Contains(version.String(), "GNU tar") {
|
|
p.Add(cli.ExitDependency, "creating tar archives requires GNU tar; the 'tar' on PATH is a different implementation")
|
|
}
|
|
}
|
|
}
|
|
|
|
// create builds the archive in a temporary directory beside the output and
|
|
// renames it into place.
|
|
func (c *creator) create(ctx context.Context) error {
|
|
tmp, err := os.MkdirTemp(c.outDir, ".c-")
|
|
if err != nil {
|
|
return cli.Errorf(cli.ExitFailure, "cannot create a temporary directory beside '%s': %v", c.output, unwrapPath(err))
|
|
}
|
|
defer fsx.RemoveAll(tmp)
|
|
// zip and 7z append an extension to a name that has none.
|
|
archive := filepath.Join(tmp, "archive."+string(c.typ))
|
|
|
|
c.log.Detail("creating %s archive '%s' (%s profile)", c.typ, c.output, c.profile)
|
|
var mon *progress.Monitor
|
|
if c.progress {
|
|
mon = progress.Start(os.Stderr, "create", "", 0, c.log.Color())
|
|
mon.Ready(c.output, c.inputSize())
|
|
}
|
|
err = c.build(ctx, archive, mon)
|
|
mon.Stop()
|
|
if err != nil {
|
|
if ctx.Err() != nil {
|
|
return ctx.Err()
|
|
}
|
|
return cli.Errorf(cli.ExitFailure, "failed to create '%s': %v; nothing was written", c.output, unwrapPath(err))
|
|
}
|
|
info, err := os.Stat(archive)
|
|
if err != nil || !info.Mode().IsRegular() {
|
|
return cli.Errorf(cli.ExitFailure, "failed to create '%s': the backend produced no archive", c.output)
|
|
}
|
|
|
|
if c.force {
|
|
err = os.Rename(archive, c.outPath)
|
|
} else {
|
|
err = fsx.RenameNoReplace(archive, c.outPath)
|
|
if errors.Is(err, fs.ErrExist) {
|
|
return cli.Errorf(cli.ExitFailure, "'%s' appeared while archiving; not replacing it", c.output)
|
|
}
|
|
}
|
|
if err != nil {
|
|
return cli.Errorf(cli.ExitFailure, "cannot move the archive to '%s': %v", c.output, unwrapPath(err))
|
|
}
|
|
c.log.Info("created '%s' (%s)", c.output, progress.FormatBytes(info.Size()))
|
|
return nil
|
|
}
|
|
|
|
// inputSize returns the total size of the regular files that will be
|
|
// archived, skipping excluded names the way the backends do. Symlinks inside
|
|
// inputs are not followed, as the backends store them as links.
|
|
func (c *creator) inputSize() int64 {
|
|
var total int64
|
|
for _, in := range c.inputs {
|
|
_ = filepath.WalkDir(filepath.Join(in.parent, in.name), func(p string, d fs.DirEntry, err error) error {
|
|
if err != nil {
|
|
return nil // unreadable: the backend will report it
|
|
}
|
|
if c.excluded(d.Name()) {
|
|
if d.IsDir() {
|
|
return filepath.SkipDir
|
|
}
|
|
return nil
|
|
}
|
|
if d.Type().IsRegular() {
|
|
if info, err := d.Info(); err == nil {
|
|
total += info.Size()
|
|
}
|
|
}
|
|
return nil
|
|
})
|
|
}
|
|
return total
|
|
}
|
|
|
|
func (c *creator) excluded(name string) bool {
|
|
for _, pattern := range c.excludes {
|
|
if ok, _ := filepath.Match(pattern, name); ok {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// resolve returns path made absolute with symlinks resolved, like realpath.
|
|
func resolve(path string) (string, error) {
|
|
abs, err := filepath.Abs(path)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return filepath.EvalSymlinks(abs)
|
|
}
|
|
|
|
// unwrapPath drops the operation and path from *fs.PathError and
|
|
// *os.LinkError, whose text would repeat the file name messages already show.
|
|
func unwrapPath(err error) error {
|
|
var pe *fs.PathError
|
|
if errors.As(err, &pe) {
|
|
return pe.Err
|
|
}
|
|
var le *os.LinkError
|
|
if errors.As(err, &le) {
|
|
return le.Err
|
|
}
|
|
return err
|
|
}
|