-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
86 lines (73 loc) · 2.56 KB
/
main.go
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
80
81
82
83
84
85
86
// Copyright Josh Komoroske. All rights reserved.
// Use of this source code is governed by the MIT license,
// a copy of which can be found in the LICENSE.txt file.
package main
import (
"errors"
"flag"
"fmt"
"os"
"strings"
"time"
"github.com/joshdk/retry/retry"
)
// version is used to hold the version string. Will be replaced at go build
// time with -ldflags.
var version = "development"
// cmdFlags represents the assorted command line flags that can be passed.
type cmdFlags struct {
retry.Spec
quiet bool
version bool
}
func main() {
var flags cmdFlags
flag.IntVar(&flags.Attempts, "attempts", 3, "maximum number of attempts")
flag.BoolVar(&flags.Backoff, "backoff", false, "use exponential backoff when sleeping")
flag.IntVar(&flags.Consecutive, "consecutive", 0, "required number of back to back successes")
flag.DurationVar(&flags.InitialDelay, "delay", 0, "initial delay period before tasks are run")
flag.BoolVar(&flags.Invert, "invert", false, "wait for task to fail rather than succeed")
flag.DurationVar(&flags.Jitter, "jitter", 0, "time range randomly added to sleep")
flag.DurationVar(&flags.TotalTime, "max-time", time.Minute, "maximum total time")
flag.BoolVar(&flags.quiet, "quiet", false, "silence all output")
flag.DurationVar(&flags.Sleep, "sleep", 5*time.Second, "time to sleep between attempts")
flag.DurationVar(&flags.TaskTime, "task-time", 0, "maximum time for a single attempt")
flag.BoolVar(&flags.version, "version", false, fmt.Sprintf("print the version %q and exit", version))
flag.Usage = usage
flag.Parse()
if err := mainCmd(flags); err != nil {
if !flags.quiet {
fmt.Fprintf(os.Stderr, "retry: %v\n", err)
}
os.Exit(1)
}
}
func mainCmd(flags cmdFlags) error {
// If the version flag (-version) was given, print the version and exit.
if flags.version {
fmt.Println(version) //nolint:forbidigo
return nil
}
// If no arguments were given, there's nothing to do.
if flag.NArg() == 0 {
return errors.New("no command given")
}
var (
task retry.Task
command = flag.Args()[0]
args = flag.Args()[1:]
)
if strings.HasPrefix(command, "http://") || strings.HasPrefix(command, "https://") {
// The command looks like it references a url (starts with http:// or
// https://).
task = retry.HTTPTask{URL: command}
} else {
// Otherwise, assume the command references a (shell) command.
task = retry.ExecTask{Name: command, Args: args, Quiet: flags.quiet}
}
return retry.Retry(flags.Spec, task)
}
func usage() {
fmt.Fprintf(flag.CommandLine.Output(), "Usage: retry [flags] command|url\n")
flag.PrintDefaults()
}