github.com/arkadijs/deis@v1.5.1/contrib/bumpver/bump.go (about)

     1  package main
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"io/ioutil"
     7  	"os"
     8  	"regexp"
     9  
    10  	docopt "github.com/docopt/docopt-go"
    11  )
    12  
    13  // Command processes command-line arguments according to a usage string specification.
    14  func Command(argv []string) (returnCode int) {
    15  	usage := `
    16  Updates the current semantic version number to a new one in the specified
    17  source and doc files.
    18  
    19  Usage:
    20    bumpver [-f <current>] <version> <files>...
    21  
    22  Options:
    23    -f --from=<current>  An explicit version string to replace. Otherwise, use
    24                         the first semantic version found in the first file.
    25   `
    26  	argv = parseArgs(argv)
    27  	// parse command-line arguments
    28  	args, err := docopt.Parse(usage, argv, true, "bumpversion 0.1.0", true, false)
    29  	if err != nil {
    30  		return 1
    31  	}
    32  	if len(args) == 0 {
    33  		return 0
    34  	}
    35  	re := regexp.MustCompile(`(\d{1,3}\.\d{1,3}\.\d{1,3})`)
    36  	// validate that <version> is a proper semver string
    37  	version := (args["<version>"].(string))
    38  	if version != re.FindString(version) {
    39  		return onError(fmt.Errorf("Error: '%s' is not a valid semantic version string", version))
    40  	}
    41  	files := args["<files>"].([]string)
    42  	var from []byte
    43  	var data []byte
    44  	if args["--from"] != nil {
    45  		from = []byte(args["--from"].(string))
    46  	}
    47  	for _, name := range files {
    48  		src, err := ioutil.ReadFile(name)
    49  		if err != nil {
    50  			return onError(err)
    51  		}
    52  		if len(from) == 0 {
    53  			// find the first semver match in the file, if any
    54  			from = re.Find(src)
    55  			if from = re.Find(src); len(from) == 0 {
    56  				fmt.Printf("Skipped %s\n", name)
    57  				continue
    58  			}
    59  		}
    60  		// replace all occurrences in source and doc files
    61  		data = bytes.Replace(src, from, []byte(version), -1)
    62  		f, err := os.Create(name)
    63  		if err != nil {
    64  			return onError(err)
    65  		}
    66  		if _, err = f.Write(data); err != nil {
    67  			return onError(err)
    68  		}
    69  		fmt.Printf("Bumped %s\n", name)
    70  	}
    71  	return 0
    72  }
    73  
    74  func onError(err error) int {
    75  	fmt.Println(err.Error())
    76  	return 1
    77  }
    78  
    79  func parseArgs(argv []string) []string {
    80  	if argv == nil {
    81  		argv = os.Args[1:]
    82  	}
    83  
    84  	if len(argv) > 0 {
    85  		// parse "help <command>" as "command> --help"
    86  		if argv[0] == "help" {
    87  			argv = append(argv[1:], "--help")
    88  		}
    89  	}
    90  	return argv
    91  }