Merge pull request #580 from philips/bump-appc

Bump appc
This commit is contained in:
Brandon Philips
2015-03-09 16:53:09 -07:00
76 changed files with 8241 additions and 139 deletions
+27 -14
View File
@@ -10,6 +10,11 @@
"Comment": "null-12",
"Rev": "7dda39b2e7d5e265014674c5af696ba4186679e9"
},
{
"ImportPath": "github.com/GoogleCloudPlatform/kubernetes/pkg/api/resource",
"Comment": "v0.12.0-270-g53ec66c",
"Rev": "53ec66caf4e952a1384ec93b9f0cde37616e4caf"
},
{
"ImportPath": "github.com/appc/docker2aci/lib",
"Rev": "616c01fe7e3d6532768ce9cc4843e97ef6592eb8"
@@ -20,37 +25,37 @@
},
{
"ImportPath": "github.com/appc/spec/aci",
"Comment": "v0.3.0-2-g4c3cbeae4798",
"Rev": "4c3cbeae47980d073828dd263a8c982667855f06"
"Comment": "v0.3.0-88-g480f581",
"Rev": "480f5812e40cb93dbc5270301092368952546bb1"
},
{
"ImportPath": "github.com/appc/spec/actool",
"Comment": "v0.3.0-2-g4c3cbeae4798",
"Rev": "4c3cbeae47980d073828dd263a8c982667855f06"
"Comment": "v0.3.0-88-g480f581",
"Rev": "480f5812e40cb93dbc5270301092368952546bb1"
},
{
"ImportPath": "github.com/appc/spec/discovery",
"Comment": "v0.3.0-2-g4c3cbeae4798",
"Rev": "4c3cbeae47980d073828dd263a8c982667855f06"
"Comment": "v0.3.0-88-g480f581",
"Rev": "480f5812e40cb93dbc5270301092368952546bb1"
},
{
"ImportPath": "github.com/appc/spec/pkg/tarheader",
"Comment": "v0.3.0-2-g4c3cbeae4798",
"Rev": "4c3cbeae47980d073828dd263a8c982667855f06"
"Comment": "v0.3.0-88-g480f581",
"Rev": "480f5812e40cb93dbc5270301092368952546bb1"
},
{
"ImportPath": "github.com/appc/spec/schema",
"Comment": "v0.3.0-2-g4c3cbeae4798",
"Rev": "4c3cbeae47980d073828dd263a8c982667855f06"
},
{
"ImportPath": "github.com/coreos/go-iptables/iptables",
"Rev": "83dfad0f13fd7310fb3c1cb8563248d8d604b95b"
"Comment": "v0.3.0-88-g480f581",
"Rev": "480f5812e40cb93dbc5270301092368952546bb1"
},
{
"ImportPath": "github.com/camlistore/lock",
"Rev": "ae27720f340952636b826119b58130b9c1a847a0"
},
{
"ImportPath": "github.com/coreos/go-iptables/iptables",
"Rev": "83dfad0f13fd7310fb3c1cb8563248d8d604b95b"
},
{
"ImportPath": "github.com/coreos/go-semver/semver",
"Rev": "6fe83ccda8fb9b7549c9ab4ba47f47858bc950aa"
@@ -112,6 +117,10 @@
"ImportPath": "github.com/peterbourgon/diskv",
"Rev": "508f5671a72eeaef05cf8c24abe7fbc1c07faf69"
},
{
"ImportPath": "github.com/spf13/pflag",
"Rev": "370c3171201099fa6b466db45c8a032cbce33d8d"
},
{
"ImportPath": "github.com/vishvananda/netlink",
"Rev": "ae3e7dba57271b4e976c4f91637861ee477135e2"
@@ -127,6 +136,10 @@
{
"ImportPath": "golang.org/x/net/html",
"Rev": "1dfe7915deaf3f80b962c163b918868d8a6d8974"
},
{
"ImportPath": "speter.net/go/exp/math/dec/inf",
"Rev": "42ca6cd68aa922bc3f32f1e056e61b65945d9ad7"
}
]
}
@@ -0,0 +1,422 @@
/*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package resource
import (
"errors"
"fmt"
"math/big"
"regexp"
"strings"
flag "github.com/coreos/rocket/Godeps/_workspace/src/github.com/spf13/pflag"
"github.com/coreos/rocket/Godeps/_workspace/src/speter.net/go/exp/math/dec/inf"
)
// Quantity is a fixed-point representation of a number.
// It provides convenient marshaling/unmarshaling in JSON and YAML,
// in addition to String() and Int64() accessors.
//
// The serialization format is:
//
// <quantity> ::= <signedNumber><suffix>
// (Note that <suffix> may be empty, from the "" case in <decimalSI>.)
// <digit> ::= 0 | 1 | ... | 9
// <digits> ::= <digit> | <digit><digits>
// <number> ::= <digits> | <digits>.<digits> | <digits>. | .<digits>
// <sign> ::= "+" | "-"
// <signedNumber> ::= <number> | <sign><number>
// <suffix> ::= <binarySI> | <decimalExponent> | <decimalSI>
// <binarySI> ::= Ki | Mi | Gi | Ti | Pi | Ei
// (International System of units; See: http://physics.nist.gov/cuu/Units/binary.html)
// <decimalSI> ::= m | "" | k | M | G | T | P | E
// (Note that 1024 = 1Ki but 1000 = 1k; I didn't choose the capitalization.)
// <decimalExponent> ::= "e" <signedNumber> | "E" <signedNumber>
//
// No matter which of the three exponent forms is used, no quantity may represent
// a number greater than 2^63-1 in magnitude, nor may it have more than 3 decimal
// places. Numbers larger or more precise will be capped or rounded up.
// (E.g.: 0.1m will rounded up to 1m.)
// This may be extended in the future if we require larger or smaller quantities.
//
// When a Quantity is parsed from a string, it will remember the type of suffix
// it had, and will use the same type again when it is serialized.
//
// Before serializing, Quantity will be put in "canonical form".
// This means that Exponent/suffix will be adjusted up or down (with a
// corresponding increase or decrease in Mantissa) such that:
// a. No precision is lost
// b. No fractional digits will be emitted
// c. The exponent (or suffix) is as large as possible.
// The sign will be omitted unless the number is negative.
//
// Examples:
// 1.5 will be serialized as "1500m"
// 1.5Gi will be serialized as "1536Mi"
//
// NOTE: We reserve the right to amend this canonical format, perhaps to
// allow 1.5 to be canonical.
// TODO: Remove above disclaimer after all bikeshedding about format is over,
// or after March 2015.
//
// Note that the quantity will NEVER be internally represented by a
// floating point number. That is the whole point of this exercise.
//
// Non-canonical values will still parse as long as they are well formed,
// but will be re-emitted in their canonical form. (So always use canonical
// form, or don't diff.)
//
// This format is intended to make it difficult to use these numbers without
// writing some sort of special handling code in the hopes that that will
// cause implementors to also use a fixed point implementation.
type Quantity struct {
// Amount is public, so you can manipulate it if the accessor
// functions are not sufficient.
Amount *inf.Dec
// Change Format at will. See the comment for Canonicalize for
// more details.
Format
}
// Format lists the three possible formattings of a quantity.
type Format string
const (
DecimalExponent = Format("DecimalExponent") // e.g., 12e6
BinarySI = Format("BinarySI") // e.g., 12Mi (12 * 2^20)
DecimalSI = Format("DecimalSI") // e.g., 12M (12 * 10^6)
)
// MustParse turns the given string into a quantity or panics; for tests
// or others cases where you know the string is valid.
func MustParse(str string) Quantity {
q, err := ParseQuantity(str)
if err != nil {
panic(fmt.Errorf("cannot parse '%v': %v", str, err))
}
return *q
}
const (
// splitREString is used to separate a number from its suffix; as such,
// this is overly permissive, but that's OK-- it will be checked later.
splitREString = "^([+-]?[0-9.]+)([eEimkKMGTP]*[-+]?[0-9]*)$"
)
var (
// splitRE is used to get the various parts of a number.
splitRE = regexp.MustCompile(splitREString)
// Errors that could happen while parsing a string.
ErrFormatWrong = errors.New("quantities must match the regular expression '" + splitREString + "'")
ErrNumeric = errors.New("unable to parse numeric part of quantity")
ErrSuffix = errors.New("unable to parse quantity's suffix")
// Commonly needed big.Int values-- treat as read only!
bigTen = big.NewInt(10)
bigZero = big.NewInt(0)
bigOne = big.NewInt(1)
bigThousand = big.NewInt(1000)
big1024 = big.NewInt(1024)
// Commonly needed inf.Dec values-- treat as read only!
decZero = inf.NewDec(0, 0)
decOne = inf.NewDec(1, 0)
decMinusOne = inf.NewDec(-1, 0)
decThousand = inf.NewDec(1000, 0)
dec1024 = inf.NewDec(1024, 0)
decMinus1024 = inf.NewDec(-1024, 0)
// Largest (in magnitude) number allowed.
maxAllowed = inf.NewDec((1<<63)-1, 0) // == max int64
// The maximum value we can represent milli-units for.
// Compare with the return value of Quantity.Value() to
// see if it's safe to use Quantity.MilliValue().
MaxMilliValue = int64(((1 << 63) - 1) / 1000)
)
// ParseQuantity turns str into a Quantity, or returns an error.
func ParseQuantity(str string) (*Quantity, error) {
parts := splitRE.FindStringSubmatch(strings.TrimSpace(str))
// regexp returns are entire match, followed by an entry for each () section.
if len(parts) != 3 {
return nil, ErrFormatWrong
}
amount := new(inf.Dec)
if _, ok := amount.SetString(parts[1]); !ok {
return nil, ErrNumeric
}
base, exponent, format, ok := quantitySuffixer.interpret(suffix(parts[2]))
if !ok {
return nil, ErrSuffix
}
// So that no one but us has to think about suffixes, remove it.
if base == 10 {
amount.SetScale(amount.Scale() + inf.Scale(-exponent))
} else if base == 2 {
// numericSuffix = 2 ** exponent
numericSuffix := big.NewInt(1).Lsh(bigOne, uint(exponent))
ub := amount.UnscaledBig()
amount.SetUnscaledBig(ub.Mul(ub, numericSuffix))
}
// Cap at min/max bounds.
sign := amount.Sign()
if sign == -1 {
amount.Neg(amount)
}
// This rounds non-zero values up to the minimum representable
// value, under the theory that if you want some resources, you
// should get some resources, even if you asked for way too small
// of an amount.
// Arguably, this should be inf.RoundHalfUp (normal rounding), but
// that would have the side effect of rounding values < .5m to zero.
amount.Round(amount, 3, inf.RoundUp)
// The max is just a simple cap.
if amount.Cmp(maxAllowed) > 0 {
amount.Set(maxAllowed)
}
if format == BinarySI && amount.Cmp(decOne) < 0 && amount.Cmp(decZero) > 0 {
// This avoids rounding and hopefully confusion, too.
format = DecimalSI
}
if sign == -1 {
amount.Neg(amount)
}
return &Quantity{amount, format}, nil
}
// removeFactors divides in a loop; the return values have the property that
// d == result * factor ^ times
// d may be modified in place.
// If d == 0, then the return values will be (0, 0)
func removeFactors(d, factor *big.Int) (result *big.Int, times int) {
q := big.NewInt(0)
m := big.NewInt(0)
for d.Cmp(bigZero) != 0 {
q.DivMod(d, factor, m)
if m.Cmp(bigZero) != 0 {
break
}
times++
d, q = q, d
}
return d, times
}
// Canonicalize returns the canonical form of q and its suffix (see comment on Quantity).
//
// Note about BinarySI:
// * If q.Format is set to BinarySI and q.Amount represents a non-zero value between
// -1 and +1, it will be emitted as if q.Format were DecimalSI.
// * Otherwise, if q.Format is set to BinarySI, frational parts of q.Amount will be
// rounded up. (1.1i becomes 2i.)
func (q *Quantity) Canonicalize() (string, suffix) {
if q.Amount == nil {
return "0", ""
}
format := q.Format
switch format {
case DecimalExponent, DecimalSI:
case BinarySI:
if q.Amount.Cmp(decMinus1024) > 0 && q.Amount.Cmp(dec1024) < 0 {
// This avoids rounding and hopefully confusion, too.
format = DecimalSI
} else {
tmp := &inf.Dec{}
tmp.Round(q.Amount, 0, inf.RoundUp)
if tmp.Cmp(q.Amount) != 0 {
// Don't lose precision-- show as DecimalSI
format = DecimalSI
}
}
default:
format = DecimalExponent
}
// TODO: If BinarySI formatting is requested but would cause rounding, upgrade to
// one of the other formats.
switch format {
case DecimalExponent, DecimalSI:
mantissa := q.Amount.UnscaledBig()
exponent := int(-q.Amount.Scale())
amount := big.NewInt(0).Set(mantissa)
// move all factors of 10 into the exponent for easy reasoning
amount, times := removeFactors(amount, bigTen)
exponent += times
// make sure exponent is a multiple of 3
for exponent%3 != 0 {
amount.Mul(amount, bigTen)
exponent--
}
suffix, _ := quantitySuffixer.construct(10, exponent, format)
number := amount.String()
return number, suffix
case BinarySI:
tmp := &inf.Dec{}
tmp.Round(q.Amount, 0, inf.RoundUp)
amount, exponent := removeFactors(tmp.UnscaledBig(), big1024)
suffix, _ := quantitySuffixer.construct(2, exponent*10, format)
number := amount.String()
return number, suffix
}
return "0", ""
}
// String formats the Quantity as a string.
func (q *Quantity) String() string {
number, suffix := q.Canonicalize()
return number + string(suffix)
}
// MarshalJSON implements the json.Marshaller interface.
func (q Quantity) MarshalJSON() ([]byte, error) {
return []byte(`"` + q.String() + `"`), nil
}
// UnmarshalJSON implements the json.Unmarshaller interface.
func (q *Quantity) UnmarshalJSON(value []byte) error {
str := string(value)
parsed, err := ParseQuantity(strings.Trim(str, `"`))
if err != nil {
return err
}
// This copy is safe because parsed will not be referred to again.
*q = *parsed
return nil
}
// NewQuantity returns a new Quantity representing the given
// value in the given format.
func NewQuantity(value int64, format Format) *Quantity {
return &Quantity{
Amount: inf.NewDec(value, 0),
Format: format,
}
}
// NewMilliQuantity returns a new Quantity representing the given
// value * 1/1000 in the given format. Note that BinarySI formatting
// will round fractional values, and will be changed to DecimalSI for
// values x where (-1 < x < 1) && (x != 0).
func NewMilliQuantity(value int64, format Format) *Quantity {
return &Quantity{
Amount: inf.NewDec(value, 3),
Format: format,
}
}
// Value returns the value of q; any fractional part will be lost.
func (q *Quantity) Value() int64 {
if q.Amount == nil {
return 0
}
tmp := &inf.Dec{}
return tmp.Round(q.Amount, 0, inf.RoundUp).UnscaledBig().Int64()
}
// MilliValue returns the value of q * 1000; this could overflow an int64;
// if that's a concern, call Value() first to verify the number is small enough.
func (q *Quantity) MilliValue() int64 {
if q.Amount == nil {
return 0
}
tmp := &inf.Dec{}
return tmp.Round(tmp.Mul(q.Amount, decThousand), 0, inf.RoundUp).UnscaledBig().Int64()
}
// Set sets q's value to be value.
func (q *Quantity) Set(value int64) {
if q.Amount == nil {
q.Amount = &inf.Dec{}
}
q.Amount.SetUnscaled(value)
q.Amount.SetScale(0)
}
// SetMilli sets q's value to be value * 1/1000.
func (q *Quantity) SetMilli(value int64) {
if q.Amount == nil {
q.Amount = &inf.Dec{}
}
q.Amount.SetUnscaled(value)
q.Amount.SetScale(3)
}
// Copy is a convenience function that makes a deep copy for you. Non-deep
// copies of quantities share pointers and you will regret that.
func (q *Quantity) Copy() *Quantity {
if q.Amount == nil {
return NewQuantity(0, q.Format)
}
tmp := &inf.Dec{}
return &Quantity{
Amount: tmp.Set(q.Amount),
Format: q.Format,
}
}
// qFlag is a helper type for the Flag function
type qFlag struct {
dest *Quantity
}
// Sets the value of the internal Quantity. (used by flag & pflag)
func (qf qFlag) Set(val string) error {
q, err := ParseQuantity(val)
if err != nil {
return err
}
// This copy is OK because q will not be referenced again.
*qf.dest = *q
return nil
}
// Converts the value of the internal Quantity to a string. (used by flag & pflag)
func (qf qFlag) String() string {
return qf.dest.String()
}
// States the type of flag this is (Quantity). (used by pflag)
func (qf qFlag) Type() string {
return "quantity"
}
// QuantityFlag is a helper that makes a quantity flag (using standard flag package).
// Will panic if defaultValue is not a valid quantity.
func QuantityFlag(flagName, defaultValue, description string) *Quantity {
q := MustParse(defaultValue)
flag.Var(NewQuantityFlagValue(&q), flagName, description)
return &q
}
// NewQuantityFlagValue returns an object that can be used to back a flag,
// pointing at the given Quantity variable.
func NewQuantityFlagValue(q *Quantity) flag.Value {
return qFlag{q}
}
@@ -0,0 +1,59 @@
/*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package resource_test
import (
"fmt"
"github.com/coreos/rocket/Godeps/_workspace/src/github.com/GoogleCloudPlatform/kubernetes/pkg/api/resource"
)
func ExampleFormat() {
memorySize := resource.NewQuantity(5*1024*1024*1024, resource.BinarySI)
fmt.Printf("memorySize = %v\n", memorySize)
diskSize := resource.NewQuantity(5*1000*1000*1000, resource.DecimalSI)
fmt.Printf("diskSize = %v\n", diskSize)
cores := resource.NewMilliQuantity(5300, resource.DecimalSI)
fmt.Printf("cores = %v\n", cores)
// Output:
// memorySize = 5Gi
// diskSize = 5G
// cores = 5300m
}
func ExampleMustParse() {
memorySize := resource.MustParse("5Gi")
fmt.Printf("memorySize = %v (%v)\n", memorySize.Value(), memorySize.Format)
diskSize := resource.MustParse("5G")
fmt.Printf("diskSize = %v (%v)\n", diskSize.Value(), diskSize.Format)
cores := resource.MustParse("5300m")
fmt.Printf("milliCores = %v (%v)\n", cores.MilliValue(), cores.Format)
cores2 := resource.MustParse("5.4")
fmt.Printf("milliCores = %v (%v)\n", cores2.MilliValue(), cores2.Format)
// Output:
// memorySize = 5368709120 (BinarySI)
// diskSize = 5000000000 (DecimalSI)
// milliCores = 5300 (DecimalSI)
// milliCores = 5400 (DecimalSI)
}
@@ -0,0 +1,497 @@
/*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package resource
import (
//"reflect"
"encoding/json"
"testing"
"github.com/coreos/rocket/Godeps/_workspace/src/github.com/spf13/pflag"
"github.com/coreos/rocket/Godeps/_workspace/src/speter.net/go/exp/math/dec/inf"
fuzz "github.com/google/gofuzz"
)
var (
testQuantityFlag = QuantityFlag("quantityFlag", "1M", "dummy flag for testing the quantity flag mechanism")
)
func dec(i int64, exponent int) *inf.Dec {
// See the below test-- scale is the negative of an exponent.
return inf.NewDec(i, inf.Scale(-exponent))
}
func TestDec(t *testing.T) {
table := []struct {
got *inf.Dec
expect string
}{
{dec(1, 0), "1"},
{dec(1, 1), "10"},
{dec(5, 2), "500"},
{dec(8, 3), "8000"},
{dec(2, 0), "2"},
{dec(1, -1), "0.1"},
{dec(3, -2), "0.03"},
{dec(4, -3), "0.004"},
}
for _, item := range table {
if e, a := item.expect, item.got.String(); e != a {
t.Errorf("expected %v, got %v", e, a)
}
}
}
func TestQuantityParse(t *testing.T) {
table := []struct {
input string
expect Quantity
}{
{"0", Quantity{dec(0, 0), DecimalSI}},
{"0m", Quantity{dec(0, 0), DecimalSI}},
{"0Ki", Quantity{dec(0, 0), BinarySI}},
{"0k", Quantity{dec(0, 0), DecimalSI}},
{"0Mi", Quantity{dec(0, 0), BinarySI}},
{"0M", Quantity{dec(0, 0), DecimalSI}},
{"0Gi", Quantity{dec(0, 0), BinarySI}},
{"0G", Quantity{dec(0, 0), DecimalSI}},
{"0Ti", Quantity{dec(0, 0), BinarySI}},
{"0T", Quantity{dec(0, 0), DecimalSI}},
// Binary suffixes
{"1Ki", Quantity{dec(1024, 0), BinarySI}},
{"8Ki", Quantity{dec(8*1024, 0), BinarySI}},
{"7Mi", Quantity{dec(7*1024*1024, 0), BinarySI}},
{"6Gi", Quantity{dec(6*1024*1024*1024, 0), BinarySI}},
{"5Ti", Quantity{dec(5*1024*1024*1024*1024, 0), BinarySI}},
{"4Pi", Quantity{dec(4*1024*1024*1024*1024*1024, 0), BinarySI}},
{"3Ei", Quantity{dec(3*1024*1024*1024*1024*1024*1024, 0), BinarySI}},
{"10Ti", Quantity{dec(10*1024*1024*1024*1024, 0), BinarySI}},
{"100Ti", Quantity{dec(100*1024*1024*1024*1024, 0), BinarySI}},
// Decimal suffixes
{"3m", Quantity{dec(3, -3), DecimalSI}},
{"9", Quantity{dec(9, 0), DecimalSI}},
{"8k", Quantity{dec(8, 3), DecimalSI}},
{"7M", Quantity{dec(7, 6), DecimalSI}},
{"6G", Quantity{dec(6, 9), DecimalSI}},
{"5T", Quantity{dec(5, 12), DecimalSI}},
{"40T", Quantity{dec(4, 13), DecimalSI}},
{"300T", Quantity{dec(3, 14), DecimalSI}},
{"2P", Quantity{dec(2, 15), DecimalSI}},
{"1E", Quantity{dec(1, 18), DecimalSI}},
// Decimal exponents
{"1E-3", Quantity{dec(1, -3), DecimalExponent}},
{"1e3", Quantity{dec(1, 3), DecimalExponent}},
{"1E6", Quantity{dec(1, 6), DecimalExponent}},
{"1e9", Quantity{dec(1, 9), DecimalExponent}},
{"1E12", Quantity{dec(1, 12), DecimalExponent}},
{"1e15", Quantity{dec(1, 15), DecimalExponent}},
{"1E18", Quantity{dec(1, 18), DecimalExponent}},
// Nonstandard but still parsable
{"1e14", Quantity{dec(1, 14), DecimalExponent}},
{"1e13", Quantity{dec(1, 13), DecimalExponent}},
{"1e3", Quantity{dec(1, 3), DecimalExponent}},
{"100.035k", Quantity{dec(100035, 0), DecimalSI}},
// Things that look like floating point
{"0.001", Quantity{dec(1, -3), DecimalSI}},
{"0.0005k", Quantity{dec(5, -1), DecimalSI}},
{"0.005", Quantity{dec(5, -3), DecimalSI}},
{"0.05", Quantity{dec(5, -2), DecimalSI}},
{"0.5", Quantity{dec(5, -1), DecimalSI}},
{"0.00050k", Quantity{dec(5, -1), DecimalSI}},
{"0.00500", Quantity{dec(5, -3), DecimalSI}},
{"0.05000", Quantity{dec(5, -2), DecimalSI}},
{"0.50000", Quantity{dec(5, -1), DecimalSI}},
{"0.5e0", Quantity{dec(5, -1), DecimalExponent}},
{"0.5e-1", Quantity{dec(5, -2), DecimalExponent}},
{"0.5e-2", Quantity{dec(5, -3), DecimalExponent}},
{"0.5e0", Quantity{dec(5, -1), DecimalExponent}},
{"10.035M", Quantity{dec(10035, 3), DecimalSI}},
{"1.2e3", Quantity{dec(12, 2), DecimalExponent}},
{"1.3E+6", Quantity{dec(13, 5), DecimalExponent}},
{"1.40e9", Quantity{dec(14, 8), DecimalExponent}},
{"1.53E12", Quantity{dec(153, 10), DecimalExponent}},
{"1.6e15", Quantity{dec(16, 14), DecimalExponent}},
{"1.7E18", Quantity{dec(17, 17), DecimalExponent}},
{"9.01", Quantity{dec(901, -2), DecimalSI}},
{"8.1k", Quantity{dec(81, 2), DecimalSI}},
{"7.123456M", Quantity{dec(7123456, 0), DecimalSI}},
{"6.987654321G", Quantity{dec(6987654321, 0), DecimalSI}},
{"5.444T", Quantity{dec(5444, 9), DecimalSI}},
{"40.1T", Quantity{dec(401, 11), DecimalSI}},
{"300.2T", Quantity{dec(3002, 11), DecimalSI}},
{"2.5P", Quantity{dec(25, 14), DecimalSI}},
{"1.01E", Quantity{dec(101, 16), DecimalSI}},
// Things that saturate/round
{"3.001m", Quantity{dec(4, -3), DecimalSI}},
{"1.1E-3", Quantity{dec(2, -3), DecimalExponent}},
{"0.0001", Quantity{dec(1, -3), DecimalSI}},
{"0.0005", Quantity{dec(1, -3), DecimalSI}},
{"0.00050", Quantity{dec(1, -3), DecimalSI}},
{"0.5e-3", Quantity{dec(1, -3), DecimalExponent}},
{"0.9m", Quantity{dec(1, -3), DecimalSI}},
{"0.12345", Quantity{dec(124, -3), DecimalSI}},
{"0.12354", Quantity{dec(124, -3), DecimalSI}},
{"9Ei", Quantity{maxAllowed, BinarySI}},
{"9223372036854775807Ki", Quantity{maxAllowed, BinarySI}},
{"12E", Quantity{maxAllowed, DecimalSI}},
// We'll accept fractional binary stuff, too.
{"100.035Ki", Quantity{dec(10243584, -2), BinarySI}},
{"0.5Mi", Quantity{dec(.5*1024*1024, 0), BinarySI}},
{"0.05Gi", Quantity{dec(536870912, -1), BinarySI}},
{"0.025Ti", Quantity{dec(274877906944, -1), BinarySI}},
// Things written by trolls
{"0.000001Ki", Quantity{dec(2, -3), DecimalSI}}, // rounds up, changes format
{".001", Quantity{dec(1, -3), DecimalSI}},
{".0001k", Quantity{dec(100, -3), DecimalSI}},
{"1.", Quantity{dec(1, 0), DecimalSI}},
{"1.G", Quantity{dec(1, 9), DecimalSI}},
}
for _, item := range table {
got, err := ParseQuantity(item.input)
if err != nil {
t.Errorf("%v: unexpected error: %v", item.input, err)
continue
}
if e, a := item.expect.Amount, got.Amount; e.Cmp(a) != 0 {
t.Errorf("%v: expected %v, got %v", item.input, e, a)
}
if e, a := item.expect.Format, got.Format; e != a {
t.Errorf("%v: expected %#v, got %#v", item.input, e, a)
}
}
// Try the negative version of everything
desired := &inf.Dec{}
for _, item := range table {
got, err := ParseQuantity("-" + item.input)
if err != nil {
t.Errorf("-%v: unexpected error: %v", item.input, err)
continue
}
desired.Neg(item.expect.Amount)
if e, a := desired, got.Amount; e.Cmp(a) != 0 {
t.Errorf("%v: expected %v, got %v", item.input, e, a)
}
if e, a := item.expect.Format, got.Format; e != a {
t.Errorf("%v: expected %#v, got %#v", item.input, e, a)
}
}
// Try everything with an explicit +
for _, item := range table {
got, err := ParseQuantity("+" + item.input)
if err != nil {
t.Errorf("-%v: unexpected error: %v", item.input, err)
continue
}
if e, a := item.expect.Amount, got.Amount; e.Cmp(a) != 0 {
t.Errorf("%v: expected %v, got %v", item.input, e, a)
}
if e, a := item.expect.Format, got.Format; e != a {
t.Errorf("%v: expected %#v, got %#v", item.input, e, a)
}
}
invalid := []string{
"1.1.M",
"1+1.0M",
"0.1mi",
"0.1am",
"aoeu",
".5i",
"1i",
"-3.01i",
}
for _, item := range invalid {
_, err := ParseQuantity(item)
if err == nil {
t.Errorf("%v parsed unexpectedly", item)
}
}
}
func TestQuantityString(t *testing.T) {
table := []struct {
in Quantity
expect string
}{
{Quantity{dec(1024*1024*1024, 0), BinarySI}, "1Gi"},
{Quantity{dec(300*1024*1024, 0), BinarySI}, "300Mi"},
{Quantity{dec(6*1024, 0), BinarySI}, "6Ki"},
{Quantity{dec(1001*1024*1024*1024, 0), BinarySI}, "1001Gi"},
{Quantity{dec(1024*1024*1024*1024, 0), BinarySI}, "1Ti"},
{Quantity{dec(5, 0), BinarySI}, "5"},
{Quantity{dec(500, -3), BinarySI}, "500m"},
{Quantity{dec(1, 9), DecimalSI}, "1G"},
{Quantity{dec(1000, 6), DecimalSI}, "1G"},
{Quantity{dec(1000000, 3), DecimalSI}, "1G"},
{Quantity{dec(1000000000, 0), DecimalSI}, "1G"},
{Quantity{dec(1, -3), DecimalSI}, "1m"},
{Quantity{dec(80, -3), DecimalSI}, "80m"},
{Quantity{dec(1080, -3), DecimalSI}, "1080m"},
{Quantity{dec(108, -2), DecimalSI}, "1080m"},
{Quantity{dec(10800, -4), DecimalSI}, "1080m"},
{Quantity{dec(300, 6), DecimalSI}, "300M"},
{Quantity{dec(1, 12), DecimalSI}, "1T"},
{Quantity{dec(1234567, 6), DecimalSI}, "1234567M"},
{Quantity{dec(1234567, -3), BinarySI}, "1234567m"},
{Quantity{dec(3, 3), DecimalSI}, "3k"},
{Quantity{dec(1025, 0), BinarySI}, "1025"},
{Quantity{dec(0, 0), DecimalSI}, "0"},
{Quantity{dec(0, 0), BinarySI}, "0"},
{Quantity{dec(1, 9), DecimalExponent}, "1e9"},
{Quantity{dec(1, -3), DecimalExponent}, "1e-3"},
{Quantity{dec(80, -3), DecimalExponent}, "80e-3"},
{Quantity{dec(300, 6), DecimalExponent}, "300e6"},
{Quantity{dec(1, 12), DecimalExponent}, "1e12"},
{Quantity{dec(1, 3), DecimalExponent}, "1e3"},
{Quantity{dec(3, 3), DecimalExponent}, "3e3"},
{Quantity{dec(3, 3), DecimalSI}, "3k"},
{Quantity{dec(0, 0), DecimalExponent}, "0"},
}
for _, item := range table {
got := item.in.String()
if e, a := item.expect, got; e != a {
t.Errorf("%#v: expected %v, got %v", item.in, e, a)
}
}
desired := &inf.Dec{} // Avoid modifying the values in the table.
for _, item := range table {
if item.in.Amount.Cmp(decZero) == 0 {
// Don't expect it to print "-0" ever
continue
}
q := item.in
q.Amount = desired.Neg(q.Amount)
if e, a := "-"+item.expect, q.String(); e != a {
t.Errorf("%#v: expected %v, got %v", item.in, e, a)
}
}
}
func TestQuantityParseEmit(t *testing.T) {
table := []struct {
in string
expect string
}{
{"1Ki", "1Ki"},
{"1Mi", "1Mi"},
{"1Gi", "1Gi"},
{"1024Mi", "1Gi"},
{"1000M", "1G"},
{".000001Ki", "2m"},
}
for _, item := range table {
q, err := ParseQuantity(item.in)
if err != nil {
t.Errorf("Couldn't parse %v", item.in)
continue
}
if e, a := item.expect, q.String(); e != a {
t.Errorf("%#v: expected %v, got %v", item.in, e, a)
}
}
for _, item := range table {
q, err := ParseQuantity("-" + item.in)
if err != nil {
t.Errorf("Couldn't parse %v", item.in)
continue
}
if q.Amount.Cmp(decZero) == 0 {
continue
}
if e, a := "-"+item.expect, q.String(); e != a {
t.Errorf("%#v: expected %v, got %v", item.in, e, a)
}
}
}
var fuzzer = fuzz.New().Funcs(
func(q *Quantity, c fuzz.Continue) {
q.Amount = &inf.Dec{}
if c.RandBool() {
q.Format = BinarySI
if c.RandBool() {
q.Amount.SetScale(0)
q.Amount.SetUnscaled(c.Int63())
return
}
// Be sure to test cases like 1Mi
q.Amount.SetScale(0)
q.Amount.SetUnscaled(c.Int63n(1024) << uint(10*c.Intn(5)))
return
}
if c.RandBool() {
q.Format = DecimalSI
} else {
q.Format = DecimalExponent
}
if c.RandBool() {
q.Amount.SetScale(inf.Scale(c.Intn(4)))
q.Amount.SetUnscaled(c.Int63())
return
}
// Be sure to test cases like 1M
q.Amount.SetScale(inf.Scale(3 - c.Intn(15)))
q.Amount.SetUnscaled(c.Int63n(1000))
},
)
func TestJSON(t *testing.T) {
for i := 0; i < 500; i++ {
q := &Quantity{}
fuzzer.Fuzz(q)
b, err := json.Marshal(q)
if err != nil {
t.Errorf("error encoding %v", q)
}
q2 := &Quantity{}
err = json.Unmarshal(b, q2)
if err != nil {
t.Errorf("%v: error decoding %v", q, string(b))
}
if q2.Amount.Cmp(q.Amount) != 0 {
t.Errorf("Expected equal: %v, %v (json was '%v')", q, q2, string(b))
}
}
}
func TestMilliNewSet(t *testing.T) {
table := []struct {
value int64
format Format
expect string
exact bool
}{
{1, DecimalSI, "1m", true},
{1000, DecimalSI, "1", true},
{1234000, DecimalSI, "1234", true},
{1024, BinarySI, "1024m", false}, // Format changes
{1000000, "invalidFormatDefaultsToExponent", "1e3", true},
{1024 * 1024, BinarySI, "1048576m", false}, // Format changes
}
for _, item := range table {
q := NewMilliQuantity(item.value, item.format)
if e, a := item.expect, q.String(); e != a {
t.Errorf("Expected %v, got %v; %#v", e, a, q)
}
if !item.exact {
continue
}
q2, err := ParseQuantity(q.String())
if err != nil {
t.Errorf("Round trip failed on %v", q)
}
if e, a := item.value, q2.MilliValue(); e != a {
t.Errorf("Expected %v, got %v", e, a)
}
}
for _, item := range table {
q := NewQuantity(0, item.format)
q.SetMilli(item.value)
if e, a := item.expect, q.String(); e != a {
t.Errorf("Set: Expected %v, got %v; %#v", e, a, q)
}
}
}
func TestNewSet(t *testing.T) {
table := []struct {
value int64
format Format
expect string
}{
{1, DecimalSI, "1"},
{1000, DecimalSI, "1k"},
{1234000, DecimalSI, "1234k"},
{1024, BinarySI, "1Ki"},
{1000000, "invalidFormatDefaultsToExponent", "1e6"},
{1024 * 1024, BinarySI, "1Mi"},
}
for _, item := range table {
q := NewQuantity(item.value, item.format)
if e, a := item.expect, q.String(); e != a {
t.Errorf("Expected %v, got %v; %#v", e, a, q)
}
q2, err := ParseQuantity(q.String())
if err != nil {
t.Errorf("Round trip failed on %v", q)
}
if e, a := item.value, q2.Value(); e != a {
t.Errorf("Expected %v, got %v", e, a)
}
}
for _, item := range table {
q := NewQuantity(0, item.format)
q.Set(item.value)
if e, a := item.expect, q.String(); e != a {
t.Errorf("Set: Expected %v, got %v; %#v", e, a, q)
}
}
}
func TestUninitializedNoCrash(t *testing.T) {
var q Quantity
q.Value()
q.MilliValue()
q.Copy()
q.String()
q.MarshalJSON()
}
func TestCopy(t *testing.T) {
q := NewQuantity(5, DecimalSI)
c := q.Copy()
c.Set(6)
if q.Value() == 6 {
t.Errorf("Copy didn't")
}
}
func TestQFlagSet(t *testing.T) {
qf := qFlag{&Quantity{}}
qf.Set("1Ki")
if e, a := "1Ki", qf.String(); e != a {
t.Errorf("Unexpected result %v != %v", e, a)
}
}
func TestQFlagIsPFlag(t *testing.T) {
var pfv pflag.Value = qFlag{}
if e, a := "quantity", pfv.Type(); e != a {
t.Errorf("Unexpected result %v != %v", e, a)
}
}
@@ -0,0 +1,134 @@
/*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package resource
import (
"strconv"
)
type suffix string
// suffixer can interpret and construct suffixes.
type suffixer interface {
interpret(suffix) (base, exponent int, fmt Format, ok bool)
construct(base, exponent int, fmt Format) (s suffix, ok bool)
}
// quantitySuffixer handles suffixes for all three formats that quantity
// can handle.
var quantitySuffixer = newSuffixer()
type bePair struct {
base, exponent int
}
type listSuffixer struct {
suffixToBE map[suffix]bePair
beToSuffix map[bePair]suffix
}
func (ls *listSuffixer) addSuffix(s suffix, pair bePair) {
if ls.suffixToBE == nil {
ls.suffixToBE = map[suffix]bePair{}
}
if ls.beToSuffix == nil {
ls.beToSuffix = map[bePair]suffix{}
}
ls.suffixToBE[s] = pair
ls.beToSuffix[pair] = s
}
func (ls *listSuffixer) lookup(s suffix) (base, exponent int, ok bool) {
pair, ok := ls.suffixToBE[s]
if !ok {
return 0, 0, false
}
return pair.base, pair.exponent, true
}
func (ls *listSuffixer) construct(base, exponent int) (s suffix, ok bool) {
s, ok = ls.beToSuffix[bePair{base, exponent}]
return
}
type suffixHandler struct {
decSuffixes listSuffixer
binSuffixes listSuffixer
}
func newSuffixer() suffixer {
sh := &suffixHandler{}
sh.binSuffixes.addSuffix("Ki", bePair{2, 10})
sh.binSuffixes.addSuffix("Mi", bePair{2, 20})
sh.binSuffixes.addSuffix("Gi", bePair{2, 30})
sh.binSuffixes.addSuffix("Ti", bePair{2, 40})
sh.binSuffixes.addSuffix("Pi", bePair{2, 50})
sh.binSuffixes.addSuffix("Ei", bePair{2, 60})
// Don't emit an error when trying to produce
// a suffix for 2^0.
sh.decSuffixes.addSuffix("", bePair{2, 0})
sh.decSuffixes.addSuffix("m", bePair{10, -3})
sh.decSuffixes.addSuffix("", bePair{10, 0})
sh.decSuffixes.addSuffix("k", bePair{10, 3})
sh.decSuffixes.addSuffix("M", bePair{10, 6})
sh.decSuffixes.addSuffix("G", bePair{10, 9})
sh.decSuffixes.addSuffix("T", bePair{10, 12})
sh.decSuffixes.addSuffix("P", bePair{10, 15})
sh.decSuffixes.addSuffix("E", bePair{10, 18})
return sh
}
func (sh *suffixHandler) construct(base, exponent int, fmt Format) (s suffix, ok bool) {
switch fmt {
case DecimalSI:
return sh.decSuffixes.construct(base, exponent)
case BinarySI:
return sh.binSuffixes.construct(base, exponent)
case DecimalExponent:
if base != 10 {
return "", false
}
if exponent == 0 {
return "", true
}
return suffix("e" + strconv.FormatInt(int64(exponent), 10)), true
}
return "", false
}
func (sh *suffixHandler) interpret(suffix suffix) (base, exponent int, fmt Format, ok bool) {
// Try lookup tables first
if b, e, ok := sh.decSuffixes.lookup(suffix); ok {
return b, e, DecimalSI, true
}
if b, e, ok := sh.binSuffixes.lookup(suffix); ok {
return b, e, BinarySI, true
}
if len(suffix) > 1 && (suffix[0] == 'E' || suffix[0] == 'e') {
parsed, err := strconv.ParseInt(string(suffix[1:]), 10, 64)
if err != nil {
return 0, 0, DecimalExponent, false
}
return 10, int(parsed), DecimalExponent, true
}
return 0, 0, DecimalExponent, false
}
+17 -18
View File
@@ -7,11 +7,13 @@ import (
"compress/gzip"
"encoding/hex"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os/exec"
"path/filepath"
"github.com/coreos/rocket/Godeps/_workspace/src/github.com/appc/spec/schema"
)
@@ -111,7 +113,6 @@ func XzReader(r io.Reader) io.ReadCloser {
// ManifestFromImage extracts a new schema.ImageManifest from the given ACI image.
func ManifestFromImage(rs io.ReadSeeker) (*schema.ImageManifest, error) {
var im schema.ImageManifest
manifestFound := false
tr, err := NewCompressedTarReader(rs)
if err != nil {
@@ -120,26 +121,24 @@ func ManifestFromImage(rs io.ReadSeeker) (*schema.ImageManifest, error) {
for {
hdr, err := tr.Next()
if err != nil {
return nil, err
}
if hdr.Name == "manifest" {
data, err := ioutil.ReadAll(tr)
if err != nil {
return nil, err
switch err {
case io.EOF:
return nil, errors.New("missing manifest")
case nil:
if filepath.Clean(hdr.Name) == ManifestFile {
data, err := ioutil.ReadAll(tr)
if err != nil {
return nil, err
}
if err := im.UnmarshalJSON(data); err != nil {
return nil, err
}
return &im, nil
}
if err := im.UnmarshalJSON(data); err != nil {
return nil, err
}
manifestFound = true
break
default:
return nil, fmt.Errorf("error extracting tarball: %v", err)
}
}
if !manifestFound {
return nil, errors.New("error: missing manifest")
}
return &im, nil
}
// NewCompressedTarReader creates a new tar.Reader reading from the given ACI image.
+38 -32
View File
@@ -8,7 +8,7 @@ import (
"testing"
)
func newTestACI() (*os.File, error) {
func newTestACI(usedotslash bool) (*os.File, error) {
tf, err := ioutil.TempFile("", "")
if err != nil {
return nil, err
@@ -19,8 +19,12 @@ func newTestACI() (*os.File, error) {
gw := gzip.NewWriter(tf)
tw := tar.NewWriter(gw)
manifestPath := "manifest"
if usedotslash {
manifestPath = "./" + manifestPath
}
hdr := &tar.Header{
Name: "manifest",
Name: manifestPath,
Size: int64(len(manifestBody)),
}
if err := tw.WriteHeader(hdr); err != nil {
@@ -55,50 +59,52 @@ func newEmptyTestACI() (*os.File, error) {
}
func TestManifestFromImage(t *testing.T) {
img, err := newTestACI()
if err != nil {
t.Fatalf("newTestACI: unexpected error %v", err)
}
defer img.Close()
defer os.Remove(img.Name())
for _, usedotslash := range []bool{false, true} {
img, err := newTestACI(usedotslash)
if err != nil {
t.Fatalf("newTestACI: unexpected error: %v", err)
}
defer img.Close()
defer os.Remove(img.Name())
im, err := ManifestFromImage(img)
if err != nil {
t.Fatalf("ManifestFromImage: unexpected error %v", err)
}
if im.Name.String() != "example.com/app" {
t.Errorf("expected %s, got %s", "example.com/app", im.Name.String())
}
im, err := ManifestFromImage(img)
if err != nil {
t.Fatalf("ManifestFromImage: unexpected error: %v", err)
}
if im.Name.String() != "example.com/app" {
t.Errorf("expected %s, got %s", "example.com/app", im.Name.String())
}
emptyImg, err := newEmptyTestACI()
if err != nil {
t.Fatalf("newEmptyTestACI: unexpected error %v", err)
}
defer emptyImg.Close()
defer os.Remove(emptyImg.Name())
emptyImg, err := newEmptyTestACI()
if err != nil {
t.Fatalf("newEmptyTestACI: unexpected error: %v", err)
}
defer emptyImg.Close()
defer os.Remove(emptyImg.Name())
im, err = ManifestFromImage(emptyImg)
if err == nil {
t.Fatalf("ManifestFromImage: expected error")
im, err = ManifestFromImage(emptyImg)
if err == nil {
t.Fatalf("ManifestFromImage: expected error")
}
}
}
func TestNewCompressedTarReader(t *testing.T) {
img, err := newTestACI()
img, err := newTestACI(false)
if err != nil {
t.Fatalf("newTestACI: unexpected error %v", err)
t.Fatalf("newTestACI: unexpected error: %v", err)
}
defer img.Close()
defer os.Remove(img.Name())
cr, err := NewCompressedTarReader(img)
if err != nil {
t.Fatalf("NewCompressedTarReader: unexpected error %v", err)
t.Fatalf("NewCompressedTarReader: unexpected error: %v", err)
}
ftype, err := DetectFileType(cr)
if err != nil {
t.Fatalf("DetectFileType: unexpected error %v", err)
t.Fatalf("DetectFileType: unexpected error: %v", err)
}
if ftype != TypeText {
@@ -107,21 +113,21 @@ func TestNewCompressedTarReader(t *testing.T) {
}
func TestNewCompressedReader(t *testing.T) {
img, err := newTestACI()
img, err := newTestACI(false)
if err != nil {
t.Fatalf("newTestACI: unexpected error %v", err)
t.Fatalf("newTestACI: unexpected error: %v", err)
}
defer img.Close()
defer os.Remove(img.Name())
cr, err := NewCompressedReader(img)
if err != nil {
t.Fatalf("NewCompressedReader: unexpected error %v", err)
t.Fatalf("NewCompressedReader: unexpected error: %v", err)
}
ftype, err := DetectFileType(cr)
if err != nil {
t.Fatalf("DetectFileType: unexpected error %v", err)
t.Fatalf("DetectFileType: unexpected error: %v", err)
}
if ftype != TypeTar {
+9 -2
View File
@@ -90,7 +90,7 @@ func ValidateLayout(dir string) error {
// Application Container Image format. If any errors are encountered during
// the validation, it will abort and return the first one.
func ValidateArchive(tr *tar.Reader) error {
var flist []string
var fseen map[string]bool = make(map[string]bool)
var imOK, rfsOK bool
var im bytes.Buffer
Tar:
@@ -118,9 +118,16 @@ Tar:
}
rfsOK = true
default:
flist = append(flist, name)
if _, seen := fseen[name]; seen {
return fmt.Errorf("duplicate file entry in archive: %s", name)
}
fseen[name] = true
}
}
var flist []string
for key := range fseen {
flist = append(flist, key)
}
return validate(imOK, &im, rfsOK, flist)
}
+8 -1
View File
@@ -2,6 +2,7 @@ package main
import (
"fmt"
"runtime"
"strings"
"github.com/coreos/rocket/Godeps/_workspace/src/github.com/appc/spec/discovery"
@@ -29,6 +30,12 @@ func runDiscover(args []string) (exit int) {
for _, name := range args {
app, err := discovery.NewAppFromString(name)
if app.Labels["os"] == "" {
app.Labels["os"] = runtime.GOOS
}
if app.Labels["arch"] == "" {
app.Labels["arch"] = runtime.GOARCH
}
if err != nil {
stderr("%s: %s", name, err)
return 1
@@ -42,7 +49,7 @@ func runDiscover(args []string) (exit int) {
fmt.Printf("discover walk: prefix: %s error: %v\n", a.Prefix, a.Error)
}
for _, aciEndpoint := range eps.ACIEndpoints {
fmt.Printf("ACI: %s, Sig: %s\n", aciEndpoint.ACI, aciEndpoint.Sig)
fmt.Printf("ACI: %s, ASC: %s\n", aciEndpoint.ACI, aciEndpoint.ASC)
}
if len(eps.Keys) > 0 {
fmt.Println("Keys: " + strings.Join(eps.Keys, ","))
+3 -3
View File
@@ -19,7 +19,7 @@ type acMeta struct {
type ACIEndpoint struct {
ACI string
Sig string
ASC string
}
type Endpoints struct {
@@ -135,7 +135,7 @@ func doDiscover(pre string, app App, insecure bool) (*Endpoints, error) {
case "ac-discovery":
// Ignore not handled variables as {ext} isn't already rendered.
uri, _ := renderTemplate(m.uri, tplVars...)
sig, ok := renderTemplate(uri, "{ext}", "sig")
asc, ok := renderTemplate(uri, "{ext}", "aci.asc")
if !ok {
continue
}
@@ -143,7 +143,7 @@ func doDiscover(pre string, app App, insecure bool) (*Endpoints, error) {
if !ok {
continue
}
de.ACIEndpoints = append(de.ACIEndpoints, ACIEndpoint{ACI: aci, Sig: sig})
de.ACIEndpoints = append(de.ACIEndpoints, ACIEndpoint{ACI: aci, ASC: asc})
case "ac-discovery-pubkeys":
de.Keys = append(de.Keys, m.uri)
+7 -7
View File
@@ -74,11 +74,11 @@ func TestDiscoverEndpoints(t *testing.T) {
[]ACIEndpoint{
ACIEndpoint{
ACI: "https://storage.example.com/example.com/myapp-1.0.0.aci?torrent",
Sig: "https://storage.example.com/example.com/myapp-1.0.0.sig?torrent",
ASC: "https://storage.example.com/example.com/myapp-1.0.0.aci.asc?torrent",
},
ACIEndpoint{
ACI: "hdfs://storage.example.com/example.com/myapp-1.0.0.aci",
Sig: "hdfs://storage.example.com/example.com/myapp-1.0.0.sig",
ASC: "hdfs://storage.example.com/example.com/myapp-1.0.0.aci.asc",
},
},
[]string{"https://example.com/pubkeys.gpg"},
@@ -97,11 +97,11 @@ func TestDiscoverEndpoints(t *testing.T) {
[]ACIEndpoint{
ACIEndpoint{
ACI: "https://storage.example.com/example.com/myapp/foobar-1.0.0.aci?torrent",
Sig: "https://storage.example.com/example.com/myapp/foobar-1.0.0.sig?torrent",
ASC: "https://storage.example.com/example.com/myapp/foobar-1.0.0.aci.asc?torrent",
},
ACIEndpoint{
ACI: "hdfs://storage.example.com/example.com/myapp/foobar-1.0.0.aci",
Sig: "hdfs://storage.example.com/example.com/myapp/foobar-1.0.0.sig",
ASC: "hdfs://storage.example.com/example.com/myapp/foobar-1.0.0.aci.asc",
},
},
[]string{"https://example.com/pubkeys.gpg"},
@@ -135,7 +135,7 @@ func TestDiscoverEndpoints(t *testing.T) {
[]ACIEndpoint{
ACIEndpoint{
ACI: "https://storage.example.com/example.com/myapp-1.0.0.aci",
Sig: "https://storage.example.com/example.com/myapp-1.0.0.sig",
ASC: "https://storage.example.com/example.com/myapp-1.0.0.aci.asc",
},
},
[]string{"https://example.com/pubkeys.gpg"},
@@ -152,7 +152,7 @@ func TestDiscoverEndpoints(t *testing.T) {
[]ACIEndpoint{
ACIEndpoint{
ACI: "https://storage.example.com/example.com/myapp-latest.aci",
Sig: "https://storage.example.com/example.com/myapp-latest.sig",
ASC: "https://storage.example.com/example.com/myapp-latest.aci.asc",
},
},
[]string{"https://example.com/pubkeys.gpg"},
@@ -171,7 +171,7 @@ func TestDiscoverEndpoints(t *testing.T) {
[]ACIEndpoint{
ACIEndpoint{
ACI: "https://storage.example.com/example.com/myapp-1.0.0.aci",
Sig: "https://storage.example.com/example.com/myapp-1.0.0.sig",
ASC: "https://storage.example.com/example.com/myapp-1.0.0.aci.asc",
},
},
[]string{"https://example.com/pubkeys.gpg"},
+23
View File
@@ -1,5 +1,24 @@
package tarheader
/*
#define _BSD_SOURCE
#define _DEFAULT_SOURCE
#include <sys/types.h>
unsigned int
my_major(dev_t dev)
{
return major(dev);
}
unsigned int
my_minor(dev_t dev)
{
return minor(dev);
}
*/
import "C"
import (
"archive/tar"
"os"
@@ -17,6 +36,10 @@ func populateHeaderUnix(h *tar.Header, fi os.FileInfo, seen map[uint64]string) {
}
h.Uid = int(st.Uid)
h.Gid = int(st.Gid)
if st.Mode&syscall.S_IFMT == syscall.S_IFBLK || st.Mode&syscall.S_IFMT == syscall.S_IFCHR {
h.Devminor = int64(C.my_minor(C.dev_t(st.Rdev)))
h.Devmajor = int64(C.my_major(C.dev_t(st.Rdev)))
}
// If we have already seen this inode, generate a hardlink
p, ok := seen[uint64(st.Ino)]
if ok {
@@ -0,0 +1,61 @@
package tarheader
import (
"archive/tar"
"io/ioutil"
"os"
"path/filepath"
"syscall"
"testing"
)
// mknod requires privilege ...
func TestHeaderUnixDev(t *testing.T) {
hExpect := tar.Header{
Name: "./dev/test0",
Size: 0,
Typeflag: tar.TypeBlock,
Devminor: 5,
Devmajor: 233,
}
// make our test block device
var path string
{
var err error
path, err = ioutil.TempDir("", "tarheader-test-")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(path)
if err := os.Mkdir(filepath.Join(path, "dev"), os.FileMode(0755)); err != nil {
t.Fatal(err)
}
mode := uint32(hExpect.Mode&07777) | syscall.S_IFBLK
dev := uint32(((hExpect.Devminor & 0xfff00) << 12) | ((hExpect.Devmajor & 0xfff) << 8) | (hExpect.Devminor & 0xff))
if err := syscall.Mknod(filepath.Join(path, hExpect.Name), mode, int(dev)); err != nil {
if err == syscall.EPERM {
t.Skip("no permission to CAP_MKNOD")
}
t.Fatal(err)
}
}
fi, err := os.Stat(filepath.Join(path, hExpect.Name))
if err != nil {
t.Fatal(err)
}
hGot := tar.Header{
Name: "./dev/test0",
Size: 0,
Typeflag: tar.TypeBlock,
}
seen := map[uint64]string{}
populateHeaderUnix(&hGot, fi, seen)
if hGot.Devminor != hExpect.Devminor {
t.Errorf("dev minor: got %d, expected %d", hGot.Devminor, hExpect.Devminor)
}
if hGot.Devmajor != hExpect.Devmajor {
t.Errorf("dev major: got %d, expected %d", hGot.Devmajor, hExpect.Devmajor)
}
}
+20 -5
View File
@@ -7,6 +7,8 @@ import (
"github.com/coreos/rocket/Godeps/_workspace/src/github.com/appc/spec/schema/types"
)
const ContainerRuntimeManifestKind = types.ACKind("ContainerRuntimeManifest")
type ContainerRuntimeManifest struct {
ACVersion types.SemVer `json:"acVersion"`
ACKind types.ACKind `json:"acKind"`
@@ -21,8 +23,12 @@ type ContainerRuntimeManifest struct {
// unmarshalling of the ContainerRuntimeManifest
type containerRuntimeManifest ContainerRuntimeManifest
func BlankContainerRuntimeManifest() *ContainerRuntimeManifest {
return &ContainerRuntimeManifest{ACKind: ContainerRuntimeManifestKind, ACVersion: AppContainerVersion}
}
func (cm *ContainerRuntimeManifest) UnmarshalJSON(data []byte) error {
c := containerRuntimeManifest{}
c := containerRuntimeManifest(*cm)
err := json.Unmarshal(data, &c)
if err != nil {
return err
@@ -42,14 +48,16 @@ func (cm ContainerRuntimeManifest) MarshalJSON() ([]byte, error) {
return json.Marshal(containerRuntimeManifest(cm))
}
var cmKindError = types.InvalidACKindError(ContainerRuntimeManifestKind)
// assertValid performs extra assertions on an ContainerRuntimeManifest to
// ensure that fields are set appropriately, etc. It is used exclusively when
// marshalling and unmarshalling an ContainerRuntimeManifest. Most
// field-specific validation is performed through the individual types being
// marshalled; assertValid() should only deal with higher-level validation.
func (cm *ContainerRuntimeManifest) assertValid() error {
if cm.ACKind != "ContainerRuntimeManifest" {
return types.ACKindError(`missing or bad ACKind (must be "ContainerRuntimeManifest")`)
if cm.ACKind != ContainerRuntimeManifestKind {
return cmKindError
}
return nil
}
@@ -89,8 +97,15 @@ func (r Mount) assertValid() error {
// RuntimeApp describes an application referenced in a ContainerRuntimeManifest
type RuntimeApp struct {
Name types.ACName `json:"name"`
ImageID types.Hash `json:"imageID"`
Image RuntimeImage `json:"image"`
App *types.App `json:"app,omitempty"`
Mounts []Mount `json:"mounts"`
Isolators []types.Isolator `json:"isolators"`
Annotations types.Annotations `json:"annotations"`
}
// RuntimeImage describes an image referenced in a RuntimeApp
type RuntimeImage struct {
Name types.ACName `json:"name"`
ID types.Hash `json:"id"`
Labels types.Labels `json:"labels"`
}
+19
View File
@@ -0,0 +1,19 @@
package schema
import "testing"
func TestContainerRuntimeManifestMerge(t *testing.T) {
cmj := `{}`
cm := &ContainerRuntimeManifest{}
if cm.UnmarshalJSON([]byte(cmj)) == nil {
t.Fatal("Manifest JSON without acKind and acVersion unmarshalled successfully")
}
cm = BlankContainerRuntimeManifest()
err := cm.UnmarshalJSON([]byte(cmj))
if err != nil {
t.Errorf("unexpected error: %v", err)
}
}
+11 -4
View File
@@ -8,7 +8,8 @@ import (
)
const (
ACIExtension = ".aci"
ACIExtension = ".aci"
ImageManifestKind = types.ACKind("ImageManifest")
)
type ImageManifest struct {
@@ -26,8 +27,12 @@ type ImageManifest struct {
// unmarshalling of the ImageManifest
type imageManifest ImageManifest
func BlankImageManifest() *ImageManifest {
return &ImageManifest{ACKind: ImageManifestKind, ACVersion: AppContainerVersion}
}
func (im *ImageManifest) UnmarshalJSON(data []byte) error {
a := imageManifest{}
a := imageManifest(*im)
err := json.Unmarshal(data, &a)
if err != nil {
return err
@@ -47,14 +52,16 @@ func (im ImageManifest) MarshalJSON() ([]byte, error) {
return json.Marshal(imageManifest(im))
}
var imKindError = types.InvalidACKindError(ImageManifestKind)
// assertValid performs extra assertions on an ImageManifest to ensure that
// fields are set appropriately, etc. It is used exclusively when marshalling
// and unmarshalling an ImageManifest. Most field-specific validation is
// performed through the individual types being marshalled; assertValid()
// should only deal with higher-level validation.
func (im *ImageManifest) assertValid() error {
if im.ACKind != "ImageManifest" {
return types.ACKindError(`missing or bad ACKind (must be "ImageManifest")`)
if im.ACKind != ImageManifestKind {
return imKindError
}
if im.ACVersion.Empty() {
return errors.New(`acVersion must be set`)
+16
View File
@@ -30,3 +30,19 @@ func TestEmptyApp(t *testing.T) {
t.Errorf("unexpected error: %v", err)
}
}
func TestImageManifestMerge(t *testing.T) {
imj := `{"name": "example.com/test"}`
im := &ImageManifest{}
if im.UnmarshalJSON([]byte(imj)) == nil {
t.Fatal("Manifest JSON without acKind and acVersion unmarshalled successfully")
}
im = BlankImageManifest()
err := im.UnmarshalJSON([]byte(imj))
if err != nil {
t.Errorf("unexpected error: %v", err)
}
}
+34
View File
@@ -43,3 +43,37 @@ func TestACKindMarshalGood(t *testing.T) {
}
}
}
func TestACKindUnmarshalBad(t *testing.T) {
tests := []string{
"ImageManifest", // Not a valid JSON-encoded string
`"garbage"`,
`"AppManifest"`,
`""`,
}
for i, in := range tests {
var a, b ACKind
err := a.UnmarshalJSON([]byte(in))
if err == nil {
t.Errorf("#%d: err=nil, want non-nil", i)
} else if !reflect.DeepEqual(a, b) {
t.Errorf("#%d: a=%v, want empty", i, a)
}
}
}
func TestACKindUnmarshalGood(t *testing.T) {
tests := map[string]ACKind{
`"ContainerRuntimeManifest"`: ACKind("ContainerRuntimeManifest"),
`"ImageManifest"`: ACKind("ImageManifest"),
}
for in, w := range tests {
var a ACKind
err := json.Unmarshal([]byte(in), &a)
if err != nil {
t.Errorf("%v: err=%v, want nil", in, err)
} else if !reflect.DeepEqual(a, w) {
t.Errorf("%v: a=%v, want %v", in, a, w)
}
}
}
+62 -15
View File
@@ -2,18 +2,31 @@ package types
import (
"encoding/json"
"fmt"
"errors"
"regexp"
"strings"
)
const (
valchars = `abcdefghijklmnopqrstuvwxyz0123456789.-/`
var (
// ValidACName is a regular expression that defines a valid ACName
ValidACName = regexp.MustCompile("^[a-z0-9]+([-./][a-z0-9]+)*$")
invalidChars = regexp.MustCompile("[^a-z0-9./-]")
invalidEdges = regexp.MustCompile("(^[./-]+)|([./-]+$)")
ErrEmptyACName = ACNameError("ACName cannot be empty")
ErrInvalidEdge = ACNameError("ACName must start and end with only lower case " +
"alphanumeric characters")
ErrInvalidChar = ACNameError("ACName must contain only lower case " +
`alphanumeric characters plus ".", "-", "/"`)
)
// ACName (an App-Container Name) is a format used by keys in different
// formats of the App Container Standard. An ACName is restricted to
// characters accepted by the DNS RFC[1] and "/"; all alphabetical characters
// must be lowercase only.
// ACName (an App-Container Name) is a format used by keys in different formats
// of the App Container Standard. An ACName is restricted to characters
// accepted by the DNS RFC[1] and "/"; all alphabetical characters must be
// lowercase only. Furthermore, the first and last character ("edges") must be
// alphanumeric, and an ACName cannot be empty. Programmatically, an ACName
// must conform to the regular expression ValidACName.
//
// [1] http://tools.ietf.org/html/rfc1123#page-13
type ACName string
@@ -22,6 +35,8 @@ func (n ACName) String() string {
return string(n)
}
// Set sets the ACName to the given value, if it is valid; if not,
// an error is returned.
func (n *ACName) Set(s string) error {
nn, err := NewACName(s)
if err == nil {
@@ -35,6 +50,7 @@ func (n ACName) Equals(o ACName) bool {
return strings.ToLower(string(n)) == strings.ToLower(string(o))
}
// Empty returns a boolean indicating whether this ACName is empty.
func (n ACName) Empty() bool {
return n.String() == ""
}
@@ -42,16 +58,25 @@ func (n ACName) Empty() bool {
// NewACName generates a new ACName from a string. If the given string is
// not a valid ACName, nil and an error are returned.
func NewACName(s string) (*ACName, error) {
n := ACName(s)
if err := n.assertValid(); err != nil {
return nil, err
}
return &n, nil
}
func (n ACName) assertValid() error {
s := string(n)
if len(s) == 0 {
return nil, fmt.Errorf("ACName cannot be empty")
return ErrEmptyACName
}
for _, c := range s {
if !strings.ContainsRune(valchars, c) {
msg := fmt.Sprintf("invalid char in ACName: %c", c)
return nil, ACNameError(msg)
}
if invalidChars.MatchString(s) {
return ErrInvalidChar
}
return (*ACName)(&s), nil
if invalidEdges.MatchString(s) {
return ErrInvalidEdge
}
return nil
}
// UnmarshalJSON implements the json.Unmarshaler interface
@@ -69,6 +94,28 @@ func (n *ACName) UnmarshalJSON(data []byte) error {
}
// MarshalJSON implements the json.Marshaler interface
func (n *ACName) MarshalJSON() ([]byte, error) {
func (n ACName) MarshalJSON() ([]byte, error) {
if err := n.assertValid(); err != nil {
return nil, err
}
return json.Marshal(n.String())
}
// SanitizeACName replaces every invalid ACName character in s with a dash
// making it a legal ACName string. If the character is an upper case letter it
// replaces it with its lower case. It also removes illegal edge characters
// (hyphens, periods and slashes).
//
// This is a helper function and its algorithm is not part of the spec. It
// should not be called without the user explicitly asking for a suggestion.
func SanitizeACName(s string) (string, error) {
s = strings.ToLower(s)
s = invalidChars.ReplaceAllString(s, "-")
s = invalidEdges.ReplaceAllString(s, "")
if s == "" {
return "", errors.New("must contain at least one valid character")
}
return s, nil
}
+199 -12
View File
@@ -1,9 +1,13 @@
package types
import "testing"
import (
"encoding/json"
"reflect"
"testing"
)
func TestNewACName(t *testing.T) {
tests := []string{
var (
goodNames = []string{
"asdf",
"foo-bar-baz",
"database",
@@ -11,7 +15,23 @@ func TestNewACName(t *testing.T) {
"example.com/ourapp-1.0.0",
"sub-domain.example.com/org/product/release-1.0.0",
}
for i, in := range tests {
badNames = []string{
"",
"foo#",
"EXAMPLE.com",
"foo.com/BAR",
"example.com/app_1",
"/app",
"app/",
"-app",
"app-",
".app",
"app.",
}
)
func TestNewACName(t *testing.T) {
for i, in := range goodNames {
l, err := NewACName(in)
if err != nil {
t.Errorf("#%d: got err=%v, want nil", i, err)
@@ -23,14 +43,7 @@ func TestNewACName(t *testing.T) {
}
func TestNewACNameBad(t *testing.T) {
tests := []string{
"",
"foo#",
"EXAMPLE.com",
"foo.com/BAR",
"example.com/app_1",
}
for i, in := range tests {
for i, in := range badNames {
l, err := NewACName(in)
if l != nil {
t.Errorf("#%d: got l=%v, want nil", i, l)
@@ -40,3 +53,177 @@ func TestNewACNameBad(t *testing.T) {
}
}
}
func TestSanitizeACName(t *testing.T) {
tests := map[string]string{
"foo#": "foo",
"EXAMPLE.com": "example.com",
"foo.com/BAR": "foo.com/bar",
"example.com/app_1": "example.com/app-1",
"/app": "app",
"app/": "app",
"-app": "app",
"app-": "app",
".app": "app",
"app.": "app",
"app///": "app",
"-/.app..": "app",
"-/app.name-test/-/": "app.name-test",
"sub-domain.example.com/org/product/release-1.0.0": "sub-domain.example.com/org/product/release-1.0.0",
}
for in, ex := range tests {
o, err := SanitizeACName(in)
if err != nil {
t.Errorf("got err=%v, want nil", err)
}
if o != ex {
t.Errorf("got l=%s, want %s", o, ex)
}
}
}
func TestACNameSetGood(t *testing.T) {
tests := map[string]ACName{
"blargh": ACName("blargh"),
"example.com/ourapp-1.0.0": ACName("example.com/ourapp-1.0.0"),
}
for in, w := range tests {
// Ensure an empty name is set appropriately
var a ACName
err := a.Set(in)
if err != nil {
t.Errorf("%v: got err=%v, want nil", in, err)
continue
}
if !reflect.DeepEqual(a, w) {
t.Errorf("%v: a=%v, want %v", in, a, w)
}
// Ensure an existing name is overwritten
var b ACName = ACName("orig")
err = b.Set(in)
if err != nil {
t.Errorf("%v: got err=%v, want nil", in, err)
continue
}
if !reflect.DeepEqual(b, w) {
t.Errorf("%v: b=%v, want %v", in, b, w)
}
}
}
func TestACNameSetBad(t *testing.T) {
for i, in := range badNames {
// Ensure an empty name stays empty
var a ACName
err := a.Set(in)
if err == nil {
t.Errorf("#%d: err=%v, want nil", i, err)
continue
}
if w := ACName(""); !reflect.DeepEqual(a, w) {
t.Errorf("%d: a=%v, want %v", i, a, w)
}
// Ensure an existing name is not overwritten
var b ACName = ACName("orig")
err = b.Set(in)
if err == nil {
t.Errorf("#%d: err=%v, want nil", i, err)
continue
}
if w := ACName("orig"); !reflect.DeepEqual(b, w) {
t.Errorf("%d: b=%v, want %v", i, b, w)
}
}
}
func TestSanitizeACNameBad(t *testing.T) {
tests := []string{
"__",
"..",
"//",
"",
".//-"}
for i, in := range tests {
l, err := SanitizeACName(in)
if l != "" {
t.Errorf("#%d: got l=%v, want nil", i, l)
}
if err == nil {
t.Errorf("#%d: got err=nil, want non-nil", i)
}
}
}
func TestACNameUnmarshalBad(t *testing.T) {
tests := []string{
"",
"garbage",
`""`,
`"EXAMPLE"`,
`"example.com/app_1"`,
}
for i, in := range tests {
var a, b ACName
err := a.UnmarshalJSON([]byte(in))
if err == nil {
t.Errorf("#%d: err=nil, want non-nil", i)
} else if !reflect.DeepEqual(a, b) {
t.Errorf("#%d: a=%v, want empty", i, a)
}
}
}
func TestACNameUnmarshalGood(t *testing.T) {
tests := map[string]ACName{
`"example"`: ACName("example"),
`"foo.com/bar"`: ACName("foo.com/bar"),
}
for in, w := range tests {
var a ACName
err := json.Unmarshal([]byte(in), &a)
if err != nil {
t.Errorf("%v: err=%v, want nil", in, err)
} else if !reflect.DeepEqual(a, w) {
t.Errorf("%v: a=%v, want %v", in, a, w)
}
}
}
func TestACNameMarshalBad(t *testing.T) {
tests := map[string]error{
"Foo": ErrInvalidChar,
"foo#": ErrInvalidChar,
"/foo": ErrInvalidEdge,
"example.com/": ErrInvalidEdge,
"": ErrEmptyACName,
}
for in, werr := range tests {
a := ACName(in)
b, gerr := json.Marshal(a)
if b != nil {
t.Errorf("ACName(%q): want b=nil, got %v", in, b)
}
if jerr, ok := gerr.(*json.MarshalerError); !ok {
t.Errorf("expected JSONMarshalerError")
} else {
if e := jerr.Err; e != werr {
t.Errorf("err=%#v, want %#v", e, werr)
}
}
}
}
func TestACNameMarshalGood(t *testing.T) {
for i, in := range goodNames {
a := ACName(in)
b, err := json.Marshal(a)
if !reflect.DeepEqual(b, []byte(`"`+in+`"`)) {
t.Errorf("#%d: marshalled=%v, want %v", i, b, []byte(in))
}
if err != nil {
t.Errorf("#%d: err=%v, want nil", i, err)
}
}
}
+1 -1
View File
@@ -55,7 +55,7 @@ func (a *Annotations) UnmarshalJSON(data []byte) error {
return err
}
na := Annotations(ja)
if err := a.assertValid(); err != nil {
if err := na.assertValid(); err != nil {
return err
}
*a = na
@@ -80,6 +80,112 @@ func TestAnnotationsAssertValid(t *testing.T) {
}
}
func TestAnnotationsMarshal(t *testing.T) {
for i, tt := range []struct {
in []Annotation
wb []byte
werr bool
}{
{
[]Annotation{
makeAnno("foo", "bar"),
makeAnno("foo", "baz"),
makeAnno("website", "http://example.com/anno"),
},
nil,
true,
},
{
[]Annotation{
makeAnno("a", "b"),
},
[]byte(`[{"name":"a","value":"b"}]`),
false,
},
{
[]Annotation{
makeAnno("foo", "bar"),
makeAnno("website", "http://example.com/anno"),
},
[]byte(`[{"name":"foo","value":"bar"},{"name":"website","value":"http://example.com/anno"}]`),
false,
},
} {
a := Annotations(tt.in)
b, err := a.MarshalJSON()
if !reflect.DeepEqual(b, tt.wb) {
t.Errorf("#%d: b=%s, want %s", i, b, tt.wb)
}
gerr := err != nil
if gerr != tt.werr {
t.Errorf("#%d: gerr=%t, want %t (err=%v)", i, gerr, tt.werr, err)
}
}
}
func TestAnnotationsUnmarshal(t *testing.T) {
tests := []struct {
in string
wann *Annotations
werr bool
}{
{
`garbage`,
&Annotations{},
true,
},
{
`[{"name":"a","value":"b"},{"name":"a","value":"b"}]`,
&Annotations{},
true,
},
{
`[{"name":"a","value":"b"}]`,
&Annotations{
makeAnno("a", "b"),
},
false,
},
}
for i, tt := range tests {
a := &Annotations{}
err := a.UnmarshalJSON([]byte(tt.in))
gerr := err != nil
if gerr != tt.werr {
t.Errorf("#%d: gerr=%t, want %t (err=%v)", i, gerr, tt.werr, err)
}
if !reflect.DeepEqual(a, tt.wann) {
t.Errorf("#%d: ann=%#v, want %#v", i, a, tt.wann)
}
}
}
func TestAnnotationsGet(t *testing.T) {
for i, tt := range []struct {
in string
wval string
wok bool
}{
{"foo", "bar", true},
{"website", "http://example.com/anno", true},
{"baz", "", false},
{"wuuf", "", false},
} {
a := Annotations{
makeAnno("foo", "bar"),
makeAnno("website", "http://example.com/anno"),
}
gval, gok := a.Get(tt.in)
if gval != tt.wval {
t.Errorf("#%d: val=%v, want %v", i, gval, tt.wval)
}
if gok != tt.wok {
t.Errorf("#%d: ok=%t, want %t", i, gok, tt.wok)
}
}
}
func TestAnnotationsSet(t *testing.T) {
a := Annotations{}
+1 -1
View File
@@ -24,7 +24,7 @@ type App struct {
type app App
func (a *App) UnmarshalJSON(data []byte) error {
ja := app{}
ja := app(*a)
err := json.Unmarshal(data, &ja)
if err != nil {
return err
+63 -1
View File
@@ -1,6 +1,9 @@
package types
import "testing"
import (
"reflect"
"testing"
)
func TestAppValid(t *testing.T) {
tests := []App{
@@ -128,8 +131,17 @@ func TestUserGroupInvalid(t *testing.T) {
func TestAppWorkingDirectoryInvalid(t *testing.T) {
tests := []App{
App{
Exec: []string{"/app"},
User: "foo",
Group: "bar",
WorkingDirectory: "stuff",
},
App{
Exec: []string{"/app"},
User: "foo",
Group: "bar",
WorkingDirectory: "../home/fred",
},
}
for i, tt := range tests {
if err := tt.assertValid(); err == nil {
@@ -141,6 +153,9 @@ func TestAppWorkingDirectoryInvalid(t *testing.T) {
func TestAppEnvironmentInvalid(t *testing.T) {
tests := []App{
App{
Exec: []string{"/app"},
User: "foo",
Group: "bar",
Environment: Environment{
EnvironmentVariable{"0DEBUG", "true"},
},
@@ -152,3 +167,50 @@ func TestAppEnvironmentInvalid(t *testing.T) {
}
}
}
func TestAppUnmarshal(t *testing.T) {
tests := []struct {
in string
wann *App
werr bool
}{
{
`garbage`,
&App{},
true,
},
{
`{"Exec":"not a list"}`,
&App{},
true,
},
{
`{"Exec":["notfullyqualified"]}`,
&App{},
true,
},
{
`{"Exec":["/a"],"User":"0","Group":"0"}`,
&App{
Exec: Exec{
"/a",
},
User: "0",
Group: "0",
Environment: make(Environment, 0),
},
false,
},
}
for i, tt := range tests {
a := &App{}
err := a.UnmarshalJSON([]byte(tt.in))
gerr := err != nil
if gerr != tt.werr {
t.Errorf("#%d: gerr=%t, want %t (err=%v)", i, gerr, tt.werr, err)
}
if !reflect.DeepEqual(a, tt.wann) {
t.Errorf("#%d: ann=%#v, want %#v", i, a, tt.wann)
}
}
}
+6 -7
View File
@@ -1,5 +1,7 @@
package types
import "fmt"
// An ACKindError is returned when the wrong ACKind is set in a manifest
type ACKindError string
@@ -7,6 +9,10 @@ func (e ACKindError) Error() string {
return string(e)
}
func InvalidACKindError(kind ACKind) ACKindError {
return ACKindError(fmt.Sprintf("missing or bad ACKind (must be %#v)", kind))
}
// An ACVersionError is returned when a bad ACVersion is set in a manifest
type ACVersionError string
@@ -20,10 +26,3 @@ type ACNameError string
func (e ACNameError) Error() string {
return string(e)
}
// An AMStartedOnError is returned when the wrong StartedOn is set in an ImageManifest
type AMStartedOnError string
func (e AMStartedOnError) Error() string {
return string(e)
}
+79 -2
View File
@@ -1,6 +1,83 @@
package types
import (
"encoding/json"
"errors"
)
var (
isolatorMap map[string]IsolatorValueConstructor
)
func init() {
isolatorMap = make(map[string]IsolatorValueConstructor)
}
type IsolatorValueConstructor func() IsolatorValue
func AddIsolatorValueConstructor(i IsolatorValueConstructor) {
t := i()
n := t.Name()
isolatorMap[n] = i
}
type Isolators []Isolator
// GetByName returns the last isolator in the list by the given name.
func (is *Isolators) GetByName(name string) *Isolator {
var i Isolator
for j := len(*is) - 1; j >= 0; j-- {
i = []Isolator(*is)[j]
if i.Name == name {
return &i
}
}
return nil
}
type IsolatorValue interface {
Name() string
UnmarshalJSON(b []byte) error
AssertValid() error
}
type Isolator struct {
Name ACName `json:"name"`
Val string `json:"value"`
Name string `json:"name"`
ValueRaw json.RawMessage `json:"value"`
value IsolatorValue
}
type isolator Isolator
func (i *Isolator) Value() IsolatorValue {
return i.value
}
func (i *Isolator) UnmarshalJSON(b []byte) error {
var ii isolator
err := json.Unmarshal(b, &ii)
if err != nil {
return err
}
var dst IsolatorValue
con, ok := isolatorMap[ii.Name]
if !ok {
return errors.New("unrecognized isolator " + ii.Name)
}
dst = con()
err = dst.UnmarshalJSON(ii.ValueRaw)
if err != nil {
return err
}
i.value = dst
i.Name = ii.Name
return nil
}
func (i *Isolator) assertValid() error {
if i.value == nil {
return errors.New("nil Value")
}
return i.value.AssertValid()
}
@@ -0,0 +1,78 @@
package types
import (
"encoding/json"
"errors"
)
const (
LinuxCapabilitiesRetainSetName string = "os/linux/capabilities-retain-set"
LinuxCapabilitiesRevokeSetName string = "os/linux/capabilities-revoke-set"
)
func init() {
AddIsolatorValueConstructor(NewLinuxCapabilitiesRetainSet)
AddIsolatorValueConstructor(NewLinuxCapabilitiesRevokeSet)
}
type LinuxCapabilitiesSet interface {
Name() string
Set() []LinuxCapability
AssertValid() error
}
type LinuxCapability string
type linuxCapabilitiesSetValue struct {
Set []LinuxCapability `json:"set"`
}
type linuxCapabilitiesSetBase struct {
val linuxCapabilitiesSetValue
}
func (l linuxCapabilitiesSetBase) AssertValid() error {
if len(l.val.Set) == 0 {
return errors.New("set must be non-empty")
}
return nil
}
func (l *linuxCapabilitiesSetBase) UnmarshalJSON(b []byte) error {
var v linuxCapabilitiesSetValue
err := json.Unmarshal(b, &v)
if err != nil {
return err
}
l.val = v
return err
}
func (l linuxCapabilitiesSetBase) Set() []LinuxCapability {
return l.val.Set
}
func NewLinuxCapabilitiesRetainSet() IsolatorValue {
return &LinuxCapabilitiesRetainSet{}
}
type LinuxCapabilitiesRetainSet struct {
linuxCapabilitiesSetBase
}
func (l LinuxCapabilitiesRetainSet) Name() string {
return LinuxCapabilitiesRetainSetName
}
func NewLinuxCapabilitiesRevokeSet() IsolatorValue {
return &LinuxCapabilitiesRevokeSet{}
}
type LinuxCapabilitiesRevokeSet struct {
linuxCapabilitiesSetBase
}
func (l LinuxCapabilitiesRevokeSet) Name() string {
return LinuxCapabilitiesRevokeSetName
}
@@ -0,0 +1,164 @@
package types
import (
"encoding/json"
"errors"
"github.com/coreos/rocket/Godeps/_workspace/src/github.com/GoogleCloudPlatform/kubernetes/pkg/api/resource"
)
var (
ErrDefaultTrue = errors.New("default must be false")
ErrDefaultRequired = errors.New("default must be true")
ErrRequestNonEmpty = errors.New("request not supported by this resource, must be empty")
)
const (
ResourceBlockBandwidthName = "resource/block-bandwidth"
ResourceBlockIOPSName = "resource/block-iops"
ResourceCPUName = "resource/cpu"
ResourceMemoryName = "resource/memory"
ResourceNetworkBandwidthName = "resource/network-bandwidth"
)
func init() {
AddIsolatorValueConstructor(NewResourceBlockBandwidth)
AddIsolatorValueConstructor(NewResourceBlockIOPS)
AddIsolatorValueConstructor(NewResourceCPU)
AddIsolatorValueConstructor(NewResourceMemory)
AddIsolatorValueConstructor(NewResourceNetworkBandwidth)
}
func NewResourceBlockBandwidth() IsolatorValue {
return &ResourceBlockBandwidth{}
}
func NewResourceBlockIOPS() IsolatorValue {
return &ResourceBlockIOPS{}
}
func NewResourceCPU() IsolatorValue {
return &ResourceCPU{}
}
func NewResourceNetworkBandwidth() IsolatorValue {
return &ResourceNetworkBandwidth{}
}
func NewResourceMemory() IsolatorValue {
return &ResourceMemory{}
}
type Resource interface {
Limit() *resource.Quantity
Request() *resource.Quantity
Default() bool
}
type ResourceBase struct {
val resourceValue
}
type resourceValue struct {
Default bool `json:"default"`
Request *resource.Quantity `json:"request"`
Limit *resource.Quantity `json:"limit"`
}
func (r ResourceBase) Limit() *resource.Quantity {
return r.val.Limit
}
func (r ResourceBase) Request() *resource.Quantity {
return r.val.Request
}
func (r ResourceBase) Default() bool {
return r.val.Default
}
func (r *ResourceBase) UnmarshalJSON(b []byte) error {
return json.Unmarshal(b, &r.val)
}
func (r ResourceBase) AssertValid() error {
return nil
}
type ResourceBlockBandwidth struct {
ResourceBase
}
func (r ResourceBlockBandwidth) AssertValid() error {
if r.Default() != true {
return ErrDefaultRequired
}
if r.Request() != nil {
return ErrRequestNonEmpty
}
return nil
}
func (r ResourceBlockBandwidth) Name() string {
return ResourceBlockBandwidthName
}
type ResourceBlockIOPS struct {
ResourceBase
}
func (r ResourceBlockIOPS) AssertValid() error {
if r.Default() != true {
return ErrDefaultRequired
}
if r.Request() != nil {
return ErrRequestNonEmpty
}
return nil
}
func (r ResourceBlockIOPS) Name() string {
return ResourceBlockIOPSName
}
type ResourceCPU struct {
ResourceBase
}
func (r ResourceCPU) AssertValid() error {
if r.Default() != false {
return ErrDefaultTrue
}
return nil
}
func (r ResourceCPU) Name() string {
return ResourceCPUName
}
type ResourceMemory struct {
ResourceBase
}
func (r ResourceMemory) AssertValid() error {
if r.Default() != false {
return ErrDefaultTrue
}
return nil
}
func (r ResourceMemory) Name() string {
return ResourceMemoryName
}
type ResourceNetworkBandwidth struct {
ResourceBase
}
func (r ResourceNetworkBandwidth) AssertValid() error {
if r.Default() != true {
return ErrDefaultRequired
}
if r.Request() != nil {
return ErrRequestNonEmpty
}
return nil
}
func (r ResourceNetworkBandwidth) Name() string {
return ResourceNetworkBandwidthName
}
@@ -0,0 +1,225 @@
package types
import (
"encoding/json"
"reflect"
"testing"
)
func TestIsolatorUnmarshal(t *testing.T) {
tests := []struct {
msg string
werr bool
werrvalid bool
}{
{
`{
"name": "os/linux/capabilities-retain-set",
"value": {"set": ["CAP_KILL"]}
}`,
false,
false,
},
{
`{
"name": "os/linux/capabilities-retain-set",
"value": {"set": ["CAP_PONIES"]}
}`,
false,
false,
},
{
`{
"name": "os/linux/capabilities-retain-set",
"value": {"set": []}
}`,
false,
true,
},
{
`{
"name": "os/linux/capabilities-retain-set",
"value": {"set": "CAP_PONIES"}
}`,
true,
true,
},
{
`{
"name": "resource/block-bandwidth",
"value": {"default": true, "limit": "1G"}
}`,
false,
false,
},
{
`{
"name": "resource/block-bandwidth",
"value": {"default": false, "limit": "1G"}
}`,
false,
true,
},
{
`{
"name": "resource/block-bandwidth",
"value": {"request": "30G", "limit": "1G"}
}`,
false,
true,
},
{
`{
"name": "resource/block-iops",
"value": {"default": true, "limit": "1G"}
}`,
false,
false,
},
{
`{
"name": "resource/block-iops",
"value": {"default": false, "limit": "1G"}
}`,
false,
true,
},
{
`{
"name": "resource/block-iops",
"value": {"request": "30G", "limit": "1G"}
}`,
false,
true,
},
{
`{
"name": "resource/cpu",
"value": {"request": "30", "limit": "1"}
}`,
false,
false,
},
{
`{
"name": "resource/memory",
"value": {"request": "1G", "limit": "2Gi"}
}`,
false,
false,
},
{
`{
"name": "resource/memory",
"value": {"default": true, "request": "1G", "limit": "2G"}
}`,
false,
true,
},
{
`{
"name": "resource/network-bandwidth",
"value": {"default": true, "limit": "1G"}
}`,
false,
false,
},
{
`{
"name": "resource/network-bandwidth",
"value": {"default": false, "limit": "1G"}
}`,
false,
true,
},
{
`{
"name": "resource/network-bandwidth",
"value": {"request": "30G", "limit": "1G"}
}`,
false,
true,
},
}
for i, tt := range tests {
var ii Isolator
err := ii.UnmarshalJSON([]byte(tt.msg))
if gerr := (err != nil); gerr != tt.werr {
t.Errorf("#%d: gerr=%t, want %t (err=%v)", i, gerr, tt.werr, err)
}
err = ii.assertValid()
if gerrvalid := (err != nil); gerrvalid != tt.werrvalid {
t.Errorf("#%d: name=%v gerrvalid=%t, want %t (err=%v)", i, ii.Name, gerrvalid, tt.werrvalid, err)
}
}
}
func TestIsolatorsGetByName(t *testing.T) {
ex := `
[
{
"name": "resource/cpu",
"value": {"request": "30", "limit": "1"}
},
{
"name": "resource/memory",
"value": {"request": "1G", "limit": "2Gi"}
},
{
"name": "os/linux/capabilities-retain-set",
"value": {"set": ["CAP_KILL"]}
},
{
"name": "os/linux/capabilities-revoke-set",
"value": {"set": ["CAP_KILL"]}
}
]
`
tests := []struct {
name string
wlimit int64
wrequest int64
wset []LinuxCapability
}{
{"resource/cpu", 1, 30, nil},
{"resource/memory", 2147483648, 1000000000, nil},
{"os/linux/capabilities-retain-set", 0, 0, []LinuxCapability{"CAP_KILL"}},
{"os/linux/capabilities-revoke-set", 0, 0, []LinuxCapability{"CAP_KILL"}},
}
var is Isolators
err := json.Unmarshal([]byte(ex), &is)
if err != nil {
panic(err)
}
if len(is) < 2 {
t.Fatalf("too few items %v", len(is))
}
for i, tt := range tests {
c := is.GetByName(tt.name)
if c == nil {
t.Fatalf("can't find item %v in %v items", tt.name, len(is))
}
switch v := c.Value().(type) {
case Resource:
var r Resource = v
glimit := r.Limit()
grequest := r.Request()
if glimit.Value() != tt.wlimit || grequest.Value() != tt.wrequest {
t.Errorf("#%d: glimit=%v, want %v, grequest=%v, want %v", i, glimit.Value(), tt.wlimit, grequest.Value(), tt.wrequest)
}
case LinuxCapabilitiesSet:
var s LinuxCapabilitiesSet = v
if !reflect.DeepEqual(s.Set(), tt.wset) {
t.Errorf("#%d: gset=%v, want %v", i, s.Set(), tt.wset)
}
default:
panic("unexecpected type")
}
}
}
+13
View File
@@ -0,0 +1,13 @@
language: go
go:
- 1.4
- 1.3
- 1.2
- tip
install:
- if ! go get code.google.com/p/go.tools/cmd/cover; then go get golang.org/x/tools/cmd/cover; fi
script:
- go test -cover
+67
View File
@@ -0,0 +1,67 @@
# How to contribute #
We'd love to accept your patches and contributions to this project. There are
a just a few small guidelines you need to follow.
## Contributor License Agreement ##
Contributions to any Google project must be accompanied by a Contributor
License Agreement. This is not a copyright **assignment**, it simply gives
Google permission to use and redistribute your contributions as part of the
project.
* If you are an individual writing original source code and you're sure you
own the intellectual property, then you'll need to sign an [individual
CLA][].
* If you work for a company that wants to allow you to contribute your work,
then you'll need to sign a [corporate CLA][].
You generally only need to submit a CLA once, so if you've already submitted
one (even if it was for a different project), you probably don't need to do it
again.
[individual CLA]: https://developers.google.com/open-source/cla/individual
[corporate CLA]: https://developers.google.com/open-source/cla/corporate
## Submitting a patch ##
1. It's generally best to start by opening a new issue describing the bug or
feature you're intending to fix. Even if you think it's relatively minor,
it's helpful to know what people are working on. Mention in the initial
issue that you are planning to work on that bug or feature so that it can
be assigned to you.
1. Follow the normal process of [forking][] the project, and setup a new
branch to work in. It's important that each group of changes be done in
separate branches in order to ensure that a pull request only includes the
commits related to that bug or feature.
1. Go makes it very simple to ensure properly formatted code, so always run
`go fmt` on your code before committing it. You should also run
[golint][] over your code. As noted in the [golint readme][], it's not
strictly necessary that your code be completely "lint-free", but this will
help you find common style issues.
1. Any significant changes should almost always be accompanied by tests. The
project already has good test coverage, so look at some of the existing
tests if you're unsure how to go about it. [gocov][] and [gocov-html][]
are invaluable tools for seeing which parts of your code aren't being
exercised by your tests.
1. Do your best to have [well-formed commit messages][] for each change.
This provides consistency throughout the project, and ensures that commit
messages are able to be formatted properly by various git tools.
1. Finally, push the commits to your fork and submit a [pull request][].
[forking]: https://help.github.com/articles/fork-a-repo
[golint]: https://github.com/golang/lint
[golint readme]: https://github.com/golang/lint/blob/master/README
[gocov]: https://github.com/axw/gocov
[gocov-html]: https://github.com/matm/gocov-html
[well-formed commit messages]: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html
[squash]: http://git-scm.com/book/en/Git-Tools-Rewriting-History#Squashing-Commits
[pull request]: https://help.github.com/articles/creating-a-pull-request
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+71
View File
@@ -0,0 +1,71 @@
gofuzz
======
gofuzz is a library for populating go objects with random values.
[![GoDoc](https://godoc.org/github.com/google/gofuzz?status.png)](https://godoc.org/github.com/google/gofuzz)
[![Travis](https://travis-ci.org/google/gofuzz.svg?branch=master)](https://travis-ci.org/google/gofuzz)
This is useful for testing:
* Do your project's objects really serialize/unserialize correctly in all cases?
* Is there an incorrectly formatted object that will cause your project to panic?
Import with ```import "github.com/google/gofuzz"```
You can use it on single variables:
```
f := fuzz.New()
var myInt int
f.Fuzz(&myInt) // myInt gets a random value.
```
You can use it on maps:
```
f := fuzz.New().NilChance(0).NumElements(1, 1)
var myMap map[ComplexKeyType]string
f.Fuzz(&myMap) // myMap will have exactly one element.
```
Customize the chance of getting a nil pointer:
```
f := fuzz.New().NilChance(.5)
var fancyStruct struct {
A, B, C, D *string
}
f.Fuzz(&fancyStruct) // About half the pointers should be set.
```
You can even customize the randomization completely if needed:
```
type MyEnum string
const (
A MyEnum = "A"
B MyEnum = "B"
)
type MyInfo struct {
Type MyEnum
AInfo *string
BInfo *string
}
f := fuzz.New().NilChance(0).Funcs(
func(e *MyInfo, c fuzz.Continue) {
switch c.Intn(2) {
case 0:
e.Type = A
c.Fuzz(&e.AInfo)
case 1:
e.Type = B
c.Fuzz(&e.BInfo)
}
},
)
var myObject MyInfo
f.Fuzz(&myObject) // Type will correspond to whether A or B info is set.
```
See more examples in ```example_test.go```.
Happy testing!
+18
View File
@@ -0,0 +1,18 @@
/*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package fuzz is a library for populating go objects with random values.
package fuzz
+225
View File
@@ -0,0 +1,225 @@
/*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package fuzz_test
import (
"encoding/json"
"fmt"
"math/rand"
"github.com/google/gofuzz"
)
func ExampleSimple() {
type MyType struct {
A string
B string
C int
D struct {
E float64
}
}
f := fuzz.New()
object := MyType{}
uniqueObjects := map[MyType]int{}
for i := 0; i < 1000; i++ {
f.Fuzz(&object)
uniqueObjects[object]++
}
fmt.Printf("Got %v unique objects.\n", len(uniqueObjects))
// Output:
// Got 1000 unique objects.
}
func ExampleCustom() {
type MyType struct {
A int
B string
}
counter := 0
f := fuzz.New().Funcs(
func(i *int, c fuzz.Continue) {
*i = counter
counter++
},
)
object := MyType{}
uniqueObjects := map[MyType]int{}
for i := 0; i < 100; i++ {
f.Fuzz(&object)
if object.A != i {
fmt.Printf("Unexpected value: %#v\n", object)
}
uniqueObjects[object]++
}
fmt.Printf("Got %v unique objects.\n", len(uniqueObjects))
// Output:
// Got 100 unique objects.
}
func ExampleComplex() {
type OtherType struct {
A string
B string
}
type MyType struct {
Pointer *OtherType
Map map[string]OtherType
PointerMap *map[string]OtherType
Slice []OtherType
SlicePointer []*OtherType
PointerSlicePointer *[]*OtherType
}
f := fuzz.New().RandSource(rand.NewSource(0)).NilChance(0).NumElements(1, 1).Funcs(
func(o *OtherType, c fuzz.Continue) {
o.A = "Foo"
o.B = "Bar"
},
func(op **OtherType, c fuzz.Continue) {
*op = &OtherType{"A", "B"}
},
func(m map[string]OtherType, c fuzz.Continue) {
m["Works Because"] = OtherType{
"Fuzzer",
"Preallocated",
}
},
)
object := MyType{}
f.Fuzz(&object)
bytes, err := json.MarshalIndent(&object, "", " ")
if err != nil {
fmt.Printf("error: %v\n", err)
}
fmt.Printf("%s\n", string(bytes))
// Output:
// {
// "Pointer": {
// "A": "A",
// "B": "B"
// },
// "Map": {
// "Works Because": {
// "A": "Fuzzer",
// "B": "Preallocated"
// }
// },
// "PointerMap": {
// "Works Because": {
// "A": "Fuzzer",
// "B": "Preallocated"
// }
// },
// "Slice": [
// {
// "A": "Foo",
// "B": "Bar"
// }
// ],
// "SlicePointer": [
// {
// "A": "A",
// "B": "B"
// }
// ],
// "PointerSlicePointer": [
// {
// "A": "A",
// "B": "B"
// }
// ]
// }
}
func ExampleMap() {
f := fuzz.New().NilChance(0).NumElements(1, 1)
var myMap map[struct{ A, B, C int }]string
f.Fuzz(&myMap)
fmt.Printf("myMap has %v element(s).\n", len(myMap))
// Output:
// myMap has 1 element(s).
}
func ExampleSingle() {
f := fuzz.New()
var i int
f.Fuzz(&i)
// Technically, we'd expect this to fail one out of 2 billion attempts...
fmt.Printf("(i == 0) == %v", i == 0)
// Output:
// (i == 0) == false
}
func ExampleEnum() {
type MyEnum string
const (
A MyEnum = "A"
B MyEnum = "B"
)
type MyInfo struct {
Type MyEnum
AInfo *string
BInfo *string
}
f := fuzz.New().NilChance(0).Funcs(
func(e *MyInfo, c fuzz.Continue) {
// Note c's embedded Rand allows for direct use.
// We could also use c.RandBool() here.
switch c.Intn(2) {
case 0:
e.Type = A
c.Fuzz(&e.AInfo)
case 1:
e.Type = B
c.Fuzz(&e.BInfo)
}
},
)
for i := 0; i < 100; i++ {
var myObject MyInfo
f.Fuzz(&myObject)
switch myObject.Type {
case A:
if myObject.AInfo == nil {
fmt.Println("AInfo should have been set!")
}
if myObject.BInfo != nil {
fmt.Println("BInfo should NOT have been set!")
}
case B:
if myObject.BInfo == nil {
fmt.Println("BInfo should have been set!")
}
if myObject.AInfo != nil {
fmt.Println("AInfo should NOT have been set!")
}
default:
fmt.Println("Invalid enum value!")
}
}
// Output:
}
+446
View File
@@ -0,0 +1,446 @@
/*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package fuzz
import (
"fmt"
"math/rand"
"reflect"
"time"
)
// fuzzFuncMap is a map from a type to a fuzzFunc that handles that type.
type fuzzFuncMap map[reflect.Type]reflect.Value
// Fuzzer knows how to fill any object with random fields.
type Fuzzer struct {
fuzzFuncs fuzzFuncMap
defaultFuzzFuncs fuzzFuncMap
r *rand.Rand
nilChance float64
minElements int
maxElements int
}
// New returns a new Fuzzer. Customize your Fuzzer further by calling Funcs,
// RandSource, NilChance, or NumElements in any order.
func New() *Fuzzer {
f := &Fuzzer{
defaultFuzzFuncs: fuzzFuncMap{
reflect.TypeOf(&time.Time{}): reflect.ValueOf(fuzzTime),
},
fuzzFuncs: fuzzFuncMap{},
r: rand.New(rand.NewSource(time.Now().UnixNano())),
nilChance: .2,
minElements: 1,
maxElements: 10,
}
return f
}
// Funcs adds each entry in fuzzFuncs as a custom fuzzing function.
//
// Each entry in fuzzFuncs must be a function taking two parameters.
// The first parameter must be a pointer or map. It is the variable that
// function will fill with random data. The second parameter must be a
// fuzz.Continue, which will provide a source of randomness and a way
// to automatically continue fuzzing smaller pieces of the first parameter.
//
// These functions are called sensibly, e.g., if you wanted custom string
// fuzzing, the function `func(s *string, c fuzz.Continue)` would get
// called and passed the address of strings. Maps and pointers will always
// be made/new'd for you, ignoring the NilChange option. For slices, it
// doesn't make much sense to pre-create them--Fuzzer doesn't know how
// long you want your slice--so take a pointer to a slice, and make it
// yourself. (If you don't want your map/pointer type pre-made, take a
// pointer to it, and make it yourself.) See the examples for a range of
// custom functions.
func (f *Fuzzer) Funcs(fuzzFuncs ...interface{}) *Fuzzer {
for i := range fuzzFuncs {
v := reflect.ValueOf(fuzzFuncs[i])
if v.Kind() != reflect.Func {
panic("Need only funcs!")
}
t := v.Type()
if t.NumIn() != 2 || t.NumOut() != 0 {
panic("Need 2 in and 0 out params!")
}
argT := t.In(0)
switch argT.Kind() {
case reflect.Ptr, reflect.Map:
default:
panic("fuzzFunc must take pointer or map type")
}
if t.In(1) != reflect.TypeOf(Continue{}) {
panic("fuzzFunc's second parameter must be type fuzz.Continue")
}
f.fuzzFuncs[argT] = v
}
return f
}
// RandSource causes f to get values from the given source of randomness.
// Use if you want deterministic fuzzing.
func (f *Fuzzer) RandSource(s rand.Source) *Fuzzer {
f.r = rand.New(s)
return f
}
// NilChance sets the probability of creating a nil pointer, map, or slice to
// 'p'. 'p' should be between 0 (no nils) and 1 (all nils), inclusive.
func (f *Fuzzer) NilChance(p float64) *Fuzzer {
if p < 0 || p > 1 {
panic("p should be between 0 and 1, inclusive.")
}
f.nilChance = p
return f
}
// NumElements sets the minimum and maximum number of elements that will be
// added to a non-nil map or slice.
func (f *Fuzzer) NumElements(atLeast, atMost int) *Fuzzer {
if atLeast > atMost {
panic("atLeast must be <= atMost")
}
if atLeast < 0 {
panic("atLeast must be >= 0")
}
f.minElements = atLeast
f.maxElements = atMost
return f
}
func (f *Fuzzer) genElementCount() int {
if f.minElements == f.maxElements {
return f.minElements
}
return f.minElements + f.r.Intn(f.maxElements-f.minElements)
}
func (f *Fuzzer) genShouldFill() bool {
return f.r.Float64() > f.nilChance
}
// Fuzz recursively fills all of obj's fields with something random. First
// this tries to find a custom fuzz function (see Funcs). If there is no
// custom function this tests whether the object implements fuzz.Interface and,
// if so, calls Fuzz on it to fuzz itself. If that fails, this will see if
// there is a default fuzz function provided by this package. If all of that
// fails, this will generate random values for all primitive fields and then
// recurse for all non-primitives.
//
// Not safe for cyclic or tree-like structs!
//
// obj must be a pointer. Only exported (public) fields can be set (thanks, golang :/ )
// Intended for tests, so will panic on bad input or unimplemented fields.
func (f *Fuzzer) Fuzz(obj interface{}) {
v := reflect.ValueOf(obj)
if v.Kind() != reflect.Ptr {
panic("needed ptr!")
}
v = v.Elem()
f.doFuzz(v, 0)
}
// FuzzNoCustom is just like Fuzz, except that any custom fuzz function for
// obj's type will not be called and obj will not be tested for fuzz.Interface
// conformance. This applies only to obj and not other instances of obj's
// type.
// Not safe for cyclic or tree-like structs!
// obj must be a pointer. Only exported (public) fields can be set (thanks, golang :/ )
// Intended for tests, so will panic on bad input or unimplemented fields.
func (f *Fuzzer) FuzzNoCustom(obj interface{}) {
v := reflect.ValueOf(obj)
if v.Kind() != reflect.Ptr {
panic("needed ptr!")
}
v = v.Elem()
f.doFuzz(v, flagNoCustomFuzz)
}
const (
// Do not try to find a custom fuzz function. Does not apply recursively.
flagNoCustomFuzz uint64 = 1 << iota
)
func (f *Fuzzer) doFuzz(v reflect.Value, flags uint64) {
if !v.CanSet() {
return
}
if flags&flagNoCustomFuzz == 0 {
// Check for both pointer and non-pointer custom functions.
if v.CanAddr() && f.tryCustom(v.Addr()) {
return
}
if f.tryCustom(v) {
return
}
}
if fn, ok := fillFuncMap[v.Kind()]; ok {
fn(v, f.r)
return
}
switch v.Kind() {
case reflect.Map:
if f.genShouldFill() {
v.Set(reflect.MakeMap(v.Type()))
n := f.genElementCount()
for i := 0; i < n; i++ {
key := reflect.New(v.Type().Key()).Elem()
f.doFuzz(key, 0)
val := reflect.New(v.Type().Elem()).Elem()
f.doFuzz(val, 0)
v.SetMapIndex(key, val)
}
return
}
v.Set(reflect.Zero(v.Type()))
case reflect.Ptr:
if f.genShouldFill() {
v.Set(reflect.New(v.Type().Elem()))
f.doFuzz(v.Elem(), 0)
return
}
v.Set(reflect.Zero(v.Type()))
case reflect.Slice:
if f.genShouldFill() {
n := f.genElementCount()
v.Set(reflect.MakeSlice(v.Type(), n, n))
for i := 0; i < n; i++ {
f.doFuzz(v.Index(i), 0)
}
return
}
v.Set(reflect.Zero(v.Type()))
case reflect.Struct:
for i := 0; i < v.NumField(); i++ {
f.doFuzz(v.Field(i), 0)
}
case reflect.Array:
fallthrough
case reflect.Chan:
fallthrough
case reflect.Func:
fallthrough
case reflect.Interface:
fallthrough
default:
panic(fmt.Sprintf("Can't handle %#v", v.Interface()))
}
}
// tryCustom searches for custom handlers, and returns true iff it finds a match
// and successfully randomizes v.
func (f *Fuzzer) tryCustom(v reflect.Value) bool {
// First: see if we have a fuzz function for it.
doCustom, ok := f.fuzzFuncs[v.Type()]
if !ok {
// Second: see if it can fuzz itself.
if v.CanInterface() {
intf := v.Interface()
if fuzzable, ok := intf.(Interface); ok {
fuzzable.Fuzz(Continue{f: f, Rand: f.r})
return true
}
}
// Finally: see if there is a default fuzz function.
doCustom, ok = f.defaultFuzzFuncs[v.Type()]
if !ok {
return false
}
}
switch v.Kind() {
case reflect.Ptr:
if v.IsNil() {
if !v.CanSet() {
return false
}
v.Set(reflect.New(v.Type().Elem()))
}
case reflect.Map:
if v.IsNil() {
if !v.CanSet() {
return false
}
v.Set(reflect.MakeMap(v.Type()))
}
default:
return false
}
doCustom.Call([]reflect.Value{v, reflect.ValueOf(Continue{
f: f,
Rand: f.r,
})})
return true
}
// Interface represents an object that knows how to fuzz itself. Any time we
// find a type that implements this interface we will delegate the act of
// fuzzing itself.
type Interface interface {
Fuzz(c Continue)
}
// Continue can be passed to custom fuzzing functions to allow them to use
// the correct source of randomness and to continue fuzzing their members.
type Continue struct {
f *Fuzzer
// For convenience, Continue implements rand.Rand via embedding.
// Use this for generating any randomness if you want your fuzzing
// to be repeatable for a given seed.
*rand.Rand
}
// Fuzz continues fuzzing obj. obj must be a pointer.
func (c Continue) Fuzz(obj interface{}) {
v := reflect.ValueOf(obj)
if v.Kind() != reflect.Ptr {
panic("needed ptr!")
}
v = v.Elem()
c.f.doFuzz(v, 0)
}
// FuzzNoCustom continues fuzzing obj, except that any custom fuzz function for
// obj's type will not be called and obj will not be tested for fuzz.Interface
// conformance. This applies only to obj and not other instances of obj's
// type.
func (c Continue) FuzzNoCustom(obj interface{}) {
v := reflect.ValueOf(obj)
if v.Kind() != reflect.Ptr {
panic("needed ptr!")
}
v = v.Elem()
c.f.doFuzz(v, flagNoCustomFuzz)
}
// RandString makes a random string up to 20 characters long. The returned string
// may include a variety of (valid) UTF-8 encodings.
func (c Continue) RandString() string {
return randString(c.Rand)
}
// RandUint64 makes random 64 bit numbers.
// Weirdly, rand doesn't have a function that gives you 64 random bits.
func (c Continue) RandUint64() uint64 {
return randUint64(c.Rand)
}
// RandBool returns true or false randomly.
func (c Continue) RandBool() bool {
return randBool(c.Rand)
}
func fuzzInt(v reflect.Value, r *rand.Rand) {
v.SetInt(int64(randUint64(r)))
}
func fuzzUint(v reflect.Value, r *rand.Rand) {
v.SetUint(randUint64(r))
}
func fuzzTime(t *time.Time, c Continue) {
var sec, nsec int64
// Allow for about 1000 years of random time values, which keeps things
// like JSON parsing reasonably happy.
sec = c.Rand.Int63n(1000 * 365 * 24 * 60 * 60)
c.Fuzz(&nsec)
*t = time.Unix(sec, nsec)
}
var fillFuncMap = map[reflect.Kind]func(reflect.Value, *rand.Rand){
reflect.Bool: func(v reflect.Value, r *rand.Rand) {
v.SetBool(randBool(r))
},
reflect.Int: fuzzInt,
reflect.Int8: fuzzInt,
reflect.Int16: fuzzInt,
reflect.Int32: fuzzInt,
reflect.Int64: fuzzInt,
reflect.Uint: fuzzUint,
reflect.Uint8: fuzzUint,
reflect.Uint16: fuzzUint,
reflect.Uint32: fuzzUint,
reflect.Uint64: fuzzUint,
reflect.Uintptr: fuzzUint,
reflect.Float32: func(v reflect.Value, r *rand.Rand) {
v.SetFloat(float64(r.Float32()))
},
reflect.Float64: func(v reflect.Value, r *rand.Rand) {
v.SetFloat(r.Float64())
},
reflect.Complex64: func(v reflect.Value, r *rand.Rand) {
panic("unimplemented")
},
reflect.Complex128: func(v reflect.Value, r *rand.Rand) {
panic("unimplemented")
},
reflect.String: func(v reflect.Value, r *rand.Rand) {
v.SetString(randString(r))
},
reflect.UnsafePointer: func(v reflect.Value, r *rand.Rand) {
panic("unimplemented")
},
}
// randBool returns true or false randomly.
func randBool(r *rand.Rand) bool {
if r.Int()&1 == 1 {
return true
}
return false
}
type charRange struct {
first, last rune
}
// choose returns a random unicode character from the given range, using the
// given randomness source.
func (r *charRange) choose(rand *rand.Rand) rune {
count := int64(r.last - r.first)
return r.first + rune(rand.Int63n(count))
}
var unicodeRanges = []charRange{
{' ', '~'}, // ASCII characters
{'\u00a0', '\u02af'}, // Multi-byte encoded characters
{'\u4e00', '\u9fff'}, // Common CJK (even longer encodings)
}
// randString makes a random string up to 20 characters long. The returned string
// may include a variety of (valid) UTF-8 encodings.
func randString(r *rand.Rand) string {
n := r.Intn(20)
runes := make([]rune, n)
for i := range runes {
runes[i] = unicodeRanges[r.Intn(len(unicodeRanges))].choose(r)
}
return string(runes)
}
// randUint64 makes random 64 bit numbers.
// Weirdly, rand doesn't have a function that gives you 64 random bits.
func randUint64(r *rand.Rand) uint64 {
return uint64(r.Uint32())<<32 | uint64(r.Uint32())
}
+384
View File
@@ -0,0 +1,384 @@
/*
Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package fuzz
import (
"reflect"
"testing"
"time"
)
func TestFuzz_basic(t *testing.T) {
obj := &struct {
I int
I8 int8
I16 int16
I32 int32
I64 int64
U uint
U8 uint8
U16 uint16
U32 uint32
U64 uint64
Uptr uintptr
S string
B bool
T time.Time
}{}
failed := map[string]int{}
for i := 0; i < 10; i++ {
New().Fuzz(obj)
if n, v := "i", obj.I; v == 0 {
failed[n] = failed[n] + 1
}
if n, v := "i8", obj.I8; v == 0 {
failed[n] = failed[n] + 1
}
if n, v := "i16", obj.I16; v == 0 {
failed[n] = failed[n] + 1
}
if n, v := "i32", obj.I32; v == 0 {
failed[n] = failed[n] + 1
}
if n, v := "i64", obj.I64; v == 0 {
failed[n] = failed[n] + 1
}
if n, v := "u", obj.U; v == 0 {
failed[n] = failed[n] + 1
}
if n, v := "u8", obj.U8; v == 0 {
failed[n] = failed[n] + 1
}
if n, v := "u16", obj.U16; v == 0 {
failed[n] = failed[n] + 1
}
if n, v := "u32", obj.U32; v == 0 {
failed[n] = failed[n] + 1
}
if n, v := "u64", obj.U64; v == 0 {
failed[n] = failed[n] + 1
}
if n, v := "uptr", obj.Uptr; v == 0 {
failed[n] = failed[n] + 1
}
if n, v := "s", obj.S; v == "" {
failed[n] = failed[n] + 1
}
if n, v := "b", obj.B; v == false {
failed[n] = failed[n] + 1
}
if n, v := "t", obj.T; v.IsZero() {
failed[n] = failed[n] + 1
}
}
checkFailed(t, failed)
}
func checkFailed(t *testing.T, failed map[string]int) {
for k, v := range failed {
if v > 8 {
t.Errorf("%v seems to not be getting set, was zero value %v times", k, v)
}
}
}
func TestFuzz_structptr(t *testing.T) {
obj := &struct {
A *struct {
S string
}
}{}
f := New().NilChance(.5)
failed := map[string]int{}
for i := 0; i < 10; i++ {
f.Fuzz(obj)
if n, v := "a not nil", obj.A; v == nil {
failed[n] = failed[n] + 1
}
if n, v := "a nil", obj.A; v != nil {
failed[n] = failed[n] + 1
}
if n, v := "as", obj.A; v == nil || v.S == "" {
failed[n] = failed[n] + 1
}
}
checkFailed(t, failed)
}
// tryFuzz tries fuzzing up to 20 times. Fail if check() never passes, report the highest
// stage it ever got to.
func tryFuzz(t *testing.T, f *Fuzzer, obj interface{}, check func() (stage int, passed bool)) {
maxStage := 0
for i := 0; i < 20; i++ {
f.Fuzz(obj)
stage, passed := check()
if stage > maxStage {
maxStage = stage
}
if passed {
return
}
}
t.Errorf("Only ever got to stage %v", maxStage)
}
func TestFuzz_structmap(t *testing.T) {
obj := &struct {
A map[struct {
S string
}]struct {
S2 string
}
B map[string]string
}{}
tryFuzz(t, New(), obj, func() (int, bool) {
if obj.A == nil {
return 1, false
}
if len(obj.A) == 0 {
return 2, false
}
for k, v := range obj.A {
if k.S == "" {
return 3, false
}
if v.S2 == "" {
return 4, false
}
}
if obj.B == nil {
return 5, false
}
if len(obj.B) == 0 {
return 6, false
}
for k, v := range obj.B {
if k == "" {
return 7, false
}
if v == "" {
return 8, false
}
}
return 9, true
})
}
func TestFuzz_structslice(t *testing.T) {
obj := &struct {
A []struct {
S string
}
B []string
}{}
tryFuzz(t, New(), obj, func() (int, bool) {
if obj.A == nil {
return 1, false
}
if len(obj.A) == 0 {
return 2, false
}
for _, v := range obj.A {
if v.S == "" {
return 3, false
}
}
if obj.B == nil {
return 4, false
}
if len(obj.B) == 0 {
return 5, false
}
for _, v := range obj.B {
if v == "" {
return 6, false
}
}
return 7, true
})
}
func TestFuzz_custom(t *testing.T) {
obj := &struct {
A string
B *string
C map[string]string
D *map[string]string
}{}
testPhrase := "gotcalled"
testMap := map[string]string{"C": "D"}
f := New().Funcs(
func(s *string, c Continue) {
*s = testPhrase
},
func(m map[string]string, c Continue) {
m["C"] = "D"
},
)
tryFuzz(t, f, obj, func() (int, bool) {
if obj.A != testPhrase {
return 1, false
}
if obj.B == nil {
return 2, false
}
if *obj.B != testPhrase {
return 3, false
}
if e, a := testMap, obj.C; !reflect.DeepEqual(e, a) {
return 4, false
}
if obj.D == nil {
return 5, false
}
if e, a := testMap, *obj.D; !reflect.DeepEqual(e, a) {
return 6, false
}
return 7, true
})
}
type SelfFuzzer string
// Implement fuzz.Interface.
func (sf *SelfFuzzer) Fuzz(c Continue) {
*sf = selfFuzzerTestPhrase
}
const selfFuzzerTestPhrase = "was fuzzed"
func TestFuzz_interface(t *testing.T) {
f := New()
var obj1 SelfFuzzer
tryFuzz(t, f, &obj1, func() (int, bool) {
if obj1 != selfFuzzerTestPhrase {
return 1, false
}
return 1, true
})
var obj2 map[int]SelfFuzzer
tryFuzz(t, f, &obj2, func() (int, bool) {
for _, v := range obj2 {
if v != selfFuzzerTestPhrase {
return 1, false
}
}
return 1, true
})
}
func TestFuzz_interfaceAndFunc(t *testing.T) {
const privateTestPhrase = "private phrase"
f := New().Funcs(
// This should take precedence over SelfFuzzer.Fuzz().
func(s *SelfFuzzer, c Continue) {
*s = privateTestPhrase
},
)
var obj1 SelfFuzzer
tryFuzz(t, f, &obj1, func() (int, bool) {
if obj1 != privateTestPhrase {
return 1, false
}
return 1, true
})
var obj2 map[int]SelfFuzzer
tryFuzz(t, f, &obj2, func() (int, bool) {
for _, v := range obj2 {
if v != privateTestPhrase {
return 1, false
}
}
return 1, true
})
}
func TestFuzz_noCustom(t *testing.T) {
type Inner struct {
Str string
}
type Outer struct {
Str string
In Inner
}
testPhrase := "gotcalled"
f := New().Funcs(
func(outer *Outer, c Continue) {
outer.Str = testPhrase
c.Fuzz(&outer.In)
},
func(inner *Inner, c Continue) {
inner.Str = testPhrase
},
)
c := Continue{f: f, Rand: f.r}
// Fuzzer.Fuzz()
obj1 := Outer{}
f.Fuzz(&obj1)
if obj1.Str != testPhrase {
t.Errorf("expected Outer custom function to have been called")
}
if obj1.In.Str != testPhrase {
t.Errorf("expected Inner custom function to have been called")
}
// Continue.Fuzz()
obj2 := Outer{}
c.Fuzz(&obj2)
if obj2.Str != testPhrase {
t.Errorf("expected Outer custom function to have been called")
}
if obj2.In.Str != testPhrase {
t.Errorf("expected Inner custom function to have been called")
}
// Fuzzer.FuzzNoCustom()
obj3 := Outer{}
f.FuzzNoCustom(&obj3)
if obj3.Str == testPhrase {
t.Errorf("expected Outer custom function to not have been called")
}
if obj3.In.Str != testPhrase {
t.Errorf("expected Inner custom function to have been called")
}
// Continue.FuzzNoCustom()
obj4 := Outer{}
c.FuzzNoCustom(&obj4)
if obj4.Str == testPhrase {
t.Errorf("expected Outer custom function to not have been called")
}
if obj4.In.Str != testPhrase {
t.Errorf("expected Inner custom function to have been called")
}
}
+28
View File
@@ -0,0 +1,28 @@
Copyright (c) 2012 Alex Ogier. All rights reserved.
Copyright (c) 2012 The Go Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+155
View File
@@ -0,0 +1,155 @@
## Description
pflag is a drop-in replacement for Go's flag package, implementing
POSIX/GNU-style --flags.
pflag is compatible with the [GNU extensions to the POSIX recommendations
for command-line options][1]. For a more precise description, see the
"Command-line flag syntax" section below.
[1]: http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html
pflag is available under the same style of BSD license as the Go language,
which can be found in the LICENSE file.
## Installation
pflag is available using the standard `go get` command.
Install by running:
go get github.com/ogier/pflag
Run tests by running:
go test github.com/ogier/pflag
## Usage
pflag is a drop-in replacement of Go's native flag package. If you import
pflag under the name "flag" then all code should continue to function
with no changes.
``` go
import flag "github.com/ogier/pflag"
```
There is one exception to this: if you directly instantiate the Flag struct
there is one more field "Shorthand" that you will need to set.
Most code never instantiates this struct directly, and instead uses
functions such as String(), BoolVar(), and Var(), and is therefore
unaffected.
Define flags using flag.String(), Bool(), Int(), etc.
This declares an integer flag, -flagname, stored in the pointer ip, with type *int.
``` go
var ip *int = flag.Int("flagname", 1234, "help message for flagname")
```
If you like, you can bind the flag to a variable using the Var() functions.
``` go
var flagvar int
func init() {
flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
}
```
Or you can create custom flags that satisfy the Value interface (with
pointer receivers) and couple them to flag parsing by
``` go
flag.Var(&flagVal, "name", "help message for flagname")
```
For such flags, the default value is just the initial value of the variable.
After all flags are defined, call
``` go
flag.Parse()
```
to parse the command line into the defined flags.
Flags may then be used directly. If you're using the flags themselves,
they are all pointers; if you bind to variables, they're values.
``` go
fmt.Println("ip has value ", *ip)
fmt.Println("flagvar has value ", flagvar)
```
After parsing, the arguments after the flag are available as the
slice flag.Args() or individually as flag.Arg(i).
The arguments are indexed from 0 through flag.NArg()-1.
The pflag package also defines some new functions that are not in flag,
that give one-letter shorthands for flags. You can use these by appending
'P' to the name of any function that defines a flag.
``` go
var ip = flag.IntP("flagname", "f", 1234, "help message")
var flagvar bool
func init() {
flag.BoolVarP("boolname", "b", true, "help message")
}
flag.VarP(&flagVar, "varname", "v", 1234, "help message")
```
Shorthand letters can be used with single dashes on the command line.
Boolean shorthand flags can be combined with other shorthand flags.
The default set of command-line flags is controlled by
top-level functions. The FlagSet type allows one to define
independent sets of flags, such as to implement subcommands
in a command-line interface. The methods of FlagSet are
analogous to the top-level functions for the command-line
flag set.
## Command line flag syntax
```
--flag // boolean flags only
--flag=x
```
Unlike the flag package, a single dash before an option means something
different than a double dash. Single dashes signify a series of shorthand
letters for flags. All but the last shorthand letter must be boolean flags.
```
// boolean flags
-f
-abc
// non-boolean flags
-n 1234
-Ifile
// mixed
-abcs "hello"
-abcn1234
```
Flag parsing stops after the terminator "--". Unlike the flag package,
flags can be interspersed with arguments anywhere on the command line
before this terminator.
Integer flags accept 1234, 0664, 0x1234 and may be negative.
Boolean flags (in their long form) accept 1, 0, t, f, true, false,
TRUE, FALSE, True, False.
Duration flags accept any input valid for time.ParseDuration.
## More info
You can see the full reference documentation of the pflag package
[at godoc.org][3], or through go's standard documentation system by
running `godoc -http=:6060` and browsing to
[http://localhost:6060/pkg/github.com/ogier/pflag][2] after
installation.
[2]: http://localhost:6060/pkg/github.com/ogier/pflag
[3]: http://godoc.org/github.com/ogier/pflag
+83
View File
@@ -0,0 +1,83 @@
package pflag
import (
"fmt"
"strconv"
)
// optional interface to indicate boolean flags that can be
// supplied without "=value" text
type boolFlag interface {
Value
IsBoolFlag() bool
}
// -- bool Value
type boolValue bool
func newBoolValue(val bool, p *bool) *boolValue {
*p = val
return (*boolValue)(p)
}
func (b *boolValue) Set(s string) error {
v, err := strconv.ParseBool(s)
*b = boolValue(v)
return err
}
func (b *boolValue) Type() string {
return "bool"
}
func (b *boolValue) String() string { return fmt.Sprintf("%v", *b) }
func (b *boolValue) IsBoolFlag() bool { return true }
// BoolVar defines a bool flag with specified name, default value, and usage string.
// The argument p points to a bool variable in which to store the value of the flag.
func (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) {
f.VarP(newBoolValue(value, p), name, "", usage)
}
// Like BoolVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) BoolVarP(p *bool, name, shorthand string, value bool, usage string) {
f.VarP(newBoolValue(value, p), name, shorthand, usage)
}
// BoolVar defines a bool flag with specified name, default value, and usage string.
// The argument p points to a bool variable in which to store the value of the flag.
func BoolVar(p *bool, name string, value bool, usage string) {
CommandLine.VarP(newBoolValue(value, p), name, "", usage)
}
// Like BoolVar, but accepts a shorthand letter that can be used after a single dash.
func BoolVarP(p *bool, name, shorthand string, value bool, usage string) {
CommandLine.VarP(newBoolValue(value, p), name, shorthand, usage)
}
// Bool defines a bool flag with specified name, default value, and usage string.
// The return value is the address of a bool variable that stores the value of the flag.
func (f *FlagSet) Bool(name string, value bool, usage string) *bool {
p := new(bool)
f.BoolVarP(p, name, "", value, usage)
return p
}
// Like Bool, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) BoolP(name, shorthand string, value bool, usage string) *bool {
p := new(bool)
f.BoolVarP(p, name, shorthand, value, usage)
return p
}
// Bool defines a bool flag with specified name, default value, and usage string.
// The return value is the address of a bool variable that stores the value of the flag.
func Bool(name string, value bool, usage string) *bool {
return CommandLine.BoolP(name, "", value, usage)
}
// Like Bool, but accepts a shorthand letter that can be used after a single dash.
func BoolP(name, shorthand string, value bool, usage string) *bool {
return CommandLine.BoolP(name, shorthand, value, usage)
}
+163
View File
@@ -0,0 +1,163 @@
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package pflag_test
import (
"fmt"
"strconv"
"testing"
. "github.com/ogier/pflag"
)
// This value can be a boolean ("true", "false") or "maybe"
type triStateValue int
const (
triStateFalse triStateValue = 0
triStateTrue triStateValue = 1
triStateMaybe triStateValue = 2
)
const strTriStateMaybe = "maybe"
func (v *triStateValue) IsBoolFlag() bool {
return true
}
func (v *triStateValue) Get() interface{} {
return triStateValue(*v)
}
func (v *triStateValue) Set(s string) error {
if s == strTriStateMaybe {
*v = triStateMaybe
return nil
}
boolVal, err := strconv.ParseBool(s)
if boolVal {
*v = triStateTrue
} else {
*v = triStateFalse
}
return err
}
func (v *triStateValue) String() string {
if *v == triStateMaybe {
return strTriStateMaybe
}
return fmt.Sprintf("%v", bool(*v == triStateTrue))
}
// The type of the flag as requred by the pflag.Value interface
func (v *triStateValue) Type() string {
return "version"
}
func setUpFlagSet(tristate *triStateValue) *FlagSet {
f := NewFlagSet("test", ContinueOnError)
*tristate = triStateFalse
f.VarP(tristate, "tristate", "t", "tristate value (true, maybe or false)")
return f
}
func TestExplicitTrue(t *testing.T) {
var tristate triStateValue
f := setUpFlagSet(&tristate)
err := f.Parse([]string{"--tristate=true"})
if err != nil {
t.Fatal("expected no error; got", err)
}
if tristate != triStateTrue {
t.Fatal("expected", triStateTrue, "(triStateTrue) but got", tristate, "instead")
}
}
func TestImplicitTrue(t *testing.T) {
var tristate triStateValue
f := setUpFlagSet(&tristate)
err := f.Parse([]string{"--tristate"})
if err != nil {
t.Fatal("expected no error; got", err)
}
if tristate != triStateTrue {
t.Fatal("expected", triStateTrue, "(triStateTrue) but got", tristate, "instead")
}
}
func TestShortFlag(t *testing.T) {
var tristate triStateValue
f := setUpFlagSet(&tristate)
err := f.Parse([]string{"-t"})
if err != nil {
t.Fatal("expected no error; got", err)
}
if tristate != triStateTrue {
t.Fatal("expected", triStateTrue, "(triStateTrue) but got", tristate, "instead")
}
}
func TestShortFlagExtraArgument(t *testing.T) {
var tristate triStateValue
f := setUpFlagSet(&tristate)
// The"maybe"turns into an arg, since short boolean options will only do true/false
err := f.Parse([]string{"-t", "maybe"})
if err != nil {
t.Fatal("expected no error; got", err)
}
if tristate != triStateTrue {
t.Fatal("expected", triStateTrue, "(triStateTrue) but got", tristate, "instead")
}
args := f.Args()
if len(args) != 1 || args[0] != "maybe" {
t.Fatal("expected an extra 'maybe' argument to stick around")
}
}
func TestExplicitMaybe(t *testing.T) {
var tristate triStateValue
f := setUpFlagSet(&tristate)
err := f.Parse([]string{"--tristate=maybe"})
if err != nil {
t.Fatal("expected no error; got", err)
}
if tristate != triStateMaybe {
t.Fatal("expected", triStateMaybe, "(triStateMaybe) but got", tristate, "instead")
}
}
func TestExplicitFalse(t *testing.T) {
var tristate triStateValue
f := setUpFlagSet(&tristate)
err := f.Parse([]string{"--tristate=false"})
if err != nil {
t.Fatal("expected no error; got", err)
}
if tristate != triStateFalse {
t.Fatal("expected", triStateFalse, "(triStateFalse) but got", tristate, "instead")
}
}
func TestImplicitFalse(t *testing.T) {
var tristate triStateValue
f := setUpFlagSet(&tristate)
err := f.Parse([]string{})
if err != nil {
t.Fatal("expected no error; got", err)
}
if tristate != triStateFalse {
t.Fatal("expected", triStateFalse, "(triStateFalse) but got", tristate, "instead")
}
}
func TestInvalidValue(t *testing.T) {
var tristate triStateValue
f := setUpFlagSet(&tristate)
err := f.Parse([]string{"--tristate=invalid"})
if err == nil {
t.Fatal("expected an error but did not get any, tristate has value", tristate)
}
}
+71
View File
@@ -0,0 +1,71 @@
package pflag
import "time"
// -- time.Duration Value
type durationValue time.Duration
func newDurationValue(val time.Duration, p *time.Duration) *durationValue {
*p = val
return (*durationValue)(p)
}
func (d *durationValue) Set(s string) error {
v, err := time.ParseDuration(s)
*d = durationValue(v)
return err
}
func (d *durationValue) Type() string {
return "duration"
}
func (d *durationValue) String() string { return (*time.Duration)(d).String() }
// DurationVar defines a time.Duration flag with specified name, default value, and usage string.
// The argument p points to a time.Duration variable in which to store the value of the flag.
func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
f.VarP(newDurationValue(value, p), name, "", usage)
}
// Like DurationVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) DurationVarP(p *time.Duration, name, shorthand string, value time.Duration, usage string) {
f.VarP(newDurationValue(value, p), name, shorthand, usage)
}
// DurationVar defines a time.Duration flag with specified name, default value, and usage string.
// The argument p points to a time.Duration variable in which to store the value of the flag.
func DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
CommandLine.VarP(newDurationValue(value, p), name, "", usage)
}
// Like DurationVar, but accepts a shorthand letter that can be used after a single dash.
func DurationVarP(p *time.Duration, name, shorthand string, value time.Duration, usage string) {
CommandLine.VarP(newDurationValue(value, p), name, shorthand, usage)
}
// Duration defines a time.Duration flag with specified name, default value, and usage string.
// The return value is the address of a time.Duration variable that stores the value of the flag.
func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time.Duration {
p := new(time.Duration)
f.DurationVarP(p, name, "", value, usage)
return p
}
// Like Duration, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) DurationP(name, shorthand string, value time.Duration, usage string) *time.Duration {
p := new(time.Duration)
f.DurationVarP(p, name, shorthand, value, usage)
return p
}
// Duration defines a time.Duration flag with specified name, default value, and usage string.
// The return value is the address of a time.Duration variable that stores the value of the flag.
func Duration(name string, value time.Duration, usage string) *time.Duration {
return CommandLine.DurationP(name, "", value, usage)
}
// Like Duration, but accepts a shorthand letter that can be used after a single dash.
func DurationP(name, shorthand string, value time.Duration, usage string) *time.Duration {
return CommandLine.DurationP(name, shorthand, value, usage)
}
+77
View File
@@ -0,0 +1,77 @@
// Copyright 2012 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// These examples demonstrate more intricate uses of the flag package.
package pflag_test
import (
"errors"
"fmt"
"strings"
"time"
flag "github.com/ogier/pflag"
)
// Example 1: A single string flag called "species" with default value "gopher".
var species = flag.String("species", "gopher", "the species we are studying")
// Example 2: A flag with a shorthand letter.
var gopherType = flag.StringP("gopher_type", "g", "pocket", "the variety of gopher")
// Example 3: A user-defined flag type, a slice of durations.
type interval []time.Duration
// String is the method to format the flag's value, part of the flag.Value interface.
// The String method's output will be used in diagnostics.
func (i *interval) String() string {
return fmt.Sprint(*i)
}
func (i *interval) Type() string {
return "interval"
}
// Set is the method to set the flag value, part of the flag.Value interface.
// Set's argument is a string to be parsed to set the flag.
// It's a comma-separated list, so we split it.
func (i *interval) Set(value string) error {
// If we wanted to allow the flag to be set multiple times,
// accumulating values, we would delete this if statement.
// That would permit usages such as
// -deltaT 10s -deltaT 15s
// and other combinations.
if len(*i) > 0 {
return errors.New("interval flag already set")
}
for _, dt := range strings.Split(value, ",") {
duration, err := time.ParseDuration(dt)
if err != nil {
return err
}
*i = append(*i, duration)
}
return nil
}
// Define a flag to accumulate durations. Because it has a special type,
// we need to use the Var function and therefore create the flag during
// init.
var intervalFlag interval
func init() {
// Tie the command-line flag to the intervalFlag variable and
// set a usage message.
flag.Var(&intervalFlag, "deltaT", "comma-separated list of intervals to use between events")
}
func Example() {
// All the interesting pieces are with the variables declared above, but
// to enable the flag package to see the flags defined there, one must
// execute, typically at the start of main (not init!):
// flag.Parse()
// We don't run it here because this is not a main function and
// the testing suite has already parsed the flags.
}
+29
View File
@@ -0,0 +1,29 @@
// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package pflag
import (
"io/ioutil"
"os"
)
// Additional routines compiled into the package only during testing.
// ResetForTesting clears all flag state and sets the usage function as directed.
// After calling ResetForTesting, parse errors in flag handling will not
// exit the program.
func ResetForTesting(usage func()) {
CommandLine = &FlagSet{
name: os.Args[0],
errorHandling: ContinueOnError,
output: ioutil.Discard,
}
Usage = usage
}
// GetCommandLine returns the default FlagSet.
func GetCommandLine() *FlagSet {
return CommandLine
}
+626
View File
@@ -0,0 +1,626 @@
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
pflag is a drop-in replacement for Go's flag package, implementing
POSIX/GNU-style --flags.
pflag is compatible with the GNU extensions to the POSIX recommendations
for command-line options. See
http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html
Usage:
pflag is a drop-in replacement of Go's native flag package. If you import
pflag under the name "flag" then all code should continue to function
with no changes.
import flag "github.com/ogier/pflag"
There is one exception to this: if you directly instantiate the Flag struct
there is one more field "Shorthand" that you will need to set.
Most code never instantiates this struct directly, and instead uses
functions such as String(), BoolVar(), and Var(), and is therefore
unaffected.
Define flags using flag.String(), Bool(), Int(), etc.
This declares an integer flag, -flagname, stored in the pointer ip, with type *int.
var ip = flag.Int("flagname", 1234, "help message for flagname")
If you like, you can bind the flag to a variable using the Var() functions.
var flagvar int
func init() {
flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
}
Or you can create custom flags that satisfy the Value interface (with
pointer receivers) and couple them to flag parsing by
flag.Var(&flagVal, "name", "help message for flagname")
For such flags, the default value is just the initial value of the variable.
After all flags are defined, call
flag.Parse()
to parse the command line into the defined flags.
Flags may then be used directly. If you're using the flags themselves,
they are all pointers; if you bind to variables, they're values.
fmt.Println("ip has value ", *ip)
fmt.Println("flagvar has value ", flagvar)
After parsing, the arguments after the flag are available as the
slice flag.Args() or individually as flag.Arg(i).
The arguments are indexed from 0 through flag.NArg()-1.
The pflag package also defines some new functions that are not in flag,
that give one-letter shorthands for flags. You can use these by appending
'P' to the name of any function that defines a flag.
var ip = flag.IntP("flagname", "f", 1234, "help message")
var flagvar bool
func init() {
flag.BoolVarP("boolname", "b", true, "help message")
}
flag.VarP(&flagVar, "varname", "v", 1234, "help message")
Shorthand letters can be used with single dashes on the command line.
Boolean shorthand flags can be combined with other shorthand flags.
Command line flag syntax:
--flag // boolean flags only
--flag=x
Unlike the flag package, a single dash before an option means something
different than a double dash. Single dashes signify a series of shorthand
letters for flags. All but the last shorthand letter must be boolean flags.
// boolean flags
-f
-abc
// non-boolean flags
-n 1234
-Ifile
// mixed
-abcs "hello"
-abcn1234
Flag parsing stops after the terminator "--". Unlike the flag package,
flags can be interspersed with arguments anywhere on the command line
before this terminator.
Integer flags accept 1234, 0664, 0x1234 and may be negative.
Boolean flags (in their long form) accept 1, 0, t, f, true, false,
TRUE, FALSE, True, False.
Duration flags accept any input valid for time.ParseDuration.
The default set of command-line flags is controlled by
top-level functions. The FlagSet type allows one to define
independent sets of flags, such as to implement subcommands
in a command-line interface. The methods of FlagSet are
analogous to the top-level functions for the command-line
flag set.
*/
package pflag
import (
"bytes"
"errors"
"fmt"
"io"
"os"
"sort"
"strings"
)
// ErrHelp is the error returned if the flag -help is invoked but no such flag is defined.
var ErrHelp = errors.New("pflag: help requested")
// ErrorHandling defines how to handle flag parsing errors.
type ErrorHandling int
const (
ContinueOnError ErrorHandling = iota
ExitOnError
PanicOnError
)
// A FlagSet represents a set of defined flags.
type FlagSet struct {
// Usage is the function called when an error occurs while parsing flags.
// The field is a function (not a method) that may be changed to point to
// a custom error handler.
Usage func()
name string
parsed bool
actual map[string]*Flag
formal map[string]*Flag
shorthands map[byte]*Flag
args []string // arguments after flags
exitOnError bool // does the program exit if there's an error?
errorHandling ErrorHandling
output io.Writer // nil means stderr; use out() accessor
interspersed bool // allow interspersed option/non-option args
}
// A Flag represents the state of a flag.
type Flag struct {
Name string // name as it appears on command line
Shorthand string // one-letter abbreviated flag
Usage string // help message
Value Value // value as set
DefValue string // default value (as text); for usage message
Changed bool // If the user set the value (or if left to default)
}
// Value is the interface to the dynamic value stored in a flag.
// (The default value is represented as a string.)
type Value interface {
String() string
Set(string) error
Type() string
}
// sortFlags returns the flags as a slice in lexicographical sorted order.
func sortFlags(flags map[string]*Flag) []*Flag {
list := make(sort.StringSlice, len(flags))
i := 0
for _, f := range flags {
list[i] = f.Name
i++
}
list.Sort()
result := make([]*Flag, len(list))
for i, name := range list {
result[i] = flags[name]
}
return result
}
func (f *FlagSet) out() io.Writer {
if f.output == nil {
return os.Stderr
}
return f.output
}
// SetOutput sets the destination for usage and error messages.
// If output is nil, os.Stderr is used.
func (f *FlagSet) SetOutput(output io.Writer) {
f.output = output
}
// VisitAll visits the flags in lexicographical order, calling fn for each.
// It visits all flags, even those not set.
func (f *FlagSet) VisitAll(fn func(*Flag)) {
for _, flag := range sortFlags(f.formal) {
fn(flag)
}
}
func (f *FlagSet) HasFlags() bool {
return len(f.formal) > 0
}
// VisitAll visits the command-line flags in lexicographical order, calling
// fn for each. It visits all flags, even those not set.
func VisitAll(fn func(*Flag)) {
CommandLine.VisitAll(fn)
}
// Visit visits the flags in lexicographical order, calling fn for each.
// It visits only those flags that have been set.
func (f *FlagSet) Visit(fn func(*Flag)) {
for _, flag := range sortFlags(f.actual) {
fn(flag)
}
}
// Visit visits the command-line flags in lexicographical order, calling fn
// for each. It visits only those flags that have been set.
func Visit(fn func(*Flag)) {
CommandLine.Visit(fn)
}
// Lookup returns the Flag structure of the named flag, returning nil if none exists.
func (f *FlagSet) Lookup(name string) *Flag {
return f.formal[name]
}
// Lookup returns the Flag structure of the named command-line flag,
// returning nil if none exists.
func Lookup(name string) *Flag {
return CommandLine.formal[name]
}
// Set sets the value of the named flag.
func (f *FlagSet) Set(name, value string) error {
flag, ok := f.formal[name]
if !ok {
return fmt.Errorf("no such flag -%v", name)
}
err := flag.Value.Set(value)
if err != nil {
return err
}
if f.actual == nil {
f.actual = make(map[string]*Flag)
}
f.actual[name] = flag
f.Lookup(name).Changed = true
return nil
}
// Set sets the value of the named command-line flag.
func Set(name, value string) error {
return CommandLine.Set(name, value)
}
// PrintDefaults prints, to standard error unless configured
// otherwise, the default values of all defined flags in the set.
func (f *FlagSet) PrintDefaults() {
f.VisitAll(func(flag *Flag) {
format := "--%s=%s: %s\n"
if _, ok := flag.Value.(*stringValue); ok {
// put quotes on the value
format = "--%s=%q: %s\n"
}
if len(flag.Shorthand) > 0 {
format = " -%s, " + format
} else {
format = " %s " + format
}
fmt.Fprintf(f.out(), format, flag.Shorthand, flag.Name, flag.DefValue, flag.Usage)
})
}
func (f *FlagSet) FlagUsages() string {
x := new(bytes.Buffer)
f.VisitAll(func(flag *Flag) {
format := "--%s=%s: %s\n"
if _, ok := flag.Value.(*stringValue); ok {
// put quotes on the value
format = "--%s=%q: %s\n"
}
if len(flag.Shorthand) > 0 {
format = " -%s, " + format
} else {
format = " %s " + format
}
fmt.Fprintf(x, format, flag.Shorthand, flag.Name, flag.DefValue, flag.Usage)
})
return x.String()
}
// PrintDefaults prints to standard error the default values of all defined command-line flags.
func PrintDefaults() {
CommandLine.PrintDefaults()
}
// defaultUsage is the default function to print a usage message.
func defaultUsage(f *FlagSet) {
fmt.Fprintf(f.out(), "Usage of %s:\n", f.name)
f.PrintDefaults()
}
// NOTE: Usage is not just defaultUsage(CommandLine)
// because it serves (via godoc flag Usage) as the example
// for how to write your own usage function.
// Usage prints to standard error a usage message documenting all defined command-line flags.
// The function is a variable that may be changed to point to a custom function.
var Usage = func() {
fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
PrintDefaults()
}
// NFlag returns the number of flags that have been set.
func (f *FlagSet) NFlag() int { return len(f.actual) }
// NFlag returns the number of command-line flags that have been set.
func NFlag() int { return len(CommandLine.actual) }
// Arg returns the i'th argument. Arg(0) is the first remaining argument
// after flags have been processed.
func (f *FlagSet) Arg(i int) string {
if i < 0 || i >= len(f.args) {
return ""
}
return f.args[i]
}
// Arg returns the i'th command-line argument. Arg(0) is the first remaining argument
// after flags have been processed.
func Arg(i int) string {
return CommandLine.Arg(i)
}
// NArg is the number of arguments remaining after flags have been processed.
func (f *FlagSet) NArg() int { return len(f.args) }
// NArg is the number of arguments remaining after flags have been processed.
func NArg() int { return len(CommandLine.args) }
// Args returns the non-flag arguments.
func (f *FlagSet) Args() []string { return f.args }
// Args returns the non-flag command-line arguments.
func Args() []string { return CommandLine.args }
// Var defines a flag with the specified name and usage string. The type and
// value of the flag are represented by the first argument, of type Value, which
// typically holds a user-defined implementation of Value. For instance, the
// caller could create a flag that turns a comma-separated string into a slice
// of strings by giving the slice the methods of Value; in particular, Set would
// decompose the comma-separated string into the slice.
func (f *FlagSet) Var(value Value, name string, usage string) {
f.VarP(value, name, "", usage)
}
// Like Var, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) VarP(value Value, name, shorthand, usage string) {
// Remember the default value as a string; it won't change.
flag := &Flag{name, shorthand, usage, value, value.String(), false}
f.AddFlag(flag)
}
func (f *FlagSet) AddFlag(flag *Flag) {
_, alreadythere := f.formal[flag.Name]
if alreadythere {
msg := fmt.Sprintf("%s flag redefined: %s", f.name, flag.Name)
fmt.Fprintln(f.out(), msg)
panic(msg) // Happens only if flags are declared with identical names
}
if f.formal == nil {
f.formal = make(map[string]*Flag)
}
f.formal[flag.Name] = flag
if len(flag.Shorthand) == 0 {
return
}
if len(flag.Shorthand) > 1 {
fmt.Fprintf(f.out(), "%s shorthand more than ASCII character: %s\n", f.name, flag.Shorthand)
panic("shorthand is more than one character")
}
if f.shorthands == nil {
f.shorthands = make(map[byte]*Flag)
}
c := flag.Shorthand[0]
old, alreadythere := f.shorthands[c]
if alreadythere {
fmt.Fprintf(f.out(), "%s shorthand reused: %q for %s already used for %s\n", f.name, c, flag.Name, old.Name)
panic("shorthand redefinition")
}
f.shorthands[c] = flag
}
// Var defines a flag with the specified name and usage string. The type and
// value of the flag are represented by the first argument, of type Value, which
// typically holds a user-defined implementation of Value. For instance, the
// caller could create a flag that turns a comma-separated string into a slice
// of strings by giving the slice the methods of Value; in particular, Set would
// decompose the comma-separated string into the slice.
func Var(value Value, name string, usage string) {
CommandLine.VarP(value, name, "", usage)
}
// Like Var, but accepts a shorthand letter that can be used after a single dash.
func VarP(value Value, name, shorthand, usage string) {
CommandLine.VarP(value, name, shorthand, usage)
}
// failf prints to standard error a formatted error and usage message and
// returns the error.
func (f *FlagSet) failf(format string, a ...interface{}) error {
err := fmt.Errorf(format, a...)
fmt.Fprintln(f.out(), err)
f.usage()
return err
}
// usage calls the Usage method for the flag set, or the usage function if
// the flag set is CommandLine.
func (f *FlagSet) usage() {
if f == CommandLine {
Usage()
} else if f.Usage == nil {
defaultUsage(f)
} else {
f.Usage()
}
}
func (f *FlagSet) setFlag(flag *Flag, value string, origArg string) error {
if err := flag.Value.Set(value); err != nil {
return f.failf("invalid argument %q for %s: %v", value, origArg, err)
}
// mark as visited for Visit()
if f.actual == nil {
f.actual = make(map[string]*Flag)
}
f.actual[flag.Name] = flag
flag.Changed = true
return nil
}
func (f *FlagSet) parseLongArg(s string, args []string) (a []string, err error) {
a = args
if len(s) == 2 { // "--" terminates the flags
f.args = append(f.args, args...)
return
}
name := s[2:]
if len(name) == 0 || name[0] == '-' || name[0] == '=' {
err = f.failf("bad flag syntax: %s", s)
return
}
split := strings.SplitN(name, "=", 2)
name = split[0]
m := f.formal
flag, alreadythere := m[name] // BUG
if !alreadythere {
if name == "help" { // special case for nice help message.
f.usage()
return args, ErrHelp
}
err = f.failf("unknown flag: --%s", name)
return
}
if len(split) == 1 {
if bv, ok := flag.Value.(boolFlag); !ok || !bv.IsBoolFlag() {
err = f.failf("flag needs an argument: %s", s)
return
}
f.setFlag(flag, "true", s)
} else {
if e := f.setFlag(flag, split[1], s); e != nil {
err = e
return
}
}
return args, nil
}
func (f *FlagSet) parseShortArg(s string, args []string) (a []string, err error) {
a = args
shorthands := s[1:]
for i := 0; i < len(shorthands); i++ {
c := shorthands[i]
flag, alreadythere := f.shorthands[c]
if !alreadythere {
if c == 'h' { // special case for nice help message.
f.usage()
err = ErrHelp
return
}
//TODO continue on error
err = f.failf("unknown shorthand flag: %q in -%s", c, shorthands)
if len(args) == 0 {
return
}
}
if alreadythere {
if bv, ok := flag.Value.(boolFlag); ok && bv.IsBoolFlag() {
f.setFlag(flag, "true", s)
continue
}
if i < len(shorthands)-1 {
if e := f.setFlag(flag, shorthands[i+1:], s); e != nil {
err = e
return
}
break
}
if len(args) == 0 {
err = f.failf("flag needs an argument: %q in -%s", c, shorthands)
return
}
if e := f.setFlag(flag, args[0], s); e != nil {
err = e
return
}
}
a = args[1:]
break // should be unnecessary
}
return
}
func (f *FlagSet) parseArgs(args []string) (err error) {
for len(args) > 0 {
s := args[0]
args = args[1:]
if len(s) == 0 || s[0] != '-' || len(s) == 1 {
if !f.interspersed {
f.args = append(f.args, s)
f.args = append(f.args, args...)
return nil
}
f.args = append(f.args, s)
continue
}
if s[1] == '-' {
args, err = f.parseLongArg(s, args)
if len(s) == 2 {
// stop parsing after --
break
}
} else {
args, err = f.parseShortArg(s, args)
}
}
return
}
// Parse parses flag definitions from the argument list, which should not
// include the command name. Must be called after all flags in the FlagSet
// are defined and before flags are accessed by the program.
// The return value will be ErrHelp if -help was set but not defined.
func (f *FlagSet) Parse(arguments []string) error {
f.parsed = true
f.args = make([]string, 0, len(arguments))
err := f.parseArgs(arguments)
if err != nil {
switch f.errorHandling {
case ContinueOnError:
return err
case ExitOnError:
os.Exit(2)
case PanicOnError:
panic(err)
}
}
return nil
}
// Parsed reports whether f.Parse has been called.
func (f *FlagSet) Parsed() bool {
return f.parsed
}
// Parse parses the command-line flags from os.Args[1:]. Must be called
// after all flags are defined and before flags are accessed by the program.
func Parse() {
// Ignore errors; CommandLine is set for ExitOnError.
CommandLine.Parse(os.Args[1:])
}
// Whether to support interspersed option/non-option arguments.
func SetInterspersed(interspersed bool) {
CommandLine.SetInterspersed(interspersed)
}
// Parsed returns true if the command-line flags have been parsed.
func Parsed() bool {
return CommandLine.Parsed()
}
// The default set of command-line flags, parsed from os.Args.
var CommandLine = NewFlagSet(os.Args[0], ExitOnError)
// NewFlagSet returns a new, empty flag set with the specified name and
// error handling property.
func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet {
f := &FlagSet{
name: name,
errorHandling: errorHandling,
interspersed: true,
}
return f
}
// Whether to support interspersed option/non-option arguments.
func (f *FlagSet) SetInterspersed(interspersed bool) {
f.interspersed = interspersed
}
// Init sets the name and error handling property for a flag set.
// By default, the zero FlagSet uses an empty name and the
// ContinueOnError error handling policy.
func (f *FlagSet) Init(name string, errorHandling ErrorHandling) {
f.name = name
f.errorHandling = errorHandling
}
+392
View File
@@ -0,0 +1,392 @@
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package pflag_test
import (
"bytes"
"fmt"
"io/ioutil"
"os"
"sort"
"strings"
"testing"
"time"
. "github.com/coreos/rocket/Godeps/_workspace/src/github.com/spf13/pflag"
)
var (
test_bool = Bool("test_bool", false, "bool value")
test_int = Int("test_int", 0, "int value")
test_int64 = Int64("test_int64", 0, "int64 value")
test_uint = Uint("test_uint", 0, "uint value")
test_uint64 = Uint64("test_uint64", 0, "uint64 value")
test_string = String("test_string", "0", "string value")
test_float64 = Float64("test_float64", 0, "float64 value")
test_duration = Duration("test_duration", 0, "time.Duration value")
)
func boolString(s string) string {
if s == "0" {
return "false"
}
return "true"
}
func TestEverything(t *testing.T) {
m := make(map[string]*Flag)
desired := "0"
visitor := func(f *Flag) {
if len(f.Name) > 5 && f.Name[0:5] == "test_" {
m[f.Name] = f
ok := false
switch {
case f.Value.String() == desired:
ok = true
case f.Name == "test_bool" && f.Value.String() == boolString(desired):
ok = true
case f.Name == "test_duration" && f.Value.String() == desired+"s":
ok = true
}
if !ok {
t.Error("Visit: bad value", f.Value.String(), "for", f.Name)
}
}
}
VisitAll(visitor)
if len(m) != 8 {
t.Error("VisitAll misses some flags")
for k, v := range m {
t.Log(k, *v)
}
}
m = make(map[string]*Flag)
Visit(visitor)
if len(m) != 0 {
t.Errorf("Visit sees unset flags")
for k, v := range m {
t.Log(k, *v)
}
}
// Now set all flags
Set("test_bool", "true")
Set("test_int", "1")
Set("test_int64", "1")
Set("test_uint", "1")
Set("test_uint64", "1")
Set("test_string", "1")
Set("test_float64", "1")
Set("test_duration", "1s")
desired = "1"
Visit(visitor)
if len(m) != 8 {
t.Error("Visit fails after set")
for k, v := range m {
t.Log(k, *v)
}
}
// Now test they're visited in sort order.
var flagNames []string
Visit(func(f *Flag) { flagNames = append(flagNames, f.Name) })
if !sort.StringsAreSorted(flagNames) {
t.Errorf("flag names not sorted: %v", flagNames)
}
}
func TestUsage(t *testing.T) {
called := false
ResetForTesting(func() { called = true })
if GetCommandLine().Parse([]string{"--x"}) == nil {
t.Error("parse did not fail for unknown flag")
}
if !called {
t.Error("did not call Usage for unknown flag")
}
}
func testParse(f *FlagSet, t *testing.T) {
if f.Parsed() {
t.Error("f.Parse() = true before Parse")
}
boolFlag := f.Bool("bool", false, "bool value")
bool2Flag := f.Bool("bool2", false, "bool2 value")
bool3Flag := f.Bool("bool3", false, "bool3 value")
intFlag := f.Int("int", 0, "int value")
int64Flag := f.Int64("int64", 0, "int64 value")
uintFlag := f.Uint("uint", 0, "uint value")
uint64Flag := f.Uint64("uint64", 0, "uint64 value")
stringFlag := f.String("string", "0", "string value")
float64Flag := f.Float64("float64", 0, "float64 value")
durationFlag := f.Duration("duration", 5*time.Second, "time.Duration value")
extra := "one-extra-argument"
args := []string{
"--bool",
"--bool2=true",
"--bool3=false",
"--int=22",
"--int64=0x23",
"--uint=24",
"--uint64=25",
"--string=hello",
"--float64=2718e28",
"--duration=2m",
extra,
}
if err := f.Parse(args); err != nil {
t.Fatal(err)
}
if !f.Parsed() {
t.Error("f.Parse() = false after Parse")
}
if *boolFlag != true {
t.Error("bool flag should be true, is ", *boolFlag)
}
if *bool2Flag != true {
t.Error("bool2 flag should be true, is ", *bool2Flag)
}
if *bool3Flag != false {
t.Error("bool3 flag should be false, is ", *bool2Flag)
}
if *intFlag != 22 {
t.Error("int flag should be 22, is ", *intFlag)
}
if *int64Flag != 0x23 {
t.Error("int64 flag should be 0x23, is ", *int64Flag)
}
if *uintFlag != 24 {
t.Error("uint flag should be 24, is ", *uintFlag)
}
if *uint64Flag != 25 {
t.Error("uint64 flag should be 25, is ", *uint64Flag)
}
if *stringFlag != "hello" {
t.Error("string flag should be `hello`, is ", *stringFlag)
}
if *float64Flag != 2718e28 {
t.Error("float64 flag should be 2718e28, is ", *float64Flag)
}
if *durationFlag != 2*time.Minute {
t.Error("duration flag should be 2m, is ", *durationFlag)
}
if len(f.Args()) != 1 {
t.Error("expected one argument, got", len(f.Args()))
} else if f.Args()[0] != extra {
t.Errorf("expected argument %q got %q", extra, f.Args()[0])
}
}
func TestShorthand(t *testing.T) {
f := NewFlagSet("shorthand", ContinueOnError)
if f.Parsed() {
t.Error("f.Parse() = true before Parse")
}
boolaFlag := f.BoolP("boola", "a", false, "bool value")
boolbFlag := f.BoolP("boolb", "b", false, "bool2 value")
boolcFlag := f.BoolP("boolc", "c", false, "bool3 value")
stringFlag := f.StringP("string", "s", "0", "string value")
extra := "interspersed-argument"
notaflag := "--i-look-like-a-flag"
args := []string{
"-ab",
extra,
"-cs",
"hello",
"--",
notaflag,
}
f.SetOutput(ioutil.Discard)
if err := f.Parse(args); err != nil {
t.Error("expected no error, got ", err)
}
if !f.Parsed() {
t.Error("f.Parse() = false after Parse")
}
if *boolaFlag != true {
t.Error("boola flag should be true, is ", *boolaFlag)
}
if *boolbFlag != true {
t.Error("boolb flag should be true, is ", *boolbFlag)
}
if *boolcFlag != true {
t.Error("boolc flag should be true, is ", *boolcFlag)
}
if *stringFlag != "hello" {
t.Error("string flag should be `hello`, is ", *stringFlag)
}
if len(f.Args()) != 2 {
t.Error("expected one argument, got", len(f.Args()))
} else if f.Args()[0] != extra {
t.Errorf("expected argument %q got %q", extra, f.Args()[0])
} else if f.Args()[1] != notaflag {
t.Errorf("expected argument %q got %q", notaflag, f.Args()[1])
}
}
func TestParse(t *testing.T) {
ResetForTesting(func() { t.Error("bad parse") })
testParse(GetCommandLine(), t)
}
func TestFlagSetParse(t *testing.T) {
testParse(NewFlagSet("test", ContinueOnError), t)
}
// Declare a user-defined flag type.
type flagVar []string
func (f *flagVar) String() string {
return fmt.Sprint([]string(*f))
}
func (f *flagVar) Set(value string) error {
*f = append(*f, value)
return nil
}
func (f *flagVar) Type() string {
return "flagVar"
}
func TestUserDefined(t *testing.T) {
var flags FlagSet
flags.Init("test", ContinueOnError)
var v flagVar
flags.VarP(&v, "v", "v", "usage")
if err := flags.Parse([]string{"--v=1", "-v2", "-v", "3"}); err != nil {
t.Error(err)
}
if len(v) != 3 {
t.Fatal("expected 3 args; got ", len(v))
}
expect := "[1 2 3]"
if v.String() != expect {
t.Errorf("expected value %q got %q", expect, v.String())
}
}
func TestSetOutput(t *testing.T) {
var flags FlagSet
var buf bytes.Buffer
flags.SetOutput(&buf)
flags.Init("test", ContinueOnError)
flags.Parse([]string{"--unknown"})
if out := buf.String(); !strings.Contains(out, "--unknown") {
t.Logf("expected output mentioning unknown; got %q", out)
}
}
// This tests that one can reset the flags. This still works but not well, and is
// superseded by FlagSet.
func TestChangingArgs(t *testing.T) {
ResetForTesting(func() { t.Fatal("bad parse") })
oldArgs := os.Args
defer func() { os.Args = oldArgs }()
os.Args = []string{"cmd", "--before", "subcmd"}
before := Bool("before", false, "")
if err := GetCommandLine().Parse(os.Args[1:]); err != nil {
t.Fatal(err)
}
cmd := Arg(0)
os.Args = []string{"subcmd", "--after", "args"}
after := Bool("after", false, "")
Parse()
args := Args()
if !*before || cmd != "subcmd" || !*after || len(args) != 1 || args[0] != "args" {
t.Fatalf("expected true subcmd true [args] got %v %v %v %v", *before, cmd, *after, args)
}
}
// Test that -help invokes the usage message and returns ErrHelp.
func TestHelp(t *testing.T) {
var helpCalled = false
fs := NewFlagSet("help test", ContinueOnError)
fs.Usage = func() { helpCalled = true }
var flag bool
fs.BoolVar(&flag, "flag", false, "regular flag")
// Regular flag invocation should work
err := fs.Parse([]string{"--flag=true"})
if err != nil {
t.Fatal("expected no error; got ", err)
}
if !flag {
t.Error("flag was not set by --flag")
}
if helpCalled {
t.Error("help called for regular flag")
helpCalled = false // reset for next test
}
// Help flag should work as expected.
err = fs.Parse([]string{"--help"})
if err == nil {
t.Fatal("error expected")
}
if err != ErrHelp {
t.Fatal("expected ErrHelp; got ", err)
}
if !helpCalled {
t.Fatal("help was not called")
}
// If we define a help flag, that should override.
var help bool
fs.BoolVar(&help, "help", false, "help flag")
helpCalled = false
err = fs.Parse([]string{"--help"})
if err != nil {
t.Fatal("expected no error for defined --help; got ", err)
}
if helpCalled {
t.Fatal("help was called; should not have been for defined help flag")
}
}
func TestNoInterspersed(t *testing.T) {
f := NewFlagSet("test", ContinueOnError)
f.SetInterspersed(false)
f.Bool("true", true, "always true")
f.Bool("false", false, "always false")
err := f.Parse([]string{"--true", "break", "--false"})
if err != nil {
t.Fatal("expected no error; got ", err)
}
args := f.Args()
if len(args) != 2 || args[0] != "break" || args[1] != "--false" {
t.Fatal("expected interspersed options/non-options to fail")
}
}
func TestTermination(t *testing.T) {
f := NewFlagSet("termination", ContinueOnError)
boolFlag := f.BoolP("bool", "l", false, "bool value")
if f.Parsed() {
t.Error("f.Parse() = true before Parse")
}
arg1 := "ls"
arg2 := "-l"
args := []string{
"--",
arg1,
arg2,
}
f.SetOutput(ioutil.Discard)
if err := f.Parse(args); err != nil {
t.Fatal("expected no error; got ", err)
}
if !f.Parsed() {
t.Error("f.Parse() = false after Parse")
}
if *boolFlag {
t.Error("expected boolFlag=false, got true")
}
if len(f.Args()) != 2 {
t.Errorf("expected 2 arguments, got %d: %v", len(f.Args()), f.Args())
}
if f.Args()[0] != arg1 {
t.Errorf("expected argument %q got %q", arg1, f.Args()[0])
}
if f.Args()[1] != arg2 {
t.Errorf("expected argument %q got %q", arg2, f.Args()[1])
}
}
+74
View File
@@ -0,0 +1,74 @@
package pflag
import (
"fmt"
"strconv"
)
// -- float32 Value
type float32Value float32
func newFloat32Value(val float32, p *float32) *float32Value {
*p = val
return (*float32Value)(p)
}
func (f *float32Value) Set(s string) error {
v, err := strconv.ParseFloat(s, 32)
*f = float32Value(v)
return err
}
func (f *float32Value) Type() string {
return "float32"
}
func (f *float32Value) String() string { return fmt.Sprintf("%v", *f) }
// Float32Var defines a float32 flag with specified name, default value, and usage string.
// The argument p points to a float32 variable in which to store the value of the flag.
func (f *FlagSet) Float32Var(p *float32, name string, value float32, usage string) {
f.VarP(newFloat32Value(value, p), name, "", usage)
}
// Like Float32Var, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Float32VarP(p *float32, name, shorthand string, value float32, usage string) {
f.VarP(newFloat32Value(value, p), name, shorthand, usage)
}
// Float32Var defines a float32 flag with specified name, default value, and usage string.
// The argument p points to a float32 variable in which to store the value of the flag.
func Float32Var(p *float32, name string, value float32, usage string) {
CommandLine.VarP(newFloat32Value(value, p), name, "", usage)
}
// Like Float32Var, but accepts a shorthand letter that can be used after a single dash.
func Float32VarP(p *float32, name, shorthand string, value float32, usage string) {
CommandLine.VarP(newFloat32Value(value, p), name, shorthand, usage)
}
// Float32 defines a float32 flag with specified name, default value, and usage string.
// The return value is the address of a float32 variable that stores the value of the flag.
func (f *FlagSet) Float32(name string, value float32, usage string) *float32 {
p := new(float32)
f.Float32VarP(p, name, "", value, usage)
return p
}
// Like Float32, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Float32P(name, shorthand string, value float32, usage string) *float32 {
p := new(float32)
f.Float32VarP(p, name, shorthand, value, usage)
return p
}
// Float32 defines a float32 flag with specified name, default value, and usage string.
// The return value is the address of a float32 variable that stores the value of the flag.
func Float32(name string, value float32, usage string) *float32 {
return CommandLine.Float32P(name, "", value, usage)
}
// Like Float32, but accepts a shorthand letter that can be used after a single dash.
func Float32P(name, shorthand string, value float32, usage string) *float32 {
return CommandLine.Float32P(name, shorthand, value, usage)
}
+74
View File
@@ -0,0 +1,74 @@
package pflag
import (
"fmt"
"strconv"
)
// -- float64 Value
type float64Value float64
func newFloat64Value(val float64, p *float64) *float64Value {
*p = val
return (*float64Value)(p)
}
func (f *float64Value) Set(s string) error {
v, err := strconv.ParseFloat(s, 64)
*f = float64Value(v)
return err
}
func (f *float64Value) Type() string {
return "float64"
}
func (f *float64Value) String() string { return fmt.Sprintf("%v", *f) }
// Float64Var defines a float64 flag with specified name, default value, and usage string.
// The argument p points to a float64 variable in which to store the value of the flag.
func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string) {
f.VarP(newFloat64Value(value, p), name, "", usage)
}
// Like Float64Var, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Float64VarP(p *float64, name, shorthand string, value float64, usage string) {
f.VarP(newFloat64Value(value, p), name, shorthand, usage)
}
// Float64Var defines a float64 flag with specified name, default value, and usage string.
// The argument p points to a float64 variable in which to store the value of the flag.
func Float64Var(p *float64, name string, value float64, usage string) {
CommandLine.VarP(newFloat64Value(value, p), name, "", usage)
}
// Like Float64Var, but accepts a shorthand letter that can be used after a single dash.
func Float64VarP(p *float64, name, shorthand string, value float64, usage string) {
CommandLine.VarP(newFloat64Value(value, p), name, shorthand, usage)
}
// Float64 defines a float64 flag with specified name, default value, and usage string.
// The return value is the address of a float64 variable that stores the value of the flag.
func (f *FlagSet) Float64(name string, value float64, usage string) *float64 {
p := new(float64)
f.Float64VarP(p, name, "", value, usage)
return p
}
// Like Float64, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Float64P(name, shorthand string, value float64, usage string) *float64 {
p := new(float64)
f.Float64VarP(p, name, shorthand, value, usage)
return p
}
// Float64 defines a float64 flag with specified name, default value, and usage string.
// The return value is the address of a float64 variable that stores the value of the flag.
func Float64(name string, value float64, usage string) *float64 {
return CommandLine.Float64P(name, "", value, usage)
}
// Like Float64, but accepts a shorthand letter that can be used after a single dash.
func Float64P(name, shorthand string, value float64, usage string) *float64 {
return CommandLine.Float64P(name, shorthand, value, usage)
}
+74
View File
@@ -0,0 +1,74 @@
package pflag
import (
"fmt"
"strconv"
)
// -- int Value
type intValue int
func newIntValue(val int, p *int) *intValue {
*p = val
return (*intValue)(p)
}
func (i *intValue) Set(s string) error {
v, err := strconv.ParseInt(s, 0, 64)
*i = intValue(v)
return err
}
func (i *intValue) Type() string {
return "int"
}
func (i *intValue) String() string { return fmt.Sprintf("%v", *i) }
// IntVar defines an int flag with specified name, default value, and usage string.
// The argument p points to an int variable in which to store the value of the flag.
func (f *FlagSet) IntVar(p *int, name string, value int, usage string) {
f.VarP(newIntValue(value, p), name, "", usage)
}
// Like IntVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) IntVarP(p *int, name, shorthand string, value int, usage string) {
f.VarP(newIntValue(value, p), name, shorthand, usage)
}
// IntVar defines an int flag with specified name, default value, and usage string.
// The argument p points to an int variable in which to store the value of the flag.
func IntVar(p *int, name string, value int, usage string) {
CommandLine.VarP(newIntValue(value, p), name, "", usage)
}
// Like IntVar, but accepts a shorthand letter that can be used after a single dash.
func IntVarP(p *int, name, shorthand string, value int, usage string) {
CommandLine.VarP(newIntValue(value, p), name, shorthand, usage)
}
// Int defines an int flag with specified name, default value, and usage string.
// The return value is the address of an int variable that stores the value of the flag.
func (f *FlagSet) Int(name string, value int, usage string) *int {
p := new(int)
f.IntVarP(p, name, "", value, usage)
return p
}
// Like Int, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) IntP(name, shorthand string, value int, usage string) *int {
p := new(int)
f.IntVarP(p, name, shorthand, value, usage)
return p
}
// Int defines an int flag with specified name, default value, and usage string.
// The return value is the address of an int variable that stores the value of the flag.
func Int(name string, value int, usage string) *int {
return CommandLine.IntP(name, "", value, usage)
}
// Like Int, but accepts a shorthand letter that can be used after a single dash.
func IntP(name, shorthand string, value int, usage string) *int {
return CommandLine.IntP(name, shorthand, value, usage)
}
+74
View File
@@ -0,0 +1,74 @@
package pflag
import (
"fmt"
"strconv"
)
// -- int32 Value
type int32Value int32
func newInt32Value(val int32, p *int32) *int32Value {
*p = val
return (*int32Value)(p)
}
func (i *int32Value) Set(s string) error {
v, err := strconv.ParseInt(s, 0, 32)
*i = int32Value(v)
return err
}
func (i *int32Value) Type() string {
return "int32"
}
func (i *int32Value) String() string { return fmt.Sprintf("%v", *i) }
// Int32Var defines an int32 flag with specified name, default value, and usage string.
// The argument p points to an int32 variable in which to store the value of the flag.
func (f *FlagSet) Int32Var(p *int32, name string, value int32, usage string) {
f.VarP(newInt32Value(value, p), name, "", usage)
}
// Like Int32Var, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Int32VarP(p *int32, name, shorthand string, value int32, usage string) {
f.VarP(newInt32Value(value, p), name, shorthand, usage)
}
// Int32Var defines an int32 flag with specified name, default value, and usage string.
// The argument p points to an int32 variable in which to store the value of the flag.
func Int32Var(p *int32, name string, value int32, usage string) {
CommandLine.VarP(newInt32Value(value, p), name, "", usage)
}
// Like Int32Var, but accepts a shorthand letter that can be used after a single dash.
func Int32VarP(p *int32, name, shorthand string, value int32, usage string) {
CommandLine.VarP(newInt32Value(value, p), name, shorthand, usage)
}
// Int32 defines an int32 flag with specified name, default value, and usage string.
// The return value is the address of an int32 variable that stores the value of the flag.
func (f *FlagSet) Int32(name string, value int32, usage string) *int32 {
p := new(int32)
f.Int32VarP(p, name, "", value, usage)
return p
}
// Like Int32, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Int32P(name, shorthand string, value int32, usage string) *int32 {
p := new(int32)
f.Int32VarP(p, name, shorthand, value, usage)
return p
}
// Int32 defines an int32 flag with specified name, default value, and usage string.
// The return value is the address of an int32 variable that stores the value of the flag.
func Int32(name string, value int32, usage string) *int32 {
return CommandLine.Int32P(name, "", value, usage)
}
// Like Int32, but accepts a shorthand letter that can be used after a single dash.
func Int32P(name, shorthand string, value int32, usage string) *int32 {
return CommandLine.Int32P(name, shorthand, value, usage)
}
+74
View File
@@ -0,0 +1,74 @@
package pflag
import (
"fmt"
"strconv"
)
// -- int64 Value
type int64Value int64
func newInt64Value(val int64, p *int64) *int64Value {
*p = val
return (*int64Value)(p)
}
func (i *int64Value) Set(s string) error {
v, err := strconv.ParseInt(s, 0, 64)
*i = int64Value(v)
return err
}
func (i *int64Value) Type() string {
return "int64"
}
func (i *int64Value) String() string { return fmt.Sprintf("%v", *i) }
// Int64Var defines an int64 flag with specified name, default value, and usage string.
// The argument p points to an int64 variable in which to store the value of the flag.
func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string) {
f.VarP(newInt64Value(value, p), name, "", usage)
}
// Like Int64Var, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Int64VarP(p *int64, name, shorthand string, value int64, usage string) {
f.VarP(newInt64Value(value, p), name, shorthand, usage)
}
// Int64Var defines an int64 flag with specified name, default value, and usage string.
// The argument p points to an int64 variable in which to store the value of the flag.
func Int64Var(p *int64, name string, value int64, usage string) {
CommandLine.VarP(newInt64Value(value, p), name, "", usage)
}
// Like Int64Var, but accepts a shorthand letter that can be used after a single dash.
func Int64VarP(p *int64, name, shorthand string, value int64, usage string) {
CommandLine.VarP(newInt64Value(value, p), name, shorthand, usage)
}
// Int64 defines an int64 flag with specified name, default value, and usage string.
// The return value is the address of an int64 variable that stores the value of the flag.
func (f *FlagSet) Int64(name string, value int64, usage string) *int64 {
p := new(int64)
f.Int64VarP(p, name, "", value, usage)
return p
}
// Like Int64, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Int64P(name, shorthand string, value int64, usage string) *int64 {
p := new(int64)
f.Int64VarP(p, name, shorthand, value, usage)
return p
}
// Int64 defines an int64 flag with specified name, default value, and usage string.
// The return value is the address of an int64 variable that stores the value of the flag.
func Int64(name string, value int64, usage string) *int64 {
return CommandLine.Int64P(name, "", value, usage)
}
// Like Int64, but accepts a shorthand letter that can be used after a single dash.
func Int64P(name, shorthand string, value int64, usage string) *int64 {
return CommandLine.Int64P(name, shorthand, value, usage)
}
+74
View File
@@ -0,0 +1,74 @@
package pflag
import (
"fmt"
"strconv"
)
// -- int8 Value
type int8Value int8
func newInt8Value(val int8, p *int8) *int8Value {
*p = val
return (*int8Value)(p)
}
func (i *int8Value) Set(s string) error {
v, err := strconv.ParseInt(s, 0, 8)
*i = int8Value(v)
return err
}
func (i *int8Value) Type() string {
return "int8"
}
func (i *int8Value) String() string { return fmt.Sprintf("%v", *i) }
// Int8Var defines an int8 flag with specified name, default value, and usage string.
// The argument p points to an int8 variable in which to store the value of the flag.
func (f *FlagSet) Int8Var(p *int8, name string, value int8, usage string) {
f.VarP(newInt8Value(value, p), name, "", usage)
}
// Like Int8Var, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Int8VarP(p *int8, name, shorthand string, value int8, usage string) {
f.VarP(newInt8Value(value, p), name, shorthand, usage)
}
// Int8Var defines an int8 flag with specified name, default value, and usage string.
// The argument p points to an int8 variable in which to store the value of the flag.
func Int8Var(p *int8, name string, value int8, usage string) {
CommandLine.VarP(newInt8Value(value, p), name, "", usage)
}
// Like Int8Var, but accepts a shorthand letter that can be used after a single dash.
func Int8VarP(p *int8, name, shorthand string, value int8, usage string) {
CommandLine.VarP(newInt8Value(value, p), name, shorthand, usage)
}
// Int8 defines an int8 flag with specified name, default value, and usage string.
// The return value is the address of an int8 variable that stores the value of the flag.
func (f *FlagSet) Int8(name string, value int8, usage string) *int8 {
p := new(int8)
f.Int8VarP(p, name, "", value, usage)
return p
}
// Like Int8, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Int8P(name, shorthand string, value int8, usage string) *int8 {
p := new(int8)
f.Int8VarP(p, name, shorthand, value, usage)
return p
}
// Int8 defines an int8 flag with specified name, default value, and usage string.
// The return value is the address of an int8 variable that stores the value of the flag.
func Int8(name string, value int8, usage string) *int8 {
return CommandLine.Int8P(name, "", value, usage)
}
// Like Int8, but accepts a shorthand letter that can be used after a single dash.
func Int8P(name, shorthand string, value int8, usage string) *int8 {
return CommandLine.Int8P(name, shorthand, value, usage)
}
+79
View File
@@ -0,0 +1,79 @@
package pflag
import (
"fmt"
"net"
)
// -- net.IP value
type ipValue net.IP
func newIPValue(val net.IP, p *net.IP) *ipValue {
*p = val
return (*ipValue)(p)
}
func (i *ipValue) String() string { return net.IP(*i).String() }
func (i *ipValue) Set(s string) error {
ip := net.ParseIP(s)
if ip == nil {
return fmt.Errorf("failed to parse IP: %q", s)
}
*i = ipValue(ip)
return nil
}
func (i *ipValue) Get() interface{} {
return net.IP(*i)
}
func (i *ipValue) Type() string {
return "ip"
}
// IPVar defines an net.IP flag with specified name, default value, and usage string.
// The argument p points to an net.IP variable in which to store the value of the flag.
func (f *FlagSet) IPVar(p *net.IP, name string, value net.IP, usage string) {
f.VarP(newIPValue(value, p), name, "", usage)
}
// Like IPVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) IPVarP(p *net.IP, name, shorthand string, value net.IP, usage string) {
f.VarP(newIPValue(value, p), name, shorthand, usage)
}
// IPVar defines an net.IP flag with specified name, default value, and usage string.
// The argument p points to an net.IP variable in which to store the value of the flag.
func IPVar(p *net.IP, name string, value net.IP, usage string) {
CommandLine.VarP(newIPValue(value, p), name, "", usage)
}
// Like IPVar, but accepts a shorthand letter that can be used after a single dash.
func IPVarP(p *net.IP, name, shorthand string, value net.IP, usage string) {
CommandLine.VarP(newIPValue(value, p), name, shorthand, usage)
}
// IP defines an net.IP flag with specified name, default value, and usage string.
// The return value is the address of an net.IP variable that stores the value of the flag.
func (f *FlagSet) IP(name string, value net.IP, usage string) *net.IP {
p := new(net.IP)
f.IPVarP(p, name, "", value, usage)
return p
}
// Like IP, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) IPP(name, shorthand string, value net.IP, usage string) *net.IP {
p := new(net.IP)
f.IPVarP(p, name, shorthand, value, usage)
return p
}
// IP defines an net.IP flag with specified name, default value, and usage string.
// The return value is the address of an net.IP variable that stores the value of the flag.
func IP(name string, value net.IP, usage string) *net.IP {
return CommandLine.IPP(name, "", value, usage)
}
// Like IP, but accepts a shorthand letter that can be used after a single dash.
func IPP(name, shorthand string, value net.IP, usage string) *net.IP {
return CommandLine.IPP(name, shorthand, value, usage)
}
+89
View File
@@ -0,0 +1,89 @@
package pflag
import (
"fmt"
"net"
)
// -- net.IPMask value
type ipMaskValue net.IPMask
func newIPMaskValue(val net.IPMask, p *net.IPMask) *ipMaskValue {
*p = val
return (*ipMaskValue)(p)
}
func (i *ipMaskValue) String() string { return net.IPMask(*i).String() }
func (i *ipMaskValue) Set(s string) error {
ip := ParseIPv4Mask(s)
if ip == nil {
return fmt.Errorf("failed to parse IP mask: %q", s)
}
*i = ipMaskValue(ip)
return nil
}
func (i *ipMaskValue) Get() interface{} {
return net.IPMask(*i)
}
func (i *ipMaskValue) Type() string {
return "ipMask"
}
// Parse IPv4 netmask written in IP form (e.g. 255.255.255.0).
// This function should really belong to the net package.
func ParseIPv4Mask(s string) net.IPMask {
mask := net.ParseIP(s)
if mask == nil {
return nil
}
return net.IPv4Mask(mask[12], mask[13], mask[14], mask[15])
}
// IPMaskVar defines an net.IPMask flag with specified name, default value, and usage string.
// The argument p points to an net.IPMask variable in which to store the value of the flag.
func (f *FlagSet) IPMaskVar(p *net.IPMask, name string, value net.IPMask, usage string) {
f.VarP(newIPMaskValue(value, p), name, "", usage)
}
// Like IPMaskVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) IPMaskVarP(p *net.IPMask, name, shorthand string, value net.IPMask, usage string) {
f.VarP(newIPMaskValue(value, p), name, shorthand, usage)
}
// IPMaskVar defines an net.IPMask flag with specified name, default value, and usage string.
// The argument p points to an net.IPMask variable in which to store the value of the flag.
func IPMaskVar(p *net.IPMask, name string, value net.IPMask, usage string) {
CommandLine.VarP(newIPMaskValue(value, p), name, "", usage)
}
// Like IPMaskVar, but accepts a shorthand letter that can be used after a single dash.
func IPMaskVarP(p *net.IPMask, name, shorthand string, value net.IPMask, usage string) {
CommandLine.VarP(newIPMaskValue(value, p), name, shorthand, usage)
}
// IPMask defines an net.IPMask flag with specified name, default value, and usage string.
// The return value is the address of an net.IPMask variable that stores the value of the flag.
func (f *FlagSet) IPMask(name string, value net.IPMask, usage string) *net.IPMask {
p := new(net.IPMask)
f.IPMaskVarP(p, name, "", value, usage)
return p
}
// Like IPMask, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) IPMaskP(name, shorthand string, value net.IPMask, usage string) *net.IPMask {
p := new(net.IPMask)
f.IPMaskVarP(p, name, shorthand, value, usage)
return p
}
// IPMask defines an net.IPMask flag with specified name, default value, and usage string.
// The return value is the address of an net.IPMask variable that stores the value of the flag.
func IPMask(name string, value net.IPMask, usage string) *net.IPMask {
return CommandLine.IPMaskP(name, "", value, usage)
}
// Like IP, but accepts a shorthand letter that can be used after a single dash.
func IPMaskP(name, shorthand string, value net.IPMask, usage string) *net.IPMask {
return CommandLine.IPMaskP(name, shorthand, value, usage)
}
+69
View File
@@ -0,0 +1,69 @@
package pflag
import "fmt"
// -- string Value
type stringValue string
func newStringValue(val string, p *string) *stringValue {
*p = val
return (*stringValue)(p)
}
func (s *stringValue) Set(val string) error {
*s = stringValue(val)
return nil
}
func (s *stringValue) Type() string {
return "string"
}
func (s *stringValue) String() string { return fmt.Sprintf("%s", *s) }
// StringVar defines a string flag with specified name, default value, and usage string.
// The argument p points to a string variable in which to store the value of the flag.
func (f *FlagSet) StringVar(p *string, name string, value string, usage string) {
f.VarP(newStringValue(value, p), name, "", usage)
}
// Like StringVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) StringVarP(p *string, name, shorthand string, value string, usage string) {
f.VarP(newStringValue(value, p), name, shorthand, usage)
}
// StringVar defines a string flag with specified name, default value, and usage string.
// The argument p points to a string variable in which to store the value of the flag.
func StringVar(p *string, name string, value string, usage string) {
CommandLine.VarP(newStringValue(value, p), name, "", usage)
}
// Like StringVar, but accepts a shorthand letter that can be used after a single dash.
func StringVarP(p *string, name, shorthand string, value string, usage string) {
CommandLine.VarP(newStringValue(value, p), name, shorthand, usage)
}
// String defines a string flag with specified name, default value, and usage string.
// The return value is the address of a string variable that stores the value of the flag.
func (f *FlagSet) String(name string, value string, usage string) *string {
p := new(string)
f.StringVarP(p, name, "", value, usage)
return p
}
// Like String, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) StringP(name, shorthand string, value string, usage string) *string {
p := new(string)
f.StringVarP(p, name, shorthand, value, usage)
return p
}
// String defines a string flag with specified name, default value, and usage string.
// The return value is the address of a string variable that stores the value of the flag.
func String(name string, value string, usage string) *string {
return CommandLine.StringP(name, "", value, usage)
}
// Like String, but accepts a shorthand letter that can be used after a single dash.
func StringP(name, shorthand string, value string, usage string) *string {
return CommandLine.StringP(name, shorthand, value, usage)
}
+74
View File
@@ -0,0 +1,74 @@
package pflag
import (
"fmt"
"strconv"
)
// -- uint Value
type uintValue uint
func newUintValue(val uint, p *uint) *uintValue {
*p = val
return (*uintValue)(p)
}
func (i *uintValue) Set(s string) error {
v, err := strconv.ParseUint(s, 0, 64)
*i = uintValue(v)
return err
}
func (i *uintValue) Type() string {
return "uint"
}
func (i *uintValue) String() string { return fmt.Sprintf("%v", *i) }
// UintVar defines a uint flag with specified name, default value, and usage string.
// The argument p points to a uint variable in which to store the value of the flag.
func (f *FlagSet) UintVar(p *uint, name string, value uint, usage string) {
f.VarP(newUintValue(value, p), name, "", usage)
}
// Like UintVar, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) UintVarP(p *uint, name, shorthand string, value uint, usage string) {
f.VarP(newUintValue(value, p), name, shorthand, usage)
}
// UintVar defines a uint flag with specified name, default value, and usage string.
// The argument p points to a uint variable in which to store the value of the flag.
func UintVar(p *uint, name string, value uint, usage string) {
CommandLine.VarP(newUintValue(value, p), name, "", usage)
}
// Like UintVar, but accepts a shorthand letter that can be used after a single dash.
func UintVarP(p *uint, name, shorthand string, value uint, usage string) {
CommandLine.VarP(newUintValue(value, p), name, shorthand, usage)
}
// Uint defines a uint flag with specified name, default value, and usage string.
// The return value is the address of a uint variable that stores the value of the flag.
func (f *FlagSet) Uint(name string, value uint, usage string) *uint {
p := new(uint)
f.UintVarP(p, name, "", value, usage)
return p
}
// Like Uint, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) UintP(name, shorthand string, value uint, usage string) *uint {
p := new(uint)
f.UintVarP(p, name, shorthand, value, usage)
return p
}
// Uint defines a uint flag with specified name, default value, and usage string.
// The return value is the address of a uint variable that stores the value of the flag.
func Uint(name string, value uint, usage string) *uint {
return CommandLine.UintP(name, "", value, usage)
}
// Like Uint, but accepts a shorthand letter that can be used after a single dash.
func UintP(name, shorthand string, value uint, usage string) *uint {
return CommandLine.UintP(name, shorthand, value, usage)
}
+76
View File
@@ -0,0 +1,76 @@
package pflag
import (
"fmt"
"strconv"
)
// -- uint16 value
type uint16Value uint16
func newUint16Value(val uint16, p *uint16) *uint16Value {
*p = val
return (*uint16Value)(p)
}
func (i *uint16Value) String() string { return fmt.Sprintf("%d", *i) }
func (i *uint16Value) Set(s string) error {
v, err := strconv.ParseUint(s, 0, 16)
*i = uint16Value(v)
return err
}
func (i *uint16Value) Get() interface{} {
return uint16(*i)
}
func (i *uint16Value) Type() string {
return "uint16"
}
// Uint16Var defines a uint flag with specified name, default value, and usage string.
// The argument p points to a uint variable in which to store the value of the flag.
func (f *FlagSet) Uint16Var(p *uint16, name string, value uint16, usage string) {
f.VarP(newUint16Value(value, p), name, "", usage)
}
// Like Uint16Var, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Uint16VarP(p *uint16, name, shorthand string, value uint16, usage string) {
f.VarP(newUint16Value(value, p), name, shorthand, usage)
}
// Uint16Var defines a uint flag with specified name, default value, and usage string.
// The argument p points to a uint variable in which to store the value of the flag.
func Uint16Var(p *uint16, name string, value uint16, usage string) {
CommandLine.VarP(newUint16Value(value, p), name, "", usage)
}
// Like Uint16Var, but accepts a shorthand letter that can be used after a single dash.
func Uint16VarP(p *uint16, name, shorthand string, value uint16, usage string) {
CommandLine.VarP(newUint16Value(value, p), name, shorthand, usage)
}
// Uint16 defines a uint flag with specified name, default value, and usage string.
// The return value is the address of a uint variable that stores the value of the flag.
func (f *FlagSet) Uint16(name string, value uint16, usage string) *uint16 {
p := new(uint16)
f.Uint16VarP(p, name, "", value, usage)
return p
}
// Like Uint16, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Uint16P(name, shorthand string, value uint16, usage string) *uint16 {
p := new(uint16)
f.Uint16VarP(p, name, shorthand, value, usage)
return p
}
// Uint16 defines a uint flag with specified name, default value, and usage string.
// The return value is the address of a uint variable that stores the value of the flag.
func Uint16(name string, value uint16, usage string) *uint16 {
return CommandLine.Uint16P(name, "", value, usage)
}
// Like Uint16, but accepts a shorthand letter that can be used after a single dash.
func Uint16P(name, shorthand string, value uint16, usage string) *uint16 {
return CommandLine.Uint16P(name, shorthand, value, usage)
}
+75
View File
@@ -0,0 +1,75 @@
package pflag
import (
"fmt"
"strconv"
)
// -- uint16 value
type uint32Value uint32
func newUint32Value(val uint32, p *uint32) *uint32Value {
*p = val
return (*uint32Value)(p)
}
func (i *uint32Value) String() string { return fmt.Sprintf("%d", *i) }
func (i *uint32Value) Set(s string) error {
v, err := strconv.ParseUint(s, 0, 32)
*i = uint32Value(v)
return err
}
func (i *uint32Value) Get() interface{} {
return uint32(*i)
}
func (i *uint32Value) Type() string {
return "uint32"
}
// Uint32Var defines a uint32 flag with specified name, default value, and usage string.
// The argument p points to a uint32 variable in which to store the value of the flag.
func (f *FlagSet) Uint32Var(p *uint32, name string, value uint32, usage string) {
f.VarP(newUint32Value(value, p), name, "", usage)
}
// Like Uint32Var, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Uint32VarP(p *uint32, name, shorthand string, value uint32, usage string) {
f.VarP(newUint32Value(value, p), name, shorthand, usage)
}
// Uint32Var defines a uint32 flag with specified name, default value, and usage string.
// The argument p points to a uint32 variable in which to store the value of the flag.
func Uint32Var(p *uint32, name string, value uint32, usage string) {
CommandLine.VarP(newUint32Value(value, p), name, "", usage)
}
// Like Uint32Var, but accepts a shorthand letter that can be used after a single dash.
func Uint32VarP(p *uint32, name, shorthand string, value uint32, usage string) {
CommandLine.VarP(newUint32Value(value, p), name, shorthand, usage)
}
// Uint32 defines a uint32 flag with specified name, default value, and usage string.
// The return value is the address of a uint32 variable that stores the value of the flag.
func (f *FlagSet) Uint32(name string, value uint32, usage string) *uint32 {
p := new(uint32)
f.Uint32VarP(p, name, "", value, usage)
return p
}
// Like Uint32, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Uint32P(name, shorthand string, value uint32, usage string) *uint32 {
p := new(uint32)
f.Uint32VarP(p, name, shorthand, value, usage)
return p
}
// Uint32 defines a uint32 flag with specified name, default value, and usage string.
// The return value is the address of a uint32 variable that stores the value of the flag.
func Uint32(name string, value uint32, usage string) *uint32 {
return CommandLine.Uint32P(name, "", value, usage)
}
// Like Uint32, but accepts a shorthand letter that can be used after a single dash.
func Uint32P(name, shorthand string, value uint32, usage string) *uint32 {
return CommandLine.Uint32P(name, shorthand, value, usage)
}
+74
View File
@@ -0,0 +1,74 @@
package pflag
import (
"fmt"
"strconv"
)
// -- uint64 Value
type uint64Value uint64
func newUint64Value(val uint64, p *uint64) *uint64Value {
*p = val
return (*uint64Value)(p)
}
func (i *uint64Value) Set(s string) error {
v, err := strconv.ParseUint(s, 0, 64)
*i = uint64Value(v)
return err
}
func (i *uint64Value) Type() string {
return "uint64"
}
func (i *uint64Value) String() string { return fmt.Sprintf("%v", *i) }
// Uint64Var defines a uint64 flag with specified name, default value, and usage string.
// The argument p points to a uint64 variable in which to store the value of the flag.
func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string) {
f.VarP(newUint64Value(value, p), name, "", usage)
}
// Like Uint64Var, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Uint64VarP(p *uint64, name, shorthand string, value uint64, usage string) {
f.VarP(newUint64Value(value, p), name, shorthand, usage)
}
// Uint64Var defines a uint64 flag with specified name, default value, and usage string.
// The argument p points to a uint64 variable in which to store the value of the flag.
func Uint64Var(p *uint64, name string, value uint64, usage string) {
CommandLine.VarP(newUint64Value(value, p), name, "", usage)
}
// Like Uint64Var, but accepts a shorthand letter that can be used after a single dash.
func Uint64VarP(p *uint64, name, shorthand string, value uint64, usage string) {
CommandLine.VarP(newUint64Value(value, p), name, shorthand, usage)
}
// Uint64 defines a uint64 flag with specified name, default value, and usage string.
// The return value is the address of a uint64 variable that stores the value of the flag.
func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64 {
p := new(uint64)
f.Uint64VarP(p, name, "", value, usage)
return p
}
// Like Uint64, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Uint64P(name, shorthand string, value uint64, usage string) *uint64 {
p := new(uint64)
f.Uint64VarP(p, name, shorthand, value, usage)
return p
}
// Uint64 defines a uint64 flag with specified name, default value, and usage string.
// The return value is the address of a uint64 variable that stores the value of the flag.
func Uint64(name string, value uint64, usage string) *uint64 {
return CommandLine.Uint64P(name, "", value, usage)
}
// Like Uint64, but accepts a shorthand letter that can be used after a single dash.
func Uint64P(name, shorthand string, value uint64, usage string) *uint64 {
return CommandLine.Uint64P(name, shorthand, value, usage)
}
+74
View File
@@ -0,0 +1,74 @@
package pflag
import (
"fmt"
"strconv"
)
// -- uint8 Value
type uint8Value uint8
func newUint8Value(val uint8, p *uint8) *uint8Value {
*p = val
return (*uint8Value)(p)
}
func (i *uint8Value) Set(s string) error {
v, err := strconv.ParseUint(s, 0, 8)
*i = uint8Value(v)
return err
}
func (i *uint8Value) Type() string {
return "uint8"
}
func (i *uint8Value) String() string { return fmt.Sprintf("%v", *i) }
// Uint8Var defines a uint8 flag with specified name, default value, and usage string.
// The argument p points to a uint8 variable in which to store the value of the flag.
func (f *FlagSet) Uint8Var(p *uint8, name string, value uint8, usage string) {
f.VarP(newUint8Value(value, p), name, "", usage)
}
// Like Uint8Var, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Uint8VarP(p *uint8, name, shorthand string, value uint8, usage string) {
f.VarP(newUint8Value(value, p), name, shorthand, usage)
}
// Uint8Var defines a uint8 flag with specified name, default value, and usage string.
// The argument p points to a uint8 variable in which to store the value of the flag.
func Uint8Var(p *uint8, name string, value uint8, usage string) {
CommandLine.VarP(newUint8Value(value, p), name, "", usage)
}
// Like Uint8Var, but accepts a shorthand letter that can be used after a single dash.
func Uint8VarP(p *uint8, name, shorthand string, value uint8, usage string) {
CommandLine.VarP(newUint8Value(value, p), name, shorthand, usage)
}
// Uint8 defines a uint8 flag with specified name, default value, and usage string.
// The return value is the address of a uint8 variable that stores the value of the flag.
func (f *FlagSet) Uint8(name string, value uint8, usage string) *uint8 {
p := new(uint8)
f.Uint8VarP(p, name, "", value, usage)
return p
}
// Like Uint8, but accepts a shorthand letter that can be used after a single dash.
func (f *FlagSet) Uint8P(name, shorthand string, value uint8, usage string) *uint8 {
p := new(uint8)
f.Uint8VarP(p, name, shorthand, value, usage)
return p
}
// Uint8 defines a uint8 flag with specified name, default value, and usage string.
// The return value is the address of a uint8 variable that stores the value of the flag.
func Uint8(name string, value uint8, usage string) *uint8 {
return CommandLine.Uint8P(name, "", value, usage)
}
// Like Uint8, but accepts a shorthand letter that can be used after a single dash.
func Uint8P(name, shorthand string, value uint8, usage string) *uint8 {
return CommandLine.Uint8P(name, shorthand, value, usage)
}
+57
View File
@@ -0,0 +1,57 @@
Copyright (c) 2012 Péter Surányi. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
Portions of inf.Dec's source code have been derived from Go and are
covered by the following license:
----------------------------------------------------------------------
Copyright (c) 2009 The Go Authors. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+210
View File
@@ -0,0 +1,210 @@
package inf
import (
"fmt"
"math/big"
"math/rand"
"sync"
"testing"
)
const maxcap = 1024 * 1024
const bits = 256
const maxscale = 32
var once sync.Once
var decInput [][2]Dec
var intInput [][2]big.Int
var initBench = func() {
decInput = make([][2]Dec, maxcap)
intInput = make([][2]big.Int, maxcap)
max := new(big.Int).Lsh(big.NewInt(1), bits)
r := rand.New(rand.NewSource(0))
for i := 0; i < cap(decInput); i++ {
decInput[i][0].SetUnscaledBig(new(big.Int).Rand(r, max)).
SetScale(Scale(r.Int31n(int32(2*maxscale-1)) - int32(maxscale)))
decInput[i][1].SetUnscaledBig(new(big.Int).Rand(r, max)).
SetScale(Scale(r.Int31n(int32(2*maxscale-1)) - int32(maxscale)))
}
for i := 0; i < cap(intInput); i++ {
intInput[i][0].Rand(r, max)
intInput[i][1].Rand(r, max)
}
}
func doBenchmarkDec1(b *testing.B, f func(z *Dec)) {
once.Do(initBench)
b.ResetTimer()
b.StartTimer()
for i := 0; i < b.N; i++ {
f(&decInput[i%maxcap][0])
}
}
func doBenchmarkDec2(b *testing.B, f func(x, y *Dec)) {
once.Do(initBench)
b.ResetTimer()
b.StartTimer()
for i := 0; i < b.N; i++ {
f(&decInput[i%maxcap][0], &decInput[i%maxcap][1])
}
}
func doBenchmarkInt1(b *testing.B, f func(z *big.Int)) {
once.Do(initBench)
b.ResetTimer()
b.StartTimer()
for i := 0; i < b.N; i++ {
f(&intInput[i%maxcap][0])
}
}
func doBenchmarkInt2(b *testing.B, f func(x, y *big.Int)) {
once.Do(initBench)
b.ResetTimer()
b.StartTimer()
for i := 0; i < b.N; i++ {
f(&intInput[i%maxcap][0], &intInput[i%maxcap][1])
}
}
func Benchmark_Dec_String(b *testing.B) {
doBenchmarkDec1(b, func(x *Dec) {
x.String()
})
}
func Benchmark_Dec_StringScan(b *testing.B) {
doBenchmarkDec1(b, func(x *Dec) {
s := x.String()
d := new(Dec)
fmt.Sscan(s, d)
})
}
func Benchmark_Dec_GobEncode(b *testing.B) {
doBenchmarkDec1(b, func(x *Dec) {
x.GobEncode()
})
}
func Benchmark_Dec_GobEnDecode(b *testing.B) {
doBenchmarkDec1(b, func(x *Dec) {
g, _ := x.GobEncode()
new(Dec).GobDecode(g)
})
}
func Benchmark_Dec_Add(b *testing.B) {
doBenchmarkDec2(b, func(x, y *Dec) {
ys := y.Scale()
y.SetScale(x.Scale())
_ = new(Dec).Add(x, y)
y.SetScale(ys)
})
}
func Benchmark_Dec_AddMixed(b *testing.B) {
doBenchmarkDec2(b, func(x, y *Dec) {
_ = new(Dec).Add(x, y)
})
}
func Benchmark_Dec_Sub(b *testing.B) {
doBenchmarkDec2(b, func(x, y *Dec) {
ys := y.Scale()
y.SetScale(x.Scale())
_ = new(Dec).Sub(x, y)
y.SetScale(ys)
})
}
func Benchmark_Dec_SubMixed(b *testing.B) {
doBenchmarkDec2(b, func(x, y *Dec) {
_ = new(Dec).Sub(x, y)
})
}
func Benchmark_Dec_Mul(b *testing.B) {
doBenchmarkDec2(b, func(x, y *Dec) {
_ = new(Dec).Mul(x, y)
})
}
func Benchmark_Dec_Mul_QuoExact(b *testing.B) {
doBenchmarkDec2(b, func(x, y *Dec) {
v := new(Dec).Mul(x, y)
_ = new(Dec).QuoExact(v, y)
})
}
func Benchmark_Dec_QuoRound_Fixed_Down(b *testing.B) {
doBenchmarkDec2(b, func(x, y *Dec) {
_ = new(Dec).QuoRound(x, y, 0, RoundDown)
})
}
func Benchmark_Dec_QuoRound_Fixed_HalfUp(b *testing.B) {
doBenchmarkDec2(b, func(x, y *Dec) {
_ = new(Dec).QuoRound(x, y, 0, RoundHalfUp)
})
}
func Benchmark_Int_String(b *testing.B) {
doBenchmarkInt1(b, func(x *big.Int) {
x.String()
})
}
func Benchmark_Int_StringScan(b *testing.B) {
doBenchmarkInt1(b, func(x *big.Int) {
s := x.String()
d := new(big.Int)
fmt.Sscan(s, d)
})
}
func Benchmark_Int_GobEncode(b *testing.B) {
doBenchmarkInt1(b, func(x *big.Int) {
x.GobEncode()
})
}
func Benchmark_Int_GobEnDecode(b *testing.B) {
doBenchmarkInt1(b, func(x *big.Int) {
g, _ := x.GobEncode()
new(big.Int).GobDecode(g)
})
}
func Benchmark_Int_Add(b *testing.B) {
doBenchmarkInt2(b, func(x, y *big.Int) {
_ = new(big.Int).Add(x, y)
})
}
func Benchmark_Int_Sub(b *testing.B) {
doBenchmarkInt2(b, func(x, y *big.Int) {
_ = new(big.Int).Sub(x, y)
})
}
func Benchmark_Int_Mul(b *testing.B) {
doBenchmarkInt2(b, func(x, y *big.Int) {
_ = new(big.Int).Mul(x, y)
})
}
func Benchmark_Int_Quo(b *testing.B) {
doBenchmarkInt2(b, func(x, y *big.Int) {
_ = new(big.Int).Quo(x, y)
})
}
func Benchmark_Int_QuoRem(b *testing.B) {
doBenchmarkInt2(b, func(x, y *big.Int) {
_, _ = new(big.Int).QuoRem(x, y, new(big.Int))
})
}
+615
View File
@@ -0,0 +1,615 @@
// Package inf (type inf.Dec) implements "infinite-precision" decimal
// arithmetic.
// "Infinite precision" describes two characteristics: practically unlimited
// precision for decimal number representation and no support for calculating
// with any specific fixed precision.
// (Although there is no practical limit on precision, inf.Dec can only
// represent finite decimals.)
//
// This package is currently in experimental stage and the API may change.
//
// This package does NOT support:
// - rounding to specific precisions (as opposed to specific decimal positions)
// - the notion of context (each rounding must be explicit)
// - NaN and Inf values, and distinguishing between positive and negative zero
// - conversions to and from float32/64 types
//
// Features considered for possible addition:
// + formatting options
// + Exp method
// + combined operations such as AddRound/MulAdd etc
// + exchanging data in decimal32/64/128 formats
//
package inf
// TODO:
// - avoid excessive deep copying (quo and rounders)
import (
"fmt"
"io"
"math/big"
"strings"
)
// A Dec represents a signed arbitrary-precision decimal.
// It is a combination of a sign, an arbitrary-precision integer coefficient
// value, and a signed fixed-precision exponent value.
// The sign and the coefficient value are handled together as a signed value
// and referred to as the unscaled value.
// (Positive and negative zero values are not distinguished.)
// Since the exponent is most commonly non-positive, it is handled in negated
// form and referred to as scale.
//
// The mathematical value of a Dec equals:
//
// unscaled * 10**(-scale)
//
// Note that different Dec representations may have equal mathematical values.
//
// unscaled scale String()
// -------------------------
// 0 0 "0"
// 0 2 "0.00"
// 0 -2 "0"
// 1 0 "1"
// 100 2 "1.00"
// 10 0 "10"
// 1 -1 "10"
//
// The zero value for a Dec represents the value 0 with scale 0.
//
// Operations are typically performed through the *Dec type.
// The semantics of the assignment operation "=" for "bare" Dec values is
// undefined and should not be relied on.
//
// Methods are typically of the form:
//
// func (z *Dec) Op(x, y *Dec) *Dec
//
// and implement operations z = x Op y with the result as receiver; if it
// is one of the operands it may be overwritten (and its memory reused).
// To enable chaining of operations, the result is also returned. Methods
// returning a result other than *Dec take one of the operands as the receiver.
//
// A "bare" Quo method (quotient / division operation) is not provided, as the
// result is not always a finite decimal and thus in general cannot be
// represented as a Dec.
// Instead, in the common case when rounding is (potentially) necessary,
// QuoRound should be used with a Scale and a Rounder.
// QuoExact or QuoRound with RoundExact can be used in the special cases when it
// is known that the result is always a finite decimal.
//
type Dec struct {
unscaled big.Int
scale Scale
}
// Scale represents the type used for the scale of a Dec.
type Scale int32
const scaleSize = 4 // bytes in a Scale value
// Scaler represents a method for obtaining the scale to use for the result of
// an operation on x and y.
type scaler interface {
Scale(x *Dec, y *Dec) Scale
}
var bigInt = [...]*big.Int{
big.NewInt(0), big.NewInt(1), big.NewInt(2), big.NewInt(3), big.NewInt(4),
big.NewInt(5), big.NewInt(6), big.NewInt(7), big.NewInt(8), big.NewInt(9),
big.NewInt(10),
}
var exp10cache [64]big.Int = func() [64]big.Int {
e10, e10i := [64]big.Int{}, bigInt[1]
for i, _ := range e10 {
e10[i].Set(e10i)
e10i = new(big.Int).Mul(e10i, bigInt[10])
}
return e10
}()
// NewDec allocates and returns a new Dec set to the given int64 unscaled value
// and scale.
func NewDec(unscaled int64, scale Scale) *Dec {
return new(Dec).SetUnscaled(unscaled).SetScale(scale)
}
// NewDecBig allocates and returns a new Dec set to the given *big.Int unscaled
// value and scale.
func NewDecBig(unscaled *big.Int, scale Scale) *Dec {
return new(Dec).SetUnscaledBig(unscaled).SetScale(scale)
}
// Scale returns the scale of x.
func (x *Dec) Scale() Scale {
return x.scale
}
// Unscaled returns the unscaled value of x for u and true for ok when the
// unscaled value can be represented as int64; otherwise it returns an undefined
// int64 value for u and false for ok. Use x.UnscaledBig().Int64() to avoid
// checking the validity of the value when the check is known to be redundant.
func (x *Dec) Unscaled() (u int64, ok bool) {
u = x.unscaled.Int64()
var i big.Int
ok = i.SetInt64(u).Cmp(&x.unscaled) == 0
return
}
// UnscaledBig returns the unscaled value of x as *big.Int.
func (x *Dec) UnscaledBig() *big.Int {
return &x.unscaled
}
// SetScale sets the scale of z, with the unscaled value unchanged, and returns
// z.
// The mathematical value of the Dec changes as if it was multiplied by
// 10**(oldscale-scale).
func (z *Dec) SetScale(scale Scale) *Dec {
z.scale = scale
return z
}
// SetUnscaled sets the unscaled value of z, with the scale unchanged, and
// returns z.
func (z *Dec) SetUnscaled(unscaled int64) *Dec {
z.unscaled.SetInt64(unscaled)
return z
}
// SetUnscaledBig sets the unscaled value of z, with the scale unchanged, and
// returns z.
func (z *Dec) SetUnscaledBig(unscaled *big.Int) *Dec {
z.unscaled.Set(unscaled)
return z
}
// Set sets z to the value of x and returns z.
// It does nothing if z == x.
func (z *Dec) Set(x *Dec) *Dec {
if z != x {
z.SetUnscaledBig(x.UnscaledBig())
z.SetScale(x.Scale())
}
return z
}
// Sign returns:
//
// -1 if x < 0
// 0 if x == 0
// +1 if x > 0
//
func (x *Dec) Sign() int {
return x.UnscaledBig().Sign()
}
// Neg sets z to -x and returns z.
func (z *Dec) Neg(x *Dec) *Dec {
z.SetScale(x.Scale())
z.UnscaledBig().Neg(x.UnscaledBig())
return z
}
// Cmp compares x and y and returns:
//
// -1 if x < y
// 0 if x == y
// +1 if x > y
//
func (x *Dec) Cmp(y *Dec) int {
xx, yy := upscale(x, y)
return xx.UnscaledBig().Cmp(yy.UnscaledBig())
}
// Abs sets z to |x| (the absolute value of x) and returns z.
func (z *Dec) Abs(x *Dec) *Dec {
z.SetScale(x.Scale())
z.UnscaledBig().Abs(x.UnscaledBig())
return z
}
// Add sets z to the sum x+y and returns z.
// The scale of z is the greater of the scales of x and y.
func (z *Dec) Add(x, y *Dec) *Dec {
xx, yy := upscale(x, y)
z.SetScale(xx.Scale())
z.UnscaledBig().Add(xx.UnscaledBig(), yy.UnscaledBig())
return z
}
// Sub sets z to the difference x-y and returns z.
// The scale of z is the greater of the scales of x and y.
func (z *Dec) Sub(x, y *Dec) *Dec {
xx, yy := upscale(x, y)
z.SetScale(xx.Scale())
z.UnscaledBig().Sub(xx.UnscaledBig(), yy.UnscaledBig())
return z
}
// Mul sets z to the product x*y and returns z.
// The scale of z is the sum of the scales of x and y.
func (z *Dec) Mul(x, y *Dec) *Dec {
z.SetScale(x.Scale() + y.Scale())
z.UnscaledBig().Mul(x.UnscaledBig(), y.UnscaledBig())
return z
}
// Round sets z to the value of x rounded to Scale s using Rounder r, and
// returns z.
func (z *Dec) Round(x *Dec, s Scale, r Rounder) *Dec {
return z.QuoRound(x, NewDec(1, 0), s, r)
}
// QuoRound sets z to the quotient x/y, rounded using the given Rounder to the
// specified scale.
//
// If the rounder is RoundExact but the result can not be expressed exactly at
// the specified scale, QuoRound returns nil, and the value of z is undefined.
//
// There is no corresponding Div method; the equivalent can be achieved through
// the choice of Rounder used.
//
func (z *Dec) QuoRound(x, y *Dec, s Scale, r Rounder) *Dec {
return z.quo(x, y, sclr{s}, r)
}
func (z *Dec) quo(x, y *Dec, s scaler, r Rounder) *Dec {
scl := s.Scale(x, y)
var zzz *Dec
if r.UseRemainder() {
zz, rA, rB := new(Dec).quoRem(x, y, scl, true, new(big.Int), new(big.Int))
zzz = r.Round(new(Dec), zz, rA, rB)
} else {
zz, _, _ := new(Dec).quoRem(x, y, scl, false, nil, nil)
zzz = r.Round(new(Dec), zz, nil, nil)
}
if zzz == nil {
return nil
}
return z.Set(zzz)
}
// QuoExact sets z to the quotient x/y and returns z when x/y is a finite
// decimal. Otherwise it returns nil and the value of z is undefined.
//
// The scale of a non-nil result is "x.Scale() - y.Scale()" or greater; it is
// calculated so that the remainder will be zero whenever x/y is a finite
// decimal.
func (z *Dec) QuoExact(x, y *Dec) *Dec {
return z.quo(x, y, scaleQuoExact{}, RoundExact)
}
// quoRem sets z to the quotient x/y with the scale s, and if useRem is true,
// it sets remNum and remDen to the numerator and denominator of the remainder.
// It returns z, remNum and remDen.
//
// The remainder is normalized to the range -1 < r < 1 to simplify rounding;
// that is, the results satisfy the following equation:
//
// x / y = z + (remNum/remDen) * 10**(-z.Scale())
//
// See Rounder for more details about rounding.
//
func (z *Dec) quoRem(x, y *Dec, s Scale, useRem bool,
remNum, remDen *big.Int) (*Dec, *big.Int, *big.Int) {
// difference (required adjustment) compared to "canonical" result scale
shift := s - (x.Scale() - y.Scale())
// pointers to adjusted unscaled dividend and divisor
var ix, iy *big.Int
switch {
case shift > 0:
// increased scale: decimal-shift dividend left
ix = new(big.Int).Mul(x.UnscaledBig(), exp10(shift))
iy = y.UnscaledBig()
case shift < 0:
// decreased scale: decimal-shift divisor left
ix = x.UnscaledBig()
iy = new(big.Int).Mul(y.UnscaledBig(), exp10(-shift))
default:
ix = x.UnscaledBig()
iy = y.UnscaledBig()
}
// save a copy of iy in case it to be overwritten with the result
iy2 := iy
if iy == z.UnscaledBig() {
iy2 = new(big.Int).Set(iy)
}
// set scale
z.SetScale(s)
// set unscaled
if useRem {
// Int division
_, intr := z.UnscaledBig().QuoRem(ix, iy, new(big.Int))
// set remainder
remNum.Set(intr)
remDen.Set(iy2)
} else {
z.UnscaledBig().Quo(ix, iy)
}
return z, remNum, remDen
}
type sclr struct{ s Scale }
func (s sclr) Scale(x, y *Dec) Scale {
return s.s
}
type scaleQuoExact struct{}
func (sqe scaleQuoExact) Scale(x, y *Dec) Scale {
rem := new(big.Rat).SetFrac(x.UnscaledBig(), y.UnscaledBig())
f2, f5 := factor2(rem.Denom()), factor(rem.Denom(), bigInt[5])
var f10 Scale
if f2 > f5 {
f10 = Scale(f2)
} else {
f10 = Scale(f5)
}
return x.Scale() - y.Scale() + f10
}
func factor(n *big.Int, p *big.Int) int {
// could be improved for large factors
d, f := n, 0
for {
dd, dm := new(big.Int).DivMod(d, p, new(big.Int))
if dm.Sign() == 0 {
f++
d = dd
} else {
break
}
}
return f
}
func factor2(n *big.Int) int {
// could be improved for large factors
f := 0
for ; n.Bit(f) == 0; f++ {
}
return f
}
func upscale(a, b *Dec) (*Dec, *Dec) {
if a.Scale() == b.Scale() {
return a, b
}
if a.Scale() > b.Scale() {
bb := b.rescale(a.Scale())
return a, bb
}
aa := a.rescale(b.Scale())
return aa, b
}
func exp10(x Scale) *big.Int {
if int(x) < len(exp10cache) {
return &exp10cache[int(x)]
}
return new(big.Int).Exp(bigInt[10], big.NewInt(int64(x)), nil)
}
func (x *Dec) rescale(newScale Scale) *Dec {
shift := newScale - x.Scale()
switch {
case shift < 0:
e := exp10(-shift)
return NewDecBig(new(big.Int).Quo(x.UnscaledBig(), e), newScale)
case shift > 0:
e := exp10(shift)
return NewDecBig(new(big.Int).Mul(x.UnscaledBig(), e), newScale)
}
return x
}
var zeros = []byte("00000000000000000000000000000000" +
"00000000000000000000000000000000")
var lzeros = Scale(len(zeros))
func appendZeros(s []byte, n Scale) []byte {
for i := Scale(0); i < n; i += lzeros {
if n > i+lzeros {
s = append(s, zeros...)
} else {
s = append(s, zeros[0:n-i]...)
}
}
return s
}
func (x *Dec) String() string {
if x == nil {
return "<nil>"
}
scale := x.Scale()
s := []byte(x.UnscaledBig().String())
if scale <= 0 {
if scale != 0 && x.unscaled.Sign() != 0 {
s = appendZeros(s, -scale)
}
return string(s)
}
negbit := Scale(-((x.Sign() - 1) / 2))
// scale > 0
lens := Scale(len(s))
if lens-negbit <= scale {
ss := make([]byte, 0, scale+2)
if negbit == 1 {
ss = append(ss, '-')
}
ss = append(ss, '0', '.')
ss = appendZeros(ss, scale-lens+negbit)
ss = append(ss, s[negbit:]...)
return string(ss)
}
// lens > scale
ss := make([]byte, 0, lens+1)
ss = append(ss, s[:lens-scale]...)
ss = append(ss, '.')
ss = append(ss, s[lens-scale:]...)
return string(ss)
}
// Format is a support routine for fmt.Formatter. It accepts the decimal
// formats 'd' and 'f', and handles both equivalently.
// Width, precision, flags and bases 2, 8, 16 are not supported.
func (x *Dec) Format(s fmt.State, ch rune) {
if ch != 'd' && ch != 'f' && ch != 'v' && ch != 's' {
fmt.Fprintf(s, "%%!%c(dec.Dec=%s)", ch, x.String())
return
}
fmt.Fprintf(s, x.String())
}
func (z *Dec) scan(r io.RuneScanner) (*Dec, error) {
unscaled := make([]byte, 0, 256) // collects chars of unscaled as bytes
dp, dg := -1, -1 // indexes of decimal point, first digit
loop:
for {
ch, _, err := r.ReadRune()
if err == io.EOF {
break loop
}
if err != nil {
return nil, err
}
switch {
case ch == '+' || ch == '-':
if len(unscaled) > 0 || dp >= 0 { // must be first character
r.UnreadRune()
break loop
}
case ch == '.':
if dp >= 0 {
r.UnreadRune()
break loop
}
dp = len(unscaled)
continue // don't add to unscaled
case ch >= '0' && ch <= '9':
if dg == -1 {
dg = len(unscaled)
}
default:
r.UnreadRune()
break loop
}
unscaled = append(unscaled, byte(ch))
}
if dg == -1 {
return nil, fmt.Errorf("no digits read")
}
if dp >= 0 {
z.SetScale(Scale(len(unscaled) - dp))
} else {
z.SetScale(0)
}
_, ok := z.UnscaledBig().SetString(string(unscaled), 10)
if !ok {
return nil, fmt.Errorf("invalid decimal: %s", string(unscaled))
}
return z, nil
}
// SetString sets z to the value of s, interpreted as a decimal (base 10),
// and returns z and a boolean indicating success. The scale of z is the
// number of digits after the decimal point (including any trailing 0s),
// or 0 if there is no decimal point. If SetString fails, the value of z
// is undefined but the returned value is nil.
func (z *Dec) SetString(s string) (*Dec, bool) {
r := strings.NewReader(s)
_, err := z.scan(r)
if err != nil {
return nil, false
}
_, _, err = r.ReadRune()
if err != io.EOF {
return nil, false
}
// err == io.EOF => scan consumed all of s
return z, true
}
// Scan is a support routine for fmt.Scanner; it sets z to the value of
// the scanned number. It accepts the decimal formats 'd' and 'f', and
// handles both equivalently. Bases 2, 8, 16 are not supported.
// The scale of z is the number of digits after the decimal point
// (including any trailing 0s), or 0 if there is no decimal point.
func (z *Dec) Scan(s fmt.ScanState, ch rune) error {
if ch != 'd' && ch != 'f' && ch != 's' && ch != 'v' {
return fmt.Errorf("Dec.Scan: invalid verb '%c'", ch)
}
s.SkipSpace()
_, err := z.scan(s)
return err
}
// Gob encoding version
const decGobVersion byte = 1
func scaleBytes(s Scale) []byte {
buf := make([]byte, scaleSize)
i := scaleSize
for j := 0; j < scaleSize; j++ {
i--
buf[i] = byte(s)
s >>= 8
}
return buf
}
func scale(b []byte) (s Scale) {
for j := 0; j < scaleSize; j++ {
s <<= 8
s |= Scale(b[j])
}
return
}
// GobEncode implements the gob.GobEncoder interface.
func (x *Dec) GobEncode() ([]byte, error) {
buf, err := x.UnscaledBig().GobEncode()
if err != nil {
return nil, err
}
buf = append(append(buf, scaleBytes(x.Scale())...), decGobVersion)
return buf, nil
}
// GobDecode implements the gob.GobDecoder interface.
func (z *Dec) GobDecode(buf []byte) error {
if len(buf) == 0 {
return fmt.Errorf("Dec.GobDecode: no data")
}
b := buf[len(buf)-1]
if b != decGobVersion {
return fmt.Errorf("Dec.GobDecode: encoding version %d not supported", b)
}
l := len(buf) - scaleSize - 1
err := z.UnscaledBig().GobDecode(buf[:l])
if err != nil {
return err
}
z.SetScale(scale(buf[l : l+scaleSize]))
return nil
}
// MarshalText implements the encoding.TextMarshaler interface.
func (x *Dec) MarshalText() ([]byte, error) {
return []byte(x.String()), nil
}
// UnmarshalText implements the encoding.TextUnmarshaler interface.
func (z *Dec) UnmarshalText(data []byte) error {
_, ok := z.SetString(string(data))
if !ok {
return fmt.Errorf("invalid inf.Dec")
}
return nil
}
+33
View File
@@ -0,0 +1,33 @@
// +build go1.2
package inf
import (
"encoding"
"encoding/json"
"testing"
)
var _ encoding.TextMarshaler = new(Dec)
var _ encoding.TextUnmarshaler = new(Dec)
type Obj struct {
Val *Dec
}
func TestDecJsonMarshalUnmarshal(t *testing.T) {
o := Obj{Val: NewDec(123, 2)}
js, err := json.Marshal(o)
if err != nil {
t.Fatalf("json.Marshal(%v): got %v, want ok", o, err)
}
o2 := &Obj{}
err = json.Unmarshal(js, o2)
if err != nil {
t.Fatalf("json.Unmarshal(%#q): got %v, want ok", js, err)
}
if o.Val.Scale() != o2.Val.Scale() ||
o.Val.UnscaledBig().Cmp(o2.Val.UnscaledBig()) != 0 {
t.Fatalf("json.Unmarshal(json.Marshal(%v)): want %v, got %v", o, o, o2)
}
}
@@ -0,0 +1,40 @@
package inf
import (
"math/big"
"testing"
)
var decQuoRemZZZ = []struct {
z, x, y *Dec
r *big.Rat
srA, srB int
}{
// basic examples
{NewDec(1, 0), NewDec(2, 0), NewDec(2, 0), big.NewRat(0, 1), 0, 1},
{NewDec(15, 1), NewDec(3, 0), NewDec(2, 0), big.NewRat(0, 1), 0, 1},
{NewDec(1, 1), NewDec(1, 0), NewDec(10, 0), big.NewRat(0, 1), 0, 1},
{NewDec(0, 0), NewDec(2, 0), NewDec(3, 0), big.NewRat(2, 3), 1, 1},
{NewDec(0, 0), NewDec(2, 0), NewDec(6, 0), big.NewRat(1, 3), 1, 1},
{NewDec(1, 1), NewDec(2, 0), NewDec(12, 0), big.NewRat(2, 3), 1, 1},
// examples from the Go Language Specification
{NewDec(1, 0), NewDec(5, 0), NewDec(3, 0), big.NewRat(2, 3), 1, 1},
{NewDec(-1, 0), NewDec(-5, 0), NewDec(3, 0), big.NewRat(-2, 3), -1, 1},
{NewDec(-1, 0), NewDec(5, 0), NewDec(-3, 0), big.NewRat(-2, 3), 1, -1},
{NewDec(1, 0), NewDec(-5, 0), NewDec(-3, 0), big.NewRat(2, 3), -1, -1},
}
func TestDecQuoRem(t *testing.T) {
for i, a := range decQuoRemZZZ {
z, rA, rB := new(Dec), new(big.Int), new(big.Int)
s := scaleQuoExact{}.Scale(a.x, a.y)
z.quoRem(a.x, a.y, s, true, rA, rB)
if a.z.Cmp(z) != 0 || a.r.Cmp(new(big.Rat).SetFrac(rA, rB)) != 0 {
t.Errorf("#%d QuoRemZZZ got %v, %v, %v; expected %v, %v", i, z, rA, rB, a.z, a.r)
}
if a.srA != rA.Sign() || a.srB != rB.Sign() {
t.Errorf("#%d QuoRemZZZ wrong signs, got %v, %v; expected %v, %v", i, rA.Sign(), rB.Sign(), a.srA, a.srB)
}
}
}
+379
View File
@@ -0,0 +1,379 @@
package inf_test
import (
"bytes"
"encoding/gob"
"fmt"
"math/big"
"strings"
"testing"
"github.com/coreos/rocket/Godeps/_workspace/src/speter.net/go/exp/math/dec/inf"
)
type decFunZZ func(z, x, y *inf.Dec) *inf.Dec
type decArgZZ struct {
z, x, y *inf.Dec
}
var decSumZZ = []decArgZZ{
{inf.NewDec(0, 0), inf.NewDec(0, 0), inf.NewDec(0, 0)},
{inf.NewDec(1, 0), inf.NewDec(1, 0), inf.NewDec(0, 0)},
{inf.NewDec(1111111110, 0), inf.NewDec(123456789, 0), inf.NewDec(987654321, 0)},
{inf.NewDec(-1, 0), inf.NewDec(-1, 0), inf.NewDec(0, 0)},
{inf.NewDec(864197532, 0), inf.NewDec(-123456789, 0), inf.NewDec(987654321, 0)},
{inf.NewDec(-1111111110, 0), inf.NewDec(-123456789, 0), inf.NewDec(-987654321, 0)},
{inf.NewDec(12, 2), inf.NewDec(1, 1), inf.NewDec(2, 2)},
}
var decProdZZ = []decArgZZ{
{inf.NewDec(0, 0), inf.NewDec(0, 0), inf.NewDec(0, 0)},
{inf.NewDec(0, 0), inf.NewDec(1, 0), inf.NewDec(0, 0)},
{inf.NewDec(1, 0), inf.NewDec(1, 0), inf.NewDec(1, 0)},
{inf.NewDec(-991*991, 0), inf.NewDec(991, 0), inf.NewDec(-991, 0)},
{inf.NewDec(2, 3), inf.NewDec(1, 1), inf.NewDec(2, 2)},
{inf.NewDec(2, -3), inf.NewDec(1, -1), inf.NewDec(2, -2)},
{inf.NewDec(2, 3), inf.NewDec(1, 1), inf.NewDec(2, 2)},
}
func TestDecSignZ(t *testing.T) {
var zero inf.Dec
for _, a := range decSumZZ {
s := a.z.Sign()
e := a.z.Cmp(&zero)
if s != e {
t.Errorf("got %d; want %d for z = %v", s, e, a.z)
}
}
}
func TestDecAbsZ(t *testing.T) {
var zero inf.Dec
for _, a := range decSumZZ {
var z inf.Dec
z.Abs(a.z)
var e inf.Dec
e.Set(a.z)
if e.Cmp(&zero) < 0 {
e.Sub(&zero, &e)
}
if z.Cmp(&e) != 0 {
t.Errorf("got z = %v; want %v", z, e)
}
}
}
func testDecFunZZ(t *testing.T, msg string, f decFunZZ, a decArgZZ) {
var z inf.Dec
f(&z, a.x, a.y)
if (&z).Cmp(a.z) != 0 {
t.Errorf("%s%+v\n\tgot z = %v; want %v", msg, a, &z, a.z)
}
}
func TestDecSumZZ(t *testing.T) {
AddZZ := func(z, x, y *inf.Dec) *inf.Dec { return z.Add(x, y) }
SubZZ := func(z, x, y *inf.Dec) *inf.Dec { return z.Sub(x, y) }
for _, a := range decSumZZ {
arg := a
testDecFunZZ(t, "AddZZ", AddZZ, arg)
arg = decArgZZ{a.z, a.y, a.x}
testDecFunZZ(t, "AddZZ symmetric", AddZZ, arg)
arg = decArgZZ{a.x, a.z, a.y}
testDecFunZZ(t, "SubZZ", SubZZ, arg)
arg = decArgZZ{a.y, a.z, a.x}
testDecFunZZ(t, "SubZZ symmetric", SubZZ, arg)
}
}
func TestDecProdZZ(t *testing.T) {
MulZZ := func(z, x, y *inf.Dec) *inf.Dec { return z.Mul(x, y) }
for _, a := range decProdZZ {
arg := a
testDecFunZZ(t, "MulZZ", MulZZ, arg)
arg = decArgZZ{a.z, a.y, a.x}
testDecFunZZ(t, "MulZZ symmetric", MulZZ, arg)
}
}
var decUnscaledTests = []struct {
d *inf.Dec
u int64 // ignored when ok == false
ok bool
}{
{new(inf.Dec), 0, true},
{inf.NewDec(-1<<63, 0), -1 << 63, true},
{inf.NewDec(-(-1<<63 + 1), 0), -(-1<<63 + 1), true},
{new(inf.Dec).Neg(inf.NewDec(-1<<63, 0)), 0, false},
{new(inf.Dec).Sub(inf.NewDec(-1<<63, 0), inf.NewDec(1, 0)), 0, false},
{inf.NewDecBig(new(big.Int).Lsh(big.NewInt(1), 64), 0), 0, false},
}
func TestDecUnscaled(t *testing.T) {
for i, tt := range decUnscaledTests {
u, ok := tt.d.Unscaled()
if ok != tt.ok {
t.Errorf("#%d Unscaled: got %v, expected %v", i, ok, tt.ok)
} else if ok && u != tt.u {
t.Errorf("#%d Unscaled: got %v, expected %v", i, u, tt.u)
}
}
}
var decRoundTests = [...]struct {
in *inf.Dec
s inf.Scale
r inf.Rounder
exp *inf.Dec
}{
{inf.NewDec(123424999999999993, 15), 2, inf.RoundHalfUp, inf.NewDec(12342, 2)},
{inf.NewDec(123425000000000001, 15), 2, inf.RoundHalfUp, inf.NewDec(12343, 2)},
{inf.NewDec(123424999999999993, 15), 15, inf.RoundHalfUp, inf.NewDec(123424999999999993, 15)},
{inf.NewDec(123424999999999993, 15), 16, inf.RoundHalfUp, inf.NewDec(1234249999999999930, 16)},
{inf.NewDecBig(new(big.Int).Lsh(big.NewInt(1), 64), 0), -1, inf.RoundHalfUp, inf.NewDec(1844674407370955162, -1)},
{inf.NewDecBig(new(big.Int).Lsh(big.NewInt(1), 64), 0), -2, inf.RoundHalfUp, inf.NewDec(184467440737095516, -2)},
{inf.NewDecBig(new(big.Int).Lsh(big.NewInt(1), 64), 0), -3, inf.RoundHalfUp, inf.NewDec(18446744073709552, -3)},
{inf.NewDecBig(new(big.Int).Lsh(big.NewInt(1), 64), 0), -4, inf.RoundHalfUp, inf.NewDec(1844674407370955, -4)},
{inf.NewDecBig(new(big.Int).Lsh(big.NewInt(1), 64), 0), -5, inf.RoundHalfUp, inf.NewDec(184467440737096, -5)},
{inf.NewDecBig(new(big.Int).Lsh(big.NewInt(1), 64), 0), -6, inf.RoundHalfUp, inf.NewDec(18446744073710, -6)},
}
func TestDecRound(t *testing.T) {
for i, tt := range decRoundTests {
z := new(inf.Dec).Round(tt.in, tt.s, tt.r)
if tt.exp.Cmp(z) != 0 {
t.Errorf("#%d Round got %v; expected %v", i, z, tt.exp)
}
}
}
var decStringTests = []struct {
in string
out string
val int64
scale inf.Scale // skip SetString if negative
ok bool
scanOk bool
}{
{in: "", ok: false, scanOk: false},
{in: "a", ok: false, scanOk: false},
{in: "z", ok: false, scanOk: false},
{in: "+", ok: false, scanOk: false},
{in: "-", ok: false, scanOk: false},
{in: "g", ok: false, scanOk: false},
{in: ".", ok: false, scanOk: false},
{in: ".-0", ok: false, scanOk: false},
{in: ".+0", ok: false, scanOk: false},
// Scannable but not SetStringable
{"0b", "ignored", 0, 0, false, true},
{"0x", "ignored", 0, 0, false, true},
{"0xg", "ignored", 0, 0, false, true},
{"0.0g", "ignored", 0, 1, false, true},
// examples from godoc for Dec
{"0", "0", 0, 0, true, true},
{"0.00", "0.00", 0, 2, true, true},
{"ignored", "0", 0, -2, true, false},
{"1", "1", 1, 0, true, true},
{"1.00", "1.00", 100, 2, true, true},
{"10", "10", 10, 0, true, true},
{"ignored", "10", 1, -1, true, false},
// other tests
{"+0", "0", 0, 0, true, true},
{"-0", "0", 0, 0, true, true},
{"0.0", "0.0", 0, 1, true, true},
{"0.1", "0.1", 1, 1, true, true},
{"0.", "0", 0, 0, true, true},
{"-10", "-10", -1, -1, true, true},
{"-1", "-1", -1, 0, true, true},
{"-0.1", "-0.1", -1, 1, true, true},
{"-0.01", "-0.01", -1, 2, true, true},
{"+0.", "0", 0, 0, true, true},
{"-0.", "0", 0, 0, true, true},
{".0", "0.0", 0, 1, true, true},
{"+.0", "0.0", 0, 1, true, true},
{"-.0", "0.0", 0, 1, true, true},
{"0.0000000000", "0.0000000000", 0, 10, true, true},
{"0.0000000001", "0.0000000001", 1, 10, true, true},
{"-0.0000000000", "0.0000000000", 0, 10, true, true},
{"-0.0000000001", "-0.0000000001", -1, 10, true, true},
{"-10", "-10", -10, 0, true, true},
{"+10", "10", 10, 0, true, true},
{"00", "0", 0, 0, true, true},
{"023", "23", 23, 0, true, true}, // decimal, not octal
{"-02.3", "-2.3", -23, 1, true, true}, // decimal, not octal
}
func TestDecGetString(t *testing.T) {
z := new(inf.Dec)
for i, test := range decStringTests {
if !test.ok {
continue
}
z.SetUnscaled(test.val)
z.SetScale(test.scale)
s := z.String()
if s != test.out {
t.Errorf("#%da got %s; want %s", i, s, test.out)
}
s = fmt.Sprintf("%d", z)
if s != test.out {
t.Errorf("#%db got %s; want %s", i, s, test.out)
}
}
}
func TestDecSetString(t *testing.T) {
tmp := new(inf.Dec)
for i, test := range decStringTests {
if test.scale < 0 {
// SetString only supports scale >= 0
continue
}
// initialize to a non-zero value so that issues with parsing
// 0 are detected
tmp.Set(inf.NewDec(1234567890, 123))
n1, ok1 := new(inf.Dec).SetString(test.in)
n2, ok2 := tmp.SetString(test.in)
expected := inf.NewDec(test.val, test.scale)
if ok1 != test.ok || ok2 != test.ok {
t.Errorf("#%d (input '%s') ok incorrect (should be %t)", i, test.in, test.ok)
continue
}
if !ok1 {
if n1 != nil {
t.Errorf("#%d (input '%s') n1 != nil", i, test.in)
}
continue
}
if !ok2 {
if n2 != nil {
t.Errorf("#%d (input '%s') n2 != nil", i, test.in)
}
continue
}
if n1.Cmp(expected) != 0 {
t.Errorf("#%d (input '%s') got: %s want: %d", i, test.in, n1, test.val)
}
if n2.Cmp(expected) != 0 {
t.Errorf("#%d (input '%s') got: %s want: %d", i, test.in, n2, test.val)
}
}
}
func TestDecScan(t *testing.T) {
tmp := new(inf.Dec)
for i, test := range decStringTests {
if test.scale < 0 {
// SetString only supports scale >= 0
continue
}
// initialize to a non-zero value so that issues with parsing
// 0 are detected
tmp.Set(inf.NewDec(1234567890, 123))
n1, n2 := new(inf.Dec), tmp
nn1, err1 := fmt.Sscan(test.in, n1)
nn2, err2 := fmt.Sscan(test.in, n2)
if !test.scanOk {
if err1 == nil || err2 == nil {
t.Errorf("#%d (input '%s') ok incorrect, should be %t", i, test.in, test.scanOk)
}
continue
}
expected := inf.NewDec(test.val, test.scale)
if nn1 != 1 || err1 != nil || nn2 != 1 || err2 != nil {
t.Errorf("#%d (input '%s') error %d %v, %d %v", i, test.in, nn1, err1, nn2, err2)
continue
}
if n1.Cmp(expected) != 0 {
t.Errorf("#%d (input '%s') got: %s want: %d", i, test.in, n1, test.val)
}
if n2.Cmp(expected) != 0 {
t.Errorf("#%d (input '%s') got: %s want: %d", i, test.in, n2, test.val)
}
}
}
var decScanNextTests = []struct {
in string
ok bool
next rune
}{
{"", false, 0},
{"a", false, 'a'},
{"z", false, 'z'},
{"+", false, 0},
{"-", false, 0},
{"g", false, 'g'},
{".", false, 0},
{".-0", false, '-'},
{".+0", false, '+'},
{"0b", true, 'b'},
{"0x", true, 'x'},
{"0xg", true, 'x'},
{"0.0g", true, 'g'},
}
func TestDecScanNext(t *testing.T) {
for i, test := range decScanNextTests {
rdr := strings.NewReader(test.in)
n1 := new(inf.Dec)
nn1, _ := fmt.Fscan(rdr, n1)
if (test.ok && nn1 == 0) || (!test.ok && nn1 > 0) {
t.Errorf("#%d (input '%s') ok incorrect should be %t", i, test.in, test.ok)
continue
}
r := rune(0)
nn2, err := fmt.Fscanf(rdr, "%c", &r)
if test.next != r {
t.Errorf("#%d (input '%s') next incorrect, got %c should be %c, %d, %v", i, test.in, r, test.next, nn2, err)
}
}
}
var decGobEncodingTests = []string{
"0",
"1",
"2",
"10",
"42",
"1234567890",
"298472983472983471903246121093472394872319615612417471234712061",
}
func TestDecGobEncoding(t *testing.T) {
var medium bytes.Buffer
enc := gob.NewEncoder(&medium)
dec := gob.NewDecoder(&medium)
for i, test := range decGobEncodingTests {
for j := 0; j < 2; j++ {
for k := inf.Scale(-5); k <= 5; k++ {
medium.Reset() // empty buffer for each test case (in case of failures)
stest := test
if j != 0 {
// negative numbers
stest = "-" + test
}
var tx inf.Dec
tx.SetString(stest)
tx.SetScale(k) // test with positive, negative, and zero scale
if err := enc.Encode(&tx); err != nil {
t.Errorf("#%d%c: encoding failed: %s", i, 'a'+j, err)
}
var rx inf.Dec
if err := dec.Decode(&rx); err != nil {
t.Errorf("#%d%c: decoding failed: %s", i, 'a'+j, err)
}
if rx.Cmp(&tx) != 0 {
t.Errorf("#%d%c: transmission failed: got %s want %s", i, 'a'+j, &rx, &tx)
}
}
}
}
}
+62
View File
@@ -0,0 +1,62 @@
package inf_test
import (
"fmt"
"log"
)
import "github.com/coreos/rocket/Godeps/_workspace/src/speter.net/go/exp/math/dec/inf"
func ExampleDec_SetString() {
d := new(inf.Dec)
d.SetString("012345.67890") // decimal; leading 0 ignored; trailing 0 kept
fmt.Println(d)
// Output: 12345.67890
}
func ExampleDec_Scan() {
// The Scan function is rarely used directly;
// the fmt package recognizes it as an implementation of fmt.Scanner.
d := new(inf.Dec)
_, err := fmt.Sscan("184467440.73709551617", d)
if err != nil {
log.Println("error scanning value:", err)
} else {
fmt.Println(d)
}
// Output: 184467440.73709551617
}
func ExampleDec_QuoRound_scale2RoundDown() {
// 10 / 3 is an infinite decimal; it has no exact Dec representation
x, y := inf.NewDec(10, 0), inf.NewDec(3, 0)
// use 2 digits beyond the decimal point, round towards 0
z := new(inf.Dec).QuoRound(x, y, 2, inf.RoundDown)
fmt.Println(z)
// Output: 3.33
}
func ExampleDec_QuoRound_scale2RoundCeil() {
// -42 / 400 is an finite decimal with 3 digits beyond the decimal point
x, y := inf.NewDec(-42, 0), inf.NewDec(400, 0)
// use 2 digits beyond decimal point, round towards positive infinity
z := new(inf.Dec).QuoRound(x, y, 2, inf.RoundCeil)
fmt.Println(z)
// Output: -0.10
}
func ExampleDec_QuoExact_ok() {
// 1 / 25 is a finite decimal; it has exact Dec representation
x, y := inf.NewDec(1, 0), inf.NewDec(25, 0)
z := new(inf.Dec).QuoExact(x, y)
fmt.Println(z)
// Output: 0.04
}
func ExampleDec_QuoExact_fail() {
// 1 / 3 is an infinite decimal; it has no exact Dec representation
x, y := inf.NewDec(1, 0), inf.NewDec(3, 0)
z := new(inf.Dec).QuoExact(x, y)
fmt.Println(z)
// Output: <nil>
}
+145
View File
@@ -0,0 +1,145 @@
package inf
import (
"math/big"
)
// Rounder represents a method for rounding the (possibly infinite decimal)
// result of a division to a finite Dec. It is used by Dec.Round() and
// Dec.Quo().
//
// See the Example for results of using each Rounder with some sample values.
//
type Rounder rounder
// See http://speleotrove.com/decimal/damodel.html#refround for more detailed
// definitions of these rounding modes.
var (
RoundDown Rounder // towards 0
RoundUp Rounder // away from 0
RoundFloor Rounder // towards -infinity
RoundCeil Rounder // towards +infinity
RoundHalfDown Rounder // to nearest; towards 0 if same distance
RoundHalfUp Rounder // to nearest; away from 0 if same distance
RoundHalfEven Rounder // to nearest; even last digit if same distance
)
// RoundExact is to be used in the case when rounding is not necessary.
// When used with Quo or Round, it returns the result verbatim when it can be
// expressed exactly with the given precision, and it returns nil otherwise.
// QuoExact is a shorthand for using Quo with RoundExact.
var RoundExact Rounder
type rounder interface {
// When UseRemainder() returns true, the Round() method is passed the
// remainder of the division, expressed as the numerator and denominator of
// a rational.
UseRemainder() bool
// Round sets the rounded value of a quotient to z, and returns z.
// quo is rounded down (truncated towards zero) to the scale obtained from
// the Scaler in Quo().
//
// When the remainder is not used, remNum and remDen are nil.
// When used, the remainder is normalized between -1 and 1; that is:
//
// -|remDen| < remNum < |remDen|
//
// remDen has the same sign as y, and remNum is zero or has the same sign
// as x.
Round(z, quo *Dec, remNum, remDen *big.Int) *Dec
}
type rndr struct {
useRem bool
round func(z, quo *Dec, remNum, remDen *big.Int) *Dec
}
func (r rndr) UseRemainder() bool {
return r.useRem
}
func (r rndr) Round(z, quo *Dec, remNum, remDen *big.Int) *Dec {
return r.round(z, quo, remNum, remDen)
}
var intSign = []*big.Int{big.NewInt(-1), big.NewInt(0), big.NewInt(1)}
func roundHalf(f func(c int, odd uint) (roundUp bool)) func(z, q *Dec, rA, rB *big.Int) *Dec {
return func(z, q *Dec, rA, rB *big.Int) *Dec {
z.Set(q)
brA, brB := rA.BitLen(), rB.BitLen()
if brA < brB-1 {
// brA < brB-1 => |rA| < |rB/2|
return z
}
roundUp := false
srA, srB := rA.Sign(), rB.Sign()
s := srA * srB
if brA == brB-1 {
rA2 := new(big.Int).Lsh(rA, 1)
if s < 0 {
rA2.Neg(rA2)
}
roundUp = f(rA2.Cmp(rB)*srB, z.UnscaledBig().Bit(0))
} else {
// brA > brB-1 => |rA| > |rB/2|
roundUp = true
}
if roundUp {
z.UnscaledBig().Add(z.UnscaledBig(), intSign[s+1])
}
return z
}
}
func init() {
RoundExact = rndr{true,
func(z, q *Dec, rA, rB *big.Int) *Dec {
if rA.Sign() != 0 {
return nil
}
return z.Set(q)
}}
RoundDown = rndr{false,
func(z, q *Dec, rA, rB *big.Int) *Dec {
return z.Set(q)
}}
RoundUp = rndr{true,
func(z, q *Dec, rA, rB *big.Int) *Dec {
z.Set(q)
if rA.Sign() != 0 {
z.UnscaledBig().Add(z.UnscaledBig(), intSign[rA.Sign()*rB.Sign()+1])
}
return z
}}
RoundFloor = rndr{true,
func(z, q *Dec, rA, rB *big.Int) *Dec {
z.Set(q)
if rA.Sign()*rB.Sign() < 0 {
z.UnscaledBig().Add(z.UnscaledBig(), intSign[0])
}
return z
}}
RoundCeil = rndr{true,
func(z, q *Dec, rA, rB *big.Int) *Dec {
z.Set(q)
if rA.Sign()*rB.Sign() > 0 {
z.UnscaledBig().Add(z.UnscaledBig(), intSign[2])
}
return z
}}
RoundHalfDown = rndr{true, roundHalf(
func(c int, odd uint) bool {
return c > 0
})}
RoundHalfUp = rndr{true, roundHalf(
func(c int, odd uint) bool {
return c >= 0
})}
RoundHalfEven = rndr{true, roundHalf(
func(c int, odd uint) bool {
return c > 0 || c == 0 && odd == 1
})}
}
@@ -0,0 +1,72 @@
package inf_test
import (
"fmt"
"os"
"text/tabwriter"
"github.com/coreos/rocket/Godeps/_workspace/src/speter.net/go/exp/math/dec/inf"
)
// This example displays the results of Dec.Round with each of the Rounders.
//
func ExampleRounder() {
var vals = []struct {
x string
s inf.Scale
}{
{"-0.18", 1}, {"-0.15", 1}, {"-0.12", 1}, {"-0.10", 1},
{"-0.08", 1}, {"-0.05", 1}, {"-0.02", 1}, {"0.00", 1},
{"0.02", 1}, {"0.05", 1}, {"0.08", 1}, {"0.10", 1},
{"0.12", 1}, {"0.15", 1}, {"0.18", 1},
}
var rounders = []struct {
name string
rounder inf.Rounder
}{
{"RoundDown", inf.RoundDown}, {"RoundUp", inf.RoundUp},
{"RoundCeil", inf.RoundCeil}, {"RoundFloor", inf.RoundFloor},
{"RoundHalfDown", inf.RoundHalfDown}, {"RoundHalfUp", inf.RoundHalfUp},
{"RoundHalfEven", inf.RoundHalfEven}, {"RoundExact", inf.RoundExact},
}
fmt.Println("The results of new(inf.Dec).Round(x, s, inf.RoundXXX):\n")
w := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', tabwriter.AlignRight)
fmt.Fprint(w, "x\ts\t|\t")
for _, r := range rounders {
fmt.Fprintf(w, "%s\t", r.name[5:])
}
fmt.Fprintln(w)
for _, v := range vals {
fmt.Fprintf(w, "%s\t%d\t|\t", v.x, v.s)
for _, r := range rounders {
x, _ := new(inf.Dec).SetString(v.x)
z := new(inf.Dec).Round(x, v.s, r.rounder)
fmt.Fprintf(w, "%d\t", z)
}
fmt.Fprintln(w)
}
w.Flush()
// Output:
// The results of new(inf.Dec).Round(x, s, inf.RoundXXX):
//
// x s | Down Up Ceil Floor HalfDown HalfUp HalfEven Exact
// -0.18 1 | -0.1 -0.2 -0.1 -0.2 -0.2 -0.2 -0.2 <nil>
// -0.15 1 | -0.1 -0.2 -0.1 -0.2 -0.1 -0.2 -0.2 <nil>
// -0.12 1 | -0.1 -0.2 -0.1 -0.2 -0.1 -0.1 -0.1 <nil>
// -0.10 1 | -0.1 -0.1 -0.1 -0.1 -0.1 -0.1 -0.1 -0.1
// -0.08 1 | 0.0 -0.1 0.0 -0.1 -0.1 -0.1 -0.1 <nil>
// -0.05 1 | 0.0 -0.1 0.0 -0.1 0.0 -0.1 0.0 <nil>
// -0.02 1 | 0.0 -0.1 0.0 -0.1 0.0 0.0 0.0 <nil>
// 0.00 1 | 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
// 0.02 1 | 0.0 0.1 0.1 0.0 0.0 0.0 0.0 <nil>
// 0.05 1 | 0.0 0.1 0.1 0.0 0.0 0.1 0.0 <nil>
// 0.08 1 | 0.0 0.1 0.1 0.0 0.1 0.1 0.1 <nil>
// 0.10 1 | 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1
// 0.12 1 | 0.1 0.2 0.2 0.1 0.1 0.1 0.1 <nil>
// 0.15 1 | 0.1 0.2 0.2 0.1 0.1 0.2 0.2 <nil>
// 0.18 1 | 0.1 0.2 0.2 0.1 0.2 0.2 0.2 <nil>
}
+109
View File
@@ -0,0 +1,109 @@
package inf_test
import (
"math/big"
"testing"
"github.com/coreos/rocket/Godeps/_workspace/src/speter.net/go/exp/math/dec/inf"
)
var decRounderInputs = [...]struct {
quo *inf.Dec
rA, rB *big.Int
}{
// examples from go language spec
{inf.NewDec(1, 0), big.NewInt(2), big.NewInt(3)}, // 5 / 3
{inf.NewDec(-1, 0), big.NewInt(-2), big.NewInt(3)}, // -5 / 3
{inf.NewDec(-1, 0), big.NewInt(2), big.NewInt(-3)}, // 5 / -3
{inf.NewDec(1, 0), big.NewInt(-2), big.NewInt(-3)}, // -5 / -3
// examples from godoc
{inf.NewDec(-1, 1), big.NewInt(-8), big.NewInt(10)},
{inf.NewDec(-1, 1), big.NewInt(-5), big.NewInt(10)},
{inf.NewDec(-1, 1), big.NewInt(-2), big.NewInt(10)},
{inf.NewDec(0, 1), big.NewInt(-8), big.NewInt(10)},
{inf.NewDec(0, 1), big.NewInt(-5), big.NewInt(10)},
{inf.NewDec(0, 1), big.NewInt(-2), big.NewInt(10)},
{inf.NewDec(0, 1), big.NewInt(0), big.NewInt(1)},
{inf.NewDec(0, 1), big.NewInt(2), big.NewInt(10)},
{inf.NewDec(0, 1), big.NewInt(5), big.NewInt(10)},
{inf.NewDec(0, 1), big.NewInt(8), big.NewInt(10)},
{inf.NewDec(1, 1), big.NewInt(2), big.NewInt(10)},
{inf.NewDec(1, 1), big.NewInt(5), big.NewInt(10)},
{inf.NewDec(1, 1), big.NewInt(8), big.NewInt(10)},
}
var decRounderResults = [...]struct {
rounder inf.Rounder
results [len(decRounderInputs)]*inf.Dec
}{
{inf.RoundExact, [...]*inf.Dec{nil, nil, nil, nil,
nil, nil, nil, nil, nil, nil,
inf.NewDec(0, 1), nil, nil, nil, nil, nil, nil}},
{inf.RoundDown, [...]*inf.Dec{
inf.NewDec(1, 0), inf.NewDec(-1, 0), inf.NewDec(-1, 0), inf.NewDec(1, 0),
inf.NewDec(-1, 1), inf.NewDec(-1, 1), inf.NewDec(-1, 1),
inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(0, 1),
inf.NewDec(0, 1),
inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(0, 1),
inf.NewDec(1, 1), inf.NewDec(1, 1), inf.NewDec(1, 1)}},
{inf.RoundUp, [...]*inf.Dec{
inf.NewDec(2, 0), inf.NewDec(-2, 0), inf.NewDec(-2, 0), inf.NewDec(2, 0),
inf.NewDec(-2, 1), inf.NewDec(-2, 1), inf.NewDec(-2, 1),
inf.NewDec(-1, 1), inf.NewDec(-1, 1), inf.NewDec(-1, 1),
inf.NewDec(0, 1),
inf.NewDec(1, 1), inf.NewDec(1, 1), inf.NewDec(1, 1),
inf.NewDec(2, 1), inf.NewDec(2, 1), inf.NewDec(2, 1)}},
{inf.RoundHalfDown, [...]*inf.Dec{
inf.NewDec(2, 0), inf.NewDec(-2, 0), inf.NewDec(-2, 0), inf.NewDec(2, 0),
inf.NewDec(-2, 1), inf.NewDec(-1, 1), inf.NewDec(-1, 1),
inf.NewDec(-1, 1), inf.NewDec(0, 1), inf.NewDec(0, 1),
inf.NewDec(0, 1),
inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(1, 1),
inf.NewDec(1, 1), inf.NewDec(1, 1), inf.NewDec(2, 1)}},
{inf.RoundHalfUp, [...]*inf.Dec{
inf.NewDec(2, 0), inf.NewDec(-2, 0), inf.NewDec(-2, 0), inf.NewDec(2, 0),
inf.NewDec(-2, 1), inf.NewDec(-2, 1), inf.NewDec(-1, 1),
inf.NewDec(-1, 1), inf.NewDec(-1, 1), inf.NewDec(0, 1),
inf.NewDec(0, 1),
inf.NewDec(0, 1), inf.NewDec(1, 1), inf.NewDec(1, 1),
inf.NewDec(1, 1), inf.NewDec(2, 1), inf.NewDec(2, 1)}},
{inf.RoundHalfEven, [...]*inf.Dec{
inf.NewDec(2, 0), inf.NewDec(-2, 0), inf.NewDec(-2, 0), inf.NewDec(2, 0),
inf.NewDec(-2, 1), inf.NewDec(-2, 1), inf.NewDec(-1, 1),
inf.NewDec(-1, 1), inf.NewDec(0, 1), inf.NewDec(0, 1),
inf.NewDec(0, 1),
inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(1, 1),
inf.NewDec(1, 1), inf.NewDec(2, 1), inf.NewDec(2, 1)}},
{inf.RoundFloor, [...]*inf.Dec{
inf.NewDec(1, 0), inf.NewDec(-2, 0), inf.NewDec(-2, 0), inf.NewDec(1, 0),
inf.NewDec(-2, 1), inf.NewDec(-2, 1), inf.NewDec(-2, 1),
inf.NewDec(-1, 1), inf.NewDec(-1, 1), inf.NewDec(-1, 1),
inf.NewDec(0, 1),
inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(0, 1),
inf.NewDec(1, 1), inf.NewDec(1, 1), inf.NewDec(1, 1)}},
{inf.RoundCeil, [...]*inf.Dec{
inf.NewDec(2, 0), inf.NewDec(-1, 0), inf.NewDec(-1, 0), inf.NewDec(2, 0),
inf.NewDec(-1, 1), inf.NewDec(-1, 1), inf.NewDec(-1, 1),
inf.NewDec(0, 1), inf.NewDec(0, 1), inf.NewDec(0, 1),
inf.NewDec(0, 1),
inf.NewDec(1, 1), inf.NewDec(1, 1), inf.NewDec(1, 1),
inf.NewDec(2, 1), inf.NewDec(2, 1), inf.NewDec(2, 1)}},
}
func TestDecRounders(t *testing.T) {
for i, a := range decRounderResults {
for j, input := range decRounderInputs {
q := new(inf.Dec).Set(input.quo)
rA, rB := new(big.Int).Set(input.rA), new(big.Int).Set(input.rB)
res := a.rounder.Round(new(inf.Dec), q, rA, rB)
if a.results[j] == nil && res == nil {
continue
}
if (a.results[j] == nil && res != nil) ||
(a.results[j] != nil && res == nil) ||
a.results[j].Cmp(res) != 0 {
t.Errorf("#%d,%d Rounder got %v; expected %v", i, j, res, a.results[j])
}
}
}
}
+2 -2
View File
@@ -124,13 +124,13 @@ func getAppImageID(c *container) (*types.Hash, error) {
case 0:
return nil, fmt.Errorf("container contains zero apps")
case 1:
return &m.Apps[0].ImageID, nil
return &m.Apps[0].Image.ID, nil
default:
}
stderr("Container contains multiple apps:")
for _, ra := range m.Apps {
stderr("\t%s: %s", types.ShortHash(ra.ImageID.String()), ra.Name.String())
stderr("\t%s: %s", types.ShortHash(ra.Image.ID.String()), ra.Name.String())
}
return nil, fmt.Errorf("specify app using \"rkt enter --imageid ...\"")
+1 -1
View File
@@ -105,7 +105,7 @@ func fetchImage(img string, ds *cas.Store, ks *keystore.Keystore, discover bool)
}
func fetchImageFromEndpoints(ep *discovery.Endpoints, ds *cas.Store, ks *keystore.Keystore) (string, error) {
return downloadImage(ep.ACIEndpoints[0].ACI, ep.ACIEndpoints[0].Sig, "", ds, ks)
return downloadImage(ep.ACIEndpoints[0].ACI, ep.ACIEndpoints[0].ASC, "", ds, ks)
}
func fetchImageFromURL(imgurl string, scheme string, ds *cas.Store, ks *keystore.Keystore) (string, error) {
+1 -1
View File
@@ -345,7 +345,7 @@ func handleAppID(w http.ResponseWriter, r *http.Request, c *mdsContainer, im *sc
if a == nil {
panic("could not find app in manifest!")
}
w.Write([]byte(a.ImageID.String()))
w.Write([]byte(a.Image.ID.String()))
}
func initCrypto() error {
+6 -2
View File
@@ -112,10 +112,14 @@ func Prepare(cfg PrepareConfig, dir string, uuid *types.UUID) error {
if am.App == nil {
return fmt.Errorf("error: image %s has no app section", img)
}
rimg := schema.RuntimeImage{
Name: am.Name,
ID: img,
}
a := schema.RuntimeApp{
Name: am.Name,
ImageID: img,
Isolators: am.App.Isolators,
Image: rimg,
App: am.App,
Annotations: am.Annotations,
}
cm.Apps = append(cm.Apps, a)
+15 -7
View File
@@ -62,7 +62,7 @@ func LoadContainer(root string) (*Container, error) {
c.Manifest = cm
for _, app := range c.Manifest.Apps {
ampath := common.ImageManifestPath(c.Root, app.ImageID)
ampath := common.ImageManifestPath(c.Root, app.Image.ID)
buf, err := ioutil.ReadFile(ampath)
if err != nil {
return nil, fmt.Errorf("failed reading app manifest %q: %v", ampath, err)
@@ -239,7 +239,7 @@ func (c *Container) ContainerToSystemd() error {
// should never happen
panic("app not found in container manifest")
}
if err := c.appToSystemd(am, a.ImageID); err != nil {
if err := c.appToSystemd(am, a.Image.ID); err != nil {
return fmt.Errorf("failed to transform app %q into systemd service: %v", am.Name, err)
}
}
@@ -286,10 +286,18 @@ func (c *Container) appToNspawnArgs(am *schema.ImageManifest, id types.Hash) ([]
}
for _, i := range am.App.Isolators {
switch i.Name {
case "capabilities/bounding-set":
capList := strings.Join(strings.Split(i.Val, " "), ",")
args = append(args, "--capability="+capList)
switch v := i.Value().(type) {
case types.LinuxCapabilitiesSet:
var caps []string
var s types.LinuxCapabilitiesSet = v
// TODO: cleanup the API on LinuxCapabilitiesSet to give strings easily.
for _, c := range v.Set() {
caps = append(caps, string(c))
}
if s.Name() == types.LinuxCapabilitiesRetainSetName {
capList := strings.Join(caps, ",")
args = append(args, "--capability="+capList)
}
}
}
@@ -309,7 +317,7 @@ func (c *Container) ContainerToNspawnArgs() ([]string, error) {
if a == nil {
panic("could not find app in container manifest!")
}
aa, err := c.appToNspawnArgs(am, a.ImageID)
aa, err := c.appToNspawnArgs(am, a.Image.ID)
if err != nil {
return nil, fmt.Errorf("failed to construct args for app %q: %v", am.Name, err)
}
+1 -1
View File
@@ -39,7 +39,7 @@ func registerContainer(c *Container, ip net.IP) error {
uid := c.Manifest.UUID.String()
for _, app := range c.Manifest.Apps {
ampath := common.ImageManifestPath(c.Root, app.ImageID)
ampath := common.ImageManifestPath(c.Root, app.Image.ID)
amf, err := os.Open(ampath)
if err != nil {
fmt.Errorf("failed reading app manifest %q: %v", ampath, err)