-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.go
More file actions
79 lines (67 loc) · 1.88 KB
/
Copy pathcli.go
File metadata and controls
79 lines (67 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package main
import (
"errors"
"flag"
"fmt"
"io"
"os"
"github.com/dustin/go-humanize"
)
// parseCliArgs parse and validate the cli args
// if any of the cli args fail validation it will print an error and exit
func parseCliArgs(stdErr io.Writer, args []string) (Args, *int) {
programName := args[0]
cli := flag.NewFlagSet(programName, flag.ContinueOnError)
cli.SetOutput(stdErr)
cli.Usage = func() {
_, _ = fmt.Fprintf(cli.Output(), "usage: %s [-sv] archive-file source-dir\n", programName)
cli.PrintDefaults()
}
var maxSizeStr string
cli.StringVar(&maxSizeStr, "s", "0", "Maximum size of all the files to include in the archive. Use 0 if all the files are to be archived")
var verbose bool
cli.BoolVar(&verbose, "v", false, "Verbose mode to list files included in the archive")
if err := cli.Parse(args[1:]); err != nil {
exitCode := ptr(1)
if errors.Is(err, flag.ErrHelp) {
exitCode = ptr(0)
}
return Args{}, exitCode
}
args = cli.Args()
if len(args) < 1 {
_, _ = fmt.Fprintln(stdErr, "archive-file missing")
cli.Usage()
return Args{}, ptr(1)
}
if len(args) < 2 {
_, _ = fmt.Fprintln(stdErr, "source-dir missing")
cli.Usage()
return Args{}, ptr(1)
}
archiveFile, sourceDir := args[0], args[1]
if sdInfo, err := os.Stat(sourceDir); os.IsNotExist(err) {
_, _ = fmt.Fprintf(stdErr, "Source directory %s does not exists\n", sourceDir)
cli.Usage()
return Args{}, ptr(1)
} else if !sdInfo.IsDir() {
_, _ = fmt.Fprintf(stdErr, "Source directory %s is not a directory\n", sourceDir)
cli.Usage()
return Args{}, ptr(1)
}
maxSize, err := humanize.ParseBytes(maxSizeStr)
if err != nil {
_, _ = fmt.Fprintln(stdErr, "Invalid format for max size")
cli.Usage()
return Args{}, ptr(1)
}
return Args{
SourceDir: sourceDir,
ArchiveFile: archiveFile,
MaxSize: maxSize,
Verbose: verbose,
}, nil
}
func ptr[T any](v T) *T {
return &v
}