Update dependencies (#34)

This commit is contained in:
Elizabeth 2018-09-24 15:39:23 -05:00 committed by GitHub
parent cee824f7ad
commit 5fc7170c1e
115 changed files with 1694 additions and 6055 deletions

113
Gopkg.lock generated
View File

@ -3,14 +3,12 @@
[[projects]] [[projects]]
branch = "master" branch = "master"
digest = "1:c5e006ec5f6460f05964be0a9d34a42e3ad25bbc2564a289d7b4f6f2290c76e5"
name = "github.com/aristanetworks/goarista" name = "github.com/aristanetworks/goarista"
packages = ["monotime"] packages = ["monotime"]
revision = "ff33da284e760fcdb03c33d37a719e5ed30ba844" revision = "ff33da284e760fcdb03c33d37a719e5ed30ba844"
[[projects]] [[projects]]
branch = "master" branch = "master"
digest = "1:735be9b1e9daa0f731c20fbd2f0d4d0d3efbebe674f415f78b72c19defc07fa1"
name = "github.com/btcsuite/btcd" name = "github.com/btcsuite/btcd"
packages = ["btcec"] packages = ["btcec"]
revision = "cff30e1d23fc9e800b2b5b4b41ef1817dda07e9f" revision = "cff30e1d23fc9e800b2b5b4b41ef1817dda07e9f"
@ -18,11 +16,10 @@
[[projects]] [[projects]]
name = "github.com/deckarep/golang-set" name = "github.com/deckarep/golang-set"
packages = ["."] packages = ["."]
revision = "1d4478f51bed434f1dadf96dcd9b43aabac66795" revision = "cbaa98ba5575e67703b32b4b19f73c91f3c4159e"
version = "v1.7" version = "v1.7.1"
[[projects]] [[projects]]
digest = "1:28913042a7cf2d6c6957eb9865b06790966772ce47e1a844a3cd5a14d18785b7"
name = "github.com/ethereum/go-ethereum" name = "github.com/ethereum/go-ethereum"
packages = [ packages = [
".", ".",
@ -53,24 +50,20 @@
"params", "params",
"rlp", "rlp",
"rpc", "rpc",
"trie", "trie"
] ]
revision = "89451f7c382ad2185987ee369f16416f89c28a7d" revision = "89451f7c382ad2185987ee369f16416f89c28a7d"
version = "v1.8.15" version = "v1.8.15"
[[projects]] [[projects]]
digest = "1:eb53021a8aa3f599d29c7102e65026242bdedce998a54837dc67f14b6a97c5fd"
name = "github.com/fsnotify/fsnotify" name = "github.com/fsnotify/fsnotify"
packages = ["."] packages = ["."]
pruneopts = ""
revision = "c2828203cd70a50dcccfb2761f8b1f8ceef9a8e9" revision = "c2828203cd70a50dcccfb2761f8b1f8ceef9a8e9"
version = "v1.4.7" version = "v1.4.7"
[[projects]] [[projects]]
digest = "1:9ca737b471693542351e112c9e86be9bf7385e42256893a09ecb2a98e2036f74"
name = "github.com/go-stack/stack" name = "github.com/go-stack/stack"
packages = ["."] packages = ["."]
<<<<<<< HEAD
revision = "2fee6af1a9795aafbe0253a0cfbdf668e1fb8a9a" revision = "2fee6af1a9795aafbe0253a0cfbdf668e1fb8a9a"
version = "v1.8.0" version = "v1.8.0"
@ -82,7 +75,6 @@
[[projects]] [[projects]]
branch = "master" branch = "master"
digest = "1:09307dfb1aa3f49a2bf869dcfa4c6c06ecd3c207221bd1c1a1141f0e51f209eb"
name = "github.com/golang/snappy" name = "github.com/golang/snappy"
packages = ["."] packages = ["."]
revision = "2e65f85255dbc3072edf28d6b5b8efc472979f5a" revision = "2e65f85255dbc3072edf28d6b5b8efc472979f5a"
@ -105,7 +97,7 @@
"hcl/token", "hcl/token",
"json/parser", "json/parser",
"json/scanner", "json/scanner",
"json/token", "json/token"
] ]
revision = "8cb6e5b959231cc1119e43259c4a608f9c51a241" revision = "8cb6e5b959231cc1119e43259c4a608f9c51a241"
version = "v1.0.0" version = "v1.0.0"
@ -124,7 +116,6 @@
[[projects]] [[projects]]
branch = "master" branch = "master"
digest = "1:b5ef0f034b2eda02c19c2cfcccc9754b372c4e04fa593972fbd8e3d9813d8d98"
name = "github.com/huin/goupnp" name = "github.com/huin/goupnp"
packages = [ packages = [
".", ".",
@ -133,33 +124,28 @@
"httpu", "httpu",
"scpd", "scpd",
"soap", "soap",
"ssdp", "ssdp"
] ]
revision = "1395d1447324cbea88d249fbfcfd70ea878fdfca" revision = "1395d1447324cbea88d249fbfcfd70ea878fdfca"
[[projects]] [[projects]]
digest = "1:870d441fe217b8e689d7949fef6e43efbc787e50f200cb1e70dbca9204a1d6be"
name = "github.com/inconshreveable/mousetrap" name = "github.com/inconshreveable/mousetrap"
packages = ["."] packages = ["."]
pruneopts = ""
revision = "76626ae9c91c4f2a10f34cad8ce83ea42c93bb75" revision = "76626ae9c91c4f2a10f34cad8ce83ea42c93bb75"
version = "v1.0" version = "v1.0"
[[projects]] [[projects]]
digest = "1:76f836364ae83ed811c415aa92e1209ce49de9f62aad85b85fca749a8b96a110"
name = "github.com/jackpal/go-nat-pmp" name = "github.com/jackpal/go-nat-pmp"
packages = ["."] packages = ["."]
pruneopts = ""
revision = "c9cfead9f2a36ddf3daa40ba269aa7f4bbba6b62" revision = "c9cfead9f2a36ddf3daa40ba269aa7f4bbba6b62"
version = "v1.0.1" version = "v1.0.1"
[[projects]] [[projects]]
branch = "master" branch = "master"
digest = "1:fff68ae49ca708829c24a986fb0a044ee2b5aa44b65a0b57b1840fbb0a81f9a6"
name = "github.com/jmoiron/sqlx" name = "github.com/jmoiron/sqlx"
packages = [ packages = [
".", ".",
"reflectx", "reflectx"
] ]
revision = "0dae4fefe7c0e190f7b5a78dac28a1c82cc8d849" revision = "0dae4fefe7c0e190f7b5a78dac28a1c82cc8d849"
@ -167,13 +153,12 @@
name = "github.com/lib/pq" name = "github.com/lib/pq"
packages = [ packages = [
".", ".",
"oid", "oid"
] ]
revision = "4ded0e9383f75c197b3a2aaa6d590ac52df6fd79" revision = "4ded0e9383f75c197b3a2aaa6d590ac52df6fd79"
version = "v1.0.0" version = "v1.0.0"
[[projects]] [[projects]]
digest = "1:739b2038a38cebb50e922d18f4b042c042256320fea2db094814aeef8891e0c1"
name = "github.com/magiconair/properties" name = "github.com/magiconair/properties"
packages = ["."] packages = ["."]
revision = "c2353362d570a7bfa228149c62842019201cfb71" revision = "c2353362d570a7bfa228149c62842019201cfb71"
@ -192,7 +177,6 @@
version = "v1.0.0" version = "v1.0.0"
[[projects]] [[projects]]
digest = "1:32b27072cd55bd2fb7244de0425943d125da6a552ae2b6517cdd965a662baf18"
name = "github.com/onsi/ginkgo" name = "github.com/onsi/ginkgo"
packages = [ packages = [
".", ".",
@ -212,13 +196,12 @@
"reporters/stenographer", "reporters/stenographer",
"reporters/stenographer/support/go-colorable", "reporters/stenographer/support/go-colorable",
"reporters/stenographer/support/go-isatty", "reporters/stenographer/support/go-isatty",
"types", "types"
] ]
revision = "3774a09d95489ccaa16032e0770d08ea77ba6184" revision = "3774a09d95489ccaa16032e0770d08ea77ba6184"
version = "v1.6.0" version = "v1.6.0"
[[projects]] [[projects]]
digest = "1:a4e59d0b2821c983b58c317f141cd77df20570979632da8a7a352e5d12698de7"
name = "github.com/onsi/gomega" name = "github.com/onsi/gomega"
packages = [ packages = [
".", ".",
@ -233,97 +216,57 @@
"matchers/support/goraph/edge", "matchers/support/goraph/edge",
"matchers/support/goraph/node", "matchers/support/goraph/node",
"matchers/support/goraph/util", "matchers/support/goraph/util",
"types", "types"
] ]
revision = "7615b9433f86a8bdf29709bf288bc4fd0636a369" revision = "7615b9433f86a8bdf29709bf288bc4fd0636a369"
version = "v1.4.2" version = "v1.4.2"
[[projects]] [[projects]]
digest = "1:63e142fc50307bcb3c57494913cfc9c12f6061160bdf97a678f78c71615f939b"
name = "github.com/pborman/uuid" name = "github.com/pborman/uuid"
packages = ["."] packages = ["."]
revision = "adf5a7427709b9deb95d29d3fa8a2bf9cfd388f1" revision = "adf5a7427709b9deb95d29d3fa8a2bf9cfd388f1"
version = "v1.2" version = "v1.2"
[[projects]] [[projects]]
digest = "1:d60cfeee185019d4fcd35e8c89c83aff576e4723b6100300bf67b05be961388f"
name = "github.com/pelletier/go-toml" name = "github.com/pelletier/go-toml"
packages = ["."] packages = ["."]
revision = "c01d1270ff3e442a8a57cddc1c92dc1138598194" revision = "c01d1270ff3e442a8a57cddc1c92dc1138598194"
version = "v1.2.0" version = "v1.2.0"
[[projects]] [[projects]]
digest = "1:210286d0cb60ffe28f1ca00b664029e8943009f95d06d8f8c336301b28e1aee5"
name = "github.com/philhofer/fwd" name = "github.com/philhofer/fwd"
packages = ["."] packages = ["."]
pruneopts = ""
revision = "bb6d471dc95d4fe11e432687f8b70ff496cf3136" revision = "bb6d471dc95d4fe11e432687f8b70ff496cf3136"
version = "v1.0.0" version = "v1.0.0"
[[projects]] [[projects]]
digest = "1:7365acd48986e205ccb8652cc746f09c8b7876030d53710ea6ef7d0bd0dcd7ca"
name = "github.com/pkg/errors"
packages = ["."]
pruneopts = ""
revision = "645ef00459ed84a119197bfb8d8205042c6df63d"
version = "v0.8.0"
[[projects]]
digest = "1:d0098a379c52ac51e219a03a8b9a8026ceaef29a7c0285cf97dbc02568f9bcc7"
name = "github.com/pressly/sup"
packages = [
".",
"cmd/sup",
]
pruneopts = ""
revision = "861527f3419541c88b9c2c1cbdc6b01f80bf2cb4"
version = "v0.5.3"
[[projects]]
digest = "1:c75c214cb979e4cd45adaaf0e0a1c6bc7554bca52fb6b6aa5bac2919f75a570a"
name = "github.com/rjeczalik/notify" name = "github.com/rjeczalik/notify"
packages = ["."] packages = ["."]
<<<<<<< HEAD
revision = "0f065fa99b48b842c3fd3e2c8b194c6f2b69f6b8" revision = "0f065fa99b48b842c3fd3e2c8b194c6f2b69f6b8"
version = "v0.9.1" version = "v0.9.1"
=======
pruneopts = ""
revision = "52ae50d8490436622a8941bd70c3dbe0acdd4bbf"
version = "v0.9.0"
>>>>>>> use Sup deployment tool to deploy to staging
[[projects]] [[projects]]
digest = "1:bfc8db90e2676a2fc0d742a536f376044a9b74f2745b2c60d339eb06c6c6988a"
name = "github.com/rs/cors" name = "github.com/rs/cors"
packages = ["."] packages = ["."]
revision = "3fb1b69b103a84de38a19c3c6ec073dd6caa4d3f" revision = "3fb1b69b103a84de38a19c3c6ec073dd6caa4d3f"
version = "v1.5.0" version = "v1.5.0"
[[projects]] [[projects]]
digest = "1:dae0d7dd55563fd389e7263a32d2030022ef29cceff941336e53f6520e0308c0"
name = "github.com/spf13/afero" name = "github.com/spf13/afero"
packages = [ packages = [
".", ".",
"mem", "mem"
] ]
<<<<<<< HEAD
revision = "d40851caa0d747393da1ffb28f7f9d8b4eeffebd" revision = "d40851caa0d747393da1ffb28f7f9d8b4eeffebd"
version = "v1.1.2" version = "v1.1.2"
=======
pruneopts = ""
revision = "bb8f1927f2a9d3ab41c9340aa034f6b803f4359c"
version = "v1.0.2"
>>>>>>> use Sup deployment tool to deploy to staging
[[projects]] [[projects]]
digest = "1:6ff9b74bfea2625f805edec59395dc37e4a06458dd3c14e3372337e3d35a2ed6"
name = "github.com/spf13/cast" name = "github.com/spf13/cast"
packages = ["."] packages = ["."]
revision = "8965335b8c7107321228e3e3702cab9832751bac" revision = "8965335b8c7107321228e3e3702cab9832751bac"
version = "v1.2.0" version = "v1.2.0"
[[projects]] [[projects]]
digest = "1:2208a80fc3259291e43b30f42f844d18f4218036dff510f42c653ec9890d460a"
name = "github.com/spf13/cobra" name = "github.com/spf13/cobra"
packages = ["."] packages = ["."]
revision = "ef82de70bb3f60c65fb8eebacbb2d122ef517385" revision = "ef82de70bb3f60c65fb8eebacbb2d122ef517385"
@ -336,14 +279,12 @@
version = "v1.0.0" version = "v1.0.0"
[[projects]] [[projects]]
digest = "1:261bc565833ef4f02121450d74eb88d5ae4bd74bfe5d0e862cddb8550ec35000"
name = "github.com/spf13/pflag" name = "github.com/spf13/pflag"
packages = ["."] packages = ["."]
revision = "9a97c102cda95a86cec2345a6f09f55a939babf5" revision = "9a97c102cda95a86cec2345a6f09f55a939babf5"
version = "v1.0.2" version = "v1.0.2"
[[projects]] [[projects]]
digest = "1:59354ad53dfe6ed1b941844cb029cd37c0377598eec3a0d49c03aee2375ef9c4"
name = "github.com/spf13/viper" name = "github.com/spf13/viper"
packages = ["."] packages = ["."]
revision = "8fb642006536c8d3760c99d4fa2389f5e2205631" revision = "8fb642006536c8d3760c99d4fa2389f5e2205631"
@ -351,7 +292,6 @@
[[projects]] [[projects]]
branch = "master" branch = "master"
digest = "1:f87eb23fc0c2b143947616f754533344626637d3ae1b03ba077136ccb17de3f2"
name = "github.com/syndtr/goleveldb" name = "github.com/syndtr/goleveldb"
packages = [ packages = [
"leveldb", "leveldb",
@ -365,27 +305,20 @@
"leveldb/opt", "leveldb/opt",
"leveldb/storage", "leveldb/storage",
"leveldb/table", "leveldb/table",
"leveldb/util", "leveldb/util"
] ]
revision = "ae2bd5eed72d46b28834ec3f60db3a3ebedd8dbd" revision = "ae2bd5eed72d46b28834ec3f60db3a3ebedd8dbd"
[[projects]] [[projects]]
digest = "1:cae65c1f3471b1f456a9d8a160440f4824ad50c718a15da4144490fbc3b12e49"
name = "github.com/tinylib/msgp" name = "github.com/tinylib/msgp"
packages = ["msgp"] packages = ["msgp"]
pruneopts = ""
revision = "b2b6a672cf1e5b90748f79b8b81fc8c5cf0571a1" revision = "b2b6a672cf1e5b90748f79b8b81fc8c5cf0571a1"
version = "1.0.2" version = "1.0.2"
[[projects]] [[projects]]
branch = "master" branch = "master"
digest = "1:450f85e389d9cbd8265299827a2a062b1b6aee8d4c7b78d849d913a6eb405908"
name = "golang.org/x/crypto" name = "golang.org/x/crypto"
packages = [ packages = [
"curve25519",
"ed25519",
"ed25519/internal/edwards25519",
"internal/chacha20",
"pbkdf2", "pbkdf2",
"scrypt" "scrypt"
] ]
@ -393,34 +326,30 @@
[[projects]] [[projects]]
branch = "master" branch = "master"
digest = "1:950b672f2ee80d0fc4c95a15a976ba9ee573a6fb8ede8a777770b2230776367e"
name = "golang.org/x/net" name = "golang.org/x/net"
packages = [ packages = [
"context", "context",
"html", "html",
"html/atom", "html/atom",
"html/charset", "html/charset",
"websocket", "websocket"
] ]
revision = "26e67e76b6c3f6ce91f7c52def5af501b4e0f3a2" revision = "26e67e76b6c3f6ce91f7c52def5af501b4e0f3a2"
[[projects]] [[projects]]
branch = "master" branch = "master"
digest = "1:b2ea75de0ccb2db2ac79356407f8a4cd8f798fe15d41b381c00abf3ae8e55ed1"
name = "golang.org/x/sync" name = "golang.org/x/sync"
packages = ["errgroup"] packages = ["errgroup"]
pruneopts = ""
revision = "1d60e4601c6fd243af51cc01ddf169918a5407ca" revision = "1d60e4601c6fd243af51cc01ddf169918a5407ca"
[[projects]] [[projects]]
branch = "master" branch = "master"
digest = "1:5da11ab130476e2736f32140f3c1aed2a3a96e9ba8963711a7d38db783d042bd"
name = "golang.org/x/sys" name = "golang.org/x/sys"
packages = [ packages = [
"unix", "unix",
"windows", "windows"
] ]
revision = "d0be0721c37eeb5299f245a996a483160fc36940" revision = "d641721ec2dead6fe5ca284096fe4b1fcd49e427"
[[projects]] [[projects]]
name = "golang.org/x/text" name = "golang.org/x/text"
@ -444,30 +373,28 @@
"runes", "runes",
"transform", "transform",
"unicode/cldr", "unicode/cldr",
"unicode/norm", "unicode/norm"
] ]
revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0" revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0"
version = "v0.3.0" version = "v0.3.0"
[[projects]] [[projects]]
branch = "master" branch = "master"
digest = "1:5245bbf30a228b22cb61683ba5ad9641b98e0f81a9c4918394f49b40f6aa80f7"
name = "golang.org/x/tools" name = "golang.org/x/tools"
packages = [ packages = [
"go/ast/astutil", "go/ast/astutil",
"imports", "imports",
"internal/fastwalk", "internal/fastwalk"
] ]
revision = "677d2ff680c188ddb7dcd2bfa6bc7d3f2f2f75b2" revision = "90fa682c2a6e6a37b3a1364ce2fe1d5e41af9d6d"
[[projects]] [[projects]]
digest = "1:978b63089734495a83968fcdef711693500c72adfa3eaa1f1a2cc3d881dc4706"
name = "gopkg.in/DataDog/dd-trace-go.v1" name = "gopkg.in/DataDog/dd-trace-go.v1"
packages = [ packages = [
"ddtrace", "ddtrace",
"ddtrace/ext", "ddtrace/ext",
"ddtrace/internal", "ddtrace/internal",
"ddtrace/tracer", "ddtrace/tracer"
] ]
revision = "bcd20367df871708a36549e7fe36183ee5b4fc55" revision = "bcd20367df871708a36549e7fe36183ee5b4fc55"
version = "v1.3.0" version = "v1.3.0"
@ -481,18 +408,14 @@
[[projects]] [[projects]]
branch = "v2" branch = "v2"
digest = "1:a585c075875ab9c344f7840a927f09f3285563f7318e761a1d61d642316f2217"
name = "gopkg.in/karalabe/cookiejar.v2" name = "gopkg.in/karalabe/cookiejar.v2"
packages = ["collections/prque"] packages = ["collections/prque"]
pruneopts = ""
revision = "8dcd6a7f4951f6ff3ee9cbb919a06d8925822e57" revision = "8dcd6a7f4951f6ff3ee9cbb919a06d8925822e57"
[[projects]] [[projects]]
branch = "v2" branch = "v2"
digest = "1:4f830ee018eb8c56d0def653ad7c9a1d2a053f0cef2ac6b2200f73b98fa6a681"
name = "gopkg.in/natefinch/npipe.v2" name = "gopkg.in/natefinch/npipe.v2"
packages = ["."] packages = ["."]
pruneopts = ""
revision = "c1b8fa8bdccecb0b8db834ee0b92fdbcfa606dd6" revision = "c1b8fa8bdccecb0b8db834ee0b92fdbcfa606dd6"
[[projects]] [[projects]]

View File

