iodine deps now coming in from minio-io/pkg/iodine
This commit is contained in:
Generated
+8
-4
@@ -11,7 +11,11 @@
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/clbanning/mxj",
|
||||
"Rev": "62dd98ae54e1d2b67c9483486b1f45e344f8388c"
|
||||
"Rev": "e11b85050263aff26728fb9863bf2ebaf6591279"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/dustin/go-humanize",
|
||||
"Rev": "8cc1aaa2d955ee82833337cfb10babc42be6bce6"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/fatih/color",
|
||||
@@ -27,12 +31,12 @@
|
||||
"Rev": "ecb385c3fefd53678e3b6beba6a608fb7c8dfac1"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/minio-io/iodine",
|
||||
"Rev": "55cc4d4256c68fbd6f0775f1a25e37e6a2f6457e"
|
||||
"ImportPath": "github.com/minio-io/minio/pkg/iodine",
|
||||
"Rev": "e2c54a0904df66b9b87f324944169b8d30afceab"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/minio-io/minio/pkg/utils/log",
|
||||
"Rev": "1ebc692ea24cbcb373b9a26837460f0e5efd4780"
|
||||
"Rev": "e2c54a0904df66b9b87f324944169b8d30afceab"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/shiena/ansicolor",
|
||||
|
||||
+6
-5
@@ -9,21 +9,21 @@ const (
|
||||
DefaultElementTag = "element"
|
||||
)
|
||||
|
||||
// Encode arbitrary value as XML.
|
||||
//
|
||||
// Encode arbitrary value as XML.
|
||||
//
|
||||
// Note: unmarshaling the resultant
|
||||
// XML may not return the original value, since tag labels may have been injected
|
||||
// to create the XML representation of the value.
|
||||
/*
|
||||
Encode an arbitrary JSON object.
|
||||
package main
|
||||
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github/clbanning/mxj"
|
||||
)
|
||||
|
||||
|
||||
func main() {
|
||||
jsondata := []byte(`[
|
||||
{ "somekey":"somevalue" },
|
||||
@@ -42,7 +42,7 @@ const (
|
||||
}
|
||||
fmt.Println(string(x))
|
||||
}
|
||||
|
||||
|
||||
output:
|
||||
<mydoc>
|
||||
<somekey>somevalue</somekey>
|
||||
@@ -110,6 +110,7 @@ func AnyXml(v interface{}, tags ...string) ([]byte, error) {
|
||||
return b, err
|
||||
}
|
||||
|
||||
|
||||
// Encode an arbitrary value as a pretty XML string.
|
||||
// Alternative values for DefaultRootTag and DefaultElementTag can be set as:
|
||||
// AnyXmlIndent( v, "", " ", myRootTag, myElementTag).
|
||||
|
||||
+2
-2
@@ -43,7 +43,7 @@ func TestAnyXml(t *testing.T) {
|
||||
}
|
||||
fmt.Println("[]->x:", string(x))
|
||||
|
||||
a := []interface{}{"try", "this", 3.14159265, true}
|
||||
a := []interface{}{ "try", "this", 3.14159265, true }
|
||||
x, err = AnyXml(a)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -82,7 +82,7 @@ func TestAnyXmlIndent(t *testing.T) {
|
||||
}
|
||||
fmt.Println("[]->x:\n", string(x))
|
||||
|
||||
a := []interface{}{"try", "this", 3.14159265, true}
|
||||
a := []interface{}{ "try", "this", 3.14159265, true }
|
||||
x, err = AnyXmlIndent(a, "", " ")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
||||
+1
@@ -36,3 +36,4 @@ var jsondata = []byte(`
|
||||
{"book":{"author":"John Hawkes","review":"A lyrical novel about the construction of Ft. Peck Dam in Montana.","title":"The Beetle Leg"}}
|
||||
{"book":{"author":{"first_name":"T.E.","last_name":"Porter"},"review":"A magical novella.","title":"King's Day"}}
|
||||
{ "here":"we", "put":"in", "an":error }`)
|
||||
|
||||
|
||||
+2
-2
@@ -31,7 +31,7 @@ SUMMARY
|
||||
Marshal Map value, 'm', to an XML Writer (io.Writer):
|
||||
err := m.XmlWriter(xmlWriter)
|
||||
raw, err := m.XmlWriterRaw(xmlWriter) // 'raw' is the raw XML that was written on xmlWriter
|
||||
|
||||
|
||||
Also, for prettified output:
|
||||
xmlValue, err := m.XmlIndent(prefix, indent, ...)
|
||||
err := m.XmlIndentWriter(xmlWriter, prefix, indent, ...)
|
||||
@@ -72,7 +72,7 @@ XML PARSING CONVENTIONS
|
||||
- Attributes are parsed to map[string]interface{} values by prefixing a hyphen, '-',
|
||||
to the attribute label. (PrependAttrWithHyphen(false) will override this.)
|
||||
- If the element is a simple element and has attributes, the element value
|
||||
is given the key '#text' for its map[string]interface{} representation.
|
||||
is given the key '#text' for its map[string]interface{} representation.
|
||||
|
||||
XML ENCODING CONVENTIONS
|
||||
|
||||
|
||||
+72
-70
@@ -8,8 +8,8 @@ package mxj_test
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"github.com/clbanning/mxj"
|
||||
"io"
|
||||
"github.com/clbanning/mxj"
|
||||
)
|
||||
|
||||
func ExampleHandleXmlReader() {
|
||||
@@ -246,59 +246,59 @@ func ExampleMap_ValuesForKeyPath() {
|
||||
}
|
||||
|
||||
func ExampleMap_UpdateValuesForPath() {
|
||||
/*
|
||||
/*
|
||||
|
||||
var biblioDoc = []byte(`
|
||||
<biblio>
|
||||
<author>
|
||||
<name>William Gaddis</name>
|
||||
<books>
|
||||
<book>
|
||||
<title>The Recognitions</title>
|
||||
<date>1955</date>
|
||||
<review>A novel that changed the face of American literature.</review>
|
||||
</book>
|
||||
<book>
|
||||
<title>JR</title>
|
||||
<date>1975</date>
|
||||
<review>Winner of National Book Award for Fiction.</review>
|
||||
</book>
|
||||
</books>
|
||||
</author>
|
||||
</biblio>`)
|
||||
|
||||
var biblioDoc = []byte(`
|
||||
<biblio>
|
||||
<author>
|
||||
<name>William Gaddis</name>
|
||||
<books>
|
||||
<book>
|
||||
<title>The Recognitions</title>
|
||||
<date>1955</date>
|
||||
<review>A novel that changed the face of American literature.</review>
|
||||
</book>
|
||||
<book>
|
||||
<title>JR</title>
|
||||
<date>1975</date>
|
||||
<review>Winner of National Book Award for Fiction.</review>
|
||||
</book>
|
||||
</books>
|
||||
</author>
|
||||
</biblio>`)
|
||||
...
|
||||
m, merr := mxj.NewMapXml(biblioDoc)
|
||||
if merr != nil {
|
||||
// handle error
|
||||
}
|
||||
|
||||
...
|
||||
m, merr := mxj.NewMapXml(biblioDoc)
|
||||
if merr != nil {
|
||||
// handle error
|
||||
}
|
||||
// change 'review' for a book
|
||||
count, err := m.UpdateValuesForPath("review:National Book Award winner." "*.*.*.*", "title:JR")
|
||||
if err != nil {
|
||||
// handle error
|
||||
}
|
||||
...
|
||||
|
||||
// change 'review' for a book
|
||||
count, err := m.UpdateValuesForPath("review:National Book Award winner." "*.*.*.*", "title:JR")
|
||||
if err != nil {
|
||||
// handle error
|
||||
}
|
||||
...
|
||||
|
||||
// change 'date' value from string type to float64 type
|
||||
// Note: the following is equivalent to m, merr := NewMapXml(biblioDoc, mxj.Cast).
|
||||
path := m.PathForKeyShortest("date")
|
||||
v, err := m.ValuesForPath(path)
|
||||
if err != nil {
|
||||
// handle error
|
||||
}
|
||||
var total int
|
||||
for _, vv := range v {
|
||||
oldVal := "date:" + vv.(string)
|
||||
newVal := "date:" + vv.(string) + ":num"
|
||||
n, err := m.UpdateValuesForPath(newVal, path, oldVal)
|
||||
if err != nil {
|
||||
// handle error
|
||||
}
|
||||
total += n
|
||||
}
|
||||
...
|
||||
*/
|
||||
// change 'date' value from string type to float64 type
|
||||
// Note: the following is equivalent to m, merr := NewMapXml(biblioDoc, mxj.Cast).
|
||||
path := m.PathForKeyShortest("date")
|
||||
v, err := m.ValuesForPath(path)
|
||||
if err != nil {
|
||||
// handle error
|
||||
}
|
||||
var total int
|
||||
for _, vv := range v {
|
||||
oldVal := "date:" + vv.(string)
|
||||
newVal := "date:" + vv.(string) + ":num"
|
||||
n, err := m.UpdateValuesForPath(newVal, path, oldVal)
|
||||
if err != nil {
|
||||
// handle error
|
||||
}
|
||||
total += n
|
||||
}
|
||||
...
|
||||
*/
|
||||
}
|
||||
|
||||
func ExampleMap_Copy() {
|
||||
@@ -313,32 +313,34 @@ func ExampleMap_Copy() {
|
||||
private string
|
||||
}
|
||||
s := str{IntVal: 4, StrVal: "now's the time", FloatVal: 3.14159, BoolVal: true, private: "Skies are blue"}
|
||||
m := make(map[string]interface{}, 0)
|
||||
m := make(map[string]interface{},0)
|
||||
m["struct"] = interface{}(s)
|
||||
m["struct_ptr"] = interface{}(&s)
|
||||
m["misc"] = interface{}(`Now is the time`)
|
||||
|
||||
|
||||
mv := mxj.Map(m)
|
||||
cp, _ := mv.Copy()
|
||||
cp,_ := mv.Copy()
|
||||
|
||||
fmt.Printf("mv:%s\n", mv.StringIndent(2))
|
||||
fmt.Printf("cp:%s\n", cp.StringIndent(2))
|
||||
|
||||
// Output:
|
||||
// mv:
|
||||
// struct :[unknown] mxj_test.str{IntVal:4, StrVal:"now's the time", FloatVal:3.14159, BoolVal:true, private:"Skies are blue"}
|
||||
// struct_ptr :[unknown] &mxj_test.str{IntVal:4, StrVal:"now's the time", FloatVal:3.14159, BoolVal:true, private:"Skies are blue"}
|
||||
// misc :[string] Now is the time
|
||||
// cp:
|
||||
// misc :[string] Now is the time
|
||||
// struct :
|
||||
// int :[float64] 4.00e+00
|
||||
// str :[string] now's the time
|
||||
// float :[float64] 3.14e+00
|
||||
// bool :[bool] true
|
||||
// struct_ptr :
|
||||
// int :[float64] 4.00e+00
|
||||
// str :[string] now's the time
|
||||
// float :[float64] 3.14e+00
|
||||
// bool :[bool] true
|
||||
// Output:
|
||||
// mv:
|
||||
// struct :[unknown] mxj_test.str{IntVal:4, StrVal:"now's the time", FloatVal:3.14159, BoolVal:true, private:"Skies are blue"}
|
||||
// struct_ptr :[unknown] &mxj_test.str{IntVal:4, StrVal:"now's the time", FloatVal:3.14159, BoolVal:true, private:"Skies are blue"}
|
||||
// misc :[string] Now is the time
|
||||
// cp:
|
||||
// misc :[string] Now is the time
|
||||
// struct :
|
||||
// int :[float64] 4.00e+00
|
||||
// str :[string] now's the time
|
||||
// float :[float64] 3.14e+00
|
||||
// bool :[bool] true
|
||||
// struct_ptr :
|
||||
// int :[float64] 4.00e+00
|
||||
// str :[string] now's the time
|
||||
// float :[float64] 3.14e+00
|
||||
// bool :[bool] true
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -4,8 +4,8 @@ package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/clbanning/mxj"
|
||||
"log"
|
||||
"github.com/clbanning/mxj"
|
||||
)
|
||||
|
||||
var xmldata = []byte(`
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
// getmetrics1.go - transform Eclipse Metrics (v3) XML report into CSV files for each metric
|
||||
// Uses NewMapXmlReader on os.File without copying the raw XML into a buffer while decoding..
|
||||
// Uses NewMapXmlReader on os.File without copying the raw XML into a buffer while decoding..
|
||||
// Shows no significant overhead for not first buffering large XML file as in getmetrics2.go.
|
||||
|
||||
/*
|
||||
@@ -38,10 +38,10 @@ package main
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"github.com/clbanning/mxj"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
"github.com/clbanning/mxj"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
+2
-2
@@ -39,10 +39,10 @@ package main
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"github.com/clbanning/mxj"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
"github.com/clbanning/mxj"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -81,7 +81,7 @@ func main() {
|
||||
fmt.Println(time.Now().String(), "... XML Unmarshaled - len:", len(m))
|
||||
|
||||
// Get just the key values of interest.
|
||||
// Could also use m.ValuesForKey("Metric"),
|
||||
// Could also use m.ValuesForKey("Metric"),
|
||||
// since there's just the one path.
|
||||
metricVals, err := m.ValuesForPath("Metrics.Metric")
|
||||
if err != nil {
|
||||
|
||||
+1
-1
@@ -40,10 +40,10 @@ package main
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"github.com/clbanning/mxj"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
"github.com/clbanning/mxj"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
+4
-4
@@ -1,7 +1,7 @@
|
||||
// getmetrics2.go - transform Eclipse Metrics (v3) XML report into CSV files for each metric
|
||||
// Uses an in-memory buffer for the XML data and direct XML decoding of the buffer into a Map.
|
||||
// Then XML buffer is decoded into a Map while the raw XML is copied using NewMapXmlReaderRaw()
|
||||
// to illustrate processing overhead relative to getmetrics2.go. Not a practical example,
|
||||
// to illustrate processing overhead relative to getmetrics2.go. Not a practical example,
|
||||
// but confirms the getmetrics1.go vs. getmetrics3.go use case.
|
||||
|
||||
/*
|
||||
@@ -41,10 +41,10 @@ import (
|
||||
"bytes"
|
||||
"flag"
|
||||
"fmt"
|
||||
"github.com/clbanning/mxj"
|
||||
"log"
|
||||
"os"
|
||||
"time"
|
||||
"github.com/clbanning/mxj"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -79,7 +79,7 @@ func main() {
|
||||
|
||||
// load XML into a Map value
|
||||
// Note: there is a single record with root tag of "Metrics".
|
||||
m, raw, merr := mxj.NewMapXmlReaderRaw(xmlReader) // don't catch the pointer to raw XML
|
||||
m, raw, merr := mxj.NewMapXmlReaderRaw(xmlReader) // don't catch the pointer to raw XML
|
||||
if merr != nil {
|
||||
log.Fatal("merr:", merr.Error())
|
||||
}
|
||||
@@ -87,7 +87,7 @@ func main() {
|
||||
fmt.Println("raw XML buffer size (should be same as File size):", len(*raw))
|
||||
|
||||
// Get just the key values of interest.
|
||||
// Could also use m.ValuesForKey("Metric"),
|
||||
// Could also use m.ValuesForKey("Metric"),
|
||||
// since there's just the one path.
|
||||
metricVals, err := m.ValuesForPath("Metrics.Metric")
|
||||
if err != nil {
|
||||
|
||||
+1
-1
@@ -6,8 +6,8 @@ package main
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"github.com/clbanning/mxj"
|
||||
"io"
|
||||
"github.com/clbanning/mxj"
|
||||
)
|
||||
|
||||
// Demo how to compensate for irregular tag labels in data.
|
||||
|
||||
+12
-12
@@ -108,9 +108,9 @@ func fullPath(xmldata [][]byte) {
|
||||
}
|
||||
|
||||
func partPath1(msg []byte) {
|
||||
fmt.Println("\nmsg:", string(msg))
|
||||
fmt.Println("\nmsg:",string(msg))
|
||||
m, _ := mxj.NewMapXml(msg)
|
||||
fmt.Println("m:", m.StringIndent())
|
||||
fmt.Println("m:",m.StringIndent())
|
||||
path := "Envelope.Body.*.*.ClaimStatusCodeRecord"
|
||||
values, err := m.ValueForPath(path)
|
||||
if err != nil {
|
||||
@@ -130,9 +130,9 @@ func partPath1(msg []byte) {
|
||||
}
|
||||
|
||||
func partPath2(msg []byte) {
|
||||
fmt.Println("\nmsg:", string(msg))
|
||||
fmt.Println("\nmsg:",string(msg))
|
||||
m, _ := mxj.NewMapXml(msg)
|
||||
fmt.Println("m:", m.StringIndent())
|
||||
fmt.Println("m:",m.StringIndent())
|
||||
path := "Envelope.Body.*.*.*"
|
||||
values, err := m.ValueForPath(path)
|
||||
if err != nil {
|
||||
@@ -152,9 +152,9 @@ func partPath2(msg []byte) {
|
||||
}
|
||||
|
||||
func partPath3(msg []byte) {
|
||||
fmt.Println("\nmsg:", string(msg))
|
||||
fmt.Println("\nmsg:",string(msg))
|
||||
m, _ := mxj.NewMapXml(msg)
|
||||
fmt.Println("m:", m.StringIndent())
|
||||
fmt.Println("m:",m.StringIndent())
|
||||
path := "*.*.*.*.*"
|
||||
values, err := m.ValueForPath(path)
|
||||
if err != nil {
|
||||
@@ -174,9 +174,9 @@ func partPath3(msg []byte) {
|
||||
}
|
||||
|
||||
func partPath4(msg []byte) {
|
||||
fmt.Println("\nmsg:", string(msg))
|
||||
fmt.Println("\nmsg:",string(msg))
|
||||
m, _ := mxj.NewMapXml(msg)
|
||||
fmt.Println("m:", m.StringIndent())
|
||||
fmt.Println("m:",m.StringIndent())
|
||||
path := "*.*.*.*.*.Description"
|
||||
values, err := m.ValueForPath(path)
|
||||
if err != nil {
|
||||
@@ -196,9 +196,9 @@ func partPath4(msg []byte) {
|
||||
}
|
||||
|
||||
func partPath5(msg []byte) {
|
||||
fmt.Println("\nmsg:", string(msg))
|
||||
fmt.Println("\nmsg:",string(msg))
|
||||
m, _ := mxj.NewMapXml(msg)
|
||||
fmt.Println("m:", m.StringIndent())
|
||||
fmt.Println("m:",m.StringIndent())
|
||||
path := "*.*.*.*.*.*"
|
||||
values, err := m.ValueForPath(path)
|
||||
if err != nil {
|
||||
@@ -218,9 +218,9 @@ func partPath5(msg []byte) {
|
||||
}
|
||||
|
||||
func partPath6(msg []byte) {
|
||||
fmt.Println("\nmsg:", string(msg))
|
||||
fmt.Println("\nmsg:",string(msg))
|
||||
m, _ := mxj.NewMapXml(msg)
|
||||
fmt.Println("m:", m.StringIndent())
|
||||
fmt.Println("m:",m.StringIndent())
|
||||
path := "*.*.*.*.*.*.*"
|
||||
values, err := m.ValueForPath(path)
|
||||
if err != nil {
|
||||
|
||||
+1
-1
@@ -45,6 +45,6 @@ func main() {
|
||||
}
|
||||
|
||||
for _, v := range values {
|
||||
fmt.Println("v:", v)
|
||||
fmt.Println("v:",v)
|
||||
}
|
||||
}
|
||||
|
||||
+1
@@ -41,3 +41,4 @@ func main() {
|
||||
}
|
||||
|
||||
var s = []byte(`{ "DBInstances": [ { "PubliclyAccessible": true, "MasterUsername": "postgres", "LicenseModel": "postgresql-license", "VpcSecurityGroups": [ { "Status": "active", "VpcSecurityGroupId": "sg-e72a4282" } ], "InstanceCreateTime": "2014-06-29T03:52:59.268Z", "OptionGroupMemberships": [ { "Status": "in-sync", "OptionGroupName": "default:postgres-9-3" } ], "PendingModifiedValues": {}, "Engine": "postgres", "MultiAZ": true, "LatestRestorableTime": "2014-06-29T12:00:34Z", "DBSecurityGroups": [ { "Status": "active", "DBSecurityGroupName": "production-dbsecuritygroup-q4f0ugxpjck8" } ], "DBParameterGroups": [ { "DBParameterGroupName": "default.postgres9.3", "ParameterApplyStatus": "in-sync" } ], "AutoMinorVersionUpgrade": true, "PreferredBackupWindow": "06:59-07:29", "DBSubnetGroup": { "Subnets": [ { "SubnetStatus": "Active", "SubnetIdentifier": "subnet-34e5d01c", "SubnetAvailabilityZone": { "Name": "us-east-1b", "ProvisionedIopsCapable": false } }, { "SubnetStatus": "Active", "SubnetIdentifier": "subnet-50759d27", "SubnetAvailabilityZone": { "Name": "us-east-1c", "ProvisionedIopsCapable": false } }, { "SubnetStatus": "Active", "SubnetIdentifier": "subnet-450a1f03", "SubnetAvailabilityZone": { "Name": "us-east-1d", "ProvisionedIopsCapable": false } } ], "DBSubnetGroupName": "default", "VpcId": "vpc-acb86cc9", "DBSubnetGroupDescription": "default", "SubnetGroupStatus": "Complete" }, "SecondaryAvailabilityZone": "us-east-1b", "ReadReplicaDBInstanceIdentifiers": [], "AllocatedStorage": 15, "BackupRetentionPeriod": 1, "DBName": "deis", "PreferredMaintenanceWindow": "fri:05:52-fri:06:22", "Endpoint": { "Port": 5432, "Address": "production.cfk8mskkbkeu.us-east-1.rds.amazonaws.com" }, "DBInstanceStatus": "available", "EngineVersion": "9.3.3", "AvailabilityZone": "us-east-1c", "DBInstanceClass": "db.m1.small", "DBInstanceIdentifier": "production" } ] }`)
|
||||
|
||||
|
||||
+7
-5
@@ -9,7 +9,7 @@ import (
|
||||
type Maps []Map
|
||||
|
||||
func NewMaps() Maps {
|
||||
return make(Maps, 0)
|
||||
return make(Maps,0)
|
||||
}
|
||||
|
||||
type MapRaw struct {
|
||||
@@ -33,7 +33,7 @@ func NewMapsFromJsonFile(name string) (Maps, error) {
|
||||
}
|
||||
defer fh.Close()
|
||||
|
||||
am := make([]Map, 0)
|
||||
am := make([]Map,0)
|
||||
for {
|
||||
m, raw, err := NewMapJsonReaderRaw(fh)
|
||||
if err != nil && err != io.EOF {
|
||||
@@ -65,7 +65,7 @@ func NewMapsFromJsonFileRaw(name string) ([]MapRaw, error) {
|
||||
}
|
||||
defer fh.Close()
|
||||
|
||||
am := make([]MapRaw, 0)
|
||||
am := make([]MapRaw,0)
|
||||
for {
|
||||
mr := new(MapRaw)
|
||||
mr.M, mr.R, err = NewMapJsonReaderRaw(fh)
|
||||
@@ -104,7 +104,7 @@ func NewMapsFromXmlFile(name string) (Maps, error) {
|
||||
}
|
||||
defer fh.Close()
|
||||
|
||||
am := make([]Map, 0)
|
||||
am := make([]Map,0)
|
||||
for {
|
||||
m, raw, err := NewMapXmlReaderRaw(fh)
|
||||
if err != nil && err != io.EOF {
|
||||
@@ -130,6 +130,7 @@ func NewMapsFromXmlFileRaw(name string) ([]MapRaw, error) {
|
||||
XmlWriterBufSize = x
|
||||
}()
|
||||
|
||||
|
||||
fi, err := os.Stat(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -144,7 +145,7 @@ func NewMapsFromXmlFileRaw(name string) ([]MapRaw, error) {
|
||||
}
|
||||
defer fh.Close()
|
||||
|
||||
am := make([]MapRaw, 0)
|
||||
am := make([]MapRaw,0)
|
||||
for {
|
||||
mr := new(MapRaw)
|
||||
mr.M, mr.R, err = NewMapXmlReaderRaw(fh)
|
||||
@@ -297,3 +298,4 @@ func (mvs Maps) XmlFileIndent(file, prefix, indent string) error {
|
||||
fh.WriteString(s)
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
+3
-3
@@ -104,7 +104,7 @@ func TestNewXmFileRaw(t *testing.T) {
|
||||
func TestMaps(t *testing.T) {
|
||||
fmt.Println("TestMaps()")
|
||||
mvs := NewMaps()
|
||||
for i := 0; i < 2; i++ {
|
||||
for i := 0 ; i < 2 ; i++ {
|
||||
m, _ := NewMapJson([]byte(`{ "this":"is", "a":"test" }`))
|
||||
mvs = append(mvs, m)
|
||||
}
|
||||
@@ -138,7 +138,7 @@ func TestJsonFile(t *testing.T) {
|
||||
}
|
||||
fmt.Println("files_test_dup.json written")
|
||||
|
||||
err = am.JsonFileIndent("files_test_indent.json", "", " ")
|
||||
err = am.JsonFileIndent("files_test_indent.json","", " ")
|
||||
if err != nil {
|
||||
t.Fatal(err.Error())
|
||||
}
|
||||
@@ -160,7 +160,7 @@ func TestXmlFile(t *testing.T) {
|
||||
}
|
||||
fmt.Println("files_test_dup.xml written")
|
||||
|
||||
err = am.XmlFileIndent("files_test_indent.xml", "", " ")
|
||||
err = am.XmlFileIndent("files_test_indent.xml","", " ")
|
||||
if err != nil {
|
||||
t.Fatal(err.Error())
|
||||
}
|
||||
|
||||
+1
@@ -6,6 +6,7 @@
|
||||
// Wrappers for end-to-end JSON to XML transformation and value manipulation.
|
||||
package j2x
|
||||
|
||||
|
||||
import (
|
||||
. "github.com/clbanning/mxj"
|
||||
"io"
|
||||
|
||||
+1
-1
@@ -4,8 +4,8 @@ package j2x
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
|
||||
+1
@@ -27,3 +27,4 @@ func TestJ2X(t *testing.T) {
|
||||
fmt.Println("j2x, m :", m)
|
||||
fmt.Println("j2x, xml :", string(x))
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -124,7 +124,7 @@ var JsonUseNumber bool
|
||||
func NewMapJson(jsonVal []byte) (Map, error) {
|
||||
// empty or nil begets empty
|
||||
if len(jsonVal) == 0 {
|
||||
m := make(map[string]interface{}, 0)
|
||||
m := make(map[string]interface{},0)
|
||||
return m, nil
|
||||
}
|
||||
// handle a goofy case ...
|
||||
|
||||
+1
-1
@@ -550,7 +550,7 @@ func (mv Map) PathsForKey(key string) []string {
|
||||
// unpack map keys to return
|
||||
res := make([]string, len(breadbasket))
|
||||
var i int
|
||||
for k := range breadbasket {
|
||||
for k, _ := range breadbasket {
|
||||
res[i] = k
|
||||
i++
|
||||
}
|
||||
|
||||
+3
-3
@@ -132,7 +132,7 @@ func TestValuesForKey(t *testing.T) {
|
||||
if sserr != nil {
|
||||
t.Fatal("sserr:", sserr.Error())
|
||||
}
|
||||
for _, v := range ss { // should be len(ss) == 0
|
||||
for _, v := range ss { // should be len(ss) == 0
|
||||
fmt.Println("... ss.v:", v)
|
||||
}
|
||||
}
|
||||
@@ -189,7 +189,7 @@ func TestValuesForPath(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestValuesForNotKey(t *testing.T) {
|
||||
func TestValuesForNotKey( t *testing.T) {
|
||||
fmt.Println("ValuesForNotKey ...")
|
||||
m, merr := NewMapXml(doc1)
|
||||
if merr != nil {
|
||||
@@ -209,7 +209,7 @@ func TestValuesForNotKey(t *testing.T) {
|
||||
if sserr != nil {
|
||||
t.Fatal("sserr:", sserr.Error())
|
||||
}
|
||||
for _, v := range ss { // expect len(ss) == 0
|
||||
for _, v := range ss { // expect len(ss) == 0
|
||||
fmt.Println("... ss.v:", v)
|
||||
}
|
||||
|
||||
|
||||
+5
-5
@@ -23,7 +23,7 @@ type LeafNode struct {
|
||||
// LeafNodes - returns an array of all LeafNode values for the Map.
|
||||
// The option no_attr argument suppresses attribute values (keys with prepended hyphen, '-')
|
||||
// as well as the "#text" key for the associated simple element value.
|
||||
func (mv Map) LeafNodes(no_attr ...bool) []LeafNode {
|
||||
func (mv Map)LeafNodes(no_attr ...bool) []LeafNode {
|
||||
var a bool
|
||||
if len(no_attr) == 1 {
|
||||
a = no_attr[0]
|
||||
@@ -64,8 +64,8 @@ func getLeafNodes(path, node string, mv interface{}, l *[]LeafNode, noattr bool)
|
||||
// LeafPaths - all paths that terminate in LeafNode values.
|
||||
func (mv Map) LeafPaths(no_attr ...bool) []string {
|
||||
ln := mv.LeafNodes()
|
||||
ss := make([]string, len(ln))
|
||||
for i := 0; i < len(ln); i++ {
|
||||
ss := make([]string,len(ln))
|
||||
for i := 0 ; i < len(ln); i++ {
|
||||
ss[i] = ln[i].Path
|
||||
}
|
||||
return ss
|
||||
@@ -74,8 +74,8 @@ func (mv Map) LeafPaths(no_attr ...bool) []string {
|
||||
// LeafValues - all terminal values in the Map.
|
||||
func (mv Map) LeafValues(no_attr ...bool) []interface{} {
|
||||
ln := mv.LeafNodes()
|
||||
vv := make([]interface{}, len(ln))
|
||||
for i := 0; i < len(ln); i++ {
|
||||
vv := make([]interface{},len(ln))
|
||||
for i := 0 ; i < len(ln); i++ {
|
||||
vv[i] = ln[i].Value
|
||||
}
|
||||
return vv
|
||||
|
||||
+1
@@ -72,6 +72,7 @@ func TestLeafNodes(t *testing.T) {
|
||||
fmt.Printf("%#v\n", v)
|
||||
}
|
||||
|
||||
|
||||
xmldata2 := []byte(`
|
||||
<doc>
|
||||
<item num="2" color="blue">Item 2 is blue</item>
|
||||
|
||||
+1
-1
@@ -38,7 +38,7 @@ func (mv Map) Old() map[string]interface{} {
|
||||
// be represented as a map[string]interface{} value.
|
||||
func (mv Map) Copy() (Map, error) {
|
||||
// this is the poor-man's deep copy
|
||||
// not efficient, but it works
|
||||
// not efficient, but it works
|
||||
j, jerr := mv.Json()
|
||||
// must handle, we don't know how mv got built
|
||||
if jerr != nil {
|
||||
|
||||
+7
-7
@@ -13,8 +13,8 @@ func TestMap(t *testing.T) {
|
||||
m := New()
|
||||
|
||||
m["key"] = interface{}("value")
|
||||
v := map[string]interface{}{"bool": true, "float": 3.14159, "string": "Now is the time"}
|
||||
vv := []interface{}{3.1415962535, false, "for all good men"}
|
||||
v := map[string]interface{}{ "bool":true, "float":3.14159, "string":"Now is the time" }
|
||||
vv := []interface{}{ 3.1415962535, false, "for all good men" }
|
||||
v["listkey"] = interface{}(vv)
|
||||
m["newkey"] = interface{}(v)
|
||||
|
||||
@@ -23,14 +23,14 @@ func TestMap(t *testing.T) {
|
||||
|
||||
o := interface{}(m.Old())
|
||||
switch o.(type) {
|
||||
case map[string]interface{}:
|
||||
// do nothing
|
||||
default:
|
||||
t.Fatal("invalid type for m.Old()")
|
||||
case map[string]interface{}:
|
||||
// do nothing
|
||||
default:
|
||||
t.Fatal("invalid type for m.Old()")
|
||||
}
|
||||
|
||||
m, _ = NewMapXml([]byte(`<doc><tag><sub_tag1>Hello</sub_tag1><sub_tag2>World</sub_tag2></tag></doc>`))
|
||||
fmt.Println("TestMap, m_fromXML:", m)
|
||||
fmt.Println("TestMap, m_fromXML:",m)
|
||||
fmt.Println("TestMap, StringIndent:", m.StringIndent())
|
||||
|
||||
mm, _ := m.Copy()
|
||||
|
||||
+8
-8
@@ -22,9 +22,9 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// (Map)NewMap - create a new Map from data in the current Map.
|
||||
// (Map)NewMap - create a new Map from data in the current Map.
|
||||
// 'keypairs' are key mappings "oldKey:newKey" and specify that the current value of 'oldKey'
|
||||
// should be the value for 'newKey' in the returned Map.
|
||||
// should be the value for 'newKey' in the returned Map.
|
||||
// - 'oldKey' supports dot-notation as described for (Map)ValuesForPath()
|
||||
// - 'newKey' supports dot-notation but with no wildcards, '*', or indexed arrays
|
||||
// - "oldKey" is shorthand for for the keypair value "oldKey:oldKey"
|
||||
@@ -32,7 +32,7 @@ import (
|
||||
// - if 'oldKey' does not exist in the current Map, it is not written to the new Map.
|
||||
// "null" is not supported unless it is the current Map.
|
||||
// - see newmap_test.go for several syntax examples
|
||||
//
|
||||
//
|
||||
// NOTE: mv.NewMap() == mxj.New().
|
||||
func (mv Map) NewMap(keypairs ...string) (Map, error) {
|
||||
n := make(map[string]interface{}, 0)
|
||||
@@ -67,7 +67,7 @@ func (mv Map) NewMap(keypairs ...string) (Map, error) {
|
||||
return n, errors.New("newKey value cannot contain indexed arrays - " + v)
|
||||
}
|
||||
if oldKey == "" || newKey == "" {
|
||||
return n, errors.New("oldKey or newKey is not specified - " + v)
|
||||
return n, errors.New("oldKey or newKey is not specified - " + v)
|
||||
}
|
||||
|
||||
// get oldKey value
|
||||
@@ -125,7 +125,7 @@ func addNewVal(n *map[string]interface{}, path []string, val []interface{}) {
|
||||
// The placement of the next value in the array is dependent
|
||||
// on the sequence of members - could land on a map or a nil
|
||||
// value first. TODO: how to test this.
|
||||
a := make([]interface{}, 0)
|
||||
a := make([]interface{},0)
|
||||
var foundmap bool
|
||||
for _, vv := range m[k].([]interface{}) {
|
||||
switch vv.(type) {
|
||||
@@ -135,7 +135,7 @@ func addNewVal(n *map[string]interface{}, path []string, val []interface{}) {
|
||||
continue
|
||||
}
|
||||
nm = make(map[string]interface{}, 0)
|
||||
a = append(a, interface{}(nm))
|
||||
a = append(a,interface{}(nm))
|
||||
foundmap = true
|
||||
case map[string]interface{}:
|
||||
if foundmap { // use the first one in array
|
||||
@@ -151,7 +151,7 @@ func addNewVal(n *map[string]interface{}, path []string, val []interface{}) {
|
||||
}
|
||||
// no map found in array
|
||||
if !foundmap {
|
||||
nm = make(map[string]interface{}, 0)
|
||||
nm = make(map[string]interface{},0)
|
||||
a = append(a, interface{}(nm))
|
||||
}
|
||||
m[k] = interface{}(a) // must insert in map
|
||||
@@ -178,6 +178,6 @@ func addNewVal(n *map[string]interface{}, path []string, val []interface{}) {
|
||||
default: // v exists:string, float64, bool, map[string]interface, etc.
|
||||
a := make([]interface{}, 0)
|
||||
a = append(a, v, newVal)
|
||||
m[k] = interface{}(a)
|
||||
m[k] =interface{}(a)
|
||||
}
|
||||
}
|
||||
|
||||
+11
-11
@@ -1,9 +1,9 @@
|
||||
package mxj
|
||||
|
||||
import (
|
||||
"io"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -18,7 +18,7 @@ func TestNewMap(t *testing.T) {
|
||||
m, _ := NewMapJson(j)
|
||||
fmt.Printf("m: %#v\n", m)
|
||||
|
||||
fmt.Println("\n", `eval - m.NewMap("A:AA", "B:BB", "C:cc", "D:help")`)
|
||||
fmt.Println("\n",`eval - m.NewMap("A:AA", "B:BB", "C:cc", "D:help")`)
|
||||
n, err := m.NewMap("A:AA", "B:BB", "C:cc", "D:help")
|
||||
if err != nil {
|
||||
fmt.Println("err:", err.Error())
|
||||
@@ -26,11 +26,11 @@ func TestNewMap(t *testing.T) {
|
||||
j, _ = n.Json()
|
||||
fmt.Println("n.Json():", string(j))
|
||||
x, _ := n.Xml()
|
||||
fmt.Println("n.Xml():\n", string(x))
|
||||
fmt.Println("n.Xml():\n",string(x))
|
||||
x, _ = n.XmlIndent("", " ")
|
||||
fmt.Println("n.XmlIndent():\n", string(x))
|
||||
fmt.Println("n.XmlIndent():\n",string(x))
|
||||
|
||||
fmt.Println("\n", `eval - m.NewMap("A:AA.A", "B:AA.B", "C:AA.B.cc", "D:hello.help")`)
|
||||
fmt.Println("\n",`eval - m.NewMap("A:AA.A", "B:AA.B", "C:AA.B.cc", "D:hello.help")`)
|
||||
n, err = m.NewMap("A:AA.A", "B:AA.B", "C:AA.B.cc", "D:hello.help")
|
||||
if err != nil {
|
||||
fmt.Println("err:", err.Error())
|
||||
@@ -38,12 +38,12 @@ func TestNewMap(t *testing.T) {
|
||||
j, _ = n.Json()
|
||||
fmt.Println("n.Json():", string(j))
|
||||
x, _ = n.Xml()
|
||||
fmt.Println("n.Xml():\n", string(x))
|
||||
fmt.Println("n.Xml():\n",string(x))
|
||||
x, _ = n.XmlIndent("", " ")
|
||||
fmt.Println("n.XmlIndent():\n", string(x))
|
||||
fmt.Println("n.XmlIndent():\n",string(x))
|
||||
|
||||
var keypairs = []string{"A:xml.AA", "B:xml.AA.hello.again", "C:xml.AA", "D:xml.AA.hello.help"}
|
||||
fmt.Println("\n", `eval - m.NewMap keypairs:`, keypairs)
|
||||
var keypairs = []string{ "A:xml.AA", "B:xml.AA.hello.again", "C:xml.AA", "D:xml.AA.hello.help" }
|
||||
fmt.Println("\n",`eval - m.NewMap keypairs:`,keypairs)
|
||||
n, err = m.NewMap(keypairs...)
|
||||
if err != nil {
|
||||
fmt.Println("err:", err.Error())
|
||||
@@ -51,9 +51,9 @@ func TestNewMap(t *testing.T) {
|
||||
j, _ = n.Json()
|
||||
fmt.Println("n.Json():", string(j))
|
||||
x, _ = n.Xml()
|
||||
fmt.Println("n.Xml():\n", string(x))
|
||||
fmt.Println("n.Xml():\n",string(x))
|
||||
x, _ = n.XmlIndent("", " ")
|
||||
fmt.Println("n.XmlIndent():\n", string(x))
|
||||
fmt.Println("n.XmlIndent():\n",string(x))
|
||||
}
|
||||
|
||||
// Need to normalize from an XML stream the values for "netid" and "idnet".
|
||||
|
||||
+2
-2
@@ -30,7 +30,7 @@ func TestSeqNumHeader(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestSeqNum(t *testing.T) {
|
||||
IncludeTagSeqNum(true)
|
||||
IncludeTagSeqNum( true )
|
||||
|
||||
m, err := NewMapXml(seqdata1, Cast)
|
||||
if err != nil {
|
||||
@@ -48,5 +48,5 @@ func TestSeqNum(t *testing.T) {
|
||||
j, _ = m.JsonIndent("", " ")
|
||||
fmt.Println(string(j))
|
||||
|
||||
IncludeTagSeqNum(false)
|
||||
IncludeTagSeqNum( false )
|
||||
}
|
||||
|
||||
+22
-21
@@ -11,29 +11,29 @@ func TestStructHeader(t *testing.T) {
|
||||
|
||||
func TestNewMapStruct(t *testing.T) {
|
||||
type str struct {
|
||||
IntVal int `json:"int"`
|
||||
StrVal string `json:"str"`
|
||||
IntVal int `json:"int"`
|
||||
StrVal string `json:"str"`
|
||||
FloatVal float64 `json:"float"`
|
||||
BoolVal bool `json:"bool"`
|
||||
private string
|
||||
BoolVal bool `json:"bool"`
|
||||
private string
|
||||
}
|
||||
s := str{IntVal: 4, StrVal: "now's the time", FloatVal: 3.14159, BoolVal: true, private: "It's my party"}
|
||||
s := str{ IntVal:4, StrVal:"now's the time", FloatVal:3.14159, BoolVal:true, private:"It's my party" }
|
||||
|
||||
m, merr := NewMapStruct(s)
|
||||
if merr != nil {
|
||||
t.Fatal("merr:", merr.Error())
|
||||
}
|
||||
|
||||
fmt.Printf("NewMapStruct, s: %#v\n", s)
|
||||
fmt.Printf("NewMapStruct, m: %#v\n", m)
|
||||
fmt.Printf("NewMapStruct, s: %#v\n",s)
|
||||
fmt.Printf("NewMapStruct, m: %#v\n",m)
|
||||
|
||||
m, merr = NewMapStruct(s)
|
||||
if merr != nil {
|
||||
t.Fatal("merr:", merr.Error())
|
||||
}
|
||||
|
||||
fmt.Printf("NewMapStruct, s: %#v\n", s)
|
||||
fmt.Printf("NewMapStruct, m: %#v\n", m)
|
||||
fmt.Printf("NewMapStruct, s: %#v\n",s)
|
||||
fmt.Printf("NewMapStruct, m: %#v\n",m)
|
||||
}
|
||||
|
||||
func TestNewMapStructError(t *testing.T) {
|
||||
@@ -43,38 +43,38 @@ func TestNewMapStructError(t *testing.T) {
|
||||
t.Fatal("NewMapStructError, merr is nil")
|
||||
}
|
||||
|
||||
fmt.Println("NewMapStructError, merr:", merr.Error())
|
||||
fmt.Println("NewMapStructError, merr:",merr.Error())
|
||||
}
|
||||
|
||||
func TestStruct(t *testing.T) {
|
||||
type str struct {
|
||||
IntVal int `json:"int"`
|
||||
StrVal string `json:"str"`
|
||||
IntVal int `json:"int"`
|
||||
StrVal string `json:"str"`
|
||||
FloatVal float64 `json:"float"`
|
||||
BoolVal bool `json:"bool"`
|
||||
private string
|
||||
BoolVal bool `json:"bool"`
|
||||
private string
|
||||
}
|
||||
var s str
|
||||
m := Map{"int": 4, "str": "now's the time", "float": 3.14159, "bool": true, "private": "Somewhere over the rainbow"}
|
||||
m := Map{ "int":4, "str":"now's the time", "float":3.14159, "bool":true, "private":"Somewhere over the rainbow" }
|
||||
|
||||
mverr := m.Struct(&s)
|
||||
if mverr != nil {
|
||||
t.Fatal("mverr:", mverr.Error())
|
||||
}
|
||||
|
||||
fmt.Printf("Struct, m: %#v\n", m)
|
||||
fmt.Printf("Struct, s: %#v\n", s)
|
||||
fmt.Printf("Struct, m: %#v\n",m)
|
||||
fmt.Printf("Struct, s: %#v\n",s)
|
||||
}
|
||||
|
||||
func TestStructError(t *testing.T) {
|
||||
type str struct {
|
||||
IntVal int `json:"int"`
|
||||
StrVal string `json:"str"`
|
||||
IntVal int `json:"int"`
|
||||
StrVal string `json:"str"`
|
||||
FloatVal float64 `json:"float"`
|
||||
BoolVal bool `json:"bool"`
|
||||
BoolVal bool `json:"bool"`
|
||||
}
|
||||
var s str
|
||||
mv := Map{"int": 4, "str": "now's the time", "float": 3.14159, "bool": true}
|
||||
mv := Map{ "int":4, "str":"now's the time", "float":3.14159, "bool":true }
|
||||
|
||||
mverr := mv.Struct(s)
|
||||
if mverr == nil {
|
||||
@@ -82,3 +82,4 @@ func TestStructError(t *testing.T) {
|
||||
}
|
||||
fmt.Println("StructError, mverr:", mverr.Error())
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -146,7 +146,7 @@ func updateValue(key string, value interface{}, m interface{}, keys0 string, sub
|
||||
switch m.(type) {
|
||||
case map[string]interface{}: // gotta have the last key
|
||||
if keys0 == "*" {
|
||||
for k := range m.(map[string]interface{}) {
|
||||
for k, _ := range m.(map[string]interface{}) {
|
||||
updateValue(key, value, m, k, subkeys, cnt)
|
||||
}
|
||||
return
|
||||
|
||||
+29
-26
@@ -11,6 +11,7 @@ func TestUVHeader(t *testing.T) {
|
||||
fmt.Println("\n---------------- updatevalues_test.go ...\n")
|
||||
}
|
||||
|
||||
|
||||
func TestUpdateValuesForPath_Author(t *testing.T) {
|
||||
m, merr := NewMapXml(doc1)
|
||||
if merr != nil {
|
||||
@@ -70,7 +71,7 @@ func TestUpdateValuesForPath_Author(t *testing.T) {
|
||||
fmt.Println("m:", m)
|
||||
|
||||
fmt.Println("m.UpdateValuesForPath(mm, \"*\")")
|
||||
mm, _ := NewMapXml(doc1)
|
||||
mm, _ := NewMapXml(doc1)
|
||||
n, err = m.UpdateValuesForPath(mm, "*")
|
||||
if err != nil {
|
||||
t.Fatal("err:", err.Error())
|
||||
@@ -82,7 +83,7 @@ func TestUpdateValuesForPath_Author(t *testing.T) {
|
||||
var newDoc = []byte(`<tag color="green" shape="square">simple element</tag>`)
|
||||
m, merr = NewMapXml(newDoc)
|
||||
if merr != nil {
|
||||
t.Fatal("merr:", merr.Error())
|
||||
t.Fatal("merr:",merr.Error())
|
||||
}
|
||||
fmt.Println("\nnewDoc:", string(newDoc))
|
||||
fmt.Println("m:", m)
|
||||
@@ -93,29 +94,29 @@ func TestUpdateValuesForPath_Author(t *testing.T) {
|
||||
n, _ = m.UpdateValuesForPath("#text:simple element again", "*")
|
||||
fmt.Println("n:", n, "m:", m)
|
||||
|
||||
/*
|
||||
fmt.Println("UpdateValuesForPath, doc.books.book, title:The Recognitions : NoBook")
|
||||
n, err = m.UpdateValuesForPath("NoBook", "doc.books.book", "title:The Recognitions")
|
||||
if err != nil {
|
||||
t.Fatal("err:", err.Error())
|
||||
}
|
||||
fmt.Println(n, "updates")
|
||||
ss, _ = m.ValuesForPath("doc.books.book")
|
||||
for _, v := range ss {
|
||||
fmt.Println("v:", v)
|
||||
}
|
||||
/*
|
||||
fmt.Println("UpdateValuesForPath, doc.books.book, title:The Recognitions : NoBook")
|
||||
n, err = m.UpdateValuesForPath("NoBook", "doc.books.book", "title:The Recognitions")
|
||||
if err != nil {
|
||||
t.Fatal("err:", err.Error())
|
||||
}
|
||||
fmt.Println(n, "updates")
|
||||
ss, _ = m.ValuesForPath("doc.books.book")
|
||||
for _, v := range ss {
|
||||
fmt.Println("v:", v)
|
||||
}
|
||||
|
||||
fmt.Println("UpdateValuesForPath, doc.books.book.title -seq=3: The Blood Oranges")
|
||||
n, err = m.UpdateValuesForPath("The Blood Oranges", "doc.books.book.title", "-seq:3")
|
||||
if err != nil {
|
||||
t.Fatal("err:", err.Error())
|
||||
}
|
||||
fmt.Println(n, "updates")
|
||||
ss, _ = m.ValuesForPath("doc.books.book.title")
|
||||
for _, v := range ss {
|
||||
fmt.Println("v:", v)
|
||||
}
|
||||
*/
|
||||
fmt.Println("UpdateValuesForPath, doc.books.book.title -seq=3: The Blood Oranges")
|
||||
n, err = m.UpdateValuesForPath("The Blood Oranges", "doc.books.book.title", "-seq:3")
|
||||
if err != nil {
|
||||
t.Fatal("err:", err.Error())
|
||||
}
|
||||
fmt.Println(n, "updates")
|
||||
ss, _ = m.ValuesForPath("doc.books.book.title")
|
||||
for _, v := range ss {
|
||||
fmt.Println("v:", v)
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
var authorDoc = []byte(`
|
||||
@@ -159,7 +160,7 @@ var authorDoc = []byte(`
|
||||
|
||||
func TestAuthorDoc(t *testing.T) {
|
||||
m, merr := NewMapXml(authorDoc)
|
||||
if merr != nil {
|
||||
if merr != nil {
|
||||
t.Fatal("merr:", merr.Error())
|
||||
}
|
||||
fmt.Println(m.StringIndent())
|
||||
@@ -174,7 +175,7 @@ func TestAuthorDoc(t *testing.T) {
|
||||
|
||||
fmt.Println("m.UpdateValuesForPath(newVal, path, oldVal)")
|
||||
path := m.PathForKeyShortest("date")
|
||||
v, _ := m.ValuesForPath(path)
|
||||
v,_ := m.ValuesForPath(path)
|
||||
var counter int
|
||||
for _, vv := range v {
|
||||
oldVal := "date:" + vv.(string)
|
||||
@@ -185,3 +186,5 @@ func TestAuthorDoc(t *testing.T) {
|
||||
fmt.Println(counter, "updates")
|
||||
fmt.Println(m.StringIndent())
|
||||
}
|
||||
|
||||
|
||||
|
||||
+1
-1
@@ -38,7 +38,7 @@ func XmlToJson(xmlVal []byte, safeEncoding ...bool) ([]byte, error) {
|
||||
func XmlToJsonWriter(xmlVal []byte, jsonWriter io.Writer, safeEncoding ...bool) ([]byte, error) {
|
||||
m, err := NewMapXml(xmlVal)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, err
|
||||
}
|
||||
return m.JsonWriterRaw(jsonWriter, safeEncoding...)
|
||||
}
|
||||
|
||||
+11
-11
@@ -79,7 +79,7 @@ func TestNewMapXmlReader(t *testing.T) {
|
||||
// --------------------- Xml() and XmlWriter() test cases -------------------
|
||||
|
||||
func TestXml_1(t *testing.T) {
|
||||
mv := Map{"tag1": "some data", "tag2": "more data", "boolean": true, "float": 3.14159625, "null": nil}
|
||||
mv := Map{"tag1": "some data", "tag2": "more data", "boolean": true, "float": 3.14159625, "null":nil}
|
||||
|
||||
x, err := mv.Xml()
|
||||
if err != nil {
|
||||
@@ -91,8 +91,8 @@ func TestXml_1(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestXml_2(t *testing.T) {
|
||||
a := []interface{}{"string", true, 36.4}
|
||||
mv := Map{"array": a}
|
||||
a := []interface{}{ "string", true, 36.4 }
|
||||
mv := Map{"array": a }
|
||||
|
||||
x, err := mv.Xml()
|
||||
if err != nil {
|
||||
@@ -104,8 +104,8 @@ func TestXml_2(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestXml_3(t *testing.T) {
|
||||
a := []interface{}{"string", true, 36.4}
|
||||
mv := Map{"array": []interface{}{a, "string2"}}
|
||||
a := []interface{}{ "string", true, 36.4 }
|
||||
mv := Map{"array": []interface{}{a, "string2"} }
|
||||
|
||||
x, err := mv.Xml()
|
||||
if err != nil {
|
||||
@@ -117,8 +117,8 @@ func TestXml_3(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestXml_4(t *testing.T) {
|
||||
a := []interface{}{"string", true, 36.4}
|
||||
mv := Map{"array": map[string]interface{}{"innerkey": []interface{}{a, "string2"}}}
|
||||
a := []interface{}{ "string", true, 36.4 }
|
||||
mv := Map{"array": map[string]interface{}{ "innerkey": []interface{}{a, "string2"} } }
|
||||
|
||||
x, err := mv.Xml()
|
||||
if err != nil {
|
||||
@@ -130,8 +130,8 @@ func TestXml_4(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestXml_5(t *testing.T) {
|
||||
a := []interface{}{"string", true, 36.4}
|
||||
mv := Map{"array": []interface{}{map[string]interface{}{"innerkey": []interface{}{a, "string2"}}, map[string]interface{}{"some": "more"}}}
|
||||
a := []interface{}{ "string", true, 36.4 }
|
||||
mv := Map{"array": []interface{}{ map[string]interface{}{ "innerkey": []interface{}{a, "string2"} }, map[string]interface{}{"some":"more"} } }
|
||||
|
||||
x, err := mv.Xml()
|
||||
if err != nil {
|
||||
@@ -148,10 +148,10 @@ func TestXmlWriter(t *testing.T) {
|
||||
|
||||
raw, err := mv.XmlWriterRaw(w, "myRootTag")
|
||||
if err != nil {
|
||||
t.Fatal("err:", err.Error())
|
||||
t.Fatal("err:",err.Error())
|
||||
}
|
||||
|
||||
b := make([]byte, w.Len())
|
||||
b := make([]byte,w.Len())
|
||||
_, err = w.Read(b)
|
||||
if err != nil {
|
||||
t.Fatal("err:", err.Error())
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
#*
|
||||
*.[568]
|
||||
*.a
|
||||
*~
|
||||
[568].out
|
||||
_*
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
Copyright (c) 2005-2008 Dustin Sallings <dustin@spy.net>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
<http://www.opensource.org/licenses/mit-license.php>
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
# Humane Units
|
||||
|
||||
Just a few functions for helping humanize times and sizes.
|
||||
|
||||
`go get` it as `github.com/dustin/go-humanize`, import it as
|
||||
`"github.com/dustin/go-humanize"`, use it as `humanize`
|
||||
|
||||
## Sizes
|
||||
|
||||
This lets you take numbers like `82854982` and convert them to useful
|
||||
strings like, `83MB` or `79MiB` (whichever you prefer).
|
||||
|
||||
Example:
|
||||
|
||||
fmt.Printf("That file is %s.", humanize.Bytes(82854982))
|
||||
|
||||
## Times
|
||||
|
||||
This lets you take a `time.Time` and spit it out in relative terms.
|
||||
For example, `12 seconds ago` or `3 days from now`.
|
||||
|
||||
Example:
|
||||
|
||||
fmt.Printf("This was touched %s", humanize.Time(someTimeInstance))
|
||||
|
||||
Thanks to Kyle Lemons for the time implementation from an IRC
|
||||
conversation one day. It's pretty neat.
|
||||
|
||||
## Ordinals
|
||||
|
||||
From a [mailing list discussion][odisc] where a user wanted to be able
|
||||
to label ordinals.
|
||||
|
||||
0 -> 0th
|
||||
1 -> 1st
|
||||
2 -> 2nd
|
||||
3 -> 3rd
|
||||
4 -> 4th
|
||||
[...]
|
||||
|
||||
Example:
|
||||
|
||||
fmt.Printf("You're my %s best friend.", humanize.Ordinal(193))
|
||||
|
||||
## Commas
|
||||
|
||||
Want to shove commas into numbers? Be my guest.
|
||||
|
||||
0 -> 0
|
||||
100 -> 100
|
||||
1000 -> 1,000
|
||||
1000000000 -> 1,000,000,000
|
||||
-100000 -> -100,000
|
||||
|
||||
Example:
|
||||
|
||||
fmt.Printf("You owe $%s.\n", humanize.Comma(6582491))
|
||||
|
||||
## Ftoa
|
||||
|
||||
Nicer float64 formatter that removes trailing zeros.
|
||||
|
||||
fmt.Printf("%f", 2.24) // 2.240000
|
||||
fmt.Printf("%s", humanize.Ftoa(2.24)) // 2.24
|
||||
fmt.Printf("%f", 2.0) // 2.000000
|
||||
fmt.Printf("%s", humanize.Ftoa(2.0)) // 2
|
||||
|
||||
## SI notation
|
||||
|
||||
Format numbers with [SI notation][sinotation].
|
||||
|
||||
Example:
|
||||
|
||||
humanize.SI(0.00000000223, "M") // 2.23nM
|
||||
|
||||
|
||||
[odisc]: https://groups.google.com/d/topic/golang-nuts/l8NhI74jl-4/discussion
|
||||
[sinotation]: http://en.wikipedia.org/wiki/Metric_prefix
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package humanize
|
||||
|
||||
import (
|
||||
"math/big"
|
||||
)
|
||||
|
||||
// order of magnitude (to a max order)
|
||||
func oomm(n, b *big.Int, maxmag int) (float64, int) {
|
||||
mag := 0
|
||||
m := &big.Int{}
|
||||
for n.Cmp(b) >= 0 {
|
||||
n.DivMod(n, b, m)
|
||||
mag++
|
||||
if mag == maxmag && maxmag >= 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
return float64(n.Int64()) + (float64(m.Int64()) / float64(b.Int64())), mag
|
||||
}
|
||||
|
||||
// total order of magnitude
|
||||
// (same as above, but with no upper limit)
|
||||
func oom(n, b *big.Int) (float64, int) {
|
||||
mag := 0
|
||||
m := &big.Int{}
|
||||
for n.Cmp(b) >= 0 {
|
||||
n.DivMod(n, b, m)
|
||||
mag++
|
||||
}
|
||||
return float64(n.Int64()) + (float64(m.Int64()) / float64(b.Int64())), mag
|
||||
}
|
||||
+164
@@ -0,0 +1,164 @@
|
||||
package humanize
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/big"
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
var (
|
||||
bigIECExp = big.NewInt(1024)
|
||||
|
||||
// BigByte is one byte in bit.Ints
|
||||
BigByte = big.NewInt(1)
|
||||
// BigKiByte is 1,024 bytes in bit.Ints
|
||||
BigKiByte = (&big.Int{}).Mul(BigByte, bigIECExp)
|
||||
// BigMiByte is 1,024 k bytes in bit.Ints
|
||||
BigMiByte = (&big.Int{}).Mul(BigKiByte, bigIECExp)
|
||||
// BigGiByte is 1,024 m bytes in bit.Ints
|
||||
BigGiByte = (&big.Int{}).Mul(BigMiByte, bigIECExp)
|
||||
// BigTiByte is 1,024 g bytes in bit.Ints
|
||||
BigTiByte = (&big.Int{}).Mul(BigGiByte, bigIECExp)
|
||||
// BigPiByte is 1,024 t bytes in bit.Ints
|
||||
BigPiByte = (&big.Int{}).Mul(BigTiByte, bigIECExp)
|
||||
// BigEiByte is 1,024 p bytes in bit.Ints
|
||||
BigEiByte = (&big.Int{}).Mul(BigPiByte, bigIECExp)
|
||||
// BigZiByte is 1,024 e bytes in bit.Ints
|
||||
BigZiByte = (&big.Int{}).Mul(BigEiByte, bigIECExp)
|
||||
// BigYiByte is 1,024 z bytes in bit.Ints
|
||||
BigYiByte = (&big.Int{}).Mul(BigZiByte, bigIECExp)
|
||||
)
|
||||
|
||||
var (
|
||||
bigSIExp = big.NewInt(1000)
|
||||
|
||||
// BigSIByte is one SI byte in big.Ints
|
||||
BigSIByte = big.NewInt(1)
|
||||
// BigKByte is 1,000 SI bytes in big.Ints
|
||||
BigKByte = (&big.Int{}).Mul(BigSIByte, bigSIExp)
|
||||
// BigMByte is 1,000 SI k bytes in big.Ints
|
||||
BigMByte = (&big.Int{}).Mul(BigKByte, bigSIExp)
|
||||
// BigGByte is 1,000 SI m bytes in big.Ints
|
||||
BigGByte = (&big.Int{}).Mul(BigMByte, bigSIExp)
|
||||
// BigTByte is 1,000 SI g bytes in big.Ints
|
||||
BigTByte = (&big.Int{}).Mul(BigGByte, bigSIExp)
|
||||
// BigPByte is 1,000 SI t bytes in big.Ints
|
||||
BigPByte = (&big.Int{}).Mul(BigTByte, bigSIExp)
|
||||
// BigEByte is 1,000 SI p bytes in big.Ints
|
||||
BigEByte = (&big.Int{}).Mul(BigPByte, bigSIExp)
|
||||
// BigZByte is 1,000 SI e bytes in big.Ints
|
||||
BigZByte = (&big.Int{}).Mul(BigEByte, bigSIExp)
|
||||
// BigYByte is 1,000 SI z bytes in big.Ints
|
||||
BigYByte = (&big.Int{}).Mul(BigZByte, bigSIExp)
|
||||
)
|
||||
|
||||
var bigBytesSizeTable = map[string]*big.Int{
|
||||
"b": BigByte,
|
||||
"kib": BigKiByte,
|
||||
"kb": BigKByte,
|
||||
"mib": BigMiByte,
|
||||
"mb": BigMByte,
|
||||
"gib": BigGiByte,
|
||||
"gb": BigGByte,
|
||||
"tib": BigTiByte,
|
||||
"tb": BigTByte,
|
||||
"pib": BigPiByte,
|
||||
"pb": BigPByte,
|
||||
"eib": BigEiByte,
|
||||
"eb": BigEByte,
|
||||
"zib": BigZiByte,
|
||||
"zb": BigZByte,
|
||||
"yib": BigYiByte,
|
||||
"yb": BigYByte,
|
||||
// Without suffix
|
||||
"": BigByte,
|
||||
"ki": BigKiByte,
|
||||
"k": BigKByte,
|
||||
"mi": BigMiByte,
|
||||
"m": BigMByte,
|
||||
"gi": BigGiByte,
|
||||
"g": BigGByte,
|
||||
"ti": BigTiByte,
|
||||
"t": BigTByte,
|
||||
"pi": BigPiByte,
|
||||
"p": BigPByte,
|
||||
"ei": BigEiByte,
|
||||
"e": BigEByte,
|
||||
"z": BigZByte,
|
||||
"zi": BigZiByte,
|
||||
"y": BigYByte,
|
||||
"yi": BigYiByte,
|
||||
}
|
||||
|
||||
var ten = big.NewInt(10)
|
||||
|
||||
func humanateBigBytes(s, base *big.Int, sizes []string) string {
|
||||
if s.Cmp(ten) < 0 {
|
||||
return fmt.Sprintf("%dB", s)
|
||||
}
|
||||
c := (&big.Int{}).Set(s)
|
||||
val, mag := oomm(c, base, len(sizes)-1)
|
||||
suffix := sizes[mag]
|
||||
f := "%.0f%s"
|
||||
if val < 10 {
|
||||
f = "%.1f%s"
|
||||
}
|
||||
|
||||
return fmt.Sprintf(f, val, suffix)
|
||||
|
||||
}
|
||||
|
||||
// BigBytes produces a human readable representation of an SI size.
|
||||
//
|
||||
// See also: ParseBigBytes.
|
||||
//
|
||||
// BigBytes(82854982) -> 83MB
|
||||
func BigBytes(s *big.Int) string {
|
||||
sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}
|
||||
return humanateBigBytes(s, bigSIExp, sizes)
|
||||
}
|
||||
|
||||
// BigIBytes produces a human readable representation of an IEC size.
|
||||
//
|
||||
// See also: ParseBigBytes.
|
||||
//
|
||||
// BigIBytes(82854982) -> 79MiB
|
||||
func BigIBytes(s *big.Int) string {
|
||||
sizes := []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"}
|
||||
return humanateBigBytes(s, bigIECExp, sizes)
|
||||
}
|
||||
|
||||
// ParseBigBytes parses a string representation of bytes into the number
|
||||
// of bytes it represents.
|
||||
//
|
||||
// See also: BigBytes, BigIBytes.
|
||||
//
|
||||
// ParseBigBytes("42MB") -> 42000000, nil
|
||||
// ParseBigBytes("42mib") -> 44040192, nil
|
||||
func ParseBigBytes(s string) (*big.Int, error) {
|
||||
lastDigit := 0
|
||||
for _, r := range s {
|
||||
if !(unicode.IsDigit(r) || r == '.') {
|
||||
break
|
||||
}
|
||||
lastDigit++
|
||||
}
|
||||
|
||||
val := &big.Rat{}
|
||||
_, err := fmt.Sscanf(s[:lastDigit], "%f", val)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
extra := strings.ToLower(strings.TrimSpace(s[lastDigit:]))
|
||||
if m, ok := bigBytesSizeTable[extra]; ok {
|
||||
mv := (&big.Rat{}).SetInt(m)
|
||||
val.Mul(val, mv)
|
||||
rv := &big.Int{}
|
||||
rv.Div(val.Num(), val.Denom())
|
||||
return rv, nil
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("unhandled size name: %v", extra)
|
||||
}
|
||||
+219
@@ -0,0 +1,219 @@
|
||||
package humanize
|
||||
|
||||
import (
|
||||
"math/big"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBigByteParsing(t *testing.T) {
|
||||
tests := []struct {
|
||||
in string
|
||||
exp uint64
|
||||
}{
|
||||
{"42", 42},
|
||||
{"42MB", 42000000},
|
||||
{"42MiB", 44040192},
|
||||
{"42mb", 42000000},
|
||||
{"42mib", 44040192},
|
||||
{"42MIB", 44040192},
|
||||
{"42 MB", 42000000},
|
||||
{"42 MiB", 44040192},
|
||||
{"42 mb", 42000000},
|
||||
{"42 mib", 44040192},
|
||||
{"42 MIB", 44040192},
|
||||
{"42.5MB", 42500000},
|
||||
{"42.5MiB", 44564480},
|
||||
{"42.5 MB", 42500000},
|
||||
{"42.5 MiB", 44564480},
|
||||
// No need to say B
|
||||
{"42M", 42000000},
|
||||
{"42Mi", 44040192},
|
||||
{"42m", 42000000},
|
||||
{"42mi", 44040192},
|
||||
{"42MI", 44040192},
|
||||
{"42 M", 42000000},
|
||||
{"42 Mi", 44040192},
|
||||
{"42 m", 42000000},
|
||||
{"42 mi", 44040192},
|
||||
{"42 MI", 44040192},
|
||||
{"42.5M", 42500000},
|
||||
{"42.5Mi", 44564480},
|
||||
{"42.5 M", 42500000},
|
||||
{"42.5 Mi", 44564480},
|
||||
// Large testing, breaks when too much larger than
|
||||
// this.
|
||||
{"12.5 EB", uint64(12.5 * float64(EByte))},
|
||||
{"12.5 E", uint64(12.5 * float64(EByte))},
|
||||
{"12.5 EiB", uint64(12.5 * float64(EiByte))},
|
||||
}
|
||||
|
||||
for _, p := range tests {
|
||||
got, err := ParseBigBytes(p.in)
|
||||
if err != nil {
|
||||
t.Errorf("Couldn't parse %v: %v", p.in, err)
|
||||
} else {
|
||||
if got.Uint64() != p.exp {
|
||||
t.Errorf("Expected %v for %v, got %v",
|
||||
p.exp, p.in, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBigByteErrors(t *testing.T) {
|
||||
got, err := ParseBigBytes("84 JB")
|
||||
if err == nil {
|
||||
t.Errorf("Expected error, got %v", got)
|
||||
}
|
||||
got, err = ParseBigBytes("")
|
||||
if err == nil {
|
||||
t.Errorf("Expected error parsing nothing")
|
||||
}
|
||||
}
|
||||
|
||||
func bbyte(in uint64) string {
|
||||
return BigBytes((&big.Int{}).SetUint64(in))
|
||||
}
|
||||
|
||||
func bibyte(in uint64) string {
|
||||
return BigIBytes((&big.Int{}).SetUint64(in))
|
||||
}
|
||||
|
||||
func TestBigBytes(t *testing.T) {
|
||||
testList{
|
||||
{"bytes(0)", bbyte(0), "0B"},
|
||||
{"bytes(1)", bbyte(1), "1B"},
|
||||
{"bytes(803)", bbyte(803), "803B"},
|
||||
{"bytes(999)", bbyte(999), "999B"},
|
||||
|
||||
{"bytes(1024)", bbyte(1024), "1.0KB"},
|
||||
{"bytes(1MB - 1)", bbyte(MByte - Byte), "1000KB"},
|
||||
|
||||
{"bytes(1MB)", bbyte(1024 * 1024), "1.0MB"},
|
||||
{"bytes(1GB - 1K)", bbyte(GByte - KByte), "1000MB"},
|
||||
|
||||
{"bytes(1GB)", bbyte(GByte), "1.0GB"},
|
||||
{"bytes(1TB - 1M)", bbyte(TByte - MByte), "1000GB"},
|
||||
|
||||
{"bytes(1TB)", bbyte(TByte), "1.0TB"},
|
||||
{"bytes(1PB - 1T)", bbyte(PByte - TByte), "999TB"},
|
||||
|
||||
{"bytes(1PB)", bbyte(PByte), "1.0PB"},
|
||||
{"bytes(1PB - 1T)", bbyte(EByte - PByte), "999PB"},
|
||||
|
||||
{"bytes(1EB)", bbyte(EByte), "1.0EB"},
|
||||
// Overflows.
|
||||
// {"bytes(1EB - 1P)", Bytes((KByte*EByte)-PByte), "1023EB"},
|
||||
|
||||
{"bytes(0)", bibyte(0), "0B"},
|
||||
{"bytes(1)", bibyte(1), "1B"},
|
||||
{"bytes(803)", bibyte(803), "803B"},
|
||||
{"bytes(1023)", bibyte(1023), "1023B"},
|
||||
|
||||
{"bytes(1024)", bibyte(1024), "1.0KiB"},
|
||||
{"bytes(1MB - 1)", bibyte(MiByte - IByte), "1024KiB"},
|
||||
|
||||
{"bytes(1MB)", bibyte(1024 * 1024), "1.0MiB"},
|
||||
{"bytes(1GB - 1K)", bibyte(GiByte - KiByte), "1024MiB"},
|
||||
|
||||
{"bytes(1GB)", bibyte(GiByte), "1.0GiB"},
|
||||
{"bytes(1TB - 1M)", bibyte(TiByte - MiByte), "1024GiB"},
|
||||
|
||||
{"bytes(1TB)", bibyte(TiByte), "1.0TiB"},
|
||||
{"bytes(1PB - 1T)", bibyte(PiByte - TiByte), "1023TiB"},
|
||||
|
||||
{"bytes(1PB)", bibyte(PiByte), "1.0PiB"},
|
||||
{"bytes(1PB - 1T)", bibyte(EiByte - PiByte), "1023PiB"},
|
||||
|
||||
{"bytes(1EiB)", bibyte(EiByte), "1.0EiB"},
|
||||
// Overflows.
|
||||
// {"bytes(1EB - 1P)", bibyte((KIByte*EIByte)-PiByte), "1023EB"},
|
||||
|
||||
{"bytes(5.5GiB)", bibyte(5.5 * GiByte), "5.5GiB"},
|
||||
|
||||
{"bytes(5.5GB)", bbyte(5.5 * GByte), "5.5GB"},
|
||||
}.validate(t)
|
||||
}
|
||||
|
||||
func TestVeryBigBytes(t *testing.T) {
|
||||
b, _ := (&big.Int{}).SetString("15347691069326346944512", 10)
|
||||
s := BigBytes(b)
|
||||
if s != "15ZB" {
|
||||
t.Errorf("Expected 15ZB, got %v", s)
|
||||
}
|
||||
s = BigIBytes(b)
|
||||
if s != "13ZiB" {
|
||||
t.Errorf("Expected 13ZiB, got %v", s)
|
||||
}
|
||||
|
||||
b, _ = (&big.Int{}).SetString("15716035654990179271180288", 10)
|
||||
s = BigBytes(b)
|
||||
if s != "16YB" {
|
||||
t.Errorf("Expected 16YB, got %v", s)
|
||||
}
|
||||
s = BigIBytes(b)
|
||||
if s != "13YiB" {
|
||||
t.Errorf("Expected 13YiB, got %v", s)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVeryVeryBigBytes(t *testing.T) {
|
||||
b, _ := (&big.Int{}).SetString("16093220510709943573688614912", 10)
|
||||
s := BigBytes(b)
|
||||
if s != "16093YB" {
|
||||
t.Errorf("Expected 16093YB, got %v", s)
|
||||
}
|
||||
s = BigIBytes(b)
|
||||
if s != "13312YiB" {
|
||||
t.Errorf("Expected 13312YiB, got %v", s)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseVeryBig(t *testing.T) {
|
||||
tests := []struct {
|
||||
in string
|
||||
out string
|
||||
}{
|
||||
{"16ZB", "16000000000000000000000"},
|
||||
{"16ZiB", "18889465931478580854784"},
|
||||
{"16.5ZB", "16500000000000000000000"},
|
||||
{"16.5ZiB", "19479761741837286506496"},
|
||||
{"16Z", "16000000000000000000000"},
|
||||
{"16Zi", "18889465931478580854784"},
|
||||
{"16.5Z", "16500000000000000000000"},
|
||||
{"16.5Zi", "19479761741837286506496"},
|
||||
|
||||
{"16YB", "16000000000000000000000000"},
|
||||
{"16YiB", "19342813113834066795298816"},
|
||||
{"16.5YB", "16500000000000000000000000"},
|
||||
{"16.5YiB", "19947276023641381382651904"},
|
||||
{"16Y", "16000000000000000000000000"},
|
||||
{"16Yi", "19342813113834066795298816"},
|
||||
{"16.5Y", "16500000000000000000000000"},
|
||||
{"16.5Yi", "19947276023641381382651904"},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
x, err := ParseBigBytes(test.in)
|
||||
if err != nil {
|
||||
t.Errorf("Error parsing %q: %v", test.in, err)
|
||||
continue
|
||||
}
|
||||
|
||||
if x.String() != test.out {
|
||||
t.Errorf("Expected %q for %q, got %v", test.out, test.in, x)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkParseBigBytes(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
ParseBigBytes("16.5Z")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkBigBytes(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
bibyte(16.5 * GByte)
|
||||
}
|
||||
}
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
package humanize
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
// IEC Sizes.
|
||||
// kibis of bits
|
||||
const (
|
||||
Byte = 1 << (iota * 10)
|
||||
KiByte
|
||||
MiByte
|
||||
GiByte
|
||||
TiByte
|
||||
PiByte
|
||||
EiByte
|
||||
)
|
||||
|
||||
// SI Sizes.
|
||||
const (
|
||||
IByte = 1
|
||||
KByte = IByte * 1000
|
||||
MByte = KByte * 1000
|
||||
GByte = MByte * 1000
|
||||
TByte = GByte * 1000
|
||||
PByte = TByte * 1000
|
||||
EByte = PByte * 1000
|
||||
)
|
||||
|
||||
var bytesSizeTable = map[string]uint64{
|
||||
"b": Byte,
|
||||
"kib": KiByte,
|
||||
"kb": KByte,
|
||||
"mib": MiByte,
|
||||
"mb": MByte,
|
||||
"gib": GiByte,
|
||||
"gb": GByte,
|
||||
"tib": TiByte,
|
||||
"tb": TByte,
|
||||
"pib": PiByte,
|
||||
"pb": PByte,
|
||||
"eib": EiByte,
|
||||
"eb": EByte,
|
||||
// Without suffix
|
||||
"": Byte,
|
||||
"ki": KiByte,
|
||||
"k": KByte,
|
||||
"mi": MiByte,
|
||||
"m": MByte,
|
||||
"gi": GiByte,
|
||||
"g": GByte,
|
||||
"ti": TiByte,
|
||||
"t": TByte,
|
||||
"pi": PiByte,
|
||||
"p": PByte,
|
||||
"ei": EiByte,
|
||||
"e": EByte,
|
||||
}
|
||||
|
||||
func logn(n, b float64) float64 {
|
||||
return math.Log(n) / math.Log(b)
|
||||
}
|
||||
|
||||
func humanateBytes(s uint64, base float64, sizes []string) string {
|
||||
if s < 10 {
|
||||
return fmt.Sprintf("%dB", s)
|
||||
}
|
||||
e := math.Floor(logn(float64(s), base))
|
||||
suffix := sizes[int(e)]
|
||||
val := math.Floor(float64(s)/math.Pow(base, e)*10+0.5) / 10
|
||||
f := "%.0f%s"
|
||||
if val < 10 {
|
||||
f = "%.1f%s"
|
||||
}
|
||||
|
||||
return fmt.Sprintf(f, val, suffix)
|
||||
}
|
||||
|
||||
// Bytes produces a human readable representation of an SI size.
|
||||
//
|
||||
// See also: ParseBytes.
|
||||
//
|
||||
// Bytes(82854982) -> 83MB
|
||||
func Bytes(s uint64) string {
|
||||
sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
|
||||
return humanateBytes(s, 1000, sizes)
|
||||
}
|
||||
|
||||
// IBytes produces a human readable representation of an IEC size.
|
||||
//
|
||||
// See also: ParseBytes.
|
||||
//
|
||||
// IBytes(82854982) -> 79MiB
|
||||
func IBytes(s uint64) string {
|
||||
sizes := []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"}
|
||||
return humanateBytes(s, 1024, sizes)
|
||||
}
|
||||
|
||||
// ParseBytes parses a string representation of bytes into the number
|
||||
// of bytes it represents.
|
||||
//
|
||||
// See Also: Bytes, IBytes.
|
||||
//
|
||||
// ParseBytes("42MB") -> 42000000, nil
|
||||
// ParseBytes("42mib") -> 44040192, nil
|
||||
func ParseBytes(s string) (uint64, error) {
|
||||
lastDigit := 0
|
||||
for _, r := range s {
|
||||
if !(unicode.IsDigit(r) || r == '.') {
|
||||
break
|
||||
}
|
||||
lastDigit++
|
||||
}
|
||||
|
||||
f, err := strconv.ParseFloat(s[:lastDigit], 64)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
extra := strings.ToLower(strings.TrimSpace(s[lastDigit:]))
|
||||
if m, ok := bytesSizeTable[extra]; ok {
|
||||
f *= float64(m)
|
||||
if f >= math.MaxUint64 {
|
||||
return 0, fmt.Errorf("too large: %v", s)
|
||||
}
|
||||
return uint64(f), nil
|
||||
}
|
||||
|
||||
return 0, fmt.Errorf("unhandled size name: %v", extra)
|
||||
}
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
package humanize
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestByteParsing(t *testing.T) {
|
||||
tests := []struct {
|
||||
in string
|
||||
exp uint64
|
||||
}{
|
||||
{"42", 42},
|
||||
{"42MB", 42000000},
|
||||
{"42MiB", 44040192},
|
||||
{"42mb", 42000000},
|
||||
{"42mib", 44040192},
|
||||
{"42MIB", 44040192},
|
||||
{"42 MB", 42000000},
|
||||
{"42 MiB", 44040192},
|
||||
{"42 mb", 42000000},
|
||||
{"42 mib", 44040192},
|
||||
{"42 MIB", 44040192},
|
||||
{"42.5MB", 42500000},
|
||||
{"42.5MiB", 44564480},
|
||||
{"42.5 MB", 42500000},
|
||||
{"42.5 MiB", 44564480},
|
||||
// No need to say B
|
||||
{"42M", 42000000},
|
||||
{"42Mi", 44040192},
|
||||
{"42m", 42000000},
|
||||
{"42mi", 44040192},
|
||||
{"42MI", 44040192},
|
||||
{"42 M", 42000000},
|
||||
{"42 Mi", 44040192},
|
||||
{"42 m", 42000000},
|
||||
{"42 mi", 44040192},
|
||||
{"42 MI", 44040192},
|
||||
{"42.5M", 42500000},
|
||||
{"42.5Mi", 44564480},
|
||||
{"42.5 M", 42500000},
|
||||
{"42.5 Mi", 44564480},
|
||||
// Large testing, breaks when too much larger than
|
||||
// this.
|
||||
{"12.5 EB", uint64(12.5 * float64(EByte))},
|
||||
{"12.5 E", uint64(12.5 * float64(EByte))},
|
||||
{"12.5 EiB", uint64(12.5 * float64(EiByte))},
|
||||
}
|
||||
|
||||
for _, p := range tests {
|
||||
got, err := ParseBytes(p.in)
|
||||
if err != nil {
|
||||
t.Errorf("Couldn't parse %v: %v", p.in, err)
|
||||
}
|
||||
if got != p.exp {
|
||||
t.Errorf("Expected %v for %v, got %v",
|
||||
p.exp, p.in, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestByteErrors(t *testing.T) {
|
||||
got, err := ParseBytes("84 JB")
|
||||
if err == nil {
|
||||
t.Errorf("Expected error, got %v", got)
|
||||
}
|
||||
got, err = ParseBytes("")
|
||||
if err == nil {
|
||||
t.Errorf("Expected error parsing nothing")
|
||||
}
|
||||
got, err = ParseBytes("16 EiB")
|
||||
if err == nil {
|
||||
t.Errorf("Expected error, got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBytes(t *testing.T) {
|
||||
testList{
|
||||
{"bytes(0)", Bytes(0), "0B"},
|
||||
{"bytes(1)", Bytes(1), "1B"},
|
||||
{"bytes(803)", Bytes(803), "803B"},
|
||||
{"bytes(999)", Bytes(999), "999B"},
|
||||
|
||||
{"bytes(1024)", Bytes(1024), "1.0KB"},
|
||||
{"bytes(9999)", Bytes(9999), "10KB"},
|
||||
{"bytes(1MB - 1)", Bytes(MByte - Byte), "1000KB"},
|
||||
|
||||
{"bytes(1MB)", Bytes(1024 * 1024), "1.0MB"},
|
||||
{"bytes(1GB - 1K)", Bytes(GByte - KByte), "1000MB"},
|
||||
|
||||
{"bytes(1GB)", Bytes(GByte), "1.0GB"},
|
||||
{"bytes(1TB - 1M)", Bytes(TByte - MByte), "1000GB"},
|
||||
{"bytes(10MB)", Bytes(9999 * 1000), "10MB"},
|
||||
|
||||
{"bytes(1TB)", Bytes(TByte), "1.0TB"},
|
||||
{"bytes(1PB - 1T)", Bytes(PByte - TByte), "999TB"},
|
||||
|
||||
{"bytes(1PB)", Bytes(PByte), "1.0PB"},
|
||||
{"bytes(1PB - 1T)", Bytes(EByte - PByte), "999PB"},
|
||||
|
||||
{"bytes(1EB)", Bytes(EByte), "1.0EB"},
|
||||
// Overflows.
|
||||
// {"bytes(1EB - 1P)", Bytes((KByte*EByte)-PByte), "1023EB"},
|
||||
|
||||
{"bytes(0)", IBytes(0), "0B"},
|
||||
{"bytes(1)", IBytes(1), "1B"},
|
||||
{"bytes(803)", IBytes(803), "803B"},
|
||||
{"bytes(1023)", IBytes(1023), "1023B"},
|
||||
|
||||
{"bytes(1024)", IBytes(1024), "1.0KiB"},
|
||||
{"bytes(1MB - 1)", IBytes(MiByte - IByte), "1024KiB"},
|
||||
|
||||
{"bytes(1MB)", IBytes(1024 * 1024), "1.0MiB"},
|
||||
{"bytes(1GB - 1K)", IBytes(GiByte - KiByte), "1024MiB"},
|
||||
|
||||
{"bytes(1GB)", IBytes(GiByte), "1.0GiB"},
|
||||
{"bytes(1TB - 1M)", IBytes(TiByte - MiByte), "1024GiB"},
|
||||
|
||||
{"bytes(1TB)", IBytes(TiByte), "1.0TiB"},
|
||||
{"bytes(1PB - 1T)", IBytes(PiByte - TiByte), "1023TiB"},
|
||||
|
||||
{"bytes(1PB)", IBytes(PiByte), "1.0PiB"},
|
||||
{"bytes(1PB - 1T)", IBytes(EiByte - PiByte), "1023PiB"},
|
||||
|
||||
{"bytes(1EiB)", IBytes(EiByte), "1.0EiB"},
|
||||
// Overflows.
|
||||
// {"bytes(1EB - 1P)", IBytes((KIByte*EIByte)-PiByte), "1023EB"},
|
||||
|
||||
{"bytes(5.5GiB)", IBytes(5.5 * GiByte), "5.5GiB"},
|
||||
|
||||
{"bytes(5.5GB)", Bytes(5.5 * GByte), "5.5GB"},
|
||||
}.validate(t)
|
||||
}
|
||||
|
||||
func BenchmarkParseBytes(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
ParseBytes("16.5GB")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkBytes(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
Bytes(16.5 * GByte)
|
||||
}
|
||||
}
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
package humanize
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"math/big"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Comma produces a string form of the given number in base 10 with
|
||||
// commas after every three orders of magnitude.
|
||||
//
|
||||
// e.g. Comma(834142) -> 834,142
|
||||
func Comma(v int64) string {
|
||||
sign := ""
|
||||
if v < 0 {
|
||||
sign = "-"
|
||||
v = 0 - v
|
||||
}
|
||||
|
||||
parts := []string{"", "", "", "", "", "", "", ""}
|
||||
j := len(parts) - 1
|
||||
|
||||
for v > 999 {
|
||||
parts[j] = strconv.FormatInt(v%1000, 10)
|
||||
switch len(parts[j]) {
|
||||
case 2:
|
||||
parts[j] = "0" + parts[j]
|
||||
case 1:
|
||||
parts[j] = "00" + parts[j]
|
||||
}
|
||||
v = v / 1000
|
||||
j--
|
||||
}
|
||||
parts[j] = strconv.Itoa(int(v))
|
||||
return sign + strings.Join(parts[j:len(parts)], ",")
|
||||
}
|
||||
|
||||
// Commaf produces a string form of the given number in base 10 with
|
||||
// commas after every three orders of magnitude.
|
||||
//
|
||||
// e.g. Comma(834142.32) -> 834,142.32
|
||||
func Commaf(v float64) string {
|
||||
buf := &bytes.Buffer{}
|
||||
if v < 0 {
|
||||
buf.Write([]byte{'-'})
|
||||
v = 0 - v
|
||||
}
|
||||
|
||||
comma := []byte{','}
|
||||
|
||||
parts := strings.Split(strconv.FormatFloat(v, 'f', -1, 64), ".")
|
||||
pos := 0
|
||||
if len(parts[0])%3 != 0 {
|
||||
pos += len(parts[0]) % 3
|
||||
buf.WriteString(parts[0][:pos])
|
||||
buf.Write(comma)
|
||||
}
|
||||
for ; pos < len(parts[0]); pos += 3 {
|
||||
buf.WriteString(parts[0][pos : pos+3])
|
||||
buf.Write(comma)
|
||||
}
|
||||
buf.Truncate(buf.Len() - 1)
|
||||
|
||||
if len(parts) > 1 {
|
||||
buf.Write([]byte{'.'})
|
||||
buf.WriteString(parts[1])
|
||||
}
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
// BigComma produces a string form of the given big.Int in base 10
|
||||
// with commas after every three orders of magnitude.
|
||||
func BigComma(b *big.Int) string {
|
||||
sign := ""
|
||||
if b.Sign() < 0 {
|
||||
sign = "-"
|
||||
b.Abs(b)
|
||||
}
|
||||
|
||||
athousand := big.NewInt(1000)
|
||||
c := (&big.Int{}).Set(b)
|
||||
_, m := oom(c, athousand)
|
||||
parts := make([]string, m+1)
|
||||
j := len(parts) - 1
|
||||
|
||||
mod := &big.Int{}
|
||||
for b.Cmp(athousand) >= 0 {
|
||||
b.DivMod(b, athousand, mod)
|
||||
parts[j] = strconv.FormatInt(mod.Int64(), 10)
|
||||
switch len(parts[j]) {
|
||||
case 2:
|
||||
parts[j] = "0" + parts[j]
|
||||
case 1:
|
||||
parts[j] = "00" + parts[j]
|
||||
}
|
||||
j--
|
||||
}
|
||||
parts[j] = strconv.Itoa(int(b.Int64()))
|
||||
return sign + strings.Join(parts[j:len(parts)], ",")
|
||||
}
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
package humanize
|
||||
|
||||
import (
|
||||
"math"
|
||||
"math/big"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCommas(t *testing.T) {
|
||||
testList{
|
||||
{"0", Comma(0), "0"},
|
||||
{"10", Comma(10), "10"},
|
||||
{"100", Comma(100), "100"},
|
||||
{"1,000", Comma(1000), "1,000"},
|
||||
{"10,000", Comma(10000), "10,000"},
|
||||
{"100,000", Comma(100000), "100,000"},
|
||||
{"10,000,000", Comma(10000000), "10,000,000"},
|
||||
{"10,100,000", Comma(10100000), "10,100,000"},
|
||||
{"10,010,000", Comma(10010000), "10,010,000"},
|
||||
{"10,001,000", Comma(10001000), "10,001,000"},
|
||||
{"123,456,789", Comma(123456789), "123,456,789"},
|
||||
{"maxint", Comma(9.223372e+18), "9,223,372,000,000,000,000"},
|
||||
{"minint", Comma(-9.223372e+18), "-9,223,372,000,000,000,000"},
|
||||
{"-123,456,789", Comma(-123456789), "-123,456,789"},
|
||||
{"-10,100,000", Comma(-10100000), "-10,100,000"},
|
||||
{"-10,010,000", Comma(-10010000), "-10,010,000"},
|
||||
{"-10,001,000", Comma(-10001000), "-10,001,000"},
|
||||
{"-10,000,000", Comma(-10000000), "-10,000,000"},
|
||||
{"-100,000", Comma(-100000), "-100,000"},
|
||||
{"-10,000", Comma(-10000), "-10,000"},
|
||||
{"-1,000", Comma(-1000), "-1,000"},
|
||||
{"-100", Comma(-100), "-100"},
|
||||
{"-10", Comma(-10), "-10"},
|
||||
}.validate(t)
|
||||
}
|
||||
|
||||
func TestCommafs(t *testing.T) {
|
||||
testList{
|
||||
{"0", Commaf(0), "0"},
|
||||
{"10.11", Commaf(10.11), "10.11"},
|
||||
{"100", Commaf(100), "100"},
|
||||
{"1,000", Commaf(1000), "1,000"},
|
||||
{"10,000", Commaf(10000), "10,000"},
|
||||
{"100,000", Commaf(100000), "100,000"},
|
||||
{"834,142.32", Commaf(834142.32), "834,142.32"},
|
||||
{"10,000,000", Commaf(10000000), "10,000,000"},
|
||||
{"10,100,000", Commaf(10100000), "10,100,000"},
|
||||
{"10,010,000", Commaf(10010000), "10,010,000"},
|
||||
{"10,001,000", Commaf(10001000), "10,001,000"},
|
||||
{"123,456,789", Commaf(123456789), "123,456,789"},
|
||||
{"maxf64", Commaf(math.MaxFloat64), "179,769,313,486,231,570,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000"},
|
||||
{"minf64", Commaf(math.SmallestNonzeroFloat64), "0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005"},
|
||||
{"-123,456,789", Commaf(-123456789), "-123,456,789"},
|
||||
{"-10,100,000", Commaf(-10100000), "-10,100,000"},
|
||||
{"-10,010,000", Commaf(-10010000), "-10,010,000"},
|
||||
{"-10,001,000", Commaf(-10001000), "-10,001,000"},
|
||||
{"-10,000,000", Commaf(-10000000), "-10,000,000"},
|
||||
{"-100,000", Commaf(-100000), "-100,000"},
|
||||
{"-10,000", Commaf(-10000), "-10,000"},
|
||||
{"-1,000", Commaf(-1000), "-1,000"},
|
||||
{"-100.11", Commaf(-100.11), "-100.11"},
|
||||
{"-10", Commaf(-10), "-10"},
|
||||
}.validate(t)
|
||||
}
|
||||
|
||||
func BenchmarkCommas(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
Comma(1234567890)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkCommaf(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
Commaf(1234567890.83584)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkBigCommas(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
BigComma(big.NewInt(1234567890))
|
||||
}
|
||||
}
|
||||
|
||||
func bigComma(i int64) string {
|
||||
return BigComma(big.NewInt(i))
|
||||
}
|
||||
|
||||
func TestBigCommas(t *testing.T) {
|
||||
testList{
|
||||
{"0", bigComma(0), "0"},
|
||||
{"10", bigComma(10), "10"},
|
||||
{"100", bigComma(100), "100"},
|
||||
{"1,000", bigComma(1000), "1,000"},
|
||||
{"10,000", bigComma(10000), "10,000"},
|
||||
{"100,000", bigComma(100000), "100,000"},
|
||||
{"10,000,000", bigComma(10000000), "10,000,000"},
|
||||
{"10,100,000", bigComma(10100000), "10,100,000"},
|
||||
{"10,010,000", bigComma(10010000), "10,010,000"},
|
||||
{"10,001,000", bigComma(10001000), "10,001,000"},
|
||||
{"123,456,789", bigComma(123456789), "123,456,789"},
|
||||
{"maxint", bigComma(9.223372e+18), "9,223,372,000,000,000,000"},
|
||||
{"minint", bigComma(-9.223372e+18), "-9,223,372,000,000,000,000"},
|
||||
{"-123,456,789", bigComma(-123456789), "-123,456,789"},
|
||||
{"-10,100,000", bigComma(-10100000), "-10,100,000"},
|
||||
{"-10,010,000", bigComma(-10010000), "-10,010,000"},
|
||||
{"-10,001,000", bigComma(-10001000), "-10,001,000"},
|
||||
{"-10,000,000", bigComma(-10000000), "-10,000,000"},
|
||||
{"-100,000", bigComma(-100000), "-100,000"},
|
||||
{"-10,000", bigComma(-10000), "-10,000"},
|
||||
{"-1,000", bigComma(-1000), "-1,000"},
|
||||
{"-100", bigComma(-100), "-100"},
|
||||
{"-10", bigComma(-10), "-10"},
|
||||
}.validate(t)
|
||||
}
|
||||
|
||||
func TestVeryBigCommas(t *testing.T) {
|
||||
tests := []struct{ in, exp string }{
|
||||
{
|
||||
"84889279597249724975972597249849757294578485",
|
||||
"84,889,279,597,249,724,975,972,597,249,849,757,294,578,485",
|
||||
},
|
||||
{
|
||||
"-84889279597249724975972597249849757294578485",
|
||||
"-84,889,279,597,249,724,975,972,597,249,849,757,294,578,485",
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
n, _ := (&big.Int{}).SetString(test.in, 10)
|
||||
got := BigComma(n)
|
||||
if test.exp != got {
|
||||
t.Errorf("Expected %q, got %q", test.exp, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package humanize
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
type testList []struct {
|
||||
name, got, exp string
|
||||
}
|
||||
|
||||
func (tl testList) validate(t *testing.T) {
|
||||
for _, test := range tl {
|
||||
if test.got != test.exp {
|
||||
t.Errorf("On %v, expected '%v', but got '%v'",
|
||||
test.name, test.exp, test.got)
|
||||
}
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package humanize
|
||||
|
||||
import "strconv"
|
||||
|
||||
func stripTrailingZeros(s string) string {
|
||||
offset := len(s) - 1
|
||||
for offset > 0 {
|
||||
if s[offset] == '.' {
|
||||
offset--
|
||||
break
|
||||
}
|
||||
if s[offset] != '0' {
|
||||
break
|
||||
}
|
||||
offset--
|
||||
}
|
||||
return s[:offset+1]
|
||||
}
|
||||
|
||||
// Ftoa converts a float to a string with no trailing zeros.
|
||||
func Ftoa(num float64) string {
|
||||
return stripTrailingZeros(strconv.FormatFloat(num, 'f', 6, 64))
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package humanize
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFtoa(t *testing.T) {
|
||||
testList{
|
||||
{"200", Ftoa(200), "200"},
|
||||
{"2", Ftoa(2), "2"},
|
||||
{"2.2", Ftoa(2.2), "2.2"},
|
||||
{"2.02", Ftoa(2.02), "2.02"},
|
||||
{"200.02", Ftoa(200.02), "200.02"},
|
||||
}.validate(t)
|
||||
}
|
||||
|
||||
func BenchmarkFtoaRegexTrailing(b *testing.B) {
|
||||
trailingZerosRegex := regexp.MustCompile(`\.?0+$`)
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
trailingZerosRegex.ReplaceAllString("2.00000", "")
|
||||
trailingZerosRegex.ReplaceAllString("2.0000", "")
|
||||
trailingZerosRegex.ReplaceAllString("2.000", "")
|
||||
trailingZerosRegex.ReplaceAllString("2.00", "")
|
||||
trailingZerosRegex.ReplaceAllString("2.0", "")
|
||||
trailingZerosRegex.ReplaceAllString("2", "")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkFtoaFunc(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
stripTrailingZeros("2.00000")
|
||||
stripTrailingZeros("2.0000")
|
||||
stripTrailingZeros("2.000")
|
||||
stripTrailingZeros("2.00")
|
||||
stripTrailingZeros("2.0")
|
||||
stripTrailingZeros("2")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkFmtF(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
fmt.Sprintf("%f", 2.03584)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkStrconvF(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
strconv.FormatFloat(2.03584, 'f', 6, 64)
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
/*
|
||||
Package humanize converts boring ugly numbers to human-friendly strings and back.
|
||||
|
||||
Durations can be turned into strings such as "3 days ago", numbers
|
||||
representing sizes like 82854982 into useful strings like, "83MB" or
|
||||
"79MiB" (whichever you prefer).
|
||||
*/
|
||||
package humanize
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package humanize
|
||||
|
||||
import "strconv"
|
||||
|
||||
// Ordinal gives you the input number in a rank/ordinal format.
|
||||
//
|
||||
// Ordinal(3) -> 3rd
|
||||
func Ordinal(x int) string {
|
||||
suffix := "th"
|
||||
switch x % 10 {
|
||||
case 1:
|
||||
if x%100 != 11 {
|
||||
suffix = "st"
|
||||
}
|
||||
case 2:
|
||||
if x%100 != 12 {
|
||||
suffix = "nd"
|
||||
}
|
||||
case 3:
|
||||
if x%100 != 13 {
|
||||
suffix = "rd"
|
||||
}
|
||||
}
|
||||
return strconv.Itoa(x) + suffix
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package humanize
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestOrdinals(t *testing.T) {
|
||||
testList{
|
||||
{"0", Ordinal(0), "0th"},
|
||||
{"1", Ordinal(1), "1st"},
|
||||
{"2", Ordinal(2), "2nd"},
|
||||
{"3", Ordinal(3), "3rd"},
|
||||
{"4", Ordinal(4), "4th"},
|
||||
{"10", Ordinal(10), "10th"},
|
||||
{"11", Ordinal(11), "11th"},
|
||||
{"12", Ordinal(12), "12th"},
|
||||
{"13", Ordinal(13), "13th"},
|
||||
{"101", Ordinal(101), "101st"},
|
||||
{"102", Ordinal(102), "102nd"},
|
||||
{"103", Ordinal(103), "103rd"},
|
||||
}.validate(t)
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
package humanize
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"math"
|
||||
"regexp"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
var siPrefixTable = map[float64]string{
|
||||
-24: "y", // yocto
|
||||
-21: "z", // zepto
|
||||
-18: "a", // atto
|
||||
-15: "f", // femto
|
||||
-12: "p", // pico
|
||||
-9: "n", // nano
|
||||
-6: "µ", // micro
|
||||
-3: "m", // milli
|
||||
0: "",
|
||||
3: "k", // kilo
|
||||
6: "M", // mega
|
||||
9: "G", // giga
|
||||
12: "T", // tera
|
||||
15: "P", // peta
|
||||
18: "E", // exa
|
||||
21: "Z", // zetta
|
||||
24: "Y", // yotta
|
||||
}
|
||||
|
||||
var revSIPrefixTable = revfmap(siPrefixTable)
|
||||
|
||||
// revfmap reverses the map and precomputes the power multiplier
|
||||
func revfmap(in map[float64]string) map[string]float64 {
|
||||
rv := map[string]float64{}
|
||||
for k, v := range in {
|
||||
rv[v] = math.Pow(10, k)
|
||||
}
|
||||
return rv
|
||||
}
|
||||
|
||||
var riParseRegex *regexp.Regexp
|
||||
|
||||
func init() {
|
||||
ri := `^([0-9.]+)([`
|
||||
for _, v := range siPrefixTable {
|
||||
ri += v
|
||||
}
|
||||
ri += `]?)(.*)`
|
||||
|
||||
riParseRegex = regexp.MustCompile(ri)
|
||||
}
|
||||
|
||||
// ComputeSI finds the most appropriate SI prefix for the given number
|
||||
// and returns the prefix along with the value adjusted to be within
|
||||
// that prefix.
|
||||
//
|
||||
// See also: SI, ParseSI.
|
||||
//
|
||||
// e.g. ComputeSI(2.2345e-12) -> (2.2345, "p")
|
||||
func ComputeSI(input float64) (float64, string) {
|
||||
if input == 0 {
|
||||
return 0, ""
|
||||
}
|
||||
exponent := math.Floor(logn(input, 10))
|
||||
exponent = math.Floor(exponent/3) * 3
|
||||
|
||||
value := input / math.Pow(10, exponent)
|
||||
|
||||
// Handle special case where value is exactly 1000.0
|
||||
// Should return 1M instead of 1000k
|
||||
if value == 1000.0 {
|
||||
exponent += 3
|
||||
value = input / math.Pow(10, exponent)
|
||||
}
|
||||
|
||||
prefix := siPrefixTable[exponent]
|
||||
return value, prefix
|
||||
}
|
||||
|
||||
// SI returns a string with default formatting.
|
||||
//
|
||||
// SI uses Ftoa to format float value, removing trailing zeros.
|
||||
//
|
||||
// See also: ComputeSI, ParseSI.
|
||||
//
|
||||
// e.g. SI(1000000, B) -> 1MB
|
||||
// e.g. SI(2.2345e-12, "F") -> 2.2345pF
|
||||
func SI(input float64, unit string) string {
|
||||
value, prefix := ComputeSI(input)
|
||||
return Ftoa(value) + prefix + unit
|
||||
}
|
||||
|
||||
var errInvalid = errors.New("invalid input")
|
||||
|
||||
// ParseSI parses an SI string back into the number and unit.
|
||||
//
|
||||
// See also: SI, ComputeSI.
|
||||
//
|
||||
// e.g. ParseSI(2.2345pF) -> (2.2345e-12, "F", nil)
|
||||
func ParseSI(input string) (float64, string, error) {
|
||||
found := riParseRegex.FindStringSubmatch(input)
|
||||
if len(found) != 4 {
|
||||
return 0, "", errInvalid
|
||||
}
|
||||
mag := revSIPrefixTable[found[2]]
|
||||
unit := found[3]
|
||||
|
||||
base, err := strconv.ParseFloat(found[1], 64)
|
||||
return base * mag, unit, err
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
package humanize
|
||||
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestSI(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
num float64
|
||||
formatted string
|
||||
}{
|
||||
{"e-24", 1e-24, "1yF"},
|
||||
{"e-21", 1e-21, "1zF"},
|
||||
{"e-18", 1e-18, "1aF"},
|
||||
{"e-15", 1e-15, "1fF"},
|
||||
{"e-12", 1e-12, "1pF"},
|
||||
{"e-12", 2.2345e-12, "2.2345pF"},
|
||||
{"e-12", 2.23e-12, "2.23pF"},
|
||||
{"e-11", 2.23e-11, "22.3pF"},
|
||||
{"e-10", 2.2e-10, "220pF"},
|
||||
{"e-9", 2.2e-9, "2.2nF"},
|
||||
{"e-8", 2.2e-8, "22nF"},
|
||||
{"e-7", 2.2e-7, "220nF"},
|
||||
{"e-6", 2.2e-6, "2.2µF"},
|
||||
{"e-6", 1e-6, "1µF"},
|
||||
{"e-5", 2.2e-5, "22µF"},
|
||||
{"e-4", 2.2e-4, "220µF"},
|
||||
{"e-3", 2.2e-3, "2.2mF"},
|
||||
{"e-2", 2.2e-2, "22mF"},
|
||||
{"e-1", 2.2e-1, "220mF"},
|
||||
{"e+0", 2.2e-0, "2.2F"},
|
||||
{"e+0", 2.2, "2.2F"},
|
||||
{"e+1", 2.2e+1, "22F"},
|
||||
{"0", 0, "0F"},
|
||||
{"e+1", 22, "22F"},
|
||||
{"e+2", 2.2e+2, "220F"},
|
||||
{"e+2", 220, "220F"},
|
||||
{"e+3", 2.2e+3, "2.2kF"},
|
||||
{"e+3", 2200, "2.2kF"},
|
||||
{"e+4", 2.2e+4, "22kF"},
|
||||
{"e+4", 22000, "22kF"},
|
||||
{"e+5", 2.2e+5, "220kF"},
|
||||
{"e+6", 2.2e+6, "2.2MF"},
|
||||
{"e+6", 1e+6, "1MF"},
|
||||
{"e+7", 2.2e+7, "22MF"},
|
||||
{"e+8", 2.2e+8, "220MF"},
|
||||
{"e+9", 2.2e+9, "2.2GF"},
|
||||
{"e+10", 2.2e+10, "22GF"},
|
||||
{"e+11", 2.2e+11, "220GF"},
|
||||
{"e+12", 2.2e+12, "2.2TF"},
|
||||
{"e+15", 2.2e+15, "2.2PF"},
|
||||
{"e+18", 2.2e+18, "2.2EF"},
|
||||
{"e+21", 2.2e+21, "2.2ZF"},
|
||||
{"e+24", 2.2e+24, "2.2YF"},
|
||||
|
||||
// special case
|
||||
{"1F", 1000 * 1000, "1MF"},
|
||||
{"1F", 1e6, "1MF"},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
got := SI(test.num, "F")
|
||||
if got != test.formatted {
|
||||
t.Errorf("On %v (%v), got %v, wanted %v",
|
||||
test.name, test.num, got, test.formatted)
|
||||
}
|
||||
|
||||
gotf, gotu, err := ParseSI(test.formatted)
|
||||
if err != nil {
|
||||
t.Errorf("Error parsing %v (%v): %v", test.name, test.formatted, err)
|
||||
continue
|
||||
}
|
||||
|
||||
if math.Abs(1-(gotf/test.num)) > 0.01 {
|
||||
t.Errorf("On %v (%v), got %v, wanted %v (±%v)",
|
||||
test.name, test.formatted, gotf, test.num,
|
||||
math.Abs(1-(gotf/test.num)))
|
||||
}
|
||||
if gotu != "F" {
|
||||
t.Errorf("On %v (%v), expected unit F, got %v",
|
||||
test.name, test.formatted, gotu)
|
||||
}
|
||||
}
|
||||
|
||||
// Parse error
|
||||
gotf, gotu, err := ParseSI("x1.21JW") // 1.21 jigga whats
|
||||
if err == nil {
|
||||
t.Errorf("Expected error on x1.21JW, got %v %v", gotf, gotu)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkParseSI(b *testing.B) {
|
||||
for i := 0; i < b.N; i++ {
|
||||
ParseSI("2.2346ZB")
|
||||
}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
package humanize
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"sort"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Seconds-based time units
|
||||
const (
|
||||
Minute = 60
|
||||
Hour = 60 * Minute
|
||||
Day = 24 * Hour
|
||||
Week = 7 * Day
|
||||
Month = 30 * Day
|
||||
Year = 12 * Month
|
||||
LongTime = 37 * Year
|
||||
)
|
||||
|
||||
// Time formats a time into a relative string.
|
||||
//
|
||||
// Time(someT) -> "3 weeks ago"
|
||||
func Time(then time.Time) string {
|
||||
return RelTime(then, time.Now(), "ago", "from now")
|
||||
}
|
||||
|
||||
var magnitudes = []struct {
|
||||
d int64
|
||||
format string
|
||||
divby int64
|
||||
}{
|
||||
{1, "now", 1},
|
||||
{2, "1 second %s", 1},
|
||||
{Minute, "%d seconds %s", 1},
|
||||
{2 * Minute, "1 minute %s", 1},
|
||||
{Hour, "%d minutes %s", Minute},
|
||||
{2 * Hour, "1 hour %s", 1},
|
||||
{Day, "%d hours %s", Hour},
|
||||
{2 * Day, "1 day %s", 1},
|
||||
{Week, "%d days %s", Day},
|
||||
{2 * Week, "1 week %s", 1},
|
||||
{Month, "%d weeks %s", Week},
|
||||
{2 * Month, "1 month %s", 1},
|
||||
{Year, "%d months %s", Month},
|
||||
{18 * Month, "1 year %s", 1},
|
||||
{2 * Year, "2 years %s", 1},
|
||||
{LongTime, "%d years %s", Year},
|
||||
{math.MaxInt64, "a long while %s", 1},
|
||||
}
|
||||
|
||||
// RelTime formats a time into a relative string.
|
||||
//
|
||||
// It takes two times and two labels. In addition to the generic time
|
||||
// delta string (e.g. 5 minutes), the labels are used applied so that
|
||||
// the label corresponding to the smaller time is applied.
|
||||
//
|
||||
// RelTime(timeInPast, timeInFuture, "earlier", "later") -> "3 weeks earlier"
|
||||
func RelTime(a, b time.Time, albl, blbl string) string {
|
||||
lbl := albl
|
||||
diff := b.Unix() - a.Unix()
|
||||
|
||||
after := a.After(b)
|
||||
if after {
|
||||
lbl = blbl
|
||||
diff = a.Unix() - b.Unix()
|
||||
}
|
||||
|
||||
n := sort.Search(len(magnitudes), func(i int) bool {
|
||||
return magnitudes[i].d > diff
|
||||
})
|
||||
|
||||
mag := magnitudes[n]
|
||||
args := []interface{}{}
|
||||
escaped := false
|
||||
for _, ch := range mag.format {
|
||||
if escaped {
|
||||
switch ch {
|
||||
case '%':
|
||||
case 's':
|
||||
args = append(args, lbl)
|
||||
case 'd':
|
||||
args = append(args, diff/mag.divby)
|
||||
}
|
||||
escaped = false
|
||||
} else {
|
||||
escaped = ch == '%'
|
||||
}
|
||||
}
|
||||
return fmt.Sprintf(mag.format, args...)
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package humanize
|
||||
|
||||
import (
|
||||
"math"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestPast(t *testing.T) {
|
||||
now := time.Now().Unix()
|
||||
testList{
|
||||
{"now", Time(time.Unix(now, 0)), "now"},
|
||||
{"1 second ago", Time(time.Unix(now-1, 0)), "1 second ago"},
|
||||
{"12 seconds ago", Time(time.Unix(now-12, 0)), "12 seconds ago"},
|
||||
{"30 seconds ago", Time(time.Unix(now-30, 0)), "30 seconds ago"},
|
||||
{"45 seconds ago", Time(time.Unix(now-45, 0)), "45 seconds ago"},
|
||||
{"1 minute ago", Time(time.Unix(now-63, 0)), "1 minute ago"},
|
||||
{"15 minutes ago", Time(time.Unix(now-15*Minute, 0)), "15 minutes ago"},
|
||||
{"1 hour ago", Time(time.Unix(now-63*Minute, 0)), "1 hour ago"},
|
||||
{"2 hours ago", Time(time.Unix(now-2*Hour, 0)), "2 hours ago"},
|
||||
{"21 hours ago", Time(time.Unix(now-21*Hour, 0)), "21 hours ago"},
|
||||
{"1 day ago", Time(time.Unix(now-26*Hour, 0)), "1 day ago"},
|
||||
{"2 days ago", Time(time.Unix(now-49*Hour, 0)), "2 days ago"},
|
||||
{"3 days ago", Time(time.Unix(now-3*Day, 0)), "3 days ago"},
|
||||
{"1 week ago (1)", Time(time.Unix(now-7*Day, 0)), "1 week ago"},
|
||||
{"1 week ago (2)", Time(time.Unix(now-12*Day, 0)), "1 week ago"},
|
||||
{"2 weeks ago", Time(time.Unix(now-15*Day, 0)), "2 weeks ago"},
|
||||
{"1 month ago", Time(time.Unix(now-39*Day, 0)), "1 month ago"},
|
||||
{"3 months ago", Time(time.Unix(now-99*Day, 0)), "3 months ago"},
|
||||
{"1 year ago (1)", Time(time.Unix(now-365*Day, 0)), "1 year ago"},
|
||||
{"1 year ago (1)", Time(time.Unix(now-400*Day, 0)), "1 year ago"},
|
||||
{"2 years ago (1)", Time(time.Unix(now-548*Day, 0)), "2 years ago"},
|
||||
{"2 years ago (2)", Time(time.Unix(now-725*Day, 0)), "2 years ago"},
|
||||
{"2 years ago (3)", Time(time.Unix(now-800*Day, 0)), "2 years ago"},
|
||||
{"3 years ago", Time(time.Unix(now-3*Year, 0)), "3 years ago"},
|
||||
{"long ago", Time(time.Unix(now-LongTime, 0)), "a long while ago"},
|
||||
}.validate(t)
|
||||
}
|
||||
|
||||
func TestFuture(t *testing.T) {
|
||||
now := time.Now().Unix()
|
||||
testList{
|
||||
{"now", Time(time.Unix(now, 0)), "now"},
|
||||
{"1 second from now", Time(time.Unix(now+1, 0)), "1 second from now"},
|
||||
{"12 seconds from now", Time(time.Unix(now+12, 0)), "12 seconds from now"},
|
||||
{"30 seconds from now", Time(time.Unix(now+30, 0)), "30 seconds from now"},
|
||||
{"45 seconds from now", Time(time.Unix(now+45, 0)), "45 seconds from now"},
|
||||
{"15 minutes from now", Time(time.Unix(now+15*Minute, 0)), "15 minutes from now"},
|
||||
{"2 hours from now", Time(time.Unix(now+2*Hour, 0)), "2 hours from now"},
|
||||
{"21 hours from now", Time(time.Unix(now+21*Hour, 0)), "21 hours from now"},
|
||||
{"1 day from now", Time(time.Unix(now+26*Hour, 0)), "1 day from now"},
|
||||
{"2 days from now", Time(time.Unix(now+49*Hour, 0)), "2 days from now"},
|
||||
{"3 days from now", Time(time.Unix(now+3*Day, 0)), "3 days from now"},
|
||||
{"1 week from now (1)", Time(time.Unix(now+7*Day, 0)), "1 week from now"},
|
||||
{"1 week from now (2)", Time(time.Unix(now+12*Day, 0)), "1 week from now"},
|
||||
{"2 weeks from now", Time(time.Unix(now+15*Day, 0)), "2 weeks from now"},
|
||||
{"1 month from now", Time(time.Unix(now+30*Day, 0)), "1 month from now"},
|
||||
{"1 year from now", Time(time.Unix(now+365*Day, 0)), "1 year from now"},
|
||||
{"2 years from now", Time(time.Unix(now+2*Year, 0)), "2 years from now"},
|
||||
{"a while from now", Time(time.Unix(now+LongTime, 0)), "a long while from now"},
|
||||
}.validate(t)
|
||||
}
|
||||
|
||||
func TestRange(t *testing.T) {
|
||||
start := time.Time{}
|
||||
end := time.Unix(math.MaxInt64, math.MaxInt64)
|
||||
x := RelTime(start, end, "ago", "from now")
|
||||
if x != "a long while from now" {
|
||||
t.Errorf("Expected a long while from now, got %q", x)
|
||||
}
|
||||
}
|
||||
Generated
Vendored
Generated
Vendored
Generated
Vendored
+15
-8
@@ -27,9 +27,11 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/dustin/go-humanize"
|
||||
)
|
||||
|
||||
// WrappedError is the iodine error which contains a pointer to the original error
|
||||
// Error is the iodine error which contains a pointer to the original error
|
||||
// and stack traces.
|
||||
type Error struct {
|
||||
EmbeddedError error `json:"-"`
|
||||
@@ -43,6 +45,7 @@ type Error struct {
|
||||
type StackEntry struct {
|
||||
Host string
|
||||
File string
|
||||
Func string
|
||||
Line int
|
||||
Data map[string]string
|
||||
}
|
||||
@@ -90,7 +93,7 @@ func GetGlobalStateKey(k string) string {
|
||||
return result
|
||||
}
|
||||
|
||||
// Error - instantiate an error, turning it into an iodine error.
|
||||
// New - instantiate an error, turning it into an iodine error.
|
||||
// Adds an initial stack trace.
|
||||
func New(err error, data map[string]string) error {
|
||||
if err != nil {
|
||||
@@ -125,7 +128,9 @@ func New(err error, data map[string]string) error {
|
||||
// createStackEntry - create stack entries
|
||||
func createStackEntry() StackEntry {
|
||||
host, _ := os.Hostname()
|
||||
_, file, line, _ := runtime.Caller(2)
|
||||
pc, file, line, _ := runtime.Caller(2)
|
||||
function := runtime.FuncForPC(pc).Name()
|
||||
_, function = path.Split(function)
|
||||
file = strings.TrimPrefix(file, gopath) // trim gopath from file
|
||||
|
||||
data := GetGlobalState()
|
||||
@@ -136,6 +141,7 @@ func createStackEntry() StackEntry {
|
||||
entry := StackEntry{
|
||||
Host: host,
|
||||
File: file,
|
||||
Func: function,
|
||||
Line: line,
|
||||
Data: data,
|
||||
}
|
||||
@@ -155,10 +161,10 @@ func getSystemData() map[string]string {
|
||||
"sys.arch": runtime.GOARCH,
|
||||
"sys.go": runtime.Version(),
|
||||
"sys.cpus": strconv.Itoa(runtime.NumCPU()),
|
||||
"sys.mem.used": strconv.FormatUint(memstats.Alloc, 10),
|
||||
"sys.mem.allocated": strconv.FormatUint(memstats.TotalAlloc, 10),
|
||||
"sys.mem.heap.used": strconv.FormatUint(memstats.HeapAlloc, 10),
|
||||
"sys.mem.heap.allocated": strconv.FormatUint(memstats.HeapSys, 10),
|
||||
"sys.mem.used": humanize.Bytes(memstats.Alloc),
|
||||
"sys.mem.allocated": humanize.Bytes(memstats.TotalAlloc),
|
||||
"sys.mem.heap.used": humanize.Bytes(memstats.HeapAlloc),
|
||||
"sys.mem.heap.allocated": humanize.Bytes(memstats.HeapSys),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -182,7 +188,8 @@ func (err Error) EmitHumanReadable() string {
|
||||
var errorBuffer bytes.Buffer
|
||||
fmt.Fprintln(&errorBuffer, err.ErrorMessage)
|
||||
for i, entry := range err.Stack {
|
||||
fmt.Fprintln(&errorBuffer, "-", i, entry.Host+":"+entry.File+":"+strconv.Itoa(entry.Line), entry.Data)
|
||||
prettyData, _ := json.Marshal(entry.Data)
|
||||
fmt.Fprintln(&errorBuffer, "-", i, entry.Host+":"+entry.File+":"+strconv.Itoa(entry.Line)+" "+entry.Func+"():", string(prettyData))
|
||||
}
|
||||
return string(errorBuffer.Bytes())
|
||||
}
|
||||
Generated
Vendored
+7
-1
@@ -17,9 +17,11 @@
|
||||
package iodine
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"encoding/json"
|
||||
)
|
||||
|
||||
func TestIodine(t *testing.T) {
|
||||
@@ -27,9 +29,13 @@ func TestIodine(t *testing.T) {
|
||||
iodineError = New(iodineError, nil)
|
||||
iodineError = New(iodineError, nil)
|
||||
iodineError = New(iodineError, nil)
|
||||
|
||||
switch typedError := iodineError.(type) {
|
||||
case Error:
|
||||
{
|
||||
// Visually watch out for formating errors
|
||||
fmt.Println(typedError.EmitHumanReadable())
|
||||
|
||||
if len(typedError.Stack) != 4 {
|
||||
t.Fail()
|
||||
}
|
||||
+1
-1
@@ -21,7 +21,7 @@ import (
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/minio-io/iodine"
|
||||
"github.com/minio-io/minio/pkg/iodine"
|
||||
)
|
||||
|
||||
// Alias for S3 hosts, saved in mc json configuration file
|
||||
|
||||
+1
-1
@@ -25,7 +25,7 @@ import (
|
||||
"net/url"
|
||||
|
||||
"github.com/cheggaaa/pb"
|
||||
"github.com/minio-io/iodine"
|
||||
"github.com/minio-io/minio/pkg/iodine"
|
||||
"github.com/minio-io/mc/pkg/client"
|
||||
"github.com/minio-io/mc/pkg/client/s3"
|
||||
)
|
||||
|
||||
+1
-1
@@ -16,7 +16,7 @@ import (
|
||||
"path/filepath"
|
||||
|
||||
"github.com/minio-io/cli"
|
||||
"github.com/minio-io/iodine"
|
||||
"github.com/minio-io/minio/pkg/iodine"
|
||||
"github.com/minio-io/minio/pkg/utils/log"
|
||||
)
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ import (
|
||||
|
||||
"github.com/cheggaaa/pb"
|
||||
"github.com/minio-io/cli"
|
||||
"github.com/minio-io/iodine"
|
||||
"github.com/minio-io/minio/pkg/iodine"
|
||||
"github.com/minio-io/minio/pkg/utils/log"
|
||||
)
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ import (
|
||||
|
||||
"github.com/cheggaaa/pb"
|
||||
"github.com/minio-io/cli"
|
||||
"github.com/minio-io/iodine"
|
||||
"github.com/minio-io/minio/pkg/iodine"
|
||||
"github.com/minio-io/mc/pkg/client"
|
||||
"github.com/minio-io/minio/pkg/utils/log"
|
||||
)
|
||||
|
||||
@@ -18,7 +18,7 @@ package main
|
||||
|
||||
import (
|
||||
"github.com/minio-io/cli"
|
||||
"github.com/minio-io/iodine"
|
||||
"github.com/minio-io/minio/pkg/iodine"
|
||||
"github.com/minio-io/mc/pkg/client/s3"
|
||||
"github.com/minio-io/minio/pkg/utils/log"
|
||||
)
|
||||
|
||||
@@ -25,7 +25,7 @@ import (
|
||||
|
||||
"github.com/cheggaaa/pb"
|
||||
"github.com/minio-io/cli"
|
||||
"github.com/minio-io/iodine"
|
||||
"github.com/minio-io/minio/pkg/iodine"
|
||||
"github.com/minio-io/minio/pkg/utils/log"
|
||||
)
|
||||
|
||||
|
||||
@@ -46,7 +46,7 @@ import (
|
||||
|
||||
"net/http"
|
||||
|
||||
"github.com/minio-io/iodine"
|
||||
"github.com/minio-io/minio/pkg/iodine"
|
||||
"github.com/minio-io/mc/pkg/client"
|
||||
)
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"github.com/minio-io/iodine"
|
||||
"github.com/minio-io/minio/pkg/iodine"
|
||||
"github.com/minio-io/mc/pkg/client"
|
||||
)
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ import (
|
||||
"net/http"
|
||||
|
||||
"github.com/clbanning/mxj"
|
||||
"github.com/minio-io/iodine"
|
||||
"github.com/minio-io/minio/pkg/iodine"
|
||||
)
|
||||
|
||||
/* **** SAMPLE ERROR RESPONSE ****
|
||||
|
||||
@@ -52,7 +52,7 @@ import (
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
|
||||
"github.com/minio-io/iodine"
|
||||
"github.com/minio-io/minio/pkg/iodine"
|
||||
)
|
||||
|
||||
/// Object API operations
|
||||
|
||||
@@ -21,7 +21,7 @@ import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/minio-io/iodine"
|
||||
"github.com/minio-io/minio/pkg/iodine"
|
||||
)
|
||||
|
||||
// Only generic HTTP S3 fields are validated using this mechanism. S3
|
||||
|
||||
@@ -22,7 +22,7 @@ import (
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
|
||||
"github.com/minio-io/iodine"
|
||||
"github.com/minio-io/minio/pkg/iodine"
|
||||
)
|
||||
|
||||
// Trace - tracing structure
|
||||
|
||||
+1
-1
@@ -22,7 +22,7 @@ import (
|
||||
"net/url"
|
||||
|
||||
"github.com/minio-io/cli"
|
||||
"github.com/minio-io/iodine"
|
||||
"github.com/minio-io/minio/pkg/iodine"
|
||||
)
|
||||
|
||||
// URLType defines supported storage protocols
|
||||
|
||||
Reference in New Issue
Block a user