github.com/mvdan/u-root-coreutils@v0.0.0-20230122170626-c2eef2898555/cmds/core/backoff/main.go (about)

     1  // Copyright 2012-2021 the u-root Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Run a command, repeatedly, until it succeeds or we are out of time
     6  //
     7  // Synopsis:
     8  //	backoff [-v] [-t duration-string] command [args...]
     9  //
    10  // Description:
    11  //	backoff will run the command until it succeeds or a timeout has passed.
    12  //	The default timeout is 30s.
    13  //	If -v is set, it will show what it is running, each time it is tried.
    14  //	If no args are given, it will just return.
    15  //
    16  // Example:
    17  //	$ backoff echo hi
    18  //	hi
    19  //	$
    20  //	$ backoff -v -t 2s false
    21  //	  2022/03/31 14:29:37 Run ["false"]
    22  //	  2022/03/31 14:29:37 Set timeout to 2s
    23  //	  2022/03/31 14:29:37 "false" []:exit status 1
    24  //	  2022/03/31 14:29:38 "false" []:exit status 1
    25  //	  2022/03/31 14:29:39 "false" []:exit status 1
    26  //	  2022/03/31 14:29:39 Error: exit status 1
    27  
    28  //go:build !test
    29  // +build !test
    30  
    31  package main
    32  
    33  import (
    34  	"flag"
    35  	"log"
    36  	"os"
    37  )
    38  
    39  var (
    40  	timeout = flag.String("t", "", "Timeout for command")
    41  	verbose = flag.Bool("v", true, "Log each attempt to run the command")
    42  	v       = func(string, ...interface{}) {}
    43  )
    44  
    45  func main() {
    46  	flag.Parse()
    47  	if *verbose {
    48  		v = log.Printf
    49  	}
    50  	a := flag.Args()
    51  	if len(a) == 0 {
    52  		flag.Usage()
    53  		os.Exit(1)
    54  	}
    55  	v("Run %q", a)
    56  	if err := runit(*timeout, a[0], a[1:]...); err != nil {
    57  		log.Fatalf("Error: %v", err)
    58  	}
    59  }