@ -162,6 +162,9 @@ type Set interface {
// Otherwise, IsSuperset will panic. // Otherwise, IsSuperset will panic.
Union(other Set) Set Union(other Set) Set
// Pop removes and returns an arbitrary item from the set.
Pop() interface{}
// Returns all subsets of a given set (Power Set). // Returns all subsets of a given set (Power Set).
PowerSet() Set PowerSet() Set

View File

@ -967,6 +967,70 @@ func Test_IteratorStop(t *testing.T) {
} }
} }
func Test_PopSafe(t *testing.T) {
a := NewSet()
a.Add("a")
a.Add("b")
a.Add("c")
a.Add("d")
captureSet := NewSet()
captureSet.Add(a.Pop())
captureSet.Add(a.Pop())
captureSet.Add(a.Pop())
captureSet.Add(a.Pop())
finalNil := a.Pop()
if captureSet.Cardinality() != 4 {
t.Error("unexpected captureSet cardinality; should be 4")
}
if a.Cardinality() != 0 {
t.Error("unepxected a cardinality; should be zero")
}
if !captureSet.Contains("c", "a", "d", "b") {
t.Error("unexpected result set; should be a,b,c,d (any order is fine")
}
if finalNil != nil {
t.Error("when original set is empty, further pops should result in nil")
}
}
func Test_PopUnsafe(t *testing.T) {
a := NewThreadUnsafeSet()
a.Add("a")
a.Add("b")
a.Add("c")
a.Add("d")
captureSet := NewThreadUnsafeSet()
captureSet.Add(a.Pop())
captureSet.Add(a.Pop())
captureSet.Add(a.Pop())
captureSet.Add(a.Pop())
finalNil := a.Pop()
if captureSet.Cardinality() != 4 {
t.Error("unexpected captureSet cardinality; should be 4")
}
if a.Cardinality() != 0 {
t.Error("unepxected a cardinality; should be zero")
}
if !captureSet.Contains("c", "a", "d", "b") {
t.Error("unexpected result set; should be a,b,c,d (any order is fine")
}
if finalNil != nil {
t.Error("when original set is empty, further pops should result in nil")
}
}
func Test_PowerSet(t *testing.T) { func Test_PowerSet(t *testing.T) {
a := NewThreadUnsafeSet() a := NewThreadUnsafeSet()
@ -981,6 +1045,20 @@ func Test_PowerSet(t *testing.T) {
} }
} }
func Test_PowerSetThreadSafe(t *testing.T) {
set := NewSet().PowerSet()
_, setIsThreadSafe := set.(*threadSafeSet)
if !setIsThreadSafe {
t.Error("result of PowerSet should be thread safe")
}
subset := set.Pop()
_, subsetIsThreadSafe := subset.(*threadSafeSet)
if !subsetIsThreadSafe {
t.Error("subsets in PowerSet result should be thread safe")
}
}
func Test_EmptySetProperties(t *testing.T) { func Test_EmptySetProperties(t *testing.T) {
empty := NewSet() empty := NewSet()

View File

@ -226,11 +226,23 @@ func (set *threadSafeSet) String() string {
func (set *threadSafeSet) PowerSet() Set { func (set *threadSafeSet) PowerSet() Set {
set.RLock() set.RLock()
ret := set.s.PowerSet() unsafePowerSet := set.s.PowerSet().(*threadUnsafeSet)
set.RUnlock() set.RUnlock()
ret := &threadSafeSet{s: newThreadUnsafeSet()}
for subset := range unsafePowerSet.Iter() {
unsafeSubset := subset.(*threadUnsafeSet)
ret.Add(&threadSafeSet{s: *unsafeSubset})
}
return ret return ret
} }
func (set *threadSafeSet) Pop() interface{} {
set.Lock()
defer set.Unlock()
return set.s.Pop()
}
func (set *threadSafeSet) CartesianProduct(other Set) Set { func (set *threadSafeSet) CartesianProduct(other Set) Set {
o := other.(*threadSafeSet) o := other.(*threadSafeSet)

View File

@ -57,8 +57,12 @@ func (pair *OrderedPair) Equal(other OrderedPair) bool {
func (set *threadUnsafeSet) Add(i interface{}) bool { func (set *threadUnsafeSet) Add(i interface{}) bool {
_, found := (*set)[i] _, found := (*set)[i]
if found {
return false //False if it existed already
}
(*set)[i] = struct{}{} (*set)[i] = struct{}{}
return !found //False if it existed already return true
} }
func (set *threadUnsafeSet) Contains(i ...interface{}) bool { func (set *threadUnsafeSet) Contains(i ...interface{}) bool {
@ -233,6 +237,14 @@ func (pair OrderedPair) String() string {
return fmt.Sprintf("(%v, %v)", pair.First, pair.Second) return fmt.Sprintf("(%v, %v)", pair.First, pair.Second)
} }
func (set *threadUnsafeSet) Pop() interface{} {
for item := range *set {
delete(*set, item)
return item
}
return nil
}
func (set *threadUnsafeSet) PowerSet() Set { func (set *threadUnsafeSet) PowerSet() Set {
powSet := NewThreadUnsafeSet() powSet := NewThreadUnsafeSet()
nullset := newThreadUnsafeSet() nullset := newThreadUnsafeSet()

View File

@ -1,9 +0,0 @@
language: go
go:
- 1.4
- tip
script:
- go test
- cd example && go build -o prefix && echo -e "1\n2\n3\n" | ./prefix | grep "> "

View File

@ -1,22 +0,0 @@
MIT License
Copyright (c) 2016 Pressly Inc. www.pressly.com
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.

View File

@ -1,69 +0,0 @@
# Prefixer
[Golang](http://golang.org/)'s [io.Reader](http://golang.org/pkg/io/#Reader) wrapper prepending every line with a given string.
[![GoDoc](https://godoc.org/github.com/goware/prefixer?status.png)](https://godoc.org/github.com/goware/prefixer)
[![Travis](https://travis-ci.org/goware/prefixer.svg?branch=master)](https://travis-ci.org/goware/prefixer)
## Use cases
1. Logger that prefixes every line with a timestamp etc.
```bash
16:54:49 My awesome server | Creating etcd client pointing to http://localhost:4001
16:54:49 My awesome server | Listening on http://localhost:8080
16:54:49 My awesome server | [restful/swagger] listing is available at 127.0.0.1:8080/swaggerapi
```
2. SSH multiplexer prepending output from multiple servers with a hostname
```bash
host1.example.com | SUCCESS
host2.example.com | SUCCESS
host3.example.com | -bash: cd: workdir: No such file or directory
host4.example.com | SUCCESS
```
3. Create an email reply (`"> "` prefix) from any text easily.
```bash
$ ./prefix
Dear John,
did you know that https://github.com/goware/prefixer is a golang pkg
that prefixes every line with a given string and accepts any io.Reader?
Cheers,
- Jane
^D
> Dear John,
> did you know that https://github.com/goware/prefixer is a golang pkg
> that prefixes every line with a given string and accepts any io.Reader?
>
> Cheers,
> - Jane
```
## Example
See the ["Prefix Line Reader" example](./example).
```go
package main
import (
"io/ioutil"
"os"
"github.com/goware/prefixer"
)
func main() {
// Prefixer accepts anything that implements io.Reader interface
prefixReader := prefixer.New(os.Stdin, "> ")
// Read all prefixed lines from STDIN into a buffer
buffer, _ := ioutil.ReadAll(prefixReader)
// Write buffer to STDOUT
os.Stdout.Write(buffer)
}
```
## License
Prefixer is licensed under the [MIT License](./LICENSE).

View File

@ -1,3 +0,0 @@
// Package prefixer implements io.Reader wrapper prepending
// every line with a given string.
package prefixer

View File

@ -1,32 +0,0 @@
# Prefixer example
See [prefix.go](./prefix.go).
## Build "prefix" binary
```bash
$ git clone https://github.com/goware/prefixer.git
$ cd prefixer/example
$ go build -o prefix
```
## Usage
Create an email reply (`"> "` prefix) from any text easily:
```bash
$ ./prefix
Dear John,
did you know that https://github.com/goware/prefixer is a golang pkg
that prefixes every line with a given string and accepts any io.Reader?
Cheers,
- Jane
^D
> Dear John,
> did you know that https://github.com/goware/prefixer is a golang pkg
> that prefixes every line with a given string and accepts any io.Reader?
>
> Cheers,
> - Jane
```

View File

@ -1,19 +0,0 @@
package main
import (
"io/ioutil"
"os"
"github.com/goware/prefixer"
)
func main() {
// Prefixer accepts anything that implements io.Reader interface
prefixReader := prefixer.New(os.Stdin, "> ")
// Read all prefixed lines from STDIN into a buffer
buffer, _ := ioutil.ReadAll(prefixReader)
// Write buffer to STDOUT
os.Stdout.Write(buffer)
}

View File

@ -1,123 +0,0 @@
package prefixer
import (
"bufio"
"io"
)
// Prefixer implements io.Reader and io.WriterTo. It reads
// data from the underlying reader and prepends every line
// with a given string.
type Prefixer struct {
reader *bufio.Reader
prefix []byte
unread []byte
eof bool
}
// New creates a new instance of Prefixer.
func New(r io.Reader, prefix string) *Prefixer {
return &Prefixer{
reader: bufio.NewReader(r),
prefix: []byte(prefix),
}
}
// Read implements io.Reader. It reads data into p from the
// underlying reader and prepends every line with a prefix.
// It does not block if no data is available yet.
// It returns the number of bytes read into p.
func (r *Prefixer) Read(p []byte) (n int, err error) {
for {
// Write unread data from previous read.
if len(r.unread) > 0 {
m := copy(p[n:], r.unread)
n += m
r.unread = r.unread[m:]
if len(r.unread) > 0 {
return n, nil
}
}
// The underlying Reader already returned EOF, do not read again.
if r.eof {
return n, io.EOF
}
// Read new line, including delim.
r.unread, err = r.reader.ReadBytes('\n')
if err == io.EOF {
r.eof = true
}
// No new data, do not block.
if len(r.unread) == 0 {
return n, err
}
// Some new data, prepend prefix.
// TODO: We could write the prefix to r.unread buffer just once
// and re-use it instead of prepending every time.
r.unread = append(r.prefix, r.unread...)
if err != nil {
if err == io.EOF && len(r.unread) > 0 {
// The underlying Reader already returned EOF, but we still
// have some unread data to send, thus clear the error.
return n, nil
}
return n, err
}
}
panic("unreachable")
}
func (r *Prefixer) WriteTo(w io.Writer) (n int64, err error) {
for {
// Write unread data from previous read.
if len(r.unread) > 0 {
m, err := w.Write(r.unread)
n += int64(m)
if err != nil {
return n, err
}
r.unread = r.unread[m:]
if len(r.unread) > 0 {
return n, nil
}
}
// The underlying Reader already returned EOF, do not read again.
if r.eof {
return n, io.EOF
}
// Read new line, including delim.
r.unread, err = r.reader.ReadBytes('\n')
if err == io.EOF {
r.eof = true
}
// No new data, do not block.
if len(r.unread) == 0 {
return n, err
}
// Some new data, prepend prefix.
// TODO: We could write the prefix to r.unread buffer just once
// and re-use it instead of prepending every time.
r.unread = append(r.prefix, r.unread...)
if err != nil {
if err == io.EOF && len(r.unread) > 0 {
// The underlying Reader already returned EOF, but we still
// have some unread data to send, thus clear the error.
return n, nil
}
return n, err
}
}
panic("unreachable")
}

View File

@ -1,57 +0,0 @@
package prefixer_test
import (
"bytes"
"io/ioutil"
"strings"
"testing"
"github.com/goware/prefixer"
)
var prefix = "Some prefix | "
func TestPrefixer(t *testing.T) {
testStrings := []struct {
in string
out string
}{
{
in: "",
out: "",
},
{
in: "x",
out: prefix + "x",
},
{
in: "\n",
out: prefix + "\n",
},
{
in: "Hello World!\n",
out: prefix + "Hello World!\n",
},
{
in: "Multiline\ntext",
out: prefix + "Multiline\n" + prefix + "text",
},
{
in: "Multiline\ntext\nis\nawesome\n",
out: prefix + "Multiline\n" + prefix + "text\n" + prefix + "is\n" + prefix + "awesome\n",
},
}
for _, tt := range testStrings {
r := prefixer.New(strings.NewReader(tt.in), prefix)
buf, err := ioutil.ReadAll(r)
if err != nil {
t.Errorf("Unexpected eror %v", err)
}
out := []byte(tt.out)
if !bytes.Equal(buf, out) {
t.Errorf("\nExpected:\n\"%s\",\ngot:\n\"%s\"", tt.out, buf)
}
}
}

View File

@ -1,7 +0,0 @@
language: go
go:
- 1.x
before_install:
- go get github.com/mattn/goveralls
script:
- $HOME/gopath/bin/goveralls -service=travis-ci

View File

@ -1,674 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View File

@ -1,56 +0,0 @@
# OpenSSH config parser for golang
[![Build Status](https://travis-ci.org/mikkeloscar/sshconfig.svg?branch=master)](https://travis-ci.org/mikkeloscar/sshconfig)
[![GoDoc](https://godoc.org/github.com/mikkeloscar/sshconfig?status.svg)](https://godoc.org/github.com/mikkeloscar/sshconfig)
[![Go Report Card](https://goreportcard.com/badge/github.com/mikkeloscar/sshconfig)](https://goreportcard.com/report/github.com/mikkeloscar/sshconfig)
[![Coverage Status](https://coveralls.io/repos/github/mikkeloscar/sshconfig/badge.svg)](https://coveralls.io/github/mikkeloscar/sshconfig)
Parses the config usually found in `~/.ssh/config` or `/etc/ssh/ssh_config`.
Only `Host`, `HostName`, `User`, `Port`, `IdentityFile`, `HostKeyAlgorithms` and `ProxyCommand` is implemented at
this point.
[OpenSSH Reference.][openssh_man]
## Usage
Example usage
```go
package main
import (
"fmt"
"github.com/mikkeloscar/sshconfig"
)
func main() {
hosts, err := ParseSSHConfig("/path/to/ssh_config")
if err != nil {
fmt.Println(err)
}
for _, host := range hosts {
fmt.Printf("Hostname: %s", host.HostName)
}
}
```
## LICENSE
Copyright (C) 2016 Mikkel Oscar Lyderik Larsen & Contributors
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
[openssh_man]: http://www.openbsd.org/cgi-bin/man.cgi/OpenBSD-current/man5/ssh_config.5?query=ssh_config&sec=5

View File

@ -1,277 +0,0 @@
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// based on the lexer from: src/pkg/text/template/parse/lex.go (golang source)
package sshconfig
import (
"fmt"
"strings"
"unicode"
"unicode/utf8"
)
// pos is a position in input being scanned
type pos int
type item struct {
typ itemType
pos pos
val string
}
func (i item) String() string {
switch {
case i.typ == itemEOF:
return "EOF"
case i.typ == itemError:
return i.val
case len(i.val) > 10:
return fmt.Sprintf("%.10q...", i.val)
}
return fmt.Sprintf("%q", i.val)
}
type itemType int
const (
itemError itemType = iota
itemEOF
itemValue
itemHost
itemHostValue
itemHostName
itemUser
itemPort
itemProxyCommand
itemHostKeyAlgorithms
itemIdentityFile
)
// variables
var variables = map[string]itemType{
"host": itemHost,
"hostname": itemHostName,
"user": itemUser,
"port": itemPort,
"proxycommand": itemProxyCommand,
"hostkeyalgorithms": itemHostKeyAlgorithms,
"identityfile": itemIdentityFile,
}
const eof = -1
// stateFn represents the state of the scanner as a function that returns the next state
type stateFn func(*lexer) stateFn
// lexer holds the state of the scanner
type lexer struct {
input string
state stateFn
pos pos
start pos
width pos
lastPos pos
items chan item // channel of scanned items
}
// next returns the next rune in the input
func (l *lexer) next() rune {
if int(l.pos) >= len(l.input) {
l.width = 0
return eof
}
r, w := utf8.DecodeRuneInString(l.input[l.pos:])
l.width = pos(w)
l.pos += l.width
return r
}
// peek returns but does not consume the next rune in the input
func (l *lexer) peek() rune {
r := l.next()
l.backup()
return r
}
// backup steps back one rune. Can only be called once per call of next
func (l *lexer) backup() {
l.pos -= l.width
}
// emit passes an item back to the client
func (l *lexer) emit(t itemType) {
l.items <- item{t, l.start, l.input[l.start:l.pos]}
l.start = l.pos
}
// ignore skips over the pending input before this point
func (l *lexer) ignore() {
l.start = l.pos
}
// errorf returns an error token and terminates the scan by passing
// back a nil pointer that will be the next state, terminating l.nextItem.
func (l *lexer) errorf(format string, args ...interface{}) stateFn {
l.items <- item{itemError, l.start, fmt.Sprintf(format, args...)}
return nil
}
// nextItem returns the next item from the input.
func (l *lexer) nextItem() item {
item := <-l.items
l.lastPos = item.pos
return item
}
func lex(input string) *lexer {
l := &lexer{
input: input,
items: make(chan item),
}
go l.run()
return l
}
func (l *lexer) run() {
for l.state = lexEnv; l.state != nil; {
l.state = l.state(l)
}
}
func lexEnv(l *lexer) stateFn {
switch r := l.next(); {
case r == eof:
l.emit(itemEOF)
return nil
case isAlphaNumeric(r):
return lexVariable
case r == '#':
return lexComment
case r == '\r':
l.ignore()
if l.next() != '\n' {
l.errorf("expected \\n")
return nil
}
l.ignore()
return lexEnv
case r == '\t' || r == ' ' || r == '\n':
l.ignore()
return lexEnv
default:
l.errorf("unable to parse character: %c", r)
return nil
}
}
func lexComment(l *lexer) stateFn {
for {
switch l.next() {
case '\r':
l.ignore()
if l.next() != '\n' {
l.errorf("expected \\n")
return nil
}
l.ignore()
return lexEnv
case '\n':
l.ignore()
return lexEnv
default:
l.ignore()
}
}
}
func lexVariable(l *lexer) stateFn {
for {
switch r := l.next(); {
case isAlphaNumeric(r):
// absorb
case r == ' ' || r == '=':
l.backup()
variable := strings.ToLower(l.input[l.start:l.pos])
if _, ok := variables[variable]; ok {
l.emit(variables[variable])
l.next()
l.ignore()
if variable == "host" {
return lexHostValue
}
return lexValue
}
return lexValue
default:
pattern := l.input[l.start:l.pos]
return l.errorf("invalid pattern: %#v", pattern)
}
}
}
func lexHostValue(l *lexer) stateFn {
for {
switch l.next() {
case ' ':
switch l.peek() {
case '\r':
if l.peek() != '\n' {
return l.errorf("expected \\n")
}
fallthrough
case '\n', eof:
break
default:
// more coming, wait
continue
}
l.emit(itemValue)
case '\r':
if l.peek() != '\n' {
return l.errorf("expected \\n")
}
fallthrough
case '\n':
l.backup()
l.emit(itemHostValue)
return lexEnv
case eof:
l.backup()
l.emit(itemHostValue)
l.next()
l.emit(itemEOF)
return nil
}
}
}
func lexValue(l *lexer) stateFn {
for {
switch l.next() {
case '\r':
if l.peek() != '\n' {
return l.errorf("expected \\n")
}
fallthrough
case '\n':
l.backup()
l.emit(itemValue)
return lexEnv
case eof:
l.backup()
l.emit(itemValue)
l.next()
l.emit(itemEOF)
return nil
}
}
}
// isAlphaNumeric reports whether r is an alphabetic or digit.
func isAlphaNumeric(r rune) bool {
return unicode.IsLetter(r) || unicode.IsDigit(r)
}

View File

@ -1,117 +0,0 @@
package sshconfig
import (
"fmt"
"io/ioutil"
"strconv"
"strings"
)
// SSHHost defines a single host entry in a ssh config
type SSHHost struct {
Host []string
HostName string
User string
Port int
ProxyCommand string
HostKeyAlgorithms string
IdentityFile string
}
// MustParseSSHConfig must parse the SSH config given by path or it will panic
func MustParseSSHConfig(path string) []*SSHHost {
config, err := ParseSSHConfig(path)
if err != nil {
panic(err)
}
return config
}
// ParseSSHConfig parses a SSH config given by path.
func ParseSSHConfig(path string) ([]*SSHHost, error) {
// read config file
content, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
return parse(string(content))
}
// parses an openssh config file
func parse(input string) ([]*SSHHost, error) {
sshConfigs := []*SSHHost{}
var next item
var sshHost *SSHHost
lexer := lex(input)
Loop:
for {
token := lexer.nextItem()
if sshHost == nil && token.typ != itemHost {
return nil, fmt.Errorf("config variable before Host variable")
}
switch token.typ {
case itemHost:
if sshHost != nil {
sshConfigs = append(sshConfigs, sshHost)
}
sshHost = &SSHHost{Host: []string{}, Port: 22}
case itemHostValue:
sshHost.Host = strings.Split(token.val, " ")
case itemHostName:
next = lexer.nextItem()
if next.typ != itemValue {
return nil, fmt.Errorf(next.val)
}
sshHost.HostName = next.val
case itemUser:
next = lexer.nextItem()
if next.typ != itemValue {
return nil, fmt.Errorf(next.val)
}
sshHost.User = next.val
case itemPort:
next = lexer.nextItem()
if next.typ != itemValue {
return nil, fmt.Errorf(next.val)
}
port, err := strconv.Atoi(next.val)
if err != nil {
return nil, err
}
sshHost.Port = port
case itemProxyCommand:
next = lexer.nextItem()
if next.typ != itemValue {
return nil, fmt.Errorf(next.val)
}
sshHost.ProxyCommand = next.val
case itemHostKeyAlgorithms:
next = lexer.nextItem()
if next.typ != itemValue {
return nil, fmt.Errorf(next.val)
}
sshHost.HostKeyAlgorithms = next.val
case itemIdentityFile:
next = lexer.nextItem()
if next.typ != itemValue {
return nil, fmt.Errorf(next.val)
}
sshHost.IdentityFile = next.val
case itemError:
return nil, fmt.Errorf("%s at pos %d", token.val, token.pos)
case itemEOF:
if sshHost != nil {
sshConfigs = append(sshConfigs, sshHost)
}
break Loop
default:
// continue onwards
}
}
return sshConfigs, nil
}

View File

@ -1,150 +0,0 @@
package sshconfig
import (
"encoding/json"
"reflect"
"strings"
"testing"
)
// Test parsing
func TestParsing(t *testing.T) {
config := `Host google
HostName google.se
User goog
Port 2222
ProxyCommand ssh -q pluto nc saturn 22
HostKeyAlgorithms ssh-dss
# comment
IdentityFile ~/.ssh/company
Host face
HostName facebook.com
User mark
Port 22`
_, err := parse(config)
if err != nil {
t.Errorf("unable to parse config: %s", err.Error())
}
configCR := strings.Replace(`Host google
HostName google.se
User goog
Port 2222
ProxyCommand ssh -q pluto nc saturn 22
HostKeyAlgorithms ssh-dss
# comment
IdentityFile ~/.ssh/company
Host face
HostName facebook.com
User mark
Port 22`, "\n", "\r\n", -1)
_, err = parse(configCR)
if err != nil {
t.Errorf("unable to parse config: %s", err.Error())
}
}
func TestMultipleHost(t *testing.T) {
config := `Host google google2 aws
HostName google.se
User goog
Port 2222`
hosts, err := parse(config)
if err != nil {
t.Errorf("unable to parse config: %s", err.Error())
}
h := hosts[0]
if ok := reflect.DeepEqual([]string{"google", "google2", "aws"}, h.Host); !ok {
t.Error("unexpected host mismatch")
}
}
// TestTrailingSpace ensures the parser does not hang when attempting to parse
// a Host declaration with a trailing space after a pattern
func TestTrailingSpace(t *testing.T) {
// in the config below, the first line is "Host google \n"
config := `
Host googlespace
HostName google.com
`
parse(config)
}
func TestIgnoreKeyword(t *testing.T) {
config := `Host google
HostName google.se
User goog
Port 2222
ProxyCommand ssh -q pluto nc saturn 22
HostKeyAlgorithms ssh-dss
# comment
IdentityOnly yes
IdentityFile ~/.ssh/company
Host face
HostName facebook.com
User mark
Port 22`
expected := []*SSHHost{
{
Host: []string{"google"},
HostName: "google.se",
User: "goog",
Port: 2222,
HostKeyAlgorithms: "ssh-dss",
ProxyCommand: "ssh -q pluto nc saturn 22",
IdentityFile: "~/.ssh/company",
},
{
Host: []string{"face"},
User: "mark",
Port: 22,
HostName: "facebook.com",
HostKeyAlgorithms: "",
ProxyCommand: "",
IdentityFile: "",
},
}
actual, err := parse(config)
if err != nil {
t.Errorf("unexpected error parsing config: %s", err.Error())
}
compare(t, expected, actual)
}
func compare(t *testing.T, expected, actual []*SSHHost) {
for i, ac := range actual {
exMap := toMap(t, expected[i])
acMap := toMap(t, ac)
if ok := reflect.DeepEqual(exMap, acMap); !ok {
t.Errorf("unexpected parsed \n expected: %+v \n actual: %+v", exMap, acMap)
}
}
}
func toMap(t *testing.T, a *SSHHost) map[string]interface{} {
ab, err := json.Marshal(a)
if err != nil {
t.Errorf("marshaling expected %s", err)
}
var aMap map[string]interface{}
if err := json.Unmarshal(ab, &aMap); err != nil {
t.Errorf("unmarshaling expected %s", err)
}
return aMap
}

View File

@ -1,24 +0,0 @@
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.test
*.prof

View File

@ -1,11 +0,0 @@
language: go
go_import_path: github.com/pkg/errors
go:
- 1.4.3
- 1.5.4
- 1.6.2
- 1.7.1
- tip
script:
- go test -v ./...

23
vendor/github.com/pkg/errors/LICENSE generated vendored
View File

@ -1,23 +0,0 @@
Copyright (c) 2015, Dave Cheney <dave@cheney.net>
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@ -1,52 +0,0 @@
# errors [![Travis-CI](https://travis-ci.org/pkg/errors.svg)](https://travis-ci.org/pkg/errors) [![AppVeyor](https://ci.appveyor.com/api/projects/status/b98mptawhudj53ep/branch/master?svg=true)](https://ci.appveyor.com/project/davecheney/errors/branch/master) [![GoDoc](https://godoc.org/github.com/pkg/errors?status.svg)](http://godoc.org/github.com/pkg/errors) [![Report card](https://goreportcard.com/badge/github.com/pkg/errors)](https://goreportcard.com/report/github.com/pkg/errors)
Package errors provides simple error handling primitives.
`go get github.com/pkg/errors`
The traditional error handling idiom in Go is roughly akin to
```go
if err != nil {
return err
}
```
which applied recursively up the call stack results in error reports without context or debugging information. The errors package allows programmers to add context to the failure path in their code in a way that does not destroy the original value of the error.
## Adding context to an error
The errors.Wrap function returns a new error that adds context to the original error. For example
```go
_, err := ioutil.ReadAll(r)
if err != nil {
return errors.Wrap(err, "read failed")
}
```
## Retrieving the cause of an error
Using `errors.Wrap` constructs a stack of errors, adding context to the preceding error. Depending on the nature of the error it may be necessary to reverse the operation of errors.Wrap to retrieve the original error for inspection. Any error value which implements this interface can be inspected by `errors.Cause`.
```go
type causer interface {
Cause() error
}
```
`errors.Cause` will recursively retrieve the topmost error which does not implement `causer`, which is assumed to be the original cause. For example:
```go
switch err := errors.Cause(err).(type) {
case *MyError:
// handle specifically
default:
// unknown error
}
```
[Read the package documentation for more information](https://godoc.org/github.com/pkg/errors).
## Contributing
We welcome pull requests, bug fixes and issue reports. With that said, the bar for adding new symbols to this package is intentionally set high.
Before proposing a change, please discuss your change by raising an issue.
## Licence
BSD-2-Clause

View File

@ -1,32 +0,0 @@
version: build-{build}.{branch}
clone_folder: C:\gopath\src\github.com\pkg\errors
shallow_clone: true # for startup speed
environment:
GOPATH: C:\gopath
platform:
- x64
# http://www.appveyor.com/docs/installed-software
install:
# some helpful output for debugging builds
- go version
- go env
# pre-installed MinGW at C:\MinGW is 32bit only
# but MSYS2 at C:\msys64 has mingw64
- set PATH=C:\msys64\mingw64\bin;%PATH%
- gcc --version
- g++ --version
build_script:
- go install -v ./...
test_script:
- set PATH=C:\gopath\bin;%PATH%
- go test -v ./...
#artifacts:
# - path: '%GOPATH%\bin\*.exe'
deploy: off

View File

@ -1,59 +0,0 @@
// +build go1.7
package errors
import (
"fmt"
"testing"
stderrors "errors"
)
func noErrors(at, depth int) error {
if at >= depth {
return stderrors.New("no error")
}
return noErrors(at+1, depth)
}
func yesErrors(at, depth int) error {
if at >= depth {
return New("ye error")
}
return yesErrors(at+1, depth)
}
func BenchmarkErrors(b *testing.B) {
var toperr error
type run struct {
stack int
std bool
}
runs := []run{
{10, false},
{10, true},
{100, false},
{100, true},
{1000, false},
{1000, true},
}
for _, r := range runs {
part := "pkg/errors"
if r.std {
part = "errors"
}
name := fmt.Sprintf("%s-stack-%d", part, r.stack)
b.Run(name, func(b *testing.B) {
var err error
f := yesErrors
if r.std {
f = noErrors
}
b.ReportAllocs()
for i := 0; i < b.N; i++ {
err = f(0, r.stack)
}
b.StopTimer()
toperr = err
})
}
}

View File

@ -1,269 +0,0 @@
// Package errors provides simple error handling primitives.
//
// The traditional error handling idiom in Go is roughly akin to
//
// if err != nil {
// return err
// }
//
// which applied recursively up the call stack results in error reports
// without context or debugging information. The errors package allows
// programmers to add context to the failure path in their code in a way
// that does not destroy the original value of the error.
//
// Adding context to an error
//
// The errors.Wrap function returns a new error that adds context to the
// original error by recording a stack trace at the point Wrap is called,
// and the supplied message. For example
//
// _, err := ioutil.ReadAll(r)
// if err != nil {
// return errors.Wrap(err, "read failed")
// }
//
// If additional control is required the errors.WithStack and errors.WithMessage
// functions destructure errors.Wrap into its component operations of annotating
// an error with a stack trace and an a message, respectively.
//
// Retrieving the cause of an error
//
// Using errors.Wrap constructs a stack of errors, adding context to the
// preceding error. Depending on the nature of the error it may be necessary
// to reverse the operation of errors.Wrap to retrieve the original error
// for inspection. Any error value which implements this interface
//
// type causer interface {
// Cause() error
// }
//
// can be inspected by errors.Cause. errors.Cause will recursively retrieve
// the topmost error which does not implement causer, which is assumed to be
// the original cause. For example:
//
// switch err := errors.Cause(err).(type) {
// case *MyError:
// // handle specifically
// default:
// // unknown error
// }
//
// causer interface is not exported by this package, but is considered a part
// of stable public API.
//
// Formatted printing of errors
//
// All error values returned from this package implement fmt.Formatter and can
// be formatted by the fmt package. The following verbs are supported
//
// %s print the error. If the error has a Cause it will be
// printed recursively
// %v see %s
// %+v extended format. Each Frame of the error's StackTrace will
// be printed in detail.
//
// Retrieving the stack trace of an error or wrapper
//
// New, Errorf, Wrap, and Wrapf record a stack trace at the point they are
// invoked. This information can be retrieved with the following interface.
//
// type stackTracer interface {
// StackTrace() errors.StackTrace
// }
//
// Where errors.StackTrace is defined as
//
// type StackTrace []Frame
//
// The Frame type represents a call site in the stack trace. Frame supports
// the fmt.Formatter interface that can be used for printing information about
// the stack trace of this error. For example:
//
// if err, ok := err.(stackTracer); ok {
// for _, f := range err.StackTrace() {
// fmt.Printf("%+s:%d", f)
// }
// }
//
// stackTracer interface is not exported by this package, but is considered a part
// of stable public API.
//
// See the documentation for Frame.Format for more details.
package errors
import (
"fmt"
"io"
)
// New returns an error with the supplied message.
// New also records the stack trace at the point it was called.
func New(message string) error {
return &fundamental{
msg: message,
stack: callers(),
}
}
// Errorf formats according to a format specifier and returns the string
// as a value that satisfies error.
// Errorf also records the stack trace at the point it was called.
func Errorf(format string, args ...interface{}) error {
return &fundamental{
msg: fmt.Sprintf(format, args...),
stack: callers(),
}
}
// fundamental is an error that has a message and a stack, but no caller.
type fundamental struct {
msg string
*stack
}
func (f *fundamental) Error() string { return f.msg }
func (f *fundamental) Format(s fmt.State, verb rune) {
switch verb {
case 'v':
if s.Flag('+') {
io.WriteString(s, f.msg)
f.stack.Format(s, verb)
return
}
fallthrough
case 's':
io.WriteString(s, f.msg)
case 'q':
fmt.Fprintf(s, "%q", f.msg)
}
}
// WithStack annotates err with a stack trace at the point WithStack was called.
// If err is nil, WithStack returns nil.
func WithStack(err error) error {
if err == nil {
return nil
}
return &withStack{
err,
callers(),
}
}
type withStack struct {
error
*stack
}
func (w *withStack) Cause() error { return w.error }
func (w *withStack) Format(s fmt.State, verb rune) {
switch verb {
case 'v':
if s.Flag('+') {
fmt.Fprintf(s, "%+v", w.Cause())
w.stack.Format(s, verb)
return
}
fallthrough
case 's':
io.WriteString(s, w.Error())
case 'q':
fmt.Fprintf(s, "%q", w.Error())
}
}
// Wrap returns an error annotating err with a stack trace
// at the point Wrap is called, and the supplied message.
// If err is nil, Wrap returns nil.
func Wrap(err error, message string) error {
if err == nil {
return nil
}
err = &withMessage{
cause: err,
msg: message,
}
return &withStack{
err,
callers(),
}
}
// Wrapf returns an error annotating err with a stack trace
// at the point Wrapf is call, and the format specifier.
// If err is nil, Wrapf returns nil.
func Wrapf(err error, format string, args ...interface{}) error {
if err == nil {
return nil
}
err = &withMessage{
cause: err,
msg: fmt.Sprintf(format, args...),
}
return &withStack{
err,
callers(),
}
}
// WithMessage annotates err with a new message.
// If err is nil, WithMessage returns nil.
func WithMessage(err error, message string) error {
if err == nil {
return nil
}
return &withMessage{
cause: err,
msg: message,
}
}
type withMessage struct {
cause error
msg string
}
func (w *withMessage) Error() string { return w.msg + ": " + w.cause.Error() }
func (w *withMessage) Cause() error { return w.cause }
func (w *withMessage) Format(s fmt.State, verb rune) {
switch verb {
case 'v':
if s.Flag('+') {
fmt.Fprintf(s, "%+v\n", w.Cause())
io.WriteString(s, w.msg)
return
}
fallthrough
case 's', 'q':
io.WriteString(s, w.Error())
}
}
// Cause returns the underlying cause of the error, if possible.
// An error value has a cause if it implements the following
// interface:
//
// type causer interface {
// Cause() error
// }
//
// If the error does not implement Cause, the original error will
// be returned. If the error is nil, nil will be returned without further
// investigation.
func Cause(err error) error {
type causer interface {
Cause() error
}
for err != nil {
cause, ok := err.(causer)
if !ok {
break
}
err = cause.Cause()
}
return err
}

View File

@ -1,226 +0,0 @@
package errors
import (
"errors"
"fmt"
"io"
"reflect"
"testing"
)
func TestNew(t *testing.T) {
tests := []struct {
err string
want error
}{
{"", fmt.Errorf("")},
{"foo", fmt.Errorf("foo")},
{"foo", New("foo")},
{"string with format specifiers: %v", errors.New("string with format specifiers: %v")},
}
for _, tt := range tests {
got := New(tt.err)
if got.Error() != tt.want.Error() {
t.Errorf("New.Error(): got: %q, want %q", got, tt.want)
}
}
}
func TestWrapNil(t *testing.T) {
got := Wrap(nil, "no error")
if got != nil {
t.Errorf("Wrap(nil, \"no error\"): got %#v, expected nil", got)
}
}
func TestWrap(t *testing.T) {
tests := []struct {
err error
message string
want string
}{
{io.EOF, "read error", "read error: EOF"},
{Wrap(io.EOF, "read error"), "client error", "client error: read error: EOF"},
}
for _, tt := range tests {
got := Wrap(tt.err, tt.message).Error()
if got != tt.want {
t.Errorf("Wrap(%v, %q): got: %v, want %v", tt.err, tt.message, got, tt.want)
}
}
}
type nilError struct{}
func (nilError) Error() string { return "nil error" }
func TestCause(t *testing.T) {
x := New("error")
tests := []struct {
err error
want error
}{{
// nil error is nil
err: nil,
want: nil,
}, {
// explicit nil error is nil
err: (error)(nil),
want: nil,
}, {
// typed nil is nil
err: (*nilError)(nil),
want: (*nilError)(nil),
}, {
// uncaused error is unaffected
err: io.EOF,
want: io.EOF,
}, {
// caused error returns cause
err: Wrap(io.EOF, "ignored"),
want: io.EOF,
}, {
err: x, // return from errors.New
want: x,
}, {
WithMessage(nil, "whoops"),
nil,
}, {
WithMessage(io.EOF, "whoops"),
io.EOF,
}, {
WithStack(nil),
nil,
}, {
WithStack(io.EOF),
io.EOF,
}}
for i, tt := range tests {
got := Cause(tt.err)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("test %d: got %#v, want %#v", i+1, got, tt.want)
}
}
}
func TestWrapfNil(t *testing.T) {
got := Wrapf(nil, "no error")
if got != nil {
t.Errorf("Wrapf(nil, \"no error\"): got %#v, expected nil", got)
}
}
func TestWrapf(t *testing.T) {
tests := []struct {
err error
message string
want string
}{
{io.EOF, "read error", "read error: EOF"},
{Wrapf(io.EOF, "read error without format specifiers"), "client error", "client error: read error without format specifiers: EOF"},
{Wrapf(io.EOF, "read error with %d format specifier", 1), "client error", "client error: read error with 1 format specifier: EOF"},
}
for _, tt := range tests {
got := Wrapf(tt.err, tt.message).Error()
if got != tt.want {
t.Errorf("Wrapf(%v, %q): got: %v, want %v", tt.err, tt.message, got, tt.want)
}
}
}
func TestErrorf(t *testing.T) {
tests := []struct {
err error
want string
}{
{Errorf("read error without format specifiers"), "read error without format specifiers"},
{Errorf("read error with %d format specifier", 1), "read error with 1 format specifier"},
}
for _, tt := range tests {
got := tt.err.Error()
if got != tt.want {
t.Errorf("Errorf(%v): got: %q, want %q", tt.err, got, tt.want)
}
}
}
func TestWithStackNil(t *testing.T) {
got := WithStack(nil)
if got != nil {
t.Errorf("WithStack(nil): got %#v, expected nil", got)
}
}
func TestWithStack(t *testing.T) {
tests := []struct {
err error
want string
}{
{io.EOF, "EOF"},
{WithStack(io.EOF), "EOF"},
}
for _, tt := range tests {
got := WithStack(tt.err).Error()
if got != tt.want {
t.Errorf("WithStack(%v): got: %v, want %v", tt.err, got, tt.want)
}
}
}
func TestWithMessageNil(t *testing.T) {
got := WithMessage(nil, "no error")
if got != nil {
t.Errorf("WithMessage(nil, \"no error\"): got %#v, expected nil", got)
}
}
func TestWithMessage(t *testing.T) {
tests := []struct {
err error
message string
want string
}{
{io.EOF, "read error", "read error: EOF"},
{WithMessage(io.EOF, "read error"), "client error", "client error: read error: EOF"},
}
for _, tt := range tests {
got := WithMessage(tt.err, tt.message).Error()
if got != tt.want {
t.Errorf("WithMessage(%v, %q): got: %q, want %q", tt.err, tt.message, got, tt.want)
}
}
}
// errors.New, etc values are not expected to be compared by value
// but the change in errors#27 made them incomparable. Assert that
// various kinds of errors have a functional equality operator, even
// if the result of that equality is always false.
func TestErrorEquality(t *testing.T) {
vals := []error{
nil,
io.EOF,
errors.New("EOF"),
New("EOF"),
Errorf("EOF"),
Wrap(io.EOF, "EOF"),
Wrapf(io.EOF, "EOF%d", 2),
WithMessage(nil, "whoops"),
WithMessage(io.EOF, "whoops"),
WithStack(io.EOF),
WithStack(nil),
}
for i := range vals {
for j := range vals {
_ = vals[i] == vals[j] // mustn't panic
}
}
}

View File

@ -1,205 +0,0 @@
package errors_test
import (
"fmt"
"github.com/pkg/errors"
)
func ExampleNew() {
err := errors.New("whoops")
fmt.Println(err)
// Output: whoops
}
func ExampleNew_printf() {
err := errors.New("whoops")
fmt.Printf("%+v", err)
// Example output:
// whoops
// github.com/pkg/errors_test.ExampleNew_printf
// /home/dfc/src/github.com/pkg/errors/example_test.go:17
// testing.runExample
// /home/dfc/go/src/testing/example.go:114
// testing.RunExamples
// /home/dfc/go/src/testing/example.go:38
// testing.(*M).Run
// /home/dfc/go/src/testing/testing.go:744
// main.main
// /github.com/pkg/errors/_test/_testmain.go:106
// runtime.main
// /home/dfc/go/src/runtime/proc.go:183
// runtime.goexit
// /home/dfc/go/src/runtime/asm_amd64.s:2059
}
func ExampleWithMessage() {
cause := errors.New("whoops")
err := errors.WithMessage(cause, "oh noes")
fmt.Println(err)
// Output: oh noes: whoops
}
func ExampleWithStack() {
cause := errors.New("whoops")
err := errors.WithStack(cause)
fmt.Println(err)
// Output: whoops
}
func ExampleWithStack_printf() {
cause := errors.New("whoops")
err := errors.WithStack(cause)
fmt.Printf("%+v", err)
// Example Output:
// whoops
// github.com/pkg/errors_test.ExampleWithStack_printf
// /home/fabstu/go/src/github.com/pkg/errors/example_test.go:55
// testing.runExample
// /usr/lib/go/src/testing/example.go:114
// testing.RunExamples
// /usr/lib/go/src/testing/example.go:38
// testing.(*M).Run
// /usr/lib/go/src/testing/testing.go:744
// main.main
// github.com/pkg/errors/_test/_testmain.go:106
// runtime.main
// /usr/lib/go/src/runtime/proc.go:183
// runtime.goexit
// /usr/lib/go/src/runtime/asm_amd64.s:2086
// github.com/pkg/errors_test.ExampleWithStack_printf
// /home/fabstu/go/src/github.com/pkg/errors/example_test.go:56
// testing.runExample
// /usr/lib/go/src/testing/example.go:114
// testing.RunExamples
// /usr/lib/go/src/testing/example.go:38
// testing.(*M).Run
// /usr/lib/go/src/testing/testing.go:744
// main.main
// github.com/pkg/errors/_test/_testmain.go:106
// runtime.main
// /usr/lib/go/src/runtime/proc.go:183
// runtime.goexit
// /usr/lib/go/src/runtime/asm_amd64.s:2086
}
func ExampleWrap() {
cause := errors.New("whoops")
err := errors.Wrap(cause, "oh noes")
fmt.Println(err)
// Output: oh noes: whoops
}
func fn() error {
e1 := errors.New("error")
e2 := errors.Wrap(e1, "inner")
e3 := errors.Wrap(e2, "middle")
return errors.Wrap(e3, "outer")
}
func ExampleCause() {
err := fn()
fmt.Println(err)
fmt.Println(errors.Cause(err))
// Output: outer: middle: inner: error
// error
}
func ExampleWrap_extended() {
err := fn()
fmt.Printf("%+v\n", err)
// Example output:
// error
// github.com/pkg/errors_test.fn
// /home/dfc/src/github.com/pkg/errors/example_test.go:47
// github.com/pkg/errors_test.ExampleCause_printf
// /home/dfc/src/github.com/pkg/errors/example_test.go:63
// testing.runExample
// /home/dfc/go/src/testing/example.go:114
// testing.RunExamples
// /home/dfc/go/src/testing/example.go:38
// testing.(*M).Run
// /home/dfc/go/src/testing/testing.go:744
// main.main
// /github.com/pkg/errors/_test/_testmain.go:104
// runtime.main
// /home/dfc/go/src/runtime/proc.go:183
// runtime.goexit
// /home/dfc/go/src/runtime/asm_amd64.s:2059
// github.com/pkg/errors_test.fn
// /home/dfc/src/github.com/pkg/errors/example_test.go:48: inner
// github.com/pkg/errors_test.fn
// /home/dfc/src/github.com/pkg/errors/example_test.go:49: middle
// github.com/pkg/errors_test.fn
// /home/dfc/src/github.com/pkg/errors/example_test.go:50: outer
}
func ExampleWrapf() {
cause := errors.New("whoops")
err := errors.Wrapf(cause, "oh noes #%d", 2)
fmt.Println(err)
// Output: oh noes #2: whoops
}
func ExampleErrorf_extended() {
err := errors.Errorf("whoops: %s", "foo")
fmt.Printf("%+v", err)
// Example output:
// whoops: foo
// github.com/pkg/errors_test.ExampleErrorf
// /home/dfc/src/github.com/pkg/errors/example_test.go:101
// testing.runExample
// /home/dfc/go/src/testing/example.go:114
// testing.RunExamples
// /home/dfc/go/src/testing/example.go:38
// testing.(*M).Run
// /home/dfc/go/src/testing/testing.go:744
// main.main
// /github.com/pkg/errors/_test/_testmain.go:102
// runtime.main
// /home/dfc/go/src/runtime/proc.go:183
// runtime.goexit
// /home/dfc/go/src/runtime/asm_amd64.s:2059
}
func Example_stackTrace() {
type stackTracer interface {
StackTrace() errors.StackTrace
}
err, ok := errors.Cause(fn()).(stackTracer)
if !ok {
panic("oops, err does not implement stackTracer")
}
st := err.StackTrace()
fmt.Printf("%+v", st[0:2]) // top two frames
// Example output:
// github.com/pkg/errors_test.fn
// /home/dfc/src/github.com/pkg/errors/example_test.go:47
// github.com/pkg/errors_test.Example_stackTrace
// /home/dfc/src/github.com/pkg/errors/example_test.go:127
}
func ExampleCause_printf() {
err := errors.Wrap(func() error {
return func() error {
return errors.Errorf("hello %s", fmt.Sprintf("world"))
}()
}(), "failed")
fmt.Printf("%v", err)
// Output: failed: hello world
}

View File

@ -1,535 +0,0 @@
package errors
import (
"errors"
"fmt"
"io"
"regexp"
"strings"
"testing"
)
func TestFormatNew(t *testing.T) {
tests := []struct {
error
format string
want string
}{{
New("error"),
"%s",
"error",
}, {
New("error"),
"%v",
"error",
}, {
New("error"),
"%+v",
"error\n" +
"github.com/pkg/errors.TestFormatNew\n" +
"\t.+/github.com/pkg/errors/format_test.go:26",
}, {
New("error"),
"%q",
`"error"`,
}}
for i, tt := range tests {
testFormatRegexp(t, i, tt.error, tt.format, tt.want)
}
}
func TestFormatErrorf(t *testing.T) {
tests := []struct {
error
format string
want string
}{{
Errorf("%s", "error"),
"%s",
"error",
}, {
Errorf("%s", "error"),
"%v",
"error",
}, {
Errorf("%s", "error"),
"%+v",
"error\n" +
"github.com/pkg/errors.TestFormatErrorf\n" +
"\t.+/github.com/pkg/errors/format_test.go:56",
}}
for i, tt := range tests {
testFormatRegexp(t, i, tt.error, tt.format, tt.want)
}
}
func TestFormatWrap(t *testing.T) {
tests := []struct {
error
format string
want string
}{{
Wrap(New("error"), "error2"),
"%s",
"error2: error",
}, {
Wrap(New("error"), "error2"),
"%v",
"error2: error",
}, {
Wrap(New("error"), "error2"),
"%+v",
"error\n" +
"github.com/pkg/errors.TestFormatWrap\n" +
"\t.+/github.com/pkg/errors/format_test.go:82",
}, {
Wrap(io.EOF, "error"),
"%s",
"error: EOF",
}, {
Wrap(io.EOF, "error"),
"%v",
"error: EOF",
}, {
Wrap(io.EOF, "error"),
"%+v",
"EOF\n" +
"error\n" +
"github.com/pkg/errors.TestFormatWrap\n" +
"\t.+/github.com/pkg/errors/format_test.go:96",
}, {
Wrap(Wrap(io.EOF, "error1"), "error2"),
"%+v",
"EOF\n" +
"error1\n" +
"github.com/pkg/errors.TestFormatWrap\n" +
"\t.+/github.com/pkg/errors/format_test.go:103\n",
}, {
Wrap(New("error with space"), "context"),
"%q",
`"context: error with space"`,
}}
for i, tt := range tests {
testFormatRegexp(t, i, tt.error, tt.format, tt.want)
}
}
func TestFormatWrapf(t *testing.T) {
tests := []struct {
error
format string
want string
}{{
Wrapf(io.EOF, "error%d", 2),
"%s",
"error2: EOF",
}, {
Wrapf(io.EOF, "error%d", 2),
"%v",
"error2: EOF",
}, {
Wrapf(io.EOF, "error%d", 2),
"%+v",
"EOF\n" +
"error2\n" +
"github.com/pkg/errors.TestFormatWrapf\n" +
"\t.+/github.com/pkg/errors/format_test.go:134",
}, {
Wrapf(New("error"), "error%d", 2),
"%s",
"error2: error",
}, {
Wrapf(New("error"), "error%d", 2),
"%v",
"error2: error",
}, {
Wrapf(New("error"), "error%d", 2),
"%+v",
"error\n" +
"github.com/pkg/errors.TestFormatWrapf\n" +
"\t.+/github.com/pkg/errors/format_test.go:149",
}}
for i, tt := range tests {
testFormatRegexp(t, i, tt.error, tt.format, tt.want)
}
}
func TestFormatWithStack(t *testing.T) {
tests := []struct {
error
format string
want []string
}{{
WithStack(io.EOF),
"%s",
[]string{"EOF"},
}, {
WithStack(io.EOF),
"%v",
[]string{"EOF"},
}, {
WithStack(io.EOF),
"%+v",
[]string{"EOF",
"github.com/pkg/errors.TestFormatWithStack\n" +
"\t.+/github.com/pkg/errors/format_test.go:175"},
}, {
WithStack(New("error")),
"%s",
[]string{"error"},
}, {
WithStack(New("error")),
"%v",
[]string{"error"},
}, {
WithStack(New("error")),
"%+v",
[]string{"error",
"github.com/pkg/errors.TestFormatWithStack\n" +
"\t.+/github.com/pkg/errors/format_test.go:189",
"github.com/pkg/errors.TestFormatWithStack\n" +
"\t.+/github.com/pkg/errors/format_test.go:189"},
}, {
WithStack(WithStack(io.EOF)),
"%+v",
[]string{"EOF",
"github.com/pkg/errors.TestFormatWithStack\n" +
"\t.+/github.com/pkg/errors/format_test.go:197",
"github.com/pkg/errors.TestFormatWithStack\n" +
"\t.+/github.com/pkg/errors/format_test.go:197"},
}, {
WithStack(WithStack(Wrapf(io.EOF, "message"))),
"%+v",
[]string{"EOF",
"message",
"github.com/pkg/errors.TestFormatWithStack\n" +
"\t.+/github.com/pkg/errors/format_test.go:205",
"github.com/pkg/errors.TestFormatWithStack\n" +
"\t.+/github.com/pkg/errors/format_test.go:205",
"github.com/pkg/errors.TestFormatWithStack\n" +
"\t.+/github.com/pkg/errors/format_test.go:205"},
}, {
WithStack(Errorf("error%d", 1)),
"%+v",
[]string{"error1",
"github.com/pkg/errors.TestFormatWithStack\n" +
"\t.+/github.com/pkg/errors/format_test.go:216",
"github.com/pkg/errors.TestFormatWithStack\n" +
"\t.+/github.com/pkg/errors/format_test.go:216"},
}}
for i, tt := range tests {
testFormatCompleteCompare(t, i, tt.error, tt.format, tt.want, true)
}
}
func TestFormatWithMessage(t *testing.T) {
tests := []struct {
error
format string
want []string
}{{
WithMessage(New("error"), "error2"),
"%s",
[]string{"error2: error"},
}, {
WithMessage(New("error"), "error2"),
"%v",
[]string{"error2: error"},
}, {
WithMessage(New("error"), "error2"),
"%+v",
[]string{
"error",
"github.com/pkg/errors.TestFormatWithMessage\n" +
"\t.+/github.com/pkg/errors/format_test.go:244",
"error2"},
}, {
WithMessage(io.EOF, "addition1"),
"%s",
[]string{"addition1: EOF"},
}, {
WithMessage(io.EOF, "addition1"),
"%v",
[]string{"addition1: EOF"},
}, {
WithMessage(io.EOF, "addition1"),
"%+v",
[]string{"EOF", "addition1"},
}, {
WithMessage(WithMessage(io.EOF, "addition1"), "addition2"),
"%v",
[]string{"addition2: addition1: EOF"},
}, {
WithMessage(WithMessage(io.EOF, "addition1"), "addition2"),
"%+v",
[]string{"EOF", "addition1", "addition2"},
}, {
Wrap(WithMessage(io.EOF, "error1"), "error2"),
"%+v",
[]string{"EOF", "error1", "error2",
"github.com/pkg/errors.TestFormatWithMessage\n" +
"\t.+/github.com/pkg/errors/format_test.go:272"},
}, {
WithMessage(Errorf("error%d", 1), "error2"),
"%+v",
[]string{"error1",
"github.com/pkg/errors.TestFormatWithMessage\n" +
"\t.+/github.com/pkg/errors/format_test.go:278",
"error2"},
}, {
WithMessage(WithStack(io.EOF), "error"),
"%+v",
[]string{
"EOF",
"github.com/pkg/errors.TestFormatWithMessage\n" +
"\t.+/github.com/pkg/errors/format_test.go:285",
"error"},
}, {
WithMessage(Wrap(WithStack(io.EOF), "inside-error"), "outside-error"),
"%+v",
[]string{
"EOF",
"github.com/pkg/errors.TestFormatWithMessage\n" +
"\t.+/github.com/pkg/errors/format_test.go:293",
"inside-error",
"github.com/pkg/errors.TestFormatWithMessage\n" +
"\t.+/github.com/pkg/errors/format_test.go:293",
"outside-error"},
}}
for i, tt := range tests {
testFormatCompleteCompare(t, i, tt.error, tt.format, tt.want, true)
}
}
func TestFormatGeneric(t *testing.T) {
starts := []struct {
err error
want []string
}{
{New("new-error"), []string{
"new-error",
"github.com/pkg/errors.TestFormatGeneric\n" +
"\t.+/github.com/pkg/errors/format_test.go:315"},
}, {Errorf("errorf-error"), []string{
"errorf-error",
"github.com/pkg/errors.TestFormatGeneric\n" +
"\t.+/github.com/pkg/errors/format_test.go:319"},
}, {errors.New("errors-new-error"), []string{
"errors-new-error"},
},
}
wrappers := []wrapper{
{
func(err error) error { return WithMessage(err, "with-message") },
[]string{"with-message"},
}, {
func(err error) error { return WithStack(err) },
[]string{
"github.com/pkg/errors.(func·002|TestFormatGeneric.func2)\n\t" +
".+/github.com/pkg/errors/format_test.go:333",
},
}, {
func(err error) error { return Wrap(err, "wrap-error") },
[]string{
"wrap-error",
"github.com/pkg/errors.(func·003|TestFormatGeneric.func3)\n\t" +
".+/github.com/pkg/errors/format_test.go:339",
},
}, {
func(err error) error { return Wrapf(err, "wrapf-error%d", 1) },
[]string{
"wrapf-error1",
"github.com/pkg/errors.(func·004|TestFormatGeneric.func4)\n\t" +
".+/github.com/pkg/errors/format_test.go:346",
},
},
}
for s := range starts {
err := starts[s].err
want := starts[s].want
testFormatCompleteCompare(t, s, err, "%+v", want, false)
testGenericRecursive(t, err, want, wrappers, 3)
}
}
func testFormatRegexp(t *testing.T, n int, arg interface{}, format, want string) {
got := fmt.Sprintf(format, arg)
gotLines := strings.SplitN(got, "\n", -1)
wantLines := strings.SplitN(want, "\n", -1)
if len(wantLines) > len(gotLines) {
t.Errorf("test %d: wantLines(%d) > gotLines(%d):\n got: %q\nwant: %q", n+1, len(wantLines), len(gotLines), got, want)
return
}
for i, w := range wantLines {
match, err := regexp.MatchString(w, gotLines[i])
if err != nil {
t.Fatal(err)
}
if !match {
t.Errorf("test %d: line %d: fmt.Sprintf(%q, err):\n got: %q\nwant: %q", n+1, i+1, format, got, want)
}
}
}
var stackLineR = regexp.MustCompile(`\.`)
// parseBlocks parses input into a slice, where:
// - incase entry contains a newline, its a stacktrace
// - incase entry contains no newline, its a solo line.
//
// Detecting stack boundaries only works incase the WithStack-calls are
// to be found on the same line, thats why it is optionally here.
//
// Example use:
//
// for _, e := range blocks {
// if strings.ContainsAny(e, "\n") {
// // Match as stack
// } else {
// // Match as line
// }
// }
//
func parseBlocks(input string, detectStackboundaries bool) ([]string, error) {
var blocks []string
stack := ""
wasStack := false
lines := map[string]bool{} // already found lines
for _, l := range strings.Split(input, "\n") {
isStackLine := stackLineR.MatchString(l)
switch {
case !isStackLine && wasStack:
blocks = append(blocks, stack, l)
stack = ""
lines = map[string]bool{}
case isStackLine:
if wasStack {
// Detecting two stacks after another, possible cause lines match in
// our tests due to WithStack(WithStack(io.EOF)) on same line.
if detectStackboundaries {
if lines[l] {
if len(stack) == 0 {
return nil, errors.New("len of block must not be zero here")
}
blocks = append(blocks, stack)
stack = l
lines = map[string]bool{l: true}
continue
}
}
stack = stack + "\n" + l
} else {
stack = l
}
lines[l] = true
case !isStackLine && !wasStack:
blocks = append(blocks, l)
default:
return nil, errors.New("must not happen")
}
wasStack = isStackLine
}
// Use up stack
if stack != "" {
blocks = append(blocks, stack)
}
return blocks, nil
}
func testFormatCompleteCompare(t *testing.T, n int, arg interface{}, format string, want []string, detectStackBoundaries bool) {
gotStr := fmt.Sprintf(format, arg)
got, err := parseBlocks(gotStr, detectStackBoundaries)
if err != nil {
t.Fatal(err)
}
if len(got) != len(want) {
t.Fatalf("test %d: fmt.Sprintf(%s, err) -> wrong number of blocks: got(%d) want(%d)\n got: %s\nwant: %s\ngotStr: %q",
n+1, format, len(got), len(want), prettyBlocks(got), prettyBlocks(want), gotStr)
}
for i := range got {
if strings.ContainsAny(want[i], "\n") {
// Match as stack
match, err := regexp.MatchString(want[i], got[i])
if err != nil {
t.Fatal(err)
}
if !match {
t.Fatalf("test %d: block %d: fmt.Sprintf(%q, err):\ngot:\n%q\nwant:\n%q\nall-got:\n%s\nall-want:\n%s\n",
n+1, i+1, format, got[i], want[i], prettyBlocks(got), prettyBlocks(want))
}
} else {
// Match as message
if got[i] != want[i] {
t.Fatalf("test %d: fmt.Sprintf(%s, err) at block %d got != want:\n got: %q\nwant: %q", n+1, format, i+1, got[i], want[i])
}
}
}
}
type wrapper struct {
wrap func(err error) error
want []string
}
func prettyBlocks(blocks []string, prefix ...string) string {
var out []string
for _, b := range blocks {
out = append(out, fmt.Sprintf("%v", b))
}
return " " + strings.Join(out, "\n ")
}
func testGenericRecursive(t *testing.T, beforeErr error, beforeWant []string, list []wrapper, maxDepth int) {
if len(beforeWant) == 0 {
panic("beforeWant must not be empty")
}
for _, w := range list {
if len(w.want) == 0 {
panic("want must not be empty")
}
err := w.wrap(beforeErr)
// Copy required cause append(beforeWant, ..) modified beforeWant subtly.
beforeCopy := make([]string, len(beforeWant))
copy(beforeCopy, beforeWant)
beforeWant := beforeCopy
last := len(beforeWant) - 1
var want []string
// Merge two stacks behind each other.
if strings.ContainsAny(beforeWant[last], "\n") && strings.ContainsAny(w.want[0], "\n") {
want = append(beforeWant[:last], append([]string{beforeWant[last] + "((?s).*)" + w.want[0]}, w.want[1:]...)...)
} else {
want = append(beforeWant, w.want...)
}
testFormatCompleteCompare(t, maxDepth, err, "%+v", want, false)
if maxDepth > 0 {
testGenericRecursive(t, err, want, list, maxDepth-1)
}
}
}

178
vendor/github.com/pkg/errors/stack.go generated vendored
View File

@ -1,178 +0,0 @@
package errors
import (
"fmt"
"io"
"path"
"runtime"
"strings"
)
// Frame represents a program counter inside a stack frame.
type Frame uintptr
// pc returns the program counter for this frame;
// multiple frames may have the same PC value.
func (f Frame) pc() uintptr { return uintptr(f) - 1 }
// file returns the full path to the file that contains the
// function for this Frame's pc.
func (f Frame) file() string {
fn := runtime.FuncForPC(f.pc())
if fn == nil {
return "unknown"
}
file, _ := fn.FileLine(f.pc())
return file
}
// line returns the line number of source code of the
// function for this Frame's pc.
func (f Frame) line() int {
fn := runtime.FuncForPC(f.pc())
if fn == nil {
return 0
}
_, line := fn.FileLine(f.pc())
return line
}
// Format formats the frame according to the fmt.Formatter interface.
//
// %s source file
// %d source line
// %n function name
// %v equivalent to %s:%d
//
// Format accepts flags that alter the printing of some verbs, as follows:
//
// %+s path of source file relative to the compile time GOPATH
// %+v equivalent to %+s:%d
func (f Frame) Format(s fmt.State, verb rune) {
switch verb {
case 's':
switch {
case s.Flag('+'):
pc := f.pc()
fn := runtime.FuncForPC(pc)
if fn == nil {
io.WriteString(s, "unknown")
} else {
file, _ := fn.FileLine(pc)
fmt.Fprintf(s, "%s\n\t%s", fn.Name(), file)
}
default:
io.WriteString(s, path.Base(f.file()))
}
case 'd':
fmt.Fprintf(s, "%d", f.line())
case 'n':
name := runtime.FuncForPC(f.pc()).Name()
io.WriteString(s, funcname(name))
case 'v':
f.Format(s, 's')
io.WriteString(s, ":")
f.Format(s, 'd')
}
}
// StackTrace is stack of Frames from innermost (newest) to outermost (oldest).
type StackTrace []Frame
func (st StackTrace) Format(s fmt.State, verb rune) {
switch verb {
case 'v':
switch {
case s.Flag('+'):
for _, f := range st {
fmt.Fprintf(s, "\n%+v", f)
}
case s.Flag('#'):
fmt.Fprintf(s, "%#v", []Frame(st))
default:
fmt.Fprintf(s, "%v", []Frame(st))
}
case 's':
fmt.Fprintf(s, "%s", []Frame(st))
}
}
// stack represents a stack of program counters.
type stack []uintptr
func (s *stack) Format(st fmt.State, verb rune) {
switch verb {
case 'v':
switch {
case st.Flag('+'):
for _, pc := range *s {
f := Frame(pc)
fmt.Fprintf(st, "\n%+v", f)
}
}
}
}
func (s *stack) StackTrace() StackTrace {
f := make([]Frame, len(*s))
for i := 0; i < len(f); i++ {
f[i] = Frame((*s)[i])
}
return f
}
func callers() *stack {
const depth = 32
var pcs [depth]uintptr
n := runtime.Callers(3, pcs[:])
var st stack = pcs[0:n]
return &st
}
// funcname removes the path prefix component of a function's name reported by func.Name().
func funcname(name string) string {
i := strings.LastIndex(name, "/")
name = name[i+1:]
i = strings.Index(name, ".")
return name[i+1:]
}
func trimGOPATH(name, file string) string {
// Here we want to get the source file path relative to the compile time
// GOPATH. As of Go 1.6.x there is no direct way to know the compiled
// GOPATH at runtime, but we can infer the number of path segments in the
// GOPATH. We note that fn.Name() returns the function name qualified by
// the import path, which does not include the GOPATH. Thus we can trim
// segments from the beginning of the file path until the number of path
// separators remaining is one more than the number of path separators in
// the function name. For example, given:
//
// GOPATH /home/user
// file /home/user/src/pkg/sub/file.go
// fn.Name() pkg/sub.Type.Method
//
// We want to produce:
//
// pkg/sub/file.go
//
// From this we can easily see that fn.Name() has one less path separator
// than our desired output. We count separators from the end of the file
// path until it finds two more than in the function name and then move
// one character forward to preserve the initial path segment without a
// leading separator.
const sep = "/"
goal := strings.Count(name, sep) + 2
i := len(file)
for n := 0; n < goal; n++ {
i = strings.LastIndex(file[:i], sep)
if i == -1 {
// not enough separators found, set i so that the slice expression
// below leaves file unmodified
i = -len(sep)
break
}
}
// get back to 0 or trim the leading separator
file = file[i+len(sep):]
return file
}

View File

@ -1,292 +0,0 @@
package errors
import (
"fmt"
"runtime"
"testing"
)
var initpc, _, _, _ = runtime.Caller(0)
func TestFrameLine(t *testing.T) {
var tests = []struct {
Frame
want int
}{{
Frame(initpc),
9,
}, {
func() Frame {
var pc, _, _, _ = runtime.Caller(0)
return Frame(pc)
}(),
20,
}, {
func() Frame {
var pc, _, _, _ = runtime.Caller(1)
return Frame(pc)
}(),
28,
}, {
Frame(0), // invalid PC
0,
}}
for _, tt := range tests {
got := tt.Frame.line()
want := tt.want
if want != got {
t.Errorf("Frame(%v): want: %v, got: %v", uintptr(tt.Frame), want, got)
}
}
}
type X struct{}
func (x X) val() Frame {
var pc, _, _, _ = runtime.Caller(0)
return Frame(pc)
}
func (x *X) ptr() Frame {
var pc, _, _, _ = runtime.Caller(0)
return Frame(pc)
}
func TestFrameFormat(t *testing.T) {
var tests = []struct {
Frame
format string
want string
}{{
Frame(initpc),
"%s",
"stack_test.go",
}, {
Frame(initpc),
"%+s",
"github.com/pkg/errors.init\n" +
"\t.+/github.com/pkg/errors/stack_test.go",
}, {
Frame(0),
"%s",
"unknown",
}, {
Frame(0),
"%+s",
"unknown",
}, {
Frame(initpc),
"%d",
"9",
}, {
Frame(0),
"%d",
"0",
}, {
Frame(initpc),
"%n",
"init",
}, {
func() Frame {
var x X
return x.ptr()
}(),
"%n",
`\(\*X\).ptr`,
}, {
func() Frame {
var x X
return x.val()
}(),
"%n",
"X.val",
}, {
Frame(0),
"%n",
"",
}, {
Frame(initpc),
"%v",
"stack_test.go:9",
}, {
Frame(initpc),
"%+v",
"github.com/pkg/errors.init\n" +
"\t.+/github.com/pkg/errors/stack_test.go:9",
}, {
Frame(0),
"%v",
"unknown:0",
}}
for i, tt := range tests {
testFormatRegexp(t, i, tt.Frame, tt.format, tt.want)
}
}
func TestFuncname(t *testing.T) {
tests := []struct {
name, want string
}{
{"", ""},
{"runtime.main", "main"},
{"github.com/pkg/errors.funcname", "funcname"},
{"funcname", "funcname"},
{"io.copyBuffer", "copyBuffer"},
{"main.(*R).Write", "(*R).Write"},
}
for _, tt := range tests {
got := funcname(tt.name)
want := tt.want
if got != want {
t.Errorf("funcname(%q): want: %q, got %q", tt.name, want, got)
}
}
}
func TestTrimGOPATH(t *testing.T) {
var tests = []struct {
Frame
want string
}{{
Frame(initpc),
"github.com/pkg/errors/stack_test.go",
}}
for i, tt := range tests {
pc := tt.Frame.pc()
fn := runtime.FuncForPC(pc)
file, _ := fn.FileLine(pc)
got := trimGOPATH(fn.Name(), file)
testFormatRegexp(t, i, got, "%s", tt.want)
}
}
func TestStackTrace(t *testing.T) {
tests := []struct {
err error
want []string
}{{
New("ooh"), []string{
"github.com/pkg/errors.TestStackTrace\n" +
"\t.+/github.com/pkg/errors/stack_test.go:172",
},
}, {
Wrap(New("ooh"), "ahh"), []string{
"github.com/pkg/errors.TestStackTrace\n" +
"\t.+/github.com/pkg/errors/stack_test.go:177", // this is the stack of Wrap, not New
},
}, {
Cause(Wrap(New("ooh"), "ahh")), []string{
"github.com/pkg/errors.TestStackTrace\n" +
"\t.+/github.com/pkg/errors/stack_test.go:182", // this is the stack of New
},
}, {
func() error { return New("ooh") }(), []string{
`github.com/pkg/errors.(func·009|TestStackTrace.func1)` +
"\n\t.+/github.com/pkg/errors/stack_test.go:187", // this is the stack of New
"github.com/pkg/errors.TestStackTrace\n" +
"\t.+/github.com/pkg/errors/stack_test.go:187", // this is the stack of New's caller
},
}, {
Cause(func() error {
return func() error {
return Errorf("hello %s", fmt.Sprintf("world"))
}()
}()), []string{
`github.com/pkg/errors.(func·010|TestStackTrace.func2.1)` +
"\n\t.+/github.com/pkg/errors/stack_test.go:196", // this is the stack of Errorf
`github.com/pkg/errors.(func·011|TestStackTrace.func2)` +
"\n\t.+/github.com/pkg/errors/stack_test.go:197", // this is the stack of Errorf's caller
"github.com/pkg/errors.TestStackTrace\n" +
"\t.+/github.com/pkg/errors/stack_test.go:198", // this is the stack of Errorf's caller's caller
},
}}
for i, tt := range tests {
x, ok := tt.err.(interface {
StackTrace() StackTrace
})
if !ok {
t.Errorf("expected %#v to implement StackTrace() StackTrace", tt.err)
continue
}
st := x.StackTrace()
for j, want := range tt.want {
testFormatRegexp(t, i, st[j], "%+v", want)
}
}
}
func stackTrace() StackTrace {
const depth = 8
var pcs [depth]uintptr
n := runtime.Callers(1, pcs[:])
var st stack = pcs[0:n]
return st.StackTrace()
}
func TestStackTraceFormat(t *testing.T) {
tests := []struct {
StackTrace
format string
want string
}{{
nil,
"%s",
`\[\]`,
}, {
nil,
"%v",
`\[\]`,
}, {
nil,
"%+v",
"",
}, {
nil,
"%#v",
`\[\]errors.Frame\(nil\)`,
}, {
make(StackTrace, 0),
"%s",
`\[\]`,
}, {
make(StackTrace, 0),
"%v",
`\[\]`,
}, {
make(StackTrace, 0),
"%+v",
"",
}, {
make(StackTrace, 0),
"%#v",
`\[\]errors.Frame{}`,
}, {
stackTrace()[:2],
"%s",
`\[stack_test.go stack_test.go\]`,
}, {
stackTrace()[:2],
"%v",
`\[stack_test.go:225 stack_test.go:272\]`,
}, {
stackTrace()[:2],
"%+v",
"\n" +
"github.com/pkg/errors.stackTrace\n" +
"\t.+/github.com/pkg/errors/stack_test.go:225\n" +
"github.com/pkg/errors.TestStackTraceFormat\n" +
"\t.+/github.com/pkg/errors/stack_test.go:276",
}, {
stackTrace()[:2],
"%#v",
`\[\]errors.Frame{stack_test.go:225, stack_test.go:284}`,
}}
for i, tt := range tests {
testFormatRegexp(t, i, tt.StackTrace, tt.format, tt.want)
}
}

View File

@ -1,2 +0,0 @@
bin/
*.sw?

View File

@ -1,11 +0,0 @@
sudo: false
language: go
go:
- 1.9
- tip
install:
- make build
script:
- make test

View File

@ -1,22 +0,0 @@
MIT License
Copyright (c) 2015 Pressly Inc. www.pressly.com
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.

View File

@ -1,44 +0,0 @@
.PHONY: all build dist test install clean tools deps update-deps
all:
@echo "build - Build sup"
@echo "dist - Build sup distribution binaries"
@echo "test - Run tests"
@echo "install - Install binary"
@echo "clean - Clean up"
@echo ""
@echo "tools - Install tools"
@echo "vendor-list - List vendor package tree"
@echo "vendor-update - Update vendored packages"
build:
@mkdir -p ./bin
@rm -f ./bin/*
go build -o ./bin/sup ./cmd/sup
dist:
@mkdir -p ./bin
@rm -f ./bin/*
GOOS=darwin GOARCH=amd64 go build -o ./bin/sup-darwin64 ./cmd/sup
GOOS=linux GOARCH=amd64 go build -o ./bin/sup-linux64 ./cmd/sup
GOOS=linux GOARCH=386 go build -o ./bin/sup-linux386 ./cmd/sup
GOOS=windows GOARCH=amd64 go build -o ./bin/sup-windows64.exe ./cmd/sup
GOOS=windows GOARCH=386 go build -o ./bin/sup-windows386.exe ./cmd/sup
test:
go test ./...
install:
go install ./cmd/sup
clean:
@rm -rf ./bin
tools:
go get -u github.com/kardianos/govendor
vendor-list:
@govendor list
vendor-update:
@govendor update +external

View File

@ -1,326 +0,0 @@
Stack Up
========
Stack Up is a simple deployment tool that performs given set of commands on multiple hosts in parallel. It reads Supfile, a YAML configuration file, which defines networks (groups of hosts), commands and targets.
# Demo
[![Sup](https://github.com/pressly/sup/blob/gif/asciinema.gif?raw=true)](https://asciinema.org/a/19742?autoplay=1)
*Note: Demo is based on [this example Supfile](./example/Supfile).*
# Installation
$ go get -u github.com/pressly/sup/cmd/sup
# Usage
$ sup [OPTIONS] NETWORK COMMAND [...]
### Options
| Option | Description |
|-------------------|----------------------------------|
| `-f Supfile` | Custom path to Supfile |
| `-e`, `--env=[]` | Set environment variables |
| `--only REGEXP` | Filter hosts matching regexp |
| `--except REGEXP` | Filter out hosts matching regexp |
| `--debug`, `-D` | Enable debug/verbose mode |
| `--disable-prefix`| Disable hostname prefix |
| `--help`, `-h` | Show help/usage |
| `--version`, `-v` | Print version |
## Network
A group of hosts.
```yaml
# Supfile
networks:
production:
hosts:
- api1.example.com
- api2.example.com
- api3.example.com
staging:
# fetch dynamic list of hosts
inventory: curl http://example.com/latest/meta-data/hostname
```
`$ sup production COMMAND` will run COMMAND on `api1`, `api2` and `api3` hosts in parallel.
## Command
A shell command(s) to be run remotely.
```yaml
# Supfile
commands:
restart:
desc: Restart example Docker container
run: sudo docker restart example
tail-logs:
desc: Watch tail of Docker logs from all hosts
run: sudo docker logs --tail=20 -f example
```
`$ sup staging restart` will restart all staging Docker containers in parallel.
`$ sup production tail-logs` will tail Docker logs from all production containers in parallel.
### Serial command (a.k.a. Rolling Update)
`serial: N` constraints a command to be run on `N` hosts at a time at maximum. Rolling Update for free!
```yaml
# Supfile
commands:
restart:
desc: Restart example Docker container
run: sudo docker restart example
serial: 2
```
`$ sup production restart` will restart all Docker containers, two at a time at maximum.
### Once command (one host only)
`once: true` constraints a command to be run only on one host. Useful for one-time tasks.
```yaml
# Supfile
commands:
build:
desc: Build Docker image and push to registry
run: sudo docker build -t image:latest . && sudo docker push image:latest
once: true # one host only
pull:
desc: Pull latest Docker image from registry
run: sudo docker pull image:latest
```
`$ sup production build pull` will build Docker image on one production host only and spread it to all hosts.
### Local command
Runs command always on localhost.
```yaml
# Supfile
commands:
prepare:
desc: Prepare to upload
local: npm run build
```
### Upload command
Uploads files/directories to all remote hosts. Uses `tar` under the hood.
```yaml
# Supfile
commands:
upload:
desc: Upload dist files to all hosts
upload:
- src: ./dist
dst: /tmp/
```
### Interactive Bash on all hosts
Do you want to interact with multiple hosts at once? Sure!
```yaml
# Supfile
commands:
bash:
desc: Interactive Bash on all hosts
stdin: true
run: bash
```
```bash
$ sup production bash
#
# type in commands and see output from all hosts!
# ^C
```
Passing prepared commands to all hosts:
```bash
$ echo 'sudo apt-get update -y' | sup production bash
# or:
$ sup production bash <<< 'sudo apt-get update -y'
# or:
$ cat <<EOF | sup production bash
sudo apt-get update -y
date
uname -a
EOF
```
### Interactive Docker Exec on all hosts
```yaml
# Supfile
commands:
exec:
desc: Exec into Docker container on all hosts
stdin: true
run: sudo docker exec -i $CONTAINER bash
```
```bash
$ sup production exec
ps aux
strace -p 1 # trace system calls and signals on all your production hosts
```
## Target
Target is an alias for multiple commands. Each command will be run on all hosts in parallel,
`sup` will check return status from all hosts, and run subsequent commands on success only
(thus any error on any host will interrupt the process).
```yaml
# Supfile
targets:
deploy:
- build
- pull
- migrate-db-up
- stop-rm-run
- health
- slack-notify
- airbrake-notify
```
`$ sup production deploy`
is equivalent to
`$ sup production build pull migrate-db-up stop-rm-run health slack-notify airbrake-notify`
# Supfile
See [example Supfile](./example/Supfile).
### Basic structure
```yaml
# Supfile
---
version: 0.4
# Global environment variables
env:
NAME: api
IMAGE: example/api
networks:
local:
hosts:
- localhost
staging:
hosts:
- stg1.example.com
production:
hosts:
- api1.example.com
- api2.example.com
commands:
echo:
desc: Print some env vars
run: echo $NAME $IMAGE $SUP_NETWORK
date:
desc: Print OS name and current date/time
run: uname -a; date
targets:
all:
- echo
- date
```
### Default environment variables available in Supfile
- `$SUP_HOST` - Current host.
- `$SUP_NETWORK` - Current network.
- `$SUP_USER` - User who invoked sup command.
- `$SUP_TIME` - Date/time of sup command invocation.
- `$SUP_ENV` - Environment variables provided on sup command invocation. You can pass `$SUP_ENV` to another `sup` or `docker` commands in your Supfile.
# Running sup from Supfile
Supfile doesn't let you import another Supfile. Instead, it lets you run `sup` sub-process from inside your Supfile. This is how you can structure larger projects:
```
./Supfile
./database/Supfile
./services/scheduler/Supfile
```
Top-level Supfile calls `sup` with Supfiles from sub-projects:
```yaml
restart-scheduler:
desc: Restart scheduler
local: >
sup -f ./services/scheduler/Supfile $SUP_ENV $SUP_NETWORK restart
db-up:
desc: Migrate database
local: >
sup -f ./database/Supfile $SUP_ENV $SUP_NETWORK up
```
# Common SSH Problem
if for some reason sup doesn't connect and you get the following error,
```bash
connecting to clients failed: connecting to remote host failed: Connect("myserver@xxx.xxx.xxx.xxx"): ssh: handshake failed: ssh: unable to authenticate, attempted methods [none publickey], no supported methods remain
```
it means that your `ssh-agent` dosen't have access to your public and private keys. in order to fix this issue, follow the below instructions:
- run the following command and make sure you have a key register with `ssh-agent`
```bash
ssh-add -l
```
if you see something like `The agent has no identities.` it means that you need to manually add your key to `ssh-agent`.
in order to do that, run the following command
```bash
ssh-add ~/.ssh/id_rsa
```
you should now be able to use sup with your ssh key.
# Development
fork it, hack it..
$ make build
create new Pull Request
We'll be happy to review & accept new Pull Requests!
# License
Licensed under the [MIT License](./LICENSE).

View File

@ -1,20 +0,0 @@
package sup
import (
"io"
"os"
)
type Client interface {
Connect(host string) error
Run(task *Task) error
Wait() error
Close() error
Prefix() (string, int)
Write(p []byte) (n int, err error)
WriteClose() error
Stdin() io.WriteCloser
Stderr() io.Reader
Stdout() io.Reader
Signal(os.Signal) error
}

View File

@ -1,383 +0,0 @@
package main
import (
"flag"
"fmt"
"io/ioutil"
"os"
"os/user"
"path/filepath"
"regexp"
"strings"
"text/tabwriter"
"time"
"github.com/mikkeloscar/sshconfig"
"github.com/pkg/errors"
"github.com/pressly/sup"
)
var (
supfile string
envVars flagStringSlice
sshConfig string
onlyHosts string
exceptHosts string
debug bool
disablePrefix bool
showVersion bool
showHelp bool
ErrUsage = errors.New("Usage: sup [OPTIONS] NETWORK COMMAND [...]\n sup [ --help | -v | --version ]")
ErrUnknownNetwork = errors.New("Unknown network")
ErrNetworkNoHosts = errors.New("No hosts defined for a given network")
ErrCmd = errors.New("Unknown command/target")
ErrTargetNoCommands = errors.New("No commands defined for a given target")
ErrConfigFile = errors.New("Unknown ssh_config file")
)
type flagStringSlice []string
func (f *flagStringSlice) String() string {
return fmt.Sprintf("%v", *f)
}
func (f *flagStringSlice) Set(value string) error {
*f = append(*f, value)
return nil
}
func init() {
flag.StringVar(&supfile, "f", "", "Custom path to ./Supfile[.yml]")
flag.Var(&envVars, "e", "Set environment variables")
flag.Var(&envVars, "env", "Set environment variables")
flag.StringVar(&sshConfig, "sshconfig", "", "Read SSH Config file, ie. ~/.ssh/config file")
flag.StringVar(&onlyHosts, "only", "", "Filter hosts using regexp")
flag.StringVar(&exceptHosts, "except", "", "Filter out hosts using regexp")
flag.BoolVar(&debug, "D", false, "Enable debug mode")
flag.BoolVar(&debug, "debug", false, "Enable debug mode")
flag.BoolVar(&disablePrefix, "disable-prefix", false, "Disable hostname prefix")
flag.BoolVar(&showVersion, "v", false, "Print version")
flag.BoolVar(&showVersion, "version", false, "Print version")
flag.BoolVar(&showHelp, "h", false, "Show help")
flag.BoolVar(&showHelp, "help", false, "Show help")
}
func networkUsage(conf *sup.Supfile) {
w := &tabwriter.Writer{}
w.Init(os.Stderr, 4, 4, 2, ' ', 0)
defer w.Flush()
// Print available networks/hosts.
fmt.Fprintln(w, "Networks:\t")
for _, name := range conf.Networks.Names {
fmt.Fprintf(w, "- %v\n", name)
network, _ := conf.Networks.Get(name)
for _, host := range network.Hosts {
fmt.Fprintf(w, "\t- %v\n", host)
}
}
fmt.Fprintln(w)
}
func cmdUsage(conf *sup.Supfile) {
w := &tabwriter.Writer{}
w.Init(os.Stderr, 4, 4, 2, ' ', 0)
defer w.Flush()
// Print available targets/commands.
fmt.Fprintln(w, "Targets:\t")
for _, name := range conf.Targets.Names {
cmds, _ := conf.Targets.Get(name)
fmt.Fprintf(w, "- %v\t%v\n", name, strings.Join(cmds, " "))
}
fmt.Fprintln(w, "\t")
fmt.Fprintln(w, "Commands:\t")
for _, name := range conf.Commands.Names {
cmd, _ := conf.Commands.Get(name)
fmt.Fprintf(w, "- %v\t%v\n", name, cmd.Desc)
}
fmt.Fprintln(w)
}
// parseArgs parses args and returns network and commands to be run.
// On error, it prints usage and exits.
func parseArgs(conf *sup.Supfile) (*sup.Network, []*sup.Command, error) {
var commands []*sup.Command
args := flag.Args()
if len(args) < 1 {
networkUsage(conf)
return nil, nil, ErrUsage
}
// Does the <network> exist?
network, ok := conf.Networks.Get(args[0])
if !ok {
networkUsage(conf)
return nil, nil, ErrUnknownNetwork
}
// Parse CLI --env flag env vars, override values defined in Network env.
for _, env := range envVars {
if len(env) == 0 {
continue
}
i := strings.Index(env, "=")
if i < 0 {
if len(env) > 0 {
network.Env.Set(env, "")
}
continue
}
network.Env.Set(env[:i], env[i+1:])
}
hosts, err := network.ParseInventory()
if err != nil {
return nil, nil, err
}
network.Hosts = append(network.Hosts, hosts...)
// Does the <network> have at least one host?
if len(network.Hosts) == 0 {
networkUsage(conf)
return nil, nil, ErrNetworkNoHosts
}
// Check for the second argument
if len(args) < 2 {
cmdUsage(conf)
return nil, nil, ErrUsage
}
// In case of the network.Env needs an initialization
if network.Env == nil {
network.Env = make(sup.EnvList, 0)
}
// Add default env variable with current network
network.Env.Set("SUP_NETWORK", args[0])
// Add default nonce
network.Env.Set("SUP_TIME", time.Now().UTC().Format(time.RFC3339))
if os.Getenv("SUP_TIME") != "" {
network.Env.Set("SUP_TIME", os.Getenv("SUP_TIME"))
}
// Add user
if os.Getenv("SUP_USER") != "" {
network.Env.Set("SUP_USER", os.Getenv("SUP_USER"))
} else {
network.Env.Set("SUP_USER", os.Getenv("USER"))
}
for _, cmd := range args[1:] {
// Target?
target, isTarget := conf.Targets.Get(cmd)
if isTarget {
// Loop over target's commands.
for _, cmd := range target {
command, isCommand := conf.Commands.Get(cmd)
if !isCommand {
cmdUsage(conf)
return nil, nil, fmt.Errorf("%v: %v", ErrCmd, cmd)
}
command.Name = cmd
commands = append(commands, &command)
}
}
// Command?
command, isCommand := conf.Commands.Get(cmd)
if isCommand {
command.Name = cmd
commands = append(commands, &command)
}
if !isTarget && !isCommand {
cmdUsage(conf)
return nil, nil, fmt.Errorf("%v: %v", ErrCmd, cmd)
}
}
return &network, commands, nil
}
func resolvePath(path string) string {
if path == "" {
return ""
}
if path[:2] == "~/" {
usr, err := user.Current()
if err == nil {
path = filepath.Join(usr.HomeDir, path[2:])
}
}
return path
}
func main() {
flag.Parse()
if showHelp {
fmt.Fprintln(os.Stderr, ErrUsage, "\n\nOptions:")
flag.PrintDefaults()
return
}
if showVersion {
fmt.Fprintln(os.Stderr, sup.VERSION)
return
}
if supfile == "" {
supfile = "./Supfile"
}
data, err := ioutil.ReadFile(resolvePath(supfile))
if err != nil {
firstErr := err
data, err = ioutil.ReadFile("./Supfile.yml") // Alternative to ./Supfile.
if err != nil {
fmt.Fprintln(os.Stderr, firstErr)
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
conf, err := sup.NewSupfile(data)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
// Parse network and commands to be run from args.
network, commands, err := parseArgs(conf)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
// --only flag filters hosts
if onlyHosts != "" {
expr, err := regexp.CompilePOSIX(onlyHosts)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
var hosts []string
for _, host := range network.Hosts {
if expr.MatchString(host) {
hosts = append(hosts, host)
}
}
if len(hosts) == 0 {
fmt.Fprintln(os.Stderr, fmt.Errorf("no hosts match --only '%v' regexp", onlyHosts))
os.Exit(1)
}
network.Hosts = hosts
}
// --except flag filters out hosts
if exceptHosts != "" {
expr, err := regexp.CompilePOSIX(exceptHosts)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
var hosts []string
for _, host := range network.Hosts {
if !expr.MatchString(host) {
hosts = append(hosts, host)
}
}
if len(hosts) == 0 {
fmt.Fprintln(os.Stderr, fmt.Errorf("no hosts left after --except '%v' regexp", onlyHosts))
os.Exit(1)
}
network.Hosts = hosts
}
// --sshconfig flag location for ssh_config file
if sshConfig != "" {
confHosts, err := sshconfig.ParseSSHConfig(resolvePath(sshConfig))
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
// flatten Host -> *SSHHost, not the prettiest
// but will do
confMap := map[string]*sshconfig.SSHHost{}
for _, conf := range confHosts {
for _, host := range conf.Host {
confMap[host] = conf
}
}
// check network.Hosts for match
for _, host := range network.Hosts {
conf, found := confMap[host]
if found {
network.User = conf.User
network.IdentityFile = resolvePath(conf.IdentityFile)
network.Hosts = []string{fmt.Sprintf("%s:%d", conf.HostName, conf.Port)}
}
}
}
var vars sup.EnvList
for _, val := range append(conf.Env, network.Env...) {
vars.Set(val.Key, val.Value)
}
if err := vars.ResolveValues(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
// Parse CLI --env flag env vars, define $SUP_ENV and override values defined in Supfile.
var cliVars sup.EnvList
for _, env := range envVars {
if len(env) == 0 {
continue
}
i := strings.Index(env, "=")
if i < 0 {
if len(env) > 0 {
vars.Set(env, "")
}
continue
}
vars.Set(env[:i], env[i+1:])
cliVars.Set(env[:i], env[i+1:])
}
// SUP_ENV is generated only from CLI env vars.
// Separate loop to omit duplicates.
supEnv := ""
for _, v := range cliVars {
supEnv += fmt.Sprintf(" -e %v=%q", v.Key, v.Value)
}
vars.Set("SUP_ENV", strings.TrimSpace(supEnv))
// Create new Stackup app.
app, err := sup.New(conf)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
app.Debug(debug)
app.Prefix(!disablePrefix)
// Run all the commands in the given network.
err = app.Run(network, vars, commands...)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}

View File

@ -1,13 +0,0 @@
package sup
var (
Colors = []string{
"\033[32m", // green
"\033[33m", // yellow
"\033[36m", // cyan
"\033[35m", // magenta
"\033[31m", // red
"\033[34m", // blue
}
ResetColor = "\033[0m"
)

View File

@ -1,27 +0,0 @@
require "language/go"
class Sup < Formula
desc "Stack Up. Super simple deployment tool - think of it like 'make' for a network of servers."
homepage "https://github.com/pressly/sup"
url "https://github.com/pressly/sup/archive/4ee5083c8321340bc2a6410f24d8a760f7ad3847.zip"
version "0.3.1"
sha256 "7fa17c20fdcd9e24d8c2fe98081e1300e936da02b3f2cf9c5a11fd699cbc487e"
depends_on "go" => :build
def install
ENV["GOBIN"] = bin
ENV["GOPATH"] = buildpath
ENV["GOHOME"] = buildpath
mkdir_p buildpath/"src/github.com/pressly/"
ln_sf buildpath, buildpath/"src/github.com/pressly/sup"
Language::Go.stage_deps resources, buildpath/"src"
system "go", "build", "-o", bin/"sup", "./cmd/sup"
end
test do
assert_equal "0.3", shell_output("#{bin}/bin/sup")
end
end

View File

@ -1,14 +0,0 @@
#FROM scratch
#FROM gliderlabs/alpine:3.1
#FORM ubuntu_lean # https://blog.jtlebi.fr/2015/04/25/how-i-shrunk-a-docker-image-by-98-8-featuring-fanotify/
FROM ubuntu:14.04
#RUN apt-get update && apt-get install --no-install-recommends -y \
# ca-certificates
COPY ./example /usr/bin/
EXPOSE 8000
CMD ["/usr/bin/example"]

View File

@ -1,146 +0,0 @@
# Supfile for "Example" Docker service
---
version: 0.4
env:
# Environment variables for all commands
NAME: example
REPO: github.com/pressly/sup
BRANCH: master
IMAGE: pressly/example
HOST_PORT: 8000
CONTAINER_PORT: 8000
networks:
# Groups of hosts
local:
hosts:
- localhost
dev:
env:
# Extra environment variable for dev hosts only
DOCKER_HOST: tcp://127.0.0.1:2375
hosts:
- docker@192.168.59.103
stg:
hosts:
- ubuntu@stg.example.com
prod:
inventory: for i in 1 2 3 4; do echo "ubuntu@prod$i.example.com"; done
commands:
# Named set of commands to be run remotely
ping:
desc: Print uname and current date/time.
run: uname -a; date
pre-build:
desc: Initialize directory
run: mkdir -p /tmp/$IMAGE
mytest:
run: echo $SUP_TIME
build:
desc: Build Docker image from current directory, push to Docker Hub
# local: sup $SUP_ENV -f ./builder/Supfile $SUP_NETWORK build
upload:
- src: ./
dst: /tmp/$IMAGE
script: ./scripts/docker-build.sh
once: true
pull:
desc: Pull latest Docker image
run: sudo docker pull $IMAGE
config:
desc: Upload/test config file.
upload:
- src: ./example.$SUP_NETWORK.cfg
dst: /tmp/
run: test -f /tmp/example.$SUP_NETWORK.cfg
stop:
desc: Stop Docker container
run: sudo docker stop $NAME || exit 0
rm:
desc: Remove Docker container
run: sudo docker rm $NAME || exit 0
start:
desc: Start a stopped Docker container
run: sudo docker start $NAME || exit 0
run:
desc: Run Docker container
run: >
sudo docker run -d \
-p $HOST_PORT:$CONTAINER_PORT \
-v /tmp/example.$SUP_NETWORK.cfg:/etc/example.cfg \
--restart=always \
--name $NAME $IMAGE
restart:
desc: Restart Docker container
run: sudo docker restart $NAME || exit 0
stop-rm-run:
desc: Rolling update (stop & remove old Docker container, run new one)
run: >
sudo docker stop $NAME || :; \
sudo docker rm $NAME || :; \
sudo docker run -d \
-p $HOST_PORT:$CONTAINER_PORT \
-v /tmp/example.$SUP_NETWORK.cfg:/etc/example.cfg \
--restart=always \
--name $NAME $IMAGE
serial: 1
ps:
desc: List running Docker containers
run: sudo docker ps | grep $NAME
logs:
desc: Docker logs
run: sudo docker logs $NAME
tail-logs:
desc: Tail Docker logs
run: sudo docker logs --tail=20 -f $NAME
health:
desc: Application health check
run: curl localhost:$HOST_PORT
slack-notify:
desc: Notify Slack about new deployment
local: >
curl -X POST --data-urlencode 'payload={"channel": "#_team_", "text": "['$SUP_NETWORK'] '$SUP_USER' deployed '$NAME'"}' \
https://hooks.slack.com/services/X/Y/Z
bash:
desc: Interactive shell on all hosts
stdin: true
run: bash
exec:
desc: Interactive docker exec on all hosts
stdin: true
run: sudo docker exec -i $NAME bash
targets: # Aliases to run multiple commands at once
deploy:
- pre-build
- build
- pull
- config
- stop-rm-run
- ps
- logs
- health
- slack-notify

View File

@ -1 +0,0 @@
development

View File

@ -1,25 +0,0 @@
package main
import (
"io/ioutil"
"log"
"net/http"
)
func main() {
config, err := ioutil.ReadFile("/etc/example.cfg")
if err != nil {
log.Fatal(err)
}
// Define handler that returns "Hello $ENV"
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello "))
w.Write(config)
})
err = http.ListenAndServe(":8000", nil)
if err != nil {
log.Fatal(err)
}
}

View File

@ -1 +0,0 @@
local

View File

@ -1 +0,0 @@
production

View File

@ -1 +0,0 @@
staging

View File

@ -1,18 +0,0 @@
#!/bin/bash
set -e
cd /tmp/$IMAGE
# Cleanup.
sudo rm -rf bin
# Bulder image. Build binaries (make dist) into bin/ dir.
sudo docker run --rm \
-v $(pwd):/go/src/$REPO/$NAME \
-w /go/src/$REPO/$NAME \
golang:1.5.2 go build
# Bake bin/* into the resulting image.
sudo docker build --no-cache -t $IMAGE .
sudo docker push $IMAGE

View File

@ -1,119 +0,0 @@
package sup
import (
"fmt"
"io"
"os"
"os/exec"
"os/user"
"github.com/pkg/errors"
)
// Client is a wrapper over the SSH connection/sessions.
type LocalhostClient struct {
cmd *exec.Cmd
user string
stdin io.WriteCloser
stdout io.Reader
stderr io.Reader
running bool
env string //export FOO="bar"; export BAR="baz";
}
func (c *LocalhostClient) Connect(_ string) error {
u, err := user.Current()
if err != nil {
return err
}
c.user = u.Username
return nil
}
func (c *LocalhostClient) Run(task *Task) error {
var err error
if c.running {
return fmt.Errorf("Command already running")
}
cmd := exec.Command("bash", "-c", c.env+task.Run)
c.cmd = cmd
c.stdout, err = cmd.StdoutPipe()
if err != nil {
return err
}
c.stderr, err = cmd.StderrPipe()
if err != nil {
return err
}
c.stdin, err = cmd.StdinPipe()
if err != nil {
return err
}
if err := c.cmd.Start(); err != nil {
return ErrTask{task, err.Error()}
}
c.running = true
return nil
}
func (c *LocalhostClient) Wait() error {
if !c.running {
return fmt.Errorf("Trying to wait on stopped command")
}
err := c.cmd.Wait()
c.running = false
return err
}
func (c *LocalhostClient) Close() error {
return nil
}
func (c *LocalhostClient) Stdin() io.WriteCloser {
return c.stdin
}
func (c *LocalhostClient) Stderr() io.Reader {
return c.stderr
}
func (c *LocalhostClient) Stdout() io.Reader {
return c.stdout
}
func (c *LocalhostClient) Prefix() (string, int) {
host := c.user + "@localhost" + " | "
return ResetColor + host, len(host)
}
func (c *LocalhostClient) Write(p []byte) (n int, err error) {
return c.stdin.Write(p)
}
func (c *LocalhostClient) WriteClose() error {
return c.stdin.Close()
}
func (c *LocalhostClient) Signal(sig os.Signal) error {
return c.cmd.Process.Signal(sig)
}
func ResolveLocalPath(cwd, path, env string) (string, error) {
// Check if file exists first. Use bash to resolve $ENV_VARs.
cmd := exec.Command("bash", "-c", env+"echo -n "+path)
cmd.Dir = cwd
resolvedFilename, err := cmd.Output()
if err != nil {
return "", errors.Wrap(err, "resolving path failed")
}
return string(resolvedFilename), nil
}

294
vendor/github.com/pressly/sup/ssh.go generated vendored
View File

@ -1,294 +0,0 @@
package sup
import (
"fmt"
"io"
"io/ioutil"
"net"
"os"
"os/user"
"path/filepath"
"strings"
"sync"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
)
// Client is a wrapper over the SSH connection/sessions.
type SSHClient struct {
conn *ssh.Client
sess *ssh.Session
user string
host string
remoteStdin io.WriteCloser
remoteStdout io.Reader
remoteStderr io.Reader
connOpened bool
sessOpened bool
running bool
env string //export FOO="bar"; export BAR="baz";
color string
}
type ErrConnect struct {
User string
Host string
Reason string
}
func (e ErrConnect) Error() string {
return fmt.Sprintf(`Connect("%v@%v"): %v`, e.User, e.Host, e.Reason)
}
// parseHost parses and normalizes <user>@<host:port> from a given string.
func (c *SSHClient) parseHost(host string) error {
c.host = host
// Remove extra "ssh://" schema
if len(c.host) > 6 && c.host[:6] == "ssh://" {
c.host = c.host[6:]
}
if at := strings.Index(c.host, "@"); at != -1 {
c.user = c.host[:at]
c.host = c.host[at+1:]
}
// Add default user, if not set
if c.user == "" {
u, err := user.Current()
if err != nil {
return err
}
c.user = u.Username
}
if strings.Index(c.host, "/") != -1 {
return ErrConnect{c.user, c.host, "unexpected slash in the host URL"}
}
// Add default port, if not set
if strings.Index(c.host, ":") == -1 {
c.host += ":22"
}
return nil
}
var initAuthMethodOnce sync.Once
var authMethod ssh.AuthMethod
// initAuthMethod initiates SSH authentication method.
func initAuthMethod() {
var signers []ssh.Signer
// If there's a running SSH Agent, try to use its Private keys.
sock, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK"))
if err == nil {
agent := agent.NewClient(sock)
signers, _ = agent.Signers()
}
// Try to read user's SSH private keys form the standard paths.
files, _ := filepath.Glob(os.Getenv("HOME") + "/.ssh/id_*")
for _, file := range files {
if strings.HasSuffix(file, ".pub") {
continue // Skip public keys.
}
data, err := ioutil.ReadFile(file)
if err != nil {
continue
}
signer, err := ssh.ParsePrivateKey(data)
if err != nil {
continue
}
signers = append(signers, signer)
}
authMethod = ssh.PublicKeys(signers...)
}
// SSHDialFunc can dial an ssh server and return a client
type SSHDialFunc func(net, addr string, config *ssh.ClientConfig) (*ssh.Client, error)
// Connect creates SSH connection to a specified host.
// It expects the host of the form "[ssh://]host[:port]".
func (c *SSHClient) Connect(host string) error {
return c.ConnectWith(host, ssh.Dial)
}
// ConnectWith creates a SSH connection to a specified host. It will use dialer to establish the
// connection.
// TODO: Split Signers to its own method.
func (c *SSHClient) ConnectWith(host string, dialer SSHDialFunc) error {
if c.connOpened {
return fmt.Errorf("Already connected")
}
initAuthMethodOnce.Do(initAuthMethod)
err := c.parseHost(host)
if err != nil {
return err
}
config := &ssh.ClientConfig{
User: c.user,
Auth: []ssh.AuthMethod{
authMethod,
},
}
c.conn, err = dialer("tcp", c.host, config)
if err != nil {
return ErrConnect{c.user, c.host, err.Error()}
}
c.connOpened = true
return nil
}
// Run runs the task.Run command remotely on c.host.
func (c *SSHClient) Run(task *Task) error {
if c.running {
return fmt.Errorf("Session already running")
}
if c.sessOpened {
return fmt.Errorf("Session already connected")
}
sess, err := c.conn.NewSession()
if err != nil {
return err
}
c.remoteStdin, err = sess.StdinPipe()
if err != nil {
return err
}
c.remoteStdout, err = sess.StdoutPipe()
if err != nil {
return err
}
c.remoteStderr, err = sess.StderrPipe()
if err != nil {
return err
}
if task.TTY {
// Set up terminal modes
modes := ssh.TerminalModes{
ssh.ECHO: 0, // disable echoing
ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
}
// Request pseudo terminal
if err := sess.RequestPty("xterm", 80, 40, modes); err != nil {
return ErrTask{task, fmt.Sprintf("request for pseudo terminal failed: %s", err)}
}
}
// Start the remote command.
if err := sess.Start(c.env + task.Run); err != nil {
return ErrTask{task, err.Error()}
}
c.sess = sess
c.sessOpened = true
c.running = true
return nil
}
// Wait waits until the remote command finishes and exits.
// It closes the SSH session.
func (c *SSHClient) Wait() error {
if !c.running {
return fmt.Errorf("Trying to wait on stopped session")
}
err := c.sess.Wait()
c.sess.Close()
c.running = false
c.sessOpened = false
return err
}
// DialThrough will create a new connection from the ssh server sc is connected to. DialThrough is an SSHDialer.
func (sc *SSHClient) DialThrough(net, addr string, config *ssh.ClientConfig) (*ssh.Client, error) {
conn, err := sc.conn.Dial(net, addr)
if err != nil {
return nil, err
}
c, chans, reqs, err := ssh.NewClientConn(conn, addr, config)
if err != nil {
return nil, err
}
return ssh.NewClient(c, chans, reqs), nil
}
// Close closes the underlying SSH connection and session.
func (c *SSHClient) Close() error {
if c.sessOpened {
c.sess.Close()
c.sessOpened = false
}
if !c.connOpened {
return fmt.Errorf("Trying to close the already closed connection")
}
err := c.conn.Close()
c.connOpened = false
c.running = false
return err
}
func (c *SSHClient) Stdin() io.WriteCloser {
return c.remoteStdin
}
func (c *SSHClient) Stderr() io.Reader {
return c.remoteStderr
}
func (c *SSHClient) Stdout() io.Reader {
return c.remoteStdout
}
func (c *SSHClient) Prefix() (string, int) {
host := c.user + "@" + c.host + " | "
return c.color + host + ResetColor, len(host)
}
func (c *SSHClient) Write(p []byte) (n int, err error) {
return c.remoteStdin.Write(p)
}
func (c *SSHClient) WriteClose() error {
return c.remoteStdin.Close()
}
func (c *SSHClient) Signal(sig os.Signal) error {
if !c.sessOpened {
return fmt.Errorf("session is not open")
}
switch sig {
case os.Interrupt:
// TODO: Turns out that .Signal(ssh.SIGHUP) doesn't work for me.
// Instead, sending \x03 to the remote session works for me,
// which sounds like something that should be fixed/resolved
// upstream in the golang.org/x/crypto/ssh pkg.
// https://github.com/golang/go/issues/4115#issuecomment-66070418
c.remoteStdin.Write([]byte("\x03"))
return c.sess.Signal(ssh.SIGINT)
default:
return fmt.Errorf("%v not supported", sig)
}
}

249
vendor/github.com/pressly/sup/sup.go generated vendored
View File

@ -1,249 +0,0 @@
package sup
import (
"fmt"
"io"
"os"
"os/signal"
"strings"
"sync"
"github.com/goware/prefixer"
"github.com/pkg/errors"
"golang.org/x/crypto/ssh"
)
const VERSION = "0.5"
type Stackup struct {
conf *Supfile
debug bool
prefix bool
}
func New(conf *Supfile) (*Stackup, error) {
return &Stackup{
conf: conf,
}, nil
}
// Run runs set of commands on multiple hosts defined by network sequentially.
// TODO: This megamoth method needs a big refactor and should be split
// to multiple smaller methods.
func (sup *Stackup) Run(network *Network, envVars EnvList, commands ...*Command) error {
if len(commands) == 0 {
return errors.New("no commands to be run")
}
env := envVars.AsExport()
// Create clients for every host (either SSH or Localhost).
var bastion *SSHClient
if network.Bastion != "" {
bastion = &SSHClient{}
if err := bastion.Connect(network.Bastion); err != nil {
return errors.Wrap(err, "connecting to bastion failed")
}
}
var wg sync.WaitGroup
clientCh := make(chan Client, len(network.Hosts))
errCh := make(chan error, len(network.Hosts))
for i, host := range network.Hosts {
wg.Add(1)
go func(i int, host string) {
defer wg.Done()
// Localhost client.
if host == "localhost" {
local := &LocalhostClient{
env: env + `export SUP_HOST="` + host + `";`,
}
if err := local.Connect(host); err != nil {
errCh <- errors.Wrap(err, "connecting to localhost failed")
return
}
clientCh <- local
return
}
// SSH client.
remote := &SSHClient{
env: env + `export SUP_HOST="` + host + `";`,
user: network.User,
color: Colors[i%len(Colors)],
}
if bastion != nil {
if err := remote.ConnectWith(host, bastion.DialThrough); err != nil {
errCh <- errors.Wrap(err, "connecting to remote host through bastion failed")
return
}
} else {
if err := remote.Connect(host); err != nil {
errCh <- errors.Wrap(err, "connecting to remote host failed")
return
}
}
clientCh <- remote
}(i, host)
}
wg.Wait()
close(clientCh)
close(errCh)
maxLen := 0
var clients []Client
for client := range clientCh {
if remote, ok := client.(*SSHClient); ok {
defer remote.Close()
}
_, prefixLen := client.Prefix()
if prefixLen > maxLen {
maxLen = prefixLen
}
clients = append(clients, client)
}
for err := range errCh {
return errors.Wrap(err, "connecting to clients failed")
}
// Run command or run multiple commands defined by target sequentially.
for _, cmd := range commands {
// Translate command into task(s).
tasks, err := sup.createTasks(cmd, clients, env)
if err != nil {
return errors.Wrap(err, "creating task failed")
}
// Run tasks sequentially.
for _, task := range tasks {
var writers []io.Writer
var wg sync.WaitGroup
// Run tasks on the provided clients.
for _, c := range task.Clients {
var prefix string
var prefixLen int
if sup.prefix {
prefix, prefixLen = c.Prefix()
if len(prefix) < maxLen { // Left padding.
prefix = strings.Repeat(" ", maxLen-prefixLen) + prefix
}
}
err := c.Run(task)
if err != nil {
return errors.Wrap(err, prefix+"task failed")
}
// Copy over tasks's STDOUT.
wg.Add(1)
go func(c Client) {
defer wg.Done()
_, err := io.Copy(os.Stdout, prefixer.New(c.Stdout(), prefix))
if err != nil && err != io.EOF {
// TODO: io.Copy() should not return io.EOF at all.
// Upstream bug? Or prefixer.WriteTo() bug?
fmt.Fprintf(os.Stderr, "%v", errors.Wrap(err, prefix+"reading STDOUT failed"))
}
}(c)
// Copy over tasks's STDERR.
wg.Add(1)
go func(c Client) {
defer wg.Done()
_, err := io.Copy(os.Stderr, prefixer.New(c.Stderr(), prefix))
if err != nil && err != io.EOF {
fmt.Fprintf(os.Stderr, "%v", errors.Wrap(err, prefix+"reading STDERR failed"))
}
}(c)
writers = append(writers, c.Stdin())
}
// Copy over task's STDIN.
if task.Input != nil {
go func() {
writer := io.MultiWriter(writers...)
_, err := io.Copy(writer, task.Input)
if err != nil && err != io.EOF {
fmt.Fprintf(os.Stderr, "%v", errors.Wrap(err, "copying STDIN failed"))
}
// TODO: Use MultiWriteCloser (not in Stdlib), so we can writer.Close() instead?
for _, c := range clients {
c.WriteClose()
}
}()
}
// Catch OS signals and pass them to all active clients.
trap := make(chan os.Signal, 1)
signal.Notify(trap, os.Interrupt)
go func() {
for {
select {
case sig, ok := <-trap:
if !ok {
return
}
for _, c := range task.Clients {
err := c.Signal(sig)
if err != nil {
fmt.Fprintf(os.Stderr, "%v", errors.Wrap(err, "sending signal failed"))
}
}
}
}
}()
// Wait for all I/O operations first.
wg.Wait()
// Make sure each client finishes the task, return on failure.
for _, c := range task.Clients {
wg.Add(1)
go func(c Client) {
defer wg.Done()
if err := c.Wait(); err != nil {
var prefix string
if sup.prefix {
var prefixLen int
prefix, prefixLen = c.Prefix()
if len(prefix) < maxLen { // Left padding.
prefix = strings.Repeat(" ", maxLen-prefixLen) + prefix
}
}
if e, ok := err.(*ssh.ExitError); ok && e.ExitStatus() != 15 {
// TODO: Store all the errors, and print them after Wait().
fmt.Fprintf(os.Stderr, "%s%v\n", prefix, e)
os.Exit(e.ExitStatus())
}
fmt.Fprintf(os.Stderr, "%s%v\n", prefix, err)
// TODO: Shouldn't os.Exit(1) here. Instead, collect the exit statuses for later.
os.Exit(1)
}
}(c)
}
// Wait for all commands to finish.
wg.Wait()
// Stop catching signals for the currently active clients.
signal.Stop(trap)
close(trap)
}
}
return nil
}
func (sup *Stackup) Debug(value bool) {
sup.debug = value
}
func (sup *Stackup) Prefix(value bool) {
sup.prefix = value
}

View File

@ -1,366 +0,0 @@
package sup
import (
"bytes"
"fmt"
"io"
"os"
"os/exec"
"strings"
"github.com/pkg/errors"
"gopkg.in/yaml.v2"
)
// Supfile represents the Stack Up configuration YAML file.
type Supfile struct {
Networks Networks `yaml:"networks"`
Commands Commands `yaml:"commands"`
Targets Targets `yaml:"targets"`
Env EnvList `yaml:"env"`
Version string `yaml:"version"`
}
// Network is group of hosts with extra custom env vars.
type Network struct {
Env EnvList `yaml:"env"`
Inventory string `yaml:"inventory"`
Hosts []string `yaml:"hosts"`
Bastion string `yaml:"bastion"` // Jump host for the environment
// Should these live on Hosts too? We'd have to change []string to struct, even in Supfile.
User string // `yaml:"user"`
IdentityFile string // `yaml:"identity_file"`
}
// Networks is a list of user-defined networks
type Networks struct {
Names []string
nets map[string]Network
}
func (n *Networks) UnmarshalYAML(unmarshal func(interface{}) error) error {
err := unmarshal(&n.nets)
if err != nil {
return err
}
var items yaml.MapSlice
err = unmarshal(&items)
if err != nil {
return err
}
n.Names = make([]string, len(items))
for i, item := range items {
n.Names[i] = item.Key.(string)
}
return nil
}
func (n *Networks) Get(name string) (Network, bool) {
net, ok := n.nets[name]
return net, ok
}
// Command represents command(s) to be run remotely.
type Command struct {
Name string `yaml:"-"` // Command name.
Desc string `yaml:"desc"` // Command description.
Local string `yaml:"local"` // Command(s) to be run locally.
Run string `yaml:"run"` // Command(s) to be run remotelly.
Script string `yaml:"script"` // Load command(s) from script and run it remotelly.
Upload []Upload `yaml:"upload"` // See Upload struct.
Stdin bool `yaml:"stdin"` // Attach localhost STDOUT to remote commands' STDIN?
Once bool `yaml:"once"` // The command should be run "once" (on one host only).
Serial int `yaml:"serial"` // Max number of clients processing a task in parallel.
// API backward compatibility. Will be deprecated in v1.0.
RunOnce bool `yaml:"run_once"` // The command should be run once only.
}
// Commands is a list of user-defined commands
type Commands struct {
Names []string
cmds map[string]Command
}
func (c *Commands) UnmarshalYAML(unmarshal func(interface{}) error) error {
err := unmarshal(&c.cmds)
if err != nil {
return err
}
var items yaml.MapSlice
err = unmarshal(&items)
if err != nil {
return err
}
c.Names = make([]string, len(items))
for i, item := range items {
c.Names[i] = item.Key.(string)
}
return nil
}
func (c *Commands) Get(name string) (Command, bool) {
cmd, ok := c.cmds[name]
return cmd, ok
}
// Targets is a list of user-defined targets
type Targets struct {
Names []string
targets map[string][]string
}
func (t *Targets) UnmarshalYAML(unmarshal func(interface{}) error) error {
err := unmarshal(&t.targets)
if err != nil {
return err
}
var items yaml.MapSlice
err = unmarshal(&items)
if err != nil {
return err
}
t.Names = make([]string, len(items))
for i, item := range items {
t.Names[i] = item.Key.(string)
}
return nil
}
func (t *Targets) Get(name string) ([]string, bool) {
cmds, ok := t.targets[name]
return cmds, ok
}
// Upload represents file copy operation from localhost Src path to Dst
// path of every host in a given Network.
type Upload struct {
Src string `yaml:"src"`
Dst string `yaml:"dst"`
Exc string `yaml:"exclude"`
}
// EnvVar represents an environment variable
type EnvVar struct {
Key string
Value string
}
func (e EnvVar) String() string {
return e.Key + `=` + e.Value
}
// AsExport returns the environment variable as a bash export statement
func (e EnvVar) AsExport() string {
return `export ` + e.Key + `="` + e.Value + `";`
}
// EnvList is a list of environment variables that maps to a YAML map,
// but maintains order, enabling late variables to reference early variables.
type EnvList []*EnvVar
func (e EnvList) Slice() []string {
envs := make([]string, len(e))
for i, env := range e {
envs[i] = env.String()
}
return envs
}
func (e *EnvList) UnmarshalYAML(unmarshal func(interface{}) error) error {
items := []yaml.MapItem{}
err := unmarshal(&items)
if err != nil {
return err
}
*e = make(EnvList, 0, len(items))
for _, v := range items {
e.Set(fmt.Sprintf("%v", v.Key), fmt.Sprintf("%v", v.Value))
}
return nil
}
// Set key to be equal value in this list.
func (e *EnvList) Set(key, value string) {
for i, v := range *e {
if v.Key == key {
(*e)[i].Value = value
return
}
}
*e = append(*e, &EnvVar{
Key: key,
Value: value,
})
}
func (e *EnvList) ResolveValues() error {
if len(*e) == 0 {
return nil
}
exports := ""
for i, v := range *e {
exports += v.AsExport()
cmd := exec.Command("bash", "-c", exports+"echo -n "+v.Value+";")
cwd, err := os.Getwd()
if err != nil {
return err
}
cmd.Dir = cwd
resolvedValue, err := cmd.Output()
if err != nil {
return errors.Wrapf(err, "resolving env var %v failed", v.Key)
}
(*e)[i].Value = string(resolvedValue)
}
return nil
}
func (e *EnvList) AsExport() string {
// Process all ENVs into a string of form
// `export FOO="bar"; export BAR="baz";`.
exports := ``
for _, v := range *e {
exports += v.AsExport() + " "
}
return exports
}
type ErrMustUpdate struct {
Msg string
}
type ErrUnsupportedSupfileVersion struct {
Msg string
}
func (e ErrMustUpdate) Error() string {
return fmt.Sprintf("%v\n\nPlease update sup by `go get -u github.com/pressly/sup/cmd/sup`", e.Msg)
}
func (e ErrUnsupportedSupfileVersion) Error() string {
return fmt.Sprintf("%v\n\nCheck your Supfile version (available latest version: v0.5)", e.Msg)
}
// NewSupfile parses configuration file and returns Supfile or error.
func NewSupfile(data []byte) (*Supfile, error) {
var conf Supfile
if err := yaml.Unmarshal(data, &conf); err != nil {
return nil, err
}
// API backward compatibility. Will be deprecated in v1.0.
switch conf.Version {
case "":
conf.Version = "0.1"
fallthrough
case "0.1":
for _, cmd := range conf.Commands.cmds {
if cmd.RunOnce {
return nil, ErrMustUpdate{"command.run_once is not supported in Supfile v" + conf.Version}
}
}
fallthrough
case "0.2":
for _, cmd := range conf.Commands.cmds {
if cmd.Once {
return nil, ErrMustUpdate{"command.once is not supported in Supfile v" + conf.Version}
}
if cmd.Local != "" {
return nil, ErrMustUpdate{"command.local is not supported in Supfile v" + conf.Version}
}
if cmd.Serial != 0 {
return nil, ErrMustUpdate{"command.serial is not supported in Supfile v" + conf.Version}
}
}
for _, network := range conf.Networks.nets {
if network.Inventory != "" {
return nil, ErrMustUpdate{"network.inventory is not supported in Supfile v" + conf.Version}
}
}
fallthrough
case "0.3":
var warning string
for key, cmd := range conf.Commands.cmds {
if cmd.RunOnce {
warning = "Warning: command.run_once was deprecated by command.once in Supfile v" + conf.Version + "\n"
cmd.Once = true
conf.Commands.cmds[key] = cmd
}
}
if warning != "" {
fmt.Fprintf(os.Stderr, warning)
}
fallthrough
case "0.4", "0.5":
default:
return nil, ErrUnsupportedSupfileVersion{"unsupported Supfile version " + conf.Version}
}
return &conf, nil
}
// ParseInventory runs the inventory command, if provided, and appends
// the command's output lines to the manually defined list of hosts.
func (n Network) ParseInventory() ([]string, error) {
if n.Inventory == "" {
return nil, nil
}
cmd := exec.Command("/bin/sh", "-c", n.Inventory)
cmd.Env = os.Environ()
cmd.Env = append(cmd.Env, n.Env.Slice()...)
cmd.Stderr = os.Stderr
output, err := cmd.Output()
if err != nil {
return nil, err
}
var hosts []string
buf := bytes.NewBuffer(output)
for {
host, err := buf.ReadString('\n')
if err != nil {
if err == io.EOF {
break
}
return nil, err
}
host = strings.TrimSpace(host)
// skip empty lines and comments
if host == "" || host[:1] == "#" {
continue
}
hosts = append(hosts, host)
}
return hosts, nil
}

53
vendor/github.com/pressly/sup/tar.go generated vendored
View File

@ -1,53 +0,0 @@
package sup
import (
"fmt"
"io"
"os/exec"
"strings"
"github.com/pkg/errors"
)
// Copying dirs/files over SSH using TAR.
// tar -C . -cvzf - $SRC | ssh $HOST "tar -C $DST -xvzf -"
// RemoteTarCommand returns command to be run on remote SSH host
// to properly receive the created TAR stream.
// TODO: Check for relative directory.
func RemoteTarCommand(dir string) string {
return fmt.Sprintf("tar -C \"%s\" -xzf -", dir)
}
func LocalTarCmdArgs(path, exclude string) []string {
args := []string{}
// Added pattens to exclude from tar compress
excludes := strings.Split(exclude, ",")
for _, exclude := range excludes {
trimmed := strings.TrimSpace(exclude)
if trimmed != "" {
args = append(args, `--exclude=`+trimmed)
}
}
args = append(args, "-C", ".", "-czf", "-", path)
return args
}
// NewTarStreamReader creates a tar stream reader from a local path.
// TODO: Refactor. Use "archive/tar" instead.
func NewTarStreamReader(cwd, path, exclude string) (io.Reader, error) {
cmd := exec.Command("tar", LocalTarCmdArgs(path, exclude)...)
cmd.Dir = cwd
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, errors.Wrap(err, "tar: stdout pipe failed")
}
if err := cmd.Start(); err != nil {
return nil, errors.Wrap(err, "tar: starting cmd failed")
}
return stdout, nil
}

168
vendor/github.com/pressly/sup/task.go generated vendored
View File

@ -1,168 +0,0 @@
package sup
import (
"fmt"
"io"
"io/ioutil"
"os"
"github.com/pkg/errors"
)
// Task represents a set of commands to be run.
type Task struct {
Run string
Input io.Reader
Clients []Client
TTY bool
}
func (sup *Stackup) createTasks(cmd *Command, clients []Client, env string) ([]*Task, error) {
var tasks []*Task
cwd, err := os.Getwd()
if err != nil {
return nil, errors.Wrap(err, "resolving CWD failed")
}
// Anything to upload?
for _, upload := range cmd.Upload {
uploadFile, err := ResolveLocalPath(cwd, upload.Src, env)
if err != nil {
return nil, errors.Wrap(err, "upload: "+upload.Src)
}
uploadTarReader, err := NewTarStreamReader(cwd, uploadFile, upload.Exc)
if err != nil {
return nil, errors.Wrap(err, "upload: "+upload.Src)
}
task := Task{
Run: RemoteTarCommand(upload.Dst),
Input: uploadTarReader,
TTY: false,
}
if cmd.Once {
task.Clients = []Client{clients[0]}
tasks = append(tasks, &task)
} else if cmd.Serial > 0 {
// Each "serial" task client group is executed sequentially.
for i := 0; i < len(clients); i += cmd.Serial {
j := i + cmd.Serial
if j > len(clients) {
j = len(clients)
}
copy := task
copy.Clients = clients[i:j]
tasks = append(tasks, &copy)
}
} else {
task.Clients = clients
tasks = append(tasks, &task)
}
}
// Script. Read the file as a multiline input command.
if cmd.Script != "" {
f, err := os.Open(cmd.Script)
if err != nil {
return nil, errors.Wrap(err, "can't open script")
}
data, err := ioutil.ReadAll(f)
if err != nil {
return nil, errors.Wrap(err, "can't read script")
}
task := Task{
Run: string(data),
TTY: true,
}
if sup.debug {
task.Run = "set -x;" + task.Run
}
if cmd.Stdin {
task.Input = os.Stdin
}
if cmd.Once {
task.Clients = []Client{clients[0]}
tasks = append(tasks, &task)
} else if cmd.Serial > 0 {
// Each "serial" task client group is executed sequentially.
for i := 0; i < len(clients); i += cmd.Serial {
j := i + cmd.Serial
if j > len(clients) {
j = len(clients)
}
copy := task
copy.Clients = clients[i:j]
tasks = append(tasks, &copy)
}
} else {
task.Clients = clients
tasks = append(tasks, &task)
}
}
// Local command.
if cmd.Local != "" {
local := &LocalhostClient{
env: env + `export SUP_HOST="localhost";`,
}
local.Connect("localhost")
task := &Task{
Run: cmd.Local,
Clients: []Client{local},
TTY: true,
}
if sup.debug {
task.Run = "set -x;" + task.Run
}
if cmd.Stdin {
task.Input = os.Stdin
}
tasks = append(tasks, task)
}
// Remote command.
if cmd.Run != "" {
task := Task{
Run: cmd.Run,
TTY: true,
}
if sup.debug {
task.Run = "set -x;" + task.Run
}
if cmd.Stdin {
task.Input = os.Stdin
}
if cmd.Once {
task.Clients = []Client{clients[0]}
tasks = append(tasks, &task)
} else if cmd.Serial > 0 {
// Each "serial" task client group is executed sequentially.
for i := 0; i < len(clients); i += cmd.Serial {
j := i + cmd.Serial
if j > len(clients) {
j = len(clients)
}
copy := task
copy.Clients = clients[i:j]
tasks = append(tasks, &copy)
}
} else {
task.Clients = clients
tasks = append(tasks, &task)
}
}
return tasks, nil
}
type ErrTask struct {
Task *Task
Reason string
}
func (e ErrTask) Error() string {
return fmt.Sprintf(`Run("%v"): %v`, e.Task, e.Reason)
}

View File

@ -6,17 +6,7 @@
// +build ppc // +build ppc
// Functions to access/create device major and minor numbers matching the // Functions to access/create device major and minor numbers matching the
// encoding used by the Linux kernel and glibc. // encoding used by AIX.
//
// The information below is extracted and adapted from bits/sysmacros.h in the
// glibc sources:
//
// dev_t in glibc is 64-bit, with 32-bit major and minor numbers. glibc's
// default encoding is MMMM Mmmm mmmM MMmm, where M is a hex digit of the major
// number and m is a hex digit of the minor number. This is backward compatible
// with legacy systems where dev_t is 16 bits wide, encoded as MMmm. It is also
// backward compatible with the Linux kernel, which for some architectures uses
// 32-bit dev_t, encoded as mmmM MMmm.
package unix package unix

View File

@ -6,17 +6,7 @@
// +build ppc64 // +build ppc64
// Functions to access/create device major and minor numbers matching the // Functions to access/create device major and minor numbers matching the
// encoding used by the Linux kernel and glibc. // encoding used AIX.
//
// The information below is extracted and adapted from bits/sysmacros.h in the
// glibc sources:
//
// dev_t in glibc is 64-bit, with 32-bit major and minor numbers. glibc's
// default encoding is MMMM Mmmm mmmM MMmm, where M is a hex digit of the major
// number and m is a hex digit of the minor number. This is backward compatible
// with legacy systems where dev_t is 16 bits wide, encoded as MMmm. It is also
// backward compatible with the Linux kernel, which for some architectures uses
// 32-bit dev_t, encoded as mmmM MMmm.
package unix package unix

View File

@ -2,7 +2,7 @@
// Use of this source code is governed by a BSD-style // Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file. // license that can be found in the LICENSE file.
// +build darwin dragonfly freebsd linux netbsd openbsd solaris // +build aix darwin dragonfly freebsd linux netbsd openbsd solaris
package unix package unix

View File

@ -581,6 +581,13 @@ const (
RTA_PREF = C.RTA_PREF RTA_PREF = C.RTA_PREF
RTA_ENCAP_TYPE = C.RTA_ENCAP_TYPE RTA_ENCAP_TYPE = C.RTA_ENCAP_TYPE
RTA_ENCAP = C.RTA_ENCAP RTA_ENCAP = C.RTA_ENCAP
RTA_EXPIRES = C.RTA_EXPIRES
RTA_PAD = C.RTA_PAD
RTA_UID = C.RTA_UID
RTA_TTL_PROPAGATE = C.RTA_TTL_PROPAGATE
RTA_IP_PROTO = C.RTA_IP_PROTO
RTA_SPORT = C.RTA_SPORT
RTA_DPORT = C.RTA_DPORT
RTN_UNSPEC = C.RTN_UNSPEC RTN_UNSPEC = C.RTN_UNSPEC
RTN_UNICAST = C.RTN_UNICAST RTN_UNICAST = C.RTN_UNICAST
RTN_LOCAL = C.RTN_LOCAL RTN_LOCAL = C.RTN_LOCAL

View File

@ -46,6 +46,7 @@ includes_AIX='
#include <sys/stropts.h> #include <sys/stropts.h>
#include <sys/mman.h> #include <sys/mman.h>
#include <sys/poll.h> #include <sys/poll.h>
#include <sys/termio.h>
#include <termios.h> #include <termios.h>
#include <fcntl.h> #include <fcntl.h>
@ -193,6 +194,7 @@ struct ltchars {
#include <linux/fs.h> #include <linux/fs.h>
#include <linux/keyctl.h> #include <linux/keyctl.h>
#include <linux/magic.h> #include <linux/magic.h>
#include <linux/memfd.h>
#include <linux/netfilter/nfnetlink.h> #include <linux/netfilter/nfnetlink.h>
#include <linux/netlink.h> #include <linux/netlink.h>
#include <linux/net_namespace.h> #include <linux/net_namespace.h>
@ -413,7 +415,7 @@ ccflags="$@"
$2 ~ /^TC[IO](ON|OFF)$/ || $2 ~ /^TC[IO](ON|OFF)$/ ||
$2 ~ /^IN_/ || $2 ~ /^IN_/ ||
$2 ~ /^LOCK_(SH|EX|NB|UN)$/ || $2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||
$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|EVFILT|NOTE|EV|SHUT|PROT|MAP|T?PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ || $2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|EVFILT|NOTE|EV|SHUT|PROT|MAP|MFD|T?PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ ||
$2 ~ /^TP_STATUS_/ || $2 ~ /^TP_STATUS_/ ||
$2 ~ /^FALLOC_/ || $2 ~ /^FALLOC_/ ||
$2 == "ICMPV6_FILTER" || $2 == "ICMPV6_FILTER" ||

View File

@ -345,11 +345,11 @@ func IoctlSetInt(fd int, req uint, value int) error {
return ioctl(fd, req, uintptr(value)) return ioctl(fd, req, uintptr(value))
} }
func IoctlSetWinsize(fd int, req uint, value *Winsize) error { func ioctlSetWinsize(fd int, req uint, value *Winsize) error {
return ioctl(fd, req, uintptr(unsafe.Pointer(value))) return ioctl(fd, req, uintptr(unsafe.Pointer(value)))
} }
func IoctlSetTermios(fd int, req uint, value *Termios) error { func ioctlSetTermios(fd int, req uint, value *Termios) error {
return ioctl(fd, req, uintptr(unsafe.Pointer(value))) return ioctl(fd, req, uintptr(unsafe.Pointer(value)))
} }
@ -419,8 +419,10 @@ func Flock(fd int, how int) (err error) {
//sysnb Getsid(pid int) (sid int, err error) //sysnb Getsid(pid int) (sid int, err error)
//sysnb Kill(pid int, sig syscall.Signal) (err error) //sysnb Kill(pid int, sig syscall.Signal) (err error)
//sys Klogctl(typ int, buf []byte) (n int, err error) = syslog //sys Klogctl(typ int, buf []byte) (n int, err error) = syslog
//sys Mkdir(dirfd int, path string, mode uint32) (err error)
//sys Mkdirat(dirfd int, path string, mode uint32) (err error) //sys Mkdirat(dirfd int, path string, mode uint32) (err error)
//sys Mkfifo(path string, mode uint32) (err error) //sys Mkfifo(path string, mode uint32) (err error)
//sys Mknod(path string, mode uint32, dev int) (err error)
//sys Mknodat(dirfd int, path string, mode uint32, dev int) (err error) //sys Mknodat(dirfd int, path string, mode uint32, dev int) (err error)
//sys Nanosleep(time *Timespec, leftover *Timespec) (err error) //sys Nanosleep(time *Timespec, leftover *Timespec) (err error)
//sys Open(path string, mode int, perm uint32) (fd int, err error) = open64 //sys Open(path string, mode int, perm uint32) (fd int, err error) = open64

View File

@ -1320,6 +1320,7 @@ func Getpgrp() (pid int) {
//sys Llistxattr(path string, dest []byte) (sz int, err error) //sys Llistxattr(path string, dest []byte) (sz int, err error)
//sys Lremovexattr(path string, attr string) (err error) //sys Lremovexattr(path string, attr string) (err error)
//sys Lsetxattr(path string, attr string, data []byte, flags int) (err error) //sys Lsetxattr(path string, attr string, data []byte, flags int) (err error)
//sys MemfdCreate(name string, flags int) (fd int, err error)
//sys Mkdirat(dirfd int, path string, mode uint32) (err error) //sys Mkdirat(dirfd int, path string, mode uint32) (err error)
//sys Mknodat(dirfd int, path string, mode uint32, dev int) (err error) //sys Mknodat(dirfd int, path string, mode uint32, dev int) (err error)
//sys Nanosleep(time *Timespec, leftover *Timespec) (err error) //sys Nanosleep(time *Timespec, leftover *Timespec) (err error)

View File

@ -22,6 +22,11 @@ package unix
#include <utime.h> #include <utime.h>
#include <sys/utsname.h> #include <sys/utsname.h>
#include <sys/poll.h> #include <sys/poll.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <sys/statfs.h>
#include <sys/termio.h>
#include <sys/ioctl.h>
#include <termios.h> #include <termios.h>
@ -33,7 +38,6 @@ package unix
#include <dirent.h> #include <dirent.h>
#include <fcntl.h> #include <fcntl.h>
#include <gcrypt.h>
enum { enum {
sizeofPtr = sizeof(void*), sizeofPtr = sizeof(void*),
@ -224,6 +228,9 @@ type Flock_t C.struct_flock64
// Statfs // Statfs
type Fsid_t C.struct_fsid_t
type Fsid64_t C.struct_fsid64_t
type Statfs_t C.struct_statfs type Statfs_t C.struct_statfs
const RNDGETENTCNT = 0x80045200 const RNDGETENTCNT = 0x80045200

View File

@ -867,6 +867,9 @@ const (
TAB2 = 0x800 TAB2 = 0x800
TAB3 = 0xc00 TAB3 = 0xc00
TABDLY = 0xc00 TABDLY = 0xc00
TCFLSH = 0x540c
TCGETA = 0x5405
TCGETS = 0x5401
TCIFLUSH = 0x0 TCIFLUSH = 0x0
TCIOFF = 0x2 TCIOFF = 0x2
TCIOFLUSH = 0x2 TCIOFLUSH = 0x2
@ -915,6 +918,15 @@ const (
TCP_TIMESTAMP_OPTLEN = 0xc TCP_TIMESTAMP_OPTLEN = 0xc
TCP_UNSETPRIV = 0x28 TCP_UNSETPRIV = 0x28
TCSAFLUSH = 0x2 TCSAFLUSH = 0x2
TCSBRK = 0x5409
TCSETA = 0x5406
TCSETAF = 0x5408
TCSETAW = 0x5407
TCSETS = 0x5402
TCSETSF = 0x5404
TCSETSW = 0x5403
TCXONC = 0x540b
TIOC = 0x5400
TIOCCBRK = 0x2000747a TIOCCBRK = 0x2000747a
TIOCCDTR = 0x20007478 TIOCCDTR = 0x20007478
TIOCCONS = 0x80047462 TIOCCONS = 0x80047462

View File

@ -867,6 +867,9 @@ const (
TAB2 = 0x800 TAB2 = 0x800
TAB3 = 0xc00 TAB3 = 0xc00
TABDLY = 0xc00 TABDLY = 0xc00
TCFLSH = 0x540c
TCGETA = 0x5405
TCGETS = 0x5401
TCIFLUSH = 0x0 TCIFLUSH = 0x0
TCIOFF = 0x2 TCIOFF = 0x2
TCIOFLUSH = 0x2 TCIOFLUSH = 0x2
@ -915,6 +918,15 @@ const (
TCP_TIMESTAMP_OPTLEN = 0xc TCP_TIMESTAMP_OPTLEN = 0xc
TCP_UNSETPRIV = 0x28 TCP_UNSETPRIV = 0x28
TCSAFLUSH = 0x2 TCSAFLUSH = 0x2
TCSBRK = 0x5409
TCSETA = 0x5406
TCSETAF = 0x5408
TCSETAW = 0x5407
TCSETS = 0x5402
TCSETSF = 0x5404
TCSETSW = 0x5403
TCXONC = 0x540b
TIOC = 0x5400
TIOCCBRK = 0x2000747a TIOCCBRK = 0x2000747a
TIOCCDTR = 0x20007478 TIOCCDTR = 0x20007478
TIOCCONS = 0xffffffff80047462 TIOCCONS = 0xffffffff80047462

View File

@ -977,6 +977,21 @@ const (
MCL_CURRENT = 0x1 MCL_CURRENT = 0x1
MCL_FUTURE = 0x2 MCL_FUTURE = 0x2
MCL_ONFAULT = 0x4 MCL_ONFAULT = 0x4
MFD_ALLOW_SEALING = 0x2
MFD_CLOEXEC = 0x1
MFD_HUGETLB = 0x4
MFD_HUGE_16GB = -0x78000000
MFD_HUGE_16MB = 0x60000000
MFD_HUGE_1GB = 0x78000000
MFD_HUGE_1MB = 0x50000000
MFD_HUGE_256MB = 0x70000000
MFD_HUGE_2GB = 0x7c000000
MFD_HUGE_2MB = 0x54000000
MFD_HUGE_512KB = 0x4c000000
MFD_HUGE_64KB = 0x40000000
MFD_HUGE_8MB = 0x5c000000
MFD_HUGE_MASK = 0x3f
MFD_HUGE_SHIFT = 0x1a
MINIX2_SUPER_MAGIC = 0x2468 MINIX2_SUPER_MAGIC = 0x2468
MINIX2_SUPER_MAGIC2 = 0x2478 MINIX2_SUPER_MAGIC2 = 0x2478
MINIX3_SUPER_MAGIC = 0x4d5a MINIX3_SUPER_MAGIC = 0x4d5a

View File

@ -977,6 +977,21 @@ const (
MCL_CURRENT = 0x1 MCL_CURRENT = 0x1
MCL_FUTURE = 0x2 MCL_FUTURE = 0x2
MCL_ONFAULT = 0x4 MCL_ONFAULT = 0x4
MFD_ALLOW_SEALING = 0x2
MFD_CLOEXEC = 0x1
MFD_HUGETLB = 0x4
MFD_HUGE_16GB = -0x78000000
MFD_HUGE_16MB = 0x60000000
MFD_HUGE_1GB = 0x78000000
MFD_HUGE_1MB = 0x50000000
MFD_HUGE_256MB = 0x70000000
MFD_HUGE_2GB = 0x7c000000
MFD_HUGE_2MB = 0x54000000
MFD_HUGE_512KB = 0x4c000000
MFD_HUGE_64KB = 0x40000000
MFD_HUGE_8MB = 0x5c000000
MFD_HUGE_MASK = 0x3f
MFD_HUGE_SHIFT = 0x1a
MINIX2_SUPER_MAGIC = 0x2468 MINIX2_SUPER_MAGIC = 0x2468
MINIX2_SUPER_MAGIC2 = 0x2478 MINIX2_SUPER_MAGIC2 = 0x2478
MINIX3_SUPER_MAGIC = 0x4d5a MINIX3_SUPER_MAGIC = 0x4d5a

View File

@ -975,6 +975,21 @@ const (
MCL_CURRENT = 0x1 MCL_CURRENT = 0x1
MCL_FUTURE = 0x2 MCL_FUTURE = 0x2
MCL_ONFAULT = 0x4 MCL_ONFAULT = 0x4
MFD_ALLOW_SEALING = 0x2
MFD_CLOEXEC = 0x1
MFD_HUGETLB = 0x4
MFD_HUGE_16GB = -0x78000000
MFD_HUGE_16MB = 0x60000000
MFD_HUGE_1GB = 0x78000000
MFD_HUGE_1MB = 0x50000000
MFD_HUGE_256MB = 0x70000000
MFD_HUGE_2GB = 0x7c000000
MFD_HUGE_2MB = 0x54000000
MFD_HUGE_512KB = 0x4c000000
MFD_HUGE_64KB = 0x40000000
MFD_HUGE_8MB = 0x5c000000
MFD_HUGE_MASK = 0x3f
MFD_HUGE_SHIFT = 0x1a
MINIX2_SUPER_MAGIC = 0x2468 MINIX2_SUPER_MAGIC = 0x2468
MINIX2_SUPER_MAGIC2 = 0x2478 MINIX2_SUPER_MAGIC2 = 0x2478
MINIX3_SUPER_MAGIC = 0x4d5a MINIX3_SUPER_MAGIC = 0x4d5a

View File

@ -978,6 +978,21 @@ const (
MCL_CURRENT = 0x1 MCL_CURRENT = 0x1
MCL_FUTURE = 0x2 MCL_FUTURE = 0x2
MCL_ONFAULT = 0x4 MCL_ONFAULT = 0x4
MFD_ALLOW_SEALING = 0x2
MFD_CLOEXEC = 0x1
MFD_HUGETLB = 0x4
MFD_HUGE_16GB = -0x78000000
MFD_HUGE_16MB = 0x60000000
MFD_HUGE_1GB = 0x78000000
MFD_HUGE_1MB = 0x50000000
MFD_HUGE_256MB = 0x70000000
MFD_HUGE_2GB = 0x7c000000
MFD_HUGE_2MB = 0x54000000
MFD_HUGE_512KB = 0x4c000000
MFD_HUGE_64KB = 0x40000000
MFD_HUGE_8MB = 0x5c000000
MFD_HUGE_MASK = 0x3f
MFD_HUGE_SHIFT = 0x1a
MINIX2_SUPER_MAGIC = 0x2468 MINIX2_SUPER_MAGIC = 0x2468
MINIX2_SUPER_MAGIC2 = 0x2478 MINIX2_SUPER_MAGIC2 = 0x2478
MINIX3_SUPER_MAGIC = 0x4d5a MINIX3_SUPER_MAGIC = 0x4d5a

View File

@ -975,6 +975,21 @@ const (
MCL_CURRENT = 0x1 MCL_CURRENT = 0x1
MCL_FUTURE = 0x2 MCL_FUTURE = 0x2
MCL_ONFAULT = 0x4 MCL_ONFAULT = 0x4
MFD_ALLOW_SEALING = 0x2
MFD_CLOEXEC = 0x1
MFD_HUGETLB = 0x4
MFD_HUGE_16GB = -0x78000000
MFD_HUGE_16MB = 0x60000000
MFD_HUGE_1GB = 0x78000000
MFD_HUGE_1MB = 0x50000000
MFD_HUGE_256MB = 0x70000000
MFD_HUGE_2GB = 0x7c000000
MFD_HUGE_2MB = 0x54000000
MFD_HUGE_512KB = 0x4c000000
MFD_HUGE_64KB = 0x40000000
MFD_HUGE_8MB = 0x5c000000
MFD_HUGE_MASK = 0x3f
MFD_HUGE_SHIFT = 0x1a
MINIX2_SUPER_MAGIC = 0x2468 MINIX2_SUPER_MAGIC = 0x2468
MINIX2_SUPER_MAGIC2 = 0x2478 MINIX2_SUPER_MAGIC2 = 0x2478
MINIX3_SUPER_MAGIC = 0x4d5a MINIX3_SUPER_MAGIC = 0x4d5a

View File

@ -975,6 +975,21 @@ const (
MCL_CURRENT = 0x1 MCL_CURRENT = 0x1
MCL_FUTURE = 0x2 MCL_FUTURE = 0x2
MCL_ONFAULT = 0x4 MCL_ONFAULT = 0x4
MFD_ALLOW_SEALING = 0x2
MFD_CLOEXEC = 0x1
MFD_HUGETLB = 0x4
MFD_HUGE_16GB = -0x78000000
MFD_HUGE_16MB = 0x60000000
MFD_HUGE_1GB = 0x78000000
MFD_HUGE_1MB = 0x50000000
MFD_HUGE_256MB = 0x70000000
MFD_HUGE_2GB = 0x7c000000
MFD_HUGE_2MB = 0x54000000
MFD_HUGE_512KB = 0x4c000000
MFD_HUGE_64KB = 0x40000000
MFD_HUGE_8MB = 0x5c000000
MFD_HUGE_MASK = 0x3f
MFD_HUGE_SHIFT = 0x1a
MINIX2_SUPER_MAGIC = 0x2468 MINIX2_SUPER_MAGIC = 0x2468
MINIX2_SUPER_MAGIC2 = 0x2478 MINIX2_SUPER_MAGIC2 = 0x2478
MINIX3_SUPER_MAGIC = 0x4d5a MINIX3_SUPER_MAGIC = 0x4d5a

View File

@ -975,6 +975,21 @@ const (
MCL_CURRENT = 0x1 MCL_CURRENT = 0x1
MCL_FUTURE = 0x2 MCL_FUTURE = 0x2
MCL_ONFAULT = 0x4 MCL_ONFAULT = 0x4
MFD_ALLOW_SEALING = 0x2
MFD_CLOEXEC = 0x1
MFD_HUGETLB = 0x4
MFD_HUGE_16GB = -0x78000000
MFD_HUGE_16MB = 0x60000000
MFD_HUGE_1GB = 0x78000000
MFD_HUGE_1MB = 0x50000000
MFD_HUGE_256MB = 0x70000000
MFD_HUGE_2GB = 0x7c000000
MFD_HUGE_2MB = 0x54000000
MFD_HUGE_512KB = 0x4c000000
MFD_HUGE_64KB = 0x40000000
MFD_HUGE_8MB = 0x5c000000
MFD_HUGE_MASK = 0x3f
MFD_HUGE_SHIFT = 0x1a
MINIX2_SUPER_MAGIC = 0x2468 MINIX2_SUPER_MAGIC = 0x2468
MINIX2_SUPER_MAGIC2 = 0x2478 MINIX2_SUPER_MAGIC2 = 0x2478
MINIX3_SUPER_MAGIC = 0x4d5a MINIX3_SUPER_MAGIC = 0x4d5a

View File

@ -975,6 +975,21 @@ const (
MCL_CURRENT = 0x1 MCL_CURRENT = 0x1
MCL_FUTURE = 0x2 MCL_FUTURE = 0x2
MCL_ONFAULT = 0x4 MCL_ONFAULT = 0x4
MFD_ALLOW_SEALING = 0x2
MFD_CLOEXEC = 0x1
MFD_HUGETLB = 0x4
MFD_HUGE_16GB = -0x78000000
MFD_HUGE_16MB = 0x60000000
MFD_HUGE_1GB = 0x78000000
MFD_HUGE_1MB = 0x50000000
MFD_HUGE_256MB = 0x70000000
MFD_HUGE_2GB = 0x7c000000
MFD_HUGE_2MB = 0x54000000
MFD_HUGE_512KB = 0x4c000000
MFD_HUGE_64KB = 0x40000000
MFD_HUGE_8MB = 0x5c000000
MFD_HUGE_MASK = 0x3f
MFD_HUGE_SHIFT = 0x1a
MINIX2_SUPER_MAGIC = 0x2468 MINIX2_SUPER_MAGIC = 0x2468
MINIX2_SUPER_MAGIC2 = 0x2478 MINIX2_SUPER_MAGIC2 = 0x2478
MINIX3_SUPER_MAGIC = 0x4d5a MINIX3_SUPER_MAGIC = 0x4d5a

View File

@ -974,6 +974,21 @@ const (
MCL_CURRENT = 0x2000 MCL_CURRENT = 0x2000
MCL_FUTURE = 0x4000 MCL_FUTURE = 0x4000
MCL_ONFAULT = 0x8000 MCL_ONFAULT = 0x8000
MFD_ALLOW_SEALING = 0x2
MFD_CLOEXEC = 0x1
MFD_HUGETLB = 0x4
MFD_HUGE_16GB = -0x78000000
MFD_HUGE_16MB = 0x60000000
MFD_HUGE_1GB = 0x78000000
MFD_HUGE_1MB = 0x50000000
MFD_HUGE_256MB = 0x70000000
MFD_HUGE_2GB = 0x7c000000
MFD_HUGE_2MB = 0x54000000
MFD_HUGE_512KB = 0x4c000000
MFD_HUGE_64KB = 0x40000000
MFD_HUGE_8MB = 0x5c000000
MFD_HUGE_MASK = 0x3f
MFD_HUGE_SHIFT = 0x1a
MINIX2_SUPER_MAGIC = 0x2468 MINIX2_SUPER_MAGIC = 0x2468
MINIX2_SUPER_MAGIC2 = 0x2478 MINIX2_SUPER_MAGIC2 = 0x2478
MINIX3_SUPER_MAGIC = 0x4d5a MINIX3_SUPER_MAGIC = 0x4d5a

View File

@ -974,6 +974,21 @@ const (
MCL_CURRENT = 0x2000 MCL_CURRENT = 0x2000
MCL_FUTURE = 0x4000 MCL_FUTURE = 0x4000
MCL_ONFAULT = 0x8000 MCL_ONFAULT = 0x8000
MFD_ALLOW_SEALING = 0x2
MFD_CLOEXEC = 0x1
MFD_HUGETLB = 0x4
MFD_HUGE_16GB = -0x78000000
MFD_HUGE_16MB = 0x60000000
MFD_HUGE_1GB = 0x78000000
MFD_HUGE_1MB = 0x50000000
MFD_HUGE_256MB = 0x70000000
MFD_HUGE_2GB = 0x7c000000
MFD_HUGE_2MB = 0x54000000
MFD_HUGE_512KB = 0x4c000000
MFD_HUGE_64KB = 0x40000000
MFD_HUGE_8MB = 0x5c000000
MFD_HUGE_MASK = 0x3f
MFD_HUGE_SHIFT = 0x1a
MINIX2_SUPER_MAGIC = 0x2468 MINIX2_SUPER_MAGIC = 0x2468
MINIX2_SUPER_MAGIC2 = 0x2478 MINIX2_SUPER_MAGIC2 = 0x2478
MINIX3_SUPER_MAGIC = 0x4d5a MINIX3_SUPER_MAGIC = 0x4d5a

View File

@ -975,6 +975,21 @@ const (
MCL_CURRENT = 0x1 MCL_CURRENT = 0x1
MCL_FUTURE = 0x2 MCL_FUTURE = 0x2
MCL_ONFAULT = 0x4 MCL_ONFAULT = 0x4
MFD_ALLOW_SEALING = 0x2
MFD_CLOEXEC = 0x1
MFD_HUGETLB = 0x4
MFD_HUGE_16GB = -0x78000000
MFD_HUGE_16MB = 0x60000000
MFD_HUGE_1GB = 0x78000000
MFD_HUGE_1MB = 0x50000000
MFD_HUGE_256MB = 0x70000000
MFD_HUGE_2GB = 0x7c000000
MFD_HUGE_2MB = 0x54000000
MFD_HUGE_512KB = 0x4c000000
MFD_HUGE_64KB = 0x40000000
MFD_HUGE_8MB = 0x5c000000
MFD_HUGE_MASK = 0x3f
MFD_HUGE_SHIFT = 0x1a
MINIX2_SUPER_MAGIC = 0x2468 MINIX2_SUPER_MAGIC = 0x2468
MINIX2_SUPER_MAGIC2 = 0x2478 MINIX2_SUPER_MAGIC2 = 0x2478
MINIX3_SUPER_MAGIC = 0x4d5a MINIX3_SUPER_MAGIC = 0x4d5a

View File

@ -975,6 +975,21 @@ const (
MCL_CURRENT = 0x1 MCL_CURRENT = 0x1
MCL_FUTURE = 0x2 MCL_FUTURE = 0x2
MCL_ONFAULT = 0x4 MCL_ONFAULT = 0x4
MFD_ALLOW_SEALING = 0x2
MFD_CLOEXEC = 0x1
MFD_HUGETLB = 0x4
MFD_HUGE_16GB = -0x78000000
MFD_HUGE_16MB = 0x60000000
MFD_HUGE_1GB = 0x78000000
MFD_HUGE_1MB = 0x50000000
MFD_HUGE_256MB = 0x70000000
MFD_HUGE_2GB = 0x7c000000
MFD_HUGE_2MB = 0x54000000
MFD_HUGE_512KB = 0x4c000000
MFD_HUGE_64KB = 0x40000000
MFD_HUGE_8MB = 0x5c000000
MFD_HUGE_MASK = 0x3f
MFD_HUGE_SHIFT = 0x1a
MINIX2_SUPER_MAGIC = 0x2468 MINIX2_SUPER_MAGIC = 0x2468
MINIX2_SUPER_MAGIC2 = 0x2478 MINIX2_SUPER_MAGIC2 = 0x2478
MINIX3_SUPER_MAGIC = 0x4d5a MINIX3_SUPER_MAGIC = 0x4d5a

View File

@ -39,8 +39,10 @@ int getrusage(int, uintptr_t);
int getsid(int); int getsid(int);
int kill(int, int); int kill(int, int);
int syslog(int, uintptr_t, size_t); int syslog(int, uintptr_t, size_t);
int mkdir(int, uintptr_t, unsigned int);
int mkdirat(int, uintptr_t, unsigned int); int mkdirat(int, uintptr_t, unsigned int);
int mkfifo(uintptr_t, unsigned int); int mkfifo(uintptr_t, unsigned int);
int mknod(uintptr_t, unsigned int, int);
int mknodat(int, uintptr_t, unsigned int, int); int mknodat(int, uintptr_t, unsigned int, int);
int nanosleep(uintptr_t, uintptr_t); int nanosleep(uintptr_t, uintptr_t);
int open64(uintptr_t, int, unsigned int); int open64(uintptr_t, int, unsigned int);
@ -502,6 +504,17 @@ func Klogctl(typ int, buf []byte) (n int, err error) {
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkdir(dirfd int, path string, mode uint32) (err error) {
_p0 := uintptr(unsafe.Pointer(C.CString(path)))
r0, er := C.mkdir(C.int(dirfd), C.uintptr_t(_p0), C.uint(mode))
if r0 == -1 && er != nil {
err = er
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkdirat(dirfd int, path string, mode uint32) (err error) { func Mkdirat(dirfd int, path string, mode uint32) (err error) {
_p0 := uintptr(unsafe.Pointer(C.CString(path))) _p0 := uintptr(unsafe.Pointer(C.CString(path)))
r0, er := C.mkdirat(C.int(dirfd), C.uintptr_t(_p0), C.uint(mode)) r0, er := C.mkdirat(C.int(dirfd), C.uintptr_t(_p0), C.uint(mode))
@ -524,6 +537,17 @@ func Mkfifo(path string, mode uint32) (err error) {
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mknod(path string, mode uint32, dev int) (err error) {
_p0 := uintptr(unsafe.Pointer(C.CString(path)))
r0, er := C.mknod(C.uintptr_t(_p0), C.uint(mode), C.int(dev))
if r0 == -1 && er != nil {
err = er
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) {
_p0 := uintptr(unsafe.Pointer(C.CString(path))) _p0 := uintptr(unsafe.Pointer(C.CString(path)))
r0, er := C.mknodat(C.int(dirfd), C.uintptr_t(_p0), C.uint(mode), C.int(dev)) r0, er := C.mknodat(C.int(dirfd), C.uintptr_t(_p0), C.uint(mode), C.int(dev))

View File

@ -39,8 +39,10 @@ int getrusage(int, uintptr_t);
int getsid(int); int getsid(int);
int kill(int, int); int kill(int, int);
int syslog(int, uintptr_t, size_t); int syslog(int, uintptr_t, size_t);
int mkdir(int, uintptr_t, unsigned int);
int mkdirat(int, uintptr_t, unsigned int); int mkdirat(int, uintptr_t, unsigned int);
int mkfifo(uintptr_t, unsigned int); int mkfifo(uintptr_t, unsigned int);
int mknod(uintptr_t, unsigned int, int);
int mknodat(int, uintptr_t, unsigned int, int); int mknodat(int, uintptr_t, unsigned int, int);
int nanosleep(uintptr_t, uintptr_t); int nanosleep(uintptr_t, uintptr_t);
int open64(uintptr_t, int, unsigned int); int open64(uintptr_t, int, unsigned int);
@ -502,6 +504,17 @@ func Klogctl(typ int, buf []byte) (n int, err error) {
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkdir(dirfd int, path string, mode uint32) (err error) {
_p0 := uintptr(unsafe.Pointer(C.CString(path)))
r0, er := C.mkdir(C.int(dirfd), C.uintptr_t(_p0), C.uint(mode))
if r0 == -1 && er != nil {
err = er
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkdirat(dirfd int, path string, mode uint32) (err error) { func Mkdirat(dirfd int, path string, mode uint32) (err error) {
_p0 := uintptr(unsafe.Pointer(C.CString(path))) _p0 := uintptr(unsafe.Pointer(C.CString(path)))
r0, er := C.mkdirat(C.int(dirfd), C.uintptr_t(_p0), C.uint(mode)) r0, er := C.mkdirat(C.int(dirfd), C.uintptr_t(_p0), C.uint(mode))
@ -524,6 +537,17 @@ func Mkfifo(path string, mode uint32) (err error) {
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mknod(path string, mode uint32, dev int) (err error) {
_p0 := uintptr(unsafe.Pointer(C.CString(path)))
r0, er := C.mknod(C.uintptr_t(_p0), C.uint(mode), C.int(dev))
if r0 == -1 && er != nil {
err = er
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) { func Mknodat(dirfd int, path string, mode uint32, dev int) (err error) {
_p0 := uintptr(unsafe.Pointer(C.CString(path))) _p0 := uintptr(unsafe.Pointer(C.CString(path)))
r0, er := C.mknodat(C.int(dirfd), C.uintptr_t(_p0), C.uint(mode), C.int(dev)) r0, er := C.mknodat(C.int(dirfd), C.uintptr_t(_p0), C.uint(mode), C.int(dev))

View File

@ -979,6 +979,22 @@ func Lsetxattr(path string, attr string, data []byte, flags int) (err error) {
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func MemfdCreate(name string, flags int) (fd int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(name)
if err != nil {
return
}
r0, _, e1 := Syscall(SYS_MEMFD_CREATE, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkdirat(dirfd int, path string, mode uint32) (err error) { func Mkdirat(dirfd int, path string, mode uint32) (err error) {
var _p0 *byte var _p0 *byte
_p0, err = BytePtrFromString(path) _p0, err = BytePtrFromString(path)

View File

@ -979,6 +979,22 @@ func Lsetxattr(path string, attr string, data []byte, flags int) (err error) {
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func MemfdCreate(name string, flags int) (fd int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(name)
if err != nil {
return
}
r0, _, e1 := Syscall(SYS_MEMFD_CREATE, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkdirat(dirfd int, path string, mode uint32) (err error) { func Mkdirat(dirfd int, path string, mode uint32) (err error) {
var _p0 *byte var _p0 *byte
_p0, err = BytePtrFromString(path) _p0, err = BytePtrFromString(path)

View File

@ -979,6 +979,22 @@ func Lsetxattr(path string, attr string, data []byte, flags int) (err error) {
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func MemfdCreate(name string, flags int) (fd int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(name)
if err != nil {
return
}
r0, _, e1 := Syscall(SYS_MEMFD_CREATE, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkdirat(dirfd int, path string, mode uint32) (err error) { func Mkdirat(dirfd int, path string, mode uint32) (err error) {
var _p0 *byte var _p0 *byte
_p0, err = BytePtrFromString(path) _p0, err = BytePtrFromString(path)

View File

@ -979,6 +979,22 @@ func Lsetxattr(path string, attr string, data []byte, flags int) (err error) {
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func MemfdCreate(name string, flags int) (fd int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(name)
if err != nil {
return
}
r0, _, e1 := Syscall(SYS_MEMFD_CREATE, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkdirat(dirfd int, path string, mode uint32) (err error) { func Mkdirat(dirfd int, path string, mode uint32) (err error) {
var _p0 *byte var _p0 *byte
_p0, err = BytePtrFromString(path) _p0, err = BytePtrFromString(path)

View File

@ -979,6 +979,22 @@ func Lsetxattr(path string, attr string, data []byte, flags int) (err error) {
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func MemfdCreate(name string, flags int) (fd int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(name)
if err != nil {
return
}
r0, _, e1 := Syscall(SYS_MEMFD_CREATE, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkdirat(dirfd int, path string, mode uint32) (err error) { func Mkdirat(dirfd int, path string, mode uint32) (err error) {
var _p0 *byte var _p0 *byte
_p0, err = BytePtrFromString(path) _p0, err = BytePtrFromString(path)

View File

@ -979,6 +979,22 @@ func Lsetxattr(path string, attr string, data []byte, flags int) (err error) {
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func MemfdCreate(name string, flags int) (fd int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(name)
if err != nil {
return
}
r0, _, e1 := Syscall(SYS_MEMFD_CREATE, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkdirat(dirfd int, path string, mode uint32) (err error) { func Mkdirat(dirfd int, path string, mode uint32) (err error) {
var _p0 *byte var _p0 *byte
_p0, err = BytePtrFromString(path) _p0, err = BytePtrFromString(path)

View File

@ -979,6 +979,22 @@ func Lsetxattr(path string, attr string, data []byte, flags int) (err error) {
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func MemfdCreate(name string, flags int) (fd int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(name)
if err != nil {
return
}
r0, _, e1 := Syscall(SYS_MEMFD_CREATE, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkdirat(dirfd int, path string, mode uint32) (err error) { func Mkdirat(dirfd int, path string, mode uint32) (err error) {
var _p0 *byte var _p0 *byte
_p0, err = BytePtrFromString(path) _p0, err = BytePtrFromString(path)

View File

@ -979,6 +979,22 @@ func Lsetxattr(path string, attr string, data []byte, flags int) (err error) {
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func MemfdCreate(name string, flags int) (fd int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(name)
if err != nil {
return
}
r0, _, e1 := Syscall(SYS_MEMFD_CREATE, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkdirat(dirfd int, path string, mode uint32) (err error) { func Mkdirat(dirfd int, path string, mode uint32) (err error) {
var _p0 *byte var _p0 *byte
_p0, err = BytePtrFromString(path) _p0, err = BytePtrFromString(path)

View File

@ -979,6 +979,22 @@ func Lsetxattr(path string, attr string, data []byte, flags int) (err error) {
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func MemfdCreate(name string, flags int) (fd int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(name)
if err != nil {
return
}
r0, _, e1 := Syscall(SYS_MEMFD_CREATE, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkdirat(dirfd int, path string, mode uint32) (err error) { func Mkdirat(dirfd int, path string, mode uint32) (err error) {
var _p0 *byte var _p0 *byte
_p0, err = BytePtrFromString(path) _p0, err = BytePtrFromString(path)

View File

@ -979,6 +979,22 @@ func Lsetxattr(path string, attr string, data []byte, flags int) (err error) {
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func MemfdCreate(name string, flags int) (fd int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(name)
if err != nil {
return
}
r0, _, e1 := Syscall(SYS_MEMFD_CREATE, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkdirat(dirfd int, path string, mode uint32) (err error) { func Mkdirat(dirfd int, path string, mode uint32) (err error) {
var _p0 *byte var _p0 *byte
_p0, err = BytePtrFromString(path) _p0, err = BytePtrFromString(path)

View File

@ -979,6 +979,22 @@ func Lsetxattr(path string, attr string, data []byte, flags int) (err error) {
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func MemfdCreate(name string, flags int) (fd int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(name)
if err != nil {
return
}
r0, _, e1 := Syscall(SYS_MEMFD_CREATE, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkdirat(dirfd int, path string, mode uint32) (err error) { func Mkdirat(dirfd int, path string, mode uint32) (err error) {
var _p0 *byte var _p0 *byte
_p0, err = BytePtrFromString(path) _p0, err = BytePtrFromString(path)

View File

@ -979,6 +979,22 @@ func Lsetxattr(path string, attr string, data []byte, flags int) (err error) {
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func MemfdCreate(name string, flags int) (fd int, err error) {
var _p0 *byte
_p0, err = BytePtrFromString(name)
if err != nil {
return
}
r0, _, e1 := Syscall(SYS_MEMFD_CREATE, uintptr(unsafe.Pointer(_p0)), uintptr(flags), 0)
fd = int(r0)
if e1 != 0 {
err = errnoErr(e1)
}
return
}
// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT
func Mkdirat(dirfd int, path string, mode uint32) (err error) { func Mkdirat(dirfd int, path string, mode uint32) (err error) {
var _p0 *byte var _p0 *byte
_p0, err = BytePtrFromString(path) _p0, err = BytePtrFromString(path)

View File

@ -268,9 +268,22 @@ type Termios struct {
Cc [16]uint8 Cc [16]uint8
} }
type Termio struct{} type Termio struct {
Iflag uint16
Oflag uint16
Cflag uint16
Lflag uint16
Line uint8
Cc [8]uint8
_ [1]byte
}
type Winsize struct{} type Winsize struct {
Row uint16
Col uint16
Xpixel uint16
Ypixel uint16
}
type PollFd struct { type PollFd struct {
Fd int32 Fd int32
@ -301,6 +314,32 @@ type Flock_t struct {
Len int64 Len int64
} }
type Statfs_t struct{} type Fsid_t struct {
Val [2]uint32
}
type Fsid64_t struct {
Val [2]uint64
}
type Statfs_t struct {
Version int32
Type int32
Bsize uint32
Blocks uint32
Bfree uint32
Bavail uint32
Files uint32
Ffree uint32
Fsid Fsid_t
Vfstype int32
Fsize uint32
Vfsnumber int32
Vfsoff int32
Vfslen int32
Vfsvers int32
Fname [32]uint8
Fpack [32]uint8
Name_max int32
}
const RNDGETENTCNT = 0x80045200 const RNDGETENTCNT = 0x80045200

View File

@ -275,9 +275,22 @@ type Termios struct {
Cc [16]uint8 Cc [16]uint8
} }
type Termio struct{} type Termio struct {
Iflag uint16
Oflag uint16
Cflag uint16
Lflag uint16
Line uint8
Cc [8]uint8
_ [1]byte
}
type Winsize struct{} type Winsize struct {
Row uint16
Col uint16
Xpixel uint16
Ypixel uint16
}
type PollFd struct { type PollFd struct {
Fd int32 Fd int32
@ -308,6 +321,34 @@ type Flock_t struct {
Len int64 Len int64
} }
type Statfs_t struct{} type Fsid_t struct {
Val [2]uint32
}
type Fsid64_t struct {
Val [2]uint64
}
type Statfs_t struct {
Version int32
Type int32
Bsize uint64
Blocks uint64
Bfree uint64
Bavail uint64
Files uint64
Ffree uint64
Fsid Fsid64_t
Vfstype int32
_ [4]byte
Fsize uint64
Vfsnumber int32
Vfsoff int32
Vfslen int32
Vfsvers int32
Fname [32]uint8
Fpack [32]uint8
Name_max int32
_ [4]byte
}
const RNDGETENTCNT = 0x80045200 const RNDGETENTCNT = 0x80045200

View File

@ -517,6 +517,13 @@ const (
RTA_PREF = 0x14 RTA_PREF = 0x14
RTA_ENCAP_TYPE = 0x15 RTA_ENCAP_TYPE = 0x15
RTA_ENCAP = 0x16 RTA_ENCAP = 0x16
RTA_EXPIRES = 0x17
RTA_PAD = 0x18
RTA_UID = 0x19
RTA_TTL_PROPAGATE = 0x1a
RTA_IP_PROTO = 0x1b
RTA_SPORT = 0x1c
RTA_DPORT = 0x1d
RTN_UNSPEC = 0x0 RTN_UNSPEC = 0x0
RTN_UNICAST = 0x1 RTN_UNICAST = 0x1
RTN_LOCAL = 0x2 RTN_LOCAL = 0x2

View File

@ -521,6 +521,13 @@ const (
RTA_PREF = 0x14 RTA_PREF = 0x14
RTA_ENCAP_TYPE = 0x15 RTA_ENCAP_TYPE = 0x15
RTA_ENCAP = 0x16 RTA_ENCAP = 0x16
RTA_EXPIRES = 0x17
RTA_PAD = 0x18
RTA_UID = 0x19
RTA_TTL_PROPAGATE = 0x1a
RTA_IP_PROTO = 0x1b
RTA_SPORT = 0x1c
RTA_DPORT = 0x1d
RTN_UNSPEC = 0x0 RTN_UNSPEC = 0x0
RTN_UNICAST = 0x1 RTN_UNICAST = 0x1
RTN_LOCAL = 0x2 RTN_LOCAL = 0x2

View File

@ -520,6 +520,13 @@ const (
RTA_PREF = 0x14 RTA_PREF = 0x14
RTA_ENCAP_TYPE = 0x15 RTA_ENCAP_TYPE = 0x15
RTA_ENCAP = 0x16 RTA_ENCAP = 0x16
RTA_EXPIRES = 0x17
RTA_PAD = 0x18
RTA_UID = 0x19
RTA_TTL_PROPAGATE = 0x1a
RTA_IP_PROTO = 0x1b
RTA_SPORT = 0x1c
RTA_DPORT = 0x1d
RTN_UNSPEC = 0x0 RTN_UNSPEC = 0x0
RTN_UNICAST = 0x1 RTN_UNICAST = 0x1
RTN_LOCAL = 0x2 RTN_LOCAL = 0x2

View File

@ -522,6 +522,13 @@ const (
RTA_PREF = 0x14 RTA_PREF = 0x14
RTA_ENCAP_TYPE = 0x15 RTA_ENCAP_TYPE = 0x15
RTA_ENCAP = 0x16 RTA_ENCAP = 0x16
RTA_EXPIRES = 0x17
RTA_PAD = 0x18
RTA_UID = 0x19
RTA_TTL_PROPAGATE = 0x1a
RTA_IP_PROTO = 0x1b
RTA_SPORT = 0x1c
RTA_DPORT = 0x1d
RTN_UNSPEC = 0x0 RTN_UNSPEC = 0x0
RTN_UNICAST = 0x1 RTN_UNICAST = 0x1
RTN_LOCAL = 0x2 RTN_LOCAL = 0x2

View File

@ -518,6 +518,13 @@ const (
RTA_PREF = 0x14 RTA_PREF = 0x14
RTA_ENCAP_TYPE = 0x15 RTA_ENCAP_TYPE = 0x15
RTA_ENCAP = 0x16 RTA_ENCAP = 0x16
RTA_EXPIRES = 0x17
RTA_PAD = 0x18
RTA_UID = 0x19
RTA_TTL_PROPAGATE = 0x1a
RTA_IP_PROTO = 0x1b
RTA_SPORT = 0x1c
RTA_DPORT = 0x1d
RTN_UNSPEC = 0x0 RTN_UNSPEC = 0x0
RTN_UNICAST = 0x1 RTN_UNICAST = 0x1
RTN_LOCAL = 0x2 RTN_LOCAL = 0x2

View File

@ -522,6 +522,13 @@ const (
RTA_PREF = 0x14 RTA_PREF = 0x14
RTA_ENCAP_TYPE = 0x15 RTA_ENCAP_TYPE = 0x15
RTA_ENCAP = 0x16 RTA_ENCAP = 0x16
RTA_EXPIRES = 0x17
RTA_PAD = 0x18
RTA_UID = 0x19
RTA_TTL_PROPAGATE = 0x1a
RTA_IP_PROTO = 0x1b
RTA_SPORT = 0x1c
RTA_DPORT = 0x1d
RTN_UNSPEC = 0x0 RTN_UNSPEC = 0x0
RTN_UNICAST = 0x1 RTN_UNICAST = 0x1
RTN_LOCAL = 0x2 RTN_LOCAL = 0x2

View File

@ -522,6 +522,13 @@ const (
RTA_PREF = 0x14 RTA_PREF = 0x14
RTA_ENCAP_TYPE = 0x15 RTA_ENCAP_TYPE = 0x15
RTA_ENCAP = 0x16 RTA_ENCAP = 0x16
RTA_EXPIRES = 0x17
RTA_PAD = 0x18
RTA_UID = 0x19
RTA_TTL_PROPAGATE = 0x1a
RTA_IP_PROTO = 0x1b
RTA_SPORT = 0x1c
RTA_DPORT = 0x1d
RTN_UNSPEC = 0x0 RTN_UNSPEC = 0x0
RTN_UNICAST = 0x1 RTN_UNICAST = 0x1
RTN_LOCAL = 0x2 RTN_LOCAL = 0x2

View File

@ -518,6 +518,13 @@ const (
RTA_PREF = 0x14 RTA_PREF = 0x14
RTA_ENCAP_TYPE = 0x15 RTA_ENCAP_TYPE = 0x15
RTA_ENCAP = 0x16 RTA_ENCAP = 0x16
RTA_EXPIRES = 0x17
RTA_PAD = 0x18
RTA_UID = 0x19
RTA_TTL_PROPAGATE = 0x1a
RTA_IP_PROTO = 0x1b
RTA_SPORT = 0x1c
RTA_DPORT = 0x1d
RTN_UNSPEC = 0x0 RTN_UNSPEC = 0x0
RTN_UNICAST = 0x1 RTN_UNICAST = 0x1
RTN_LOCAL = 0x2 RTN_LOCAL = 0x2

Some files were not shown because too many files have changed in this diff Show More