зеркало из https://github.com/Azure/ARO-RP.git
vendor
This commit is contained in:
Родитель
b7af8242ce
Коммит
a248811b80
|
@ -48,7 +48,7 @@
|
|||
version = "v42.3.0"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:4621d189edcc3acfc8f9e1b98513f24d9b318574df1406b28cde265d598e8c85"
|
||||
digest = "1:837909599d3b4e95163a3f819453b7013c345bc7455cd13e5fe74108a38d6925"
|
||||
name = "github.com/Azure/go-autorest"
|
||||
packages = [
|
||||
"autorest",
|
||||
|
@ -63,8 +63,8 @@
|
|||
"tracing",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "778ae565bde392f58e04c3c8ff07c2ac506d00c9"
|
||||
version = "v14.1.1"
|
||||
revision = "e7b391b759b050d6719cc6fd8bb87b6dc038bca6"
|
||||
version = "v14.2.0"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:9f3b30d9f8e0d7040f729b82dcbc8f0dead820a133b3147ce355fc451f32d761"
|
||||
|
@ -432,6 +432,14 @@
|
|||
revision = "bf22ed9311622d93e213ba31e4ae7a5771e5d379"
|
||||
version = "v4.6.0"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:bde2a1ce1de28312f165a88926c12f4acd19dc4d7da96a445dfa5a29eae07a93"
|
||||
name = "github.com/fatih/color"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "daf2830f2741ebb735b21709a520c5f37d642d85"
|
||||
version = "v1.9.0"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:2cd7915ab26ede7d95b8749e6b1f933f1c6d5398030684e6505940a10f31cfda"
|
||||
name = "github.com/ghodss/yaml"
|
||||
|
@ -451,6 +459,14 @@
|
|||
revision = "ff7109080027ec152dabb369e157c4f359b76f31"
|
||||
version = "v3.1.2"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:edd2fa4578eb086265db78a9201d15e76b298dfd0d5c379da83e9c61712cf6df"
|
||||
name = "github.com/go-logr/logr"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "9fb12b3b21c5415d16ac18dc5cd42c1cfdd40c4e"
|
||||
version = "v0.1.0"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:ed15647db08b6d63666bf9755d337725960c302bbfa5e23754b4b915a4797e42"
|
||||
name = "github.com/go-openapi/jsonpointer"
|
||||
|
@ -483,6 +499,14 @@
|
|||
revision = "8a84ec635f1b280a7062edeab609f0667a053248"
|
||||
version = "v0.19.6"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:eec9b9a9f07a9b0de09431545481e22c233181b1af40170d0bc1f50b83690738"
|
||||
name = "github.com/gobuffalo/flect"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "7a04ff140e0fd2ea77adfd5b8bd2b0c80ab739a9"
|
||||
version = "v0.2.1"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:582e25eccee928dc12416ea4c23b6dae8f3b5687730632aa1473ebebe80a2359"
|
||||
name = "github.com/gogo/protobuf"
|
||||
|
@ -632,6 +656,17 @@
|
|||
pruneopts = "UT"
|
||||
revision = "901d90724c7919163f472a9812253fb26761123d"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:e631368e174090a276fc00b48283f92ac4ccfbbb1945bcfcee083f5f9210dc00"
|
||||
name = "github.com/hashicorp/golang-lru"
|
||||
packages = [
|
||||
".",
|
||||
"simplelru",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "14eae340515388ca95aa8e7b86f0de668e981f54"
|
||||
version = "v0.5.4"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:a1038ef593beb4771c8f0f9c26e8b00410acd800af5c6864651d9bf160ea1813"
|
||||
name = "github.com/hpcloud/tail"
|
||||
|
@ -654,6 +689,14 @@
|
|||
revision = "1afb36080aec31e0d1528973ebe6721b191b0369"
|
||||
version = "v0.3.8"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:870d441fe217b8e689d7949fef6e43efbc787e50f200cb1e70dbca9204a1d6be"
|
||||
name = "github.com/inconshreveable/mousetrap"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "76626ae9c91c4f2a10f34cad8ce83ea42c93bb75"
|
||||
version = "v1.0"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:11a561b078819a1cd5d9d9c52031e8476e9ee7622f2b3b054850940a7d167971"
|
||||
|
@ -1165,6 +1208,14 @@
|
|||
pruneopts = "UT"
|
||||
revision = "da87dd6d947d66eb810d74622fb7664289148423"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:7a8874002044d748dd5ec9f4f1cb6053d8125e7a29ab9665ef64f7628f910141"
|
||||
name = "github.com/operator-framework/operator-sdk"
|
||||
packages = ["pkg/status"]
|
||||
pruneopts = "UT"
|
||||
revision = "8e28aca60994c5cb1aec0251b85f0116cc4c9427"
|
||||
version = "v0.19.0"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:78a8e7c73f3409bc2a9361e12ccfe0dee905f292e514400122299a5079348bea"
|
||||
|
@ -1300,6 +1351,14 @@
|
|||
revision = "839c75faf7f98a33d445d181f3018b5c3409a45e"
|
||||
version = "v1.4.2"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:f6adcf4df6c030a53a14a8fdbb3fade7cac3d014ff78a4e0de500b4c0cf5154f"
|
||||
name = "github.com/spf13/cobra"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "a684a6d7f5e37385d954dd3b5a14fc6912c6ab9d"
|
||||
version = "v1.0.0"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:524b71991fc7d9246cc7dc2d9e0886ccb97648091c63e30eef619e6862c955dd"
|
||||
name = "github.com/spf13/pflag"
|
||||
|
@ -1543,7 +1602,7 @@
|
|||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:8bb1d2f050249349dbaeda1ce06e22d9f185acda87c0a5c5a4c43da45d46ed69"
|
||||
digest = "1:5e0fb9e9d8578aed12222c1a7eb7e57f35f6eb305b7aab02eeabbe4d36c60442"
|
||||
name = "golang.org/x/tools"
|
||||
packages = [
|
||||
"cmd/goimports",
|
||||
|
@ -1554,6 +1613,7 @@
|
|||
"go/internal/packagesdriver",
|
||||
"go/packages",
|
||||
"go/types/typeutil",
|
||||
"imports",
|
||||
"internal/fastwalk",
|
||||
"internal/gopathwalk",
|
||||
"internal/imports",
|
||||
|
@ -1564,6 +1624,14 @@
|
|||
pruneopts = "UT"
|
||||
revision = "dbc83e6dc05ede08439f32f7024b36e4e9e5b406"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:a4e6161ffbea6b872a122961fff978f81af9c064f1757c559e21d2d322f13958"
|
||||
name = "gomodules.xyz/jsonpatch"
|
||||
packages = ["v2"]
|
||||
pruneopts = "UT"
|
||||
revision = "1c2a0262323edc27502942d9727c95646b1c3cbe"
|
||||
version = "v2.1.0"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:f3661f6218166acf60f5d551b44a537f7ecb8686be02ece061c5950cbfc9ba17"
|
||||
name = "google.golang.org/api"
|
||||
|
@ -1707,11 +1775,20 @@
|
|||
revision = "1f64d6156d11335c3f22d9330b0ad14fc1e789ce"
|
||||
version = "v2.2.7"
|
||||
|
||||
[[projects]]
|
||||
branch = "v3"
|
||||
digest = "1:229cb0f6192914f518cc1241ede6d6f1f458b31debfa18bf3a5c9e4f7b01e24b"
|
||||
name = "gopkg.in/yaml.v3"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "eeeca48fe7764f320e4870d231902bf9c1be2c08"
|
||||
|
||||
[[projects]]
|
||||
branch = "origin-4.4-kubernetes-1.17.1"
|
||||
digest = "1:cd7322a2669aba7fe506383dc31ece3881fc3e39ccac5334360c50f946a8ade4"
|
||||
digest = "1:5cb5278f126e316f9e793b2ed967f113d3d5407694e7a789cbf6e2137579b504"
|
||||
name = "k8s.io/api"
|
||||
packages = [
|
||||
"admission/v1beta1",
|
||||
"admissionregistration/v1",
|
||||
"admissionregistration/v1beta1",
|
||||
"apps/v1",
|
||||
|
@ -1757,17 +1834,36 @@
|
|||
revision = "7643814f1c97f24ccfb38c2b85a7bb3c7f494346"
|
||||
source = "https://github.com/openshift/kubernetes-api"
|
||||
|
||||
[[projects]]
|
||||
branch = "release-1.17"
|
||||
digest = "1:f0b431fe72d7510dfe7f3f177317391621ddb500843f5661dab7520d22735a66"
|
||||
name = "k8s.io/apiextensions-apiserver"
|
||||
packages = [
|
||||
"pkg/apis/apiextensions",
|
||||
"pkg/apis/apiextensions/v1",
|
||||
"pkg/apis/apiextensions/v1beta1",
|
||||
"pkg/client/clientset/clientset",
|
||||
"pkg/client/clientset/clientset/scheme",
|
||||
"pkg/client/clientset/clientset/typed/apiextensions/v1",
|
||||
"pkg/client/clientset/clientset/typed/apiextensions/v1beta1",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "88d23e1d281b9aa0cb534c4cdf3ed01af4b180b9"
|
||||
|
||||
[[projects]]
|
||||
branch = "origin-4.4-kubernetes-1.17.1"
|
||||
digest = "1:fac15195ebd43a8833c5cabfcfe87a6497fa12cf04df21b3a797bfcb933a4181"
|
||||
digest = "1:ecc89c50eb2d0860f5b7a63d5f2672d82c0df9b2b213fbfd1239c11f889cd446"
|
||||
name = "k8s.io/apimachinery"
|
||||
packages = [
|
||||
"pkg/api/equality",
|
||||
"pkg/api/errors",
|
||||
"pkg/api/meta",
|
||||
"pkg/api/resource",
|
||||
"pkg/apis/meta/internalversion",
|
||||
"pkg/apis/meta/v1",
|
||||
"pkg/apis/meta/v1/unstructured",
|
||||
"pkg/apis/meta/v1/validation",
|
||||
"pkg/apis/meta/v1beta1",
|
||||
"pkg/conversion",
|
||||
"pkg/conversion/queryparams",
|
||||
"pkg/fields",
|
||||
|
@ -1782,7 +1878,9 @@
|
|||
"pkg/runtime/serializer/versioning",
|
||||
"pkg/selection",
|
||||
"pkg/types",
|
||||
"pkg/util/cache",
|
||||
"pkg/util/clock",
|
||||
"pkg/util/diff",
|
||||
"pkg/util/errors",
|
||||
"pkg/util/framer",
|
||||
"pkg/util/httpstream",
|
||||
|
@ -1796,6 +1894,7 @@
|
|||
"pkg/util/runtime",
|
||||
"pkg/util/sets",
|
||||
"pkg/util/strategicpatch",
|
||||
"pkg/util/uuid",
|
||||
"pkg/util/validation",
|
||||
"pkg/util/validation/field",
|
||||
"pkg/util/wait",
|
||||
|
@ -1812,13 +1911,14 @@
|
|||
|
||||
[[projects]]
|
||||
branch = "origin-4.4-kubernetes-1.17.1"
|
||||
digest = "1:f51508c5ebfc8da2cb944a2aeb3c6a9f321a6b76c9cafd5c3464bbca1f4004e2"
|
||||
digest = "1:72e2d2937f1e2315cfdb5887de8976d53038fab35d23116c44958464807a294c"
|
||||
name = "k8s.io/client-go"
|
||||
packages = [
|
||||
"discovery",
|
||||
"discovery/cached/disk",
|
||||
"discovery/fake",
|
||||
"dynamic",
|
||||
"dynamic/fake",
|
||||
"kubernetes",
|
||||
"kubernetes/fake",
|
||||
"kubernetes/scheme",
|
||||
|
@ -1909,13 +2009,20 @@
|
|||
"plugin/pkg/client/auth/exec",
|
||||
"rest",
|
||||
"rest/watch",
|
||||
"restmapper",
|
||||
"testing",
|
||||
"tools/auth",
|
||||
"tools/cache",
|
||||
"tools/clientcmd",
|
||||
"tools/clientcmd/api",
|
||||
"tools/clientcmd/api/latest",
|
||||
"tools/clientcmd/api/v1",
|
||||
"tools/leaderelection",
|
||||
"tools/leaderelection/resourcelock",
|
||||
"tools/metrics",
|
||||
"tools/pager",
|
||||
"tools/record",
|
||||
"tools/record/util",
|
||||
"tools/reference",
|
||||
"transport",
|
||||
"util/cert",
|
||||
|
@ -1930,6 +2037,42 @@
|
|||
revision = "bb38286aebfbd8b39c317114442ed28d37c7617e"
|
||||
source = "https://github.com/openshift/kubernetes-client-go"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:349858f235d044e8de69128b54440553ffe3be06dd8b1343d60f18484b7201f5"
|
||||
name = "k8s.io/code-generator"
|
||||
packages = [
|
||||
"cmd/client-gen",
|
||||
"cmd/client-gen/args",
|
||||
"cmd/client-gen/generators",
|
||||
"cmd/client-gen/generators/fake",
|
||||
"cmd/client-gen/generators/scheme",
|
||||
"cmd/client-gen/generators/util",
|
||||
"cmd/client-gen/path",
|
||||
"cmd/client-gen/types",
|
||||
"cmd/deepcopy-gen",
|
||||
"cmd/deepcopy-gen/args",
|
||||
"pkg/namer",
|
||||
"pkg/util",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "e95606b614f049ef6087115cb340d8d5805b8da7"
|
||||
version = "kubernetes-1.17.1"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:28514fabca4356625720ffb012408790a9d00d31963a9bd9daf7b5ccd894c301"
|
||||
name = "k8s.io/gengo"
|
||||
packages = [
|
||||
"args",
|
||||
"examples/deepcopy-gen/generators",
|
||||
"examples/set-gen/sets",
|
||||
"generator",
|
||||
"namer",
|
||||
"parser",
|
||||
"types",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "f8a0810f38afb8478882b3835a615aebfda39afa"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:93e82f25d75aba18436ad1ac042cb49493f096011f2541075721ed6f9e05c044"
|
||||
name = "k8s.io/klog"
|
||||
|
@ -1950,11 +2093,13 @@
|
|||
revision = "30be4d16710ac61bce31eb28a01054596fe6a9f1"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:01dbe4c86aa758aaa7502784c7e81642f3f0995c0fd6a094a8daaf5cb962ac73"
|
||||
digest = "1:bb09c1841fd8100fe09b784fa13563ebffd9921d18012e72c8727ce9d4ea0144"
|
||||
name = "k8s.io/utils"
|
||||
packages = [
|
||||
"buffer",
|
||||
"integer",
|
||||
"pointer",
|
||||
"trace",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "581e00157fb1a0435d4fac54a52d1ca1e481d60e"
|
||||
|
@ -1997,12 +2142,71 @@
|
|||
source = "https://github.com/openshift/cluster-api-provider-openstack.git"
|
||||
|
||||
[[projects]]
|
||||
branch = "release-0.2"
|
||||
digest = "1:c4e8f6509ee8cec911985a812ed3f9cc024404acc45ac613fa103f735cf3222a"
|
||||
branch = "release-0.5"
|
||||
digest = "1:adf6def2bee7c9fa8a026e8193770e6665258666ad2e0d63438701248c7fbf30"
|
||||
name = "sigs.k8s.io/controller-runtime"
|
||||
packages = ["pkg/scheme"]
|
||||
packages = [
|
||||
".",
|
||||
"pkg/builder",
|
||||
"pkg/cache",
|
||||
"pkg/cache/internal",
|
||||
"pkg/client",
|
||||
"pkg/client/apiutil",
|
||||
"pkg/client/config",
|
||||
"pkg/controller",
|
||||
"pkg/controller/controllerutil",
|
||||
"pkg/conversion",
|
||||
"pkg/event",
|
||||
"pkg/handler",
|
||||
"pkg/healthz",
|
||||
"pkg/internal/controller",
|
||||
"pkg/internal/controller/metrics",
|
||||
"pkg/internal/log",
|
||||
"pkg/internal/recorder",
|
||||
"pkg/leaderelection",
|
||||
"pkg/log",
|
||||
"pkg/manager",
|
||||
"pkg/manager/signals",
|
||||
"pkg/metrics",
|
||||
"pkg/predicate",
|
||||
"pkg/ratelimiter",
|
||||
"pkg/reconcile",
|
||||
"pkg/recorder",
|
||||
"pkg/runtime/inject",
|
||||
"pkg/scheme",
|
||||
"pkg/source",
|
||||
"pkg/source/internal",
|
||||
"pkg/webhook",
|
||||
"pkg/webhook/admission",
|
||||
"pkg/webhook/conversion",
|
||||
"pkg/webhook/internal/certwatcher",
|
||||
"pkg/webhook/internal/metrics",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "fc5542c693e3340f8abbe91c6345bd64c494a60c"
|
||||
revision = "fef04902823b5a3bed3ba29518e50cbf6560594d"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:a2ae73d1f36d28a2936c672c0976782c506562ee21a07fb8f589136c5cef3fd2"
|
||||
name = "sigs.k8s.io/controller-tools"
|
||||
packages = [
|
||||
"cmd/controller-gen",
|
||||
"pkg/crd",
|
||||
"pkg/crd/markers",
|
||||
"pkg/deepcopy",
|
||||
"pkg/genall",
|
||||
"pkg/genall/help",
|
||||
"pkg/genall/help/pretty",
|
||||
"pkg/loader",
|
||||
"pkg/markers",
|
||||
"pkg/rbac",
|
||||
"pkg/schemapatcher",
|
||||
"pkg/schemapatcher/internal/yaml",
|
||||
"pkg/version",
|
||||
"pkg/webhook",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "93a4eed983cf9670deabcf3cfa837a4b69988c6e"
|
||||
version = "v0.2.9"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:7719608fe0b52a4ece56c2dde37bedd95b938677d1ab0f84b8a7852e4c59f849"
|
||||
|
@ -2053,6 +2257,7 @@
|
|||
"github.com/dgrijalva/jwt-go",
|
||||
"github.com/ghodss/yaml",
|
||||
"github.com/go-bindata/go-bindata/go-bindata",
|
||||
"github.com/go-logr/logr",
|
||||
"github.com/golang/mock/gomock",
|
||||
"github.com/golang/mock/mockgen",
|
||||
"github.com/google/go-cmp/cmp",
|
||||
|
@ -2111,6 +2316,7 @@
|
|||
"github.com/openshift/machine-config-operator/pkg/apis/machineconfiguration.openshift.io/v1",
|
||||
"github.com/openshift/machine-config-operator/pkg/generated/clientset/versioned",
|
||||
"github.com/openshift/machine-config-operator/pkg/generated/clientset/versioned/fake",
|
||||
"github.com/operator-framework/operator-sdk/pkg/status",
|
||||
"github.com/pkg/errors",
|
||||
"github.com/prometheus/common/model",
|
||||
"github.com/satori/go.uuid",
|
||||
|
@ -2124,33 +2330,55 @@
|
|||
"golang.org/x/tools/cmd/goimports",
|
||||
"golang.org/x/tools/go/ast/astutil",
|
||||
"golang.org/x/tools/go/packages",
|
||||
"gopkg.in/yaml.v2",
|
||||
"k8s.io/api/apps/v1",
|
||||
"k8s.io/api/core/v1",
|
||||
"k8s.io/api/rbac/v1",
|
||||
"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1",
|
||||
"k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset",
|
||||
"k8s.io/apimachinery/pkg/api/errors",
|
||||
"k8s.io/apimachinery/pkg/api/meta",
|
||||
"k8s.io/apimachinery/pkg/api/resource",
|
||||
"k8s.io/apimachinery/pkg/apis/meta/v1",
|
||||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured",
|
||||
"k8s.io/apimachinery/pkg/labels",
|
||||
"k8s.io/apimachinery/pkg/runtime",
|
||||
"k8s.io/apimachinery/pkg/runtime/schema",
|
||||
"k8s.io/apimachinery/pkg/runtime/serializer",
|
||||
"k8s.io/apimachinery/pkg/types",
|
||||
"k8s.io/apimachinery/pkg/util/httpstream",
|
||||
"k8s.io/apimachinery/pkg/util/httpstream/spdy",
|
||||
"k8s.io/apimachinery/pkg/util/runtime",
|
||||
"k8s.io/apimachinery/pkg/util/wait",
|
||||
"k8s.io/apimachinery/pkg/version",
|
||||
"k8s.io/apimachinery/pkg/watch",
|
||||
"k8s.io/client-go/discovery",
|
||||
"k8s.io/client-go/discovery/cached/disk",
|
||||
"k8s.io/client-go/discovery/fake",
|
||||
"k8s.io/client-go/dynamic",
|
||||
"k8s.io/client-go/dynamic/fake",
|
||||
"k8s.io/client-go/kubernetes",
|
||||
"k8s.io/client-go/kubernetes/fake",
|
||||
"k8s.io/client-go/kubernetes/scheme",
|
||||
"k8s.io/client-go/kubernetes/typed/apps/v1",
|
||||
"k8s.io/client-go/kubernetes/typed/core/v1",
|
||||
"k8s.io/client-go/rest",
|
||||
"k8s.io/client-go/testing",
|
||||
"k8s.io/client-go/tools/clientcmd",
|
||||
"k8s.io/client-go/tools/clientcmd/api/v1",
|
||||
"k8s.io/client-go/tools/metrics",
|
||||
"k8s.io/client-go/util/flowcontrol",
|
||||
"k8s.io/client-go/util/retry",
|
||||
"k8s.io/code-generator/cmd/client-gen",
|
||||
"k8s.io/code-generator/cmd/deepcopy-gen",
|
||||
"k8s.io/gengo/generator",
|
||||
"sigs.k8s.io/controller-runtime",
|
||||
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil",
|
||||
"sigs.k8s.io/controller-runtime/pkg/event",
|
||||
"sigs.k8s.io/controller-runtime/pkg/predicate",
|
||||
"sigs.k8s.io/controller-runtime/pkg/reconcile",
|
||||
"sigs.k8s.io/controller-runtime/pkg/scheme",
|
||||
"sigs.k8s.io/controller-tools/cmd/controller-gen",
|
||||
]
|
||||
solver-name = "gps-cdcl"
|
||||
solver-version = 1
|
||||
|
|
28
Gopkg.toml
28
Gopkg.toml
|
@ -6,8 +6,12 @@ required = [
|
|||
"golang.org/x/tools/cmd/goimports",
|
||||
"github.com/jstemmer/go-junit-report",
|
||||
"github.com/axw/gocov/gocov",
|
||||
"github.com/AlekSi/gocov-xml",
|
||||
"github.com/metal3-io/baremetal-operator/pkg/apis/metal3/v1alpha1"
|
||||
"github.com/metal3-io/baremetal-operator/pkg/apis/metal3/v1alpha1",
|
||||
"github.com/AlekSi/gocov-xml",
|
||||
"k8s.io/code-generator/cmd/client-gen",
|
||||
"k8s.io/code-generator/cmd/deepcopy-gen",
|
||||
"k8s.io/gengo/generator",
|
||||
"sigs.k8s.io/controller-tools/cmd/controller-gen",
|
||||
]
|
||||
|
||||
[[constraint]]
|
||||
|
@ -18,6 +22,26 @@ required = [
|
|||
name = "github.com/Azure/azure-sdk-for-go"
|
||||
version = "42.1.0"
|
||||
|
||||
[[override]]
|
||||
name = "k8s.io/code-generator"
|
||||
version = "kubernetes-1.17.1"
|
||||
|
||||
[[override]]
|
||||
name = "sigs.k8s.io/controller-tools"
|
||||
version = "v0.2.5"
|
||||
|
||||
[[override]]
|
||||
name = "sigs.k8s.io/controller-runtime"
|
||||
branch = "release-0.5"
|
||||
|
||||
[[override]]
|
||||
name = "k8s.io/apiextensions-apiserver"
|
||||
branch = "release-1.17"
|
||||
|
||||
[[constraint]]
|
||||
name = "k8s.io/gengo"
|
||||
revision = "f8a0810f38afb8478882b3835a615aebfda39afa"
|
||||
|
||||
[[override]]
|
||||
name = "github.com/containers/image"
|
||||
version = "v2.0.1"
|
||||
|
|
121
cgmanifest.json
121
cgmanifest.json
|
@ -31,7 +31,7 @@
|
|||
"component": {
|
||||
"type": "git",
|
||||
"git": {
|
||||
"commitHash": "778ae565bde392f58e04c3c8ff07c2ac506d00c9",
|
||||
"commitHash": "e7b391b759b050d6719cc6fd8bb87b6dc038bca6",
|
||||
"repositoryUrl": "https://github.com/Azure/go-autorest/"
|
||||
}
|
||||
}
|
||||
|
@ -306,6 +306,15 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"component": {
|
||||
"type": "git",
|
||||
"git": {
|
||||
"commitHash": "daf2830f2741ebb735b21709a520c5f37d642d85",
|
||||
"repositoryUrl": "https://github.com/fatih/color/"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"component": {
|
||||
"type": "git",
|
||||
|
@ -324,6 +333,15 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"component": {
|
||||
"type": "git",
|
||||
"git": {
|
||||
"commitHash": "9fb12b3b21c5415d16ac18dc5cd42c1cfdd40c4e",
|
||||
"repositoryUrl": "https://github.com/go-logr/logr/"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"component": {
|
||||
"type": "git",
|
||||
|
@ -360,6 +378,15 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"component": {
|
||||
"type": "git",
|
||||
"git": {
|
||||
"commitHash": "7a04ff140e0fd2ea77adfd5b8bd2b0c80ab739a9",
|
||||
"repositoryUrl": "https://github.com/gobuffalo/flect/"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"component": {
|
||||
"type": "git",
|
||||
|
@ -477,6 +504,15 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"component": {
|
||||
"type": "git",
|
||||
"git": {
|
||||
"commitHash": "14eae340515388ca95aa8e7b86f0de668e981f54",
|
||||
"repositoryUrl": "https://github.com/hashicorp/golang-lru/"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"component": {
|
||||
"type": "git",
|
||||
|
@ -495,6 +531,15 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"component": {
|
||||
"type": "git",
|
||||
"git": {
|
||||
"commitHash": "76626ae9c91c4f2a10f34cad8ce83ea42c93bb75",
|
||||
"repositoryUrl": "https://github.com/inconshreveable/mousetrap/"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"component": {
|
||||
"type": "git",
|
||||
|
@ -828,6 +873,15 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"component": {
|
||||
"type": "git",
|
||||
"git": {
|
||||
"commitHash": "8e28aca60994c5cb1aec0251b85f0116cc4c9427",
|
||||
"repositoryUrl": "https://github.com/operator-framework/operator-sdk/"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"component": {
|
||||
"type": "git",
|
||||
|
@ -963,6 +1017,15 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"component": {
|
||||
"type": "git",
|
||||
"git": {
|
||||
"commitHash": "a684a6d7f5e37385d954dd3b5a14fc6912c6ab9d",
|
||||
"repositoryUrl": "https://github.com/spf13/cobra/"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"component": {
|
||||
"type": "git",
|
||||
|
@ -1107,6 +1170,15 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"component": {
|
||||
"type": "git",
|
||||
"git": {
|
||||
"commitHash": "1c2a0262323edc27502942d9727c95646b1c3cbe",
|
||||
"repositoryUrl": "https://gomodules.xyz/jsonpatch/"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"component": {
|
||||
"type": "git",
|
||||
|
@ -1197,6 +1269,15 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"component": {
|
||||
"type": "git",
|
||||
"git": {
|
||||
"commitHash": "eeeca48fe7764f320e4870d231902bf9c1be2c08",
|
||||
"repositoryUrl": "https://gopkg.in/yaml.v3/"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"component": {
|
||||
"type": "git",
|
||||
|
@ -1206,6 +1287,15 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"component": {
|
||||
"type": "git",
|
||||
"git": {
|
||||
"commitHash": "88d23e1d281b9aa0cb534c4cdf3ed01af4b180b9",
|
||||
"repositoryUrl": "https://github.com/kubernetes/apiextensions-apiserver/"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"component": {
|
||||
"type": "git",
|
||||
|
@ -1224,6 +1314,24 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"component": {
|
||||
"type": "git",
|
||||
"git": {
|
||||
"commitHash": "e95606b614f049ef6087115cb340d8d5805b8da7",
|
||||
"repositoryUrl": "https://github.com/kubernetes/code-generator/"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"component": {
|
||||
"type": "git",
|
||||
"git": {
|
||||
"commitHash": "f8a0810f38afb8478882b3835a615aebfda39afa",
|
||||
"repositoryUrl": "https://github.com/kubernetes/gengo/"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"component": {
|
||||
"type": "git",
|
||||
|
@ -1282,11 +1390,20 @@
|
|||
"component": {
|
||||
"type": "git",
|
||||
"git": {
|
||||
"commitHash": "fc5542c693e3340f8abbe91c6345bd64c494a60c",
|
||||
"commitHash": "fef04902823b5a3bed3ba29518e50cbf6560594d",
|
||||
"repositoryUrl": "https://sigs.k8s.io/controller-runtime/"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"component": {
|
||||
"type": "git",
|
||||
"git": {
|
||||
"commitHash": "93a4eed983cf9670deabcf3cfa837a4b69988c6e",
|
||||
"repositoryUrl": "https://sigs.k8s.io/controller-tools/"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"component": {
|
||||
"type": "git",
|
||||
|
|
|
@ -19,7 +19,7 @@ import (
|
|||
"runtime"
|
||||
)
|
||||
|
||||
const number = "v14.1.1"
|
||||
const number = "v14.2.0"
|
||||
|
||||
var (
|
||||
userAgent = fmt.Sprintf("Go/%s (%s-%s) go-autorest/%s",
|
||||
|
|
|
@ -1,3 +1 @@
|
|||
module github.com/dimchansky/utfbom
|
||||
|
||||
go 1.14
|
||||
module github.com/dimchansky/utfbom
|
|
@ -0,0 +1,20 @@
|
|||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2013 Fatih Arslan
|
||||
|
||||
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.
|
|
@ -0,0 +1,182 @@
|
|||
# Archived project. No maintenance.
|
||||
|
||||
This project is not maintained anymore and is archived. Feel free to fork and
|
||||
make your own changes if needed. For more detail read my blog post: [Taking an indefinite sabbatical from my projects](https://arslan.io/2018/10/09/taking-an-indefinite-sabbatical-from-my-projects/)
|
||||
|
||||
Thanks to everyone for their valuable feedback and contributions.
|
||||
|
||||
|
||||
# Color [![GoDoc](https://godoc.org/github.com/fatih/color?status.svg)](https://godoc.org/github.com/fatih/color)
|
||||
|
||||
Color lets you use colorized outputs in terms of [ANSI Escape
|
||||
Codes](http://en.wikipedia.org/wiki/ANSI_escape_code#Colors) in Go (Golang). It
|
||||
has support for Windows too! The API can be used in several ways, pick one that
|
||||
suits you.
|
||||
|
||||
|
||||
![Color](https://i.imgur.com/c1JI0lA.png)
|
||||
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
go get github.com/fatih/color
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
### Standard colors
|
||||
|
||||
```go
|
||||
// Print with default helper functions
|
||||
color.Cyan("Prints text in cyan.")
|
||||
|
||||
// A newline will be appended automatically
|
||||
color.Blue("Prints %s in blue.", "text")
|
||||
|
||||
// These are using the default foreground colors
|
||||
color.Red("We have red")
|
||||
color.Magenta("And many others ..")
|
||||
|
||||
```
|
||||
|
||||
### Mix and reuse colors
|
||||
|
||||
```go
|
||||
// Create a new color object
|
||||
c := color.New(color.FgCyan).Add(color.Underline)
|
||||
c.Println("Prints cyan text with an underline.")
|
||||
|
||||
// Or just add them to New()
|
||||
d := color.New(color.FgCyan, color.Bold)
|
||||
d.Printf("This prints bold cyan %s\n", "too!.")
|
||||
|
||||
// Mix up foreground and background colors, create new mixes!
|
||||
red := color.New(color.FgRed)
|
||||
|
||||
boldRed := red.Add(color.Bold)
|
||||
boldRed.Println("This will print text in bold red.")
|
||||
|
||||
whiteBackground := red.Add(color.BgWhite)
|
||||
whiteBackground.Println("Red text with white background.")
|
||||
```
|
||||
|
||||
### Use your own output (io.Writer)
|
||||
|
||||
```go
|
||||
// Use your own io.Writer output
|
||||
color.New(color.FgBlue).Fprintln(myWriter, "blue color!")
|
||||
|
||||
blue := color.New(color.FgBlue)
|
||||
blue.Fprint(writer, "This will print text in blue.")
|
||||
```
|
||||
|
||||
### Custom print functions (PrintFunc)
|
||||
|
||||
```go
|
||||
// Create a custom print function for convenience
|
||||
red := color.New(color.FgRed).PrintfFunc()
|
||||
red("Warning")
|
||||
red("Error: %s", err)
|
||||
|
||||
// Mix up multiple attributes
|
||||
notice := color.New(color.Bold, color.FgGreen).PrintlnFunc()
|
||||
notice("Don't forget this...")
|
||||
```
|
||||
|
||||
### Custom fprint functions (FprintFunc)
|
||||
|
||||
```go
|
||||
blue := color.New(FgBlue).FprintfFunc()
|
||||
blue(myWriter, "important notice: %s", stars)
|
||||
|
||||
// Mix up with multiple attributes
|
||||
success := color.New(color.Bold, color.FgGreen).FprintlnFunc()
|
||||
success(myWriter, "Don't forget this...")
|
||||
```
|
||||
|
||||
### Insert into noncolor strings (SprintFunc)
|
||||
|
||||
```go
|
||||
// Create SprintXxx functions to mix strings with other non-colorized strings:
|
||||
yellow := color.New(color.FgYellow).SprintFunc()
|
||||
red := color.New(color.FgRed).SprintFunc()
|
||||
fmt.Printf("This is a %s and this is %s.\n", yellow("warning"), red("error"))
|
||||
|
||||
info := color.New(color.FgWhite, color.BgGreen).SprintFunc()
|
||||
fmt.Printf("This %s rocks!\n", info("package"))
|
||||
|
||||
// Use helper functions
|
||||
fmt.Println("This", color.RedString("warning"), "should be not neglected.")
|
||||
fmt.Printf("%v %v\n", color.GreenString("Info:"), "an important message.")
|
||||
|
||||
// Windows supported too! Just don't forget to change the output to color.Output
|
||||
fmt.Fprintf(color.Output, "Windows support: %s", color.GreenString("PASS"))
|
||||
```
|
||||
|
||||
### Plug into existing code
|
||||
|
||||
```go
|
||||
// Use handy standard colors
|
||||
color.Set(color.FgYellow)
|
||||
|
||||
fmt.Println("Existing text will now be in yellow")
|
||||
fmt.Printf("This one %s\n", "too")
|
||||
|
||||
color.Unset() // Don't forget to unset
|
||||
|
||||
// You can mix up parameters
|
||||
color.Set(color.FgMagenta, color.Bold)
|
||||
defer color.Unset() // Use it in your function
|
||||
|
||||
fmt.Println("All text will now be bold magenta.")
|
||||
```
|
||||
|
||||
### Disable/Enable color
|
||||
|
||||
There might be a case where you want to explicitly disable/enable color output. the
|
||||
`go-isatty` package will automatically disable color output for non-tty output streams
|
||||
(for example if the output were piped directly to `less`)
|
||||
|
||||
`Color` has support to disable/enable colors both globally and for single color
|
||||
definitions. For example suppose you have a CLI app and a `--no-color` bool flag. You
|
||||
can easily disable the color output with:
|
||||
|
||||
```go
|
||||
|
||||
var flagNoColor = flag.Bool("no-color", false, "Disable color output")
|
||||
|
||||
if *flagNoColor {
|
||||
color.NoColor = true // disables colorized output
|
||||
}
|
||||
```
|
||||
|
||||
It also has support for single color definitions (local). You can
|
||||
disable/enable color output on the fly:
|
||||
|
||||
```go
|
||||
c := color.New(color.FgCyan)
|
||||
c.Println("Prints cyan text")
|
||||
|
||||
c.DisableColor()
|
||||
c.Println("This is printed without any color")
|
||||
|
||||
c.EnableColor()
|
||||
c.Println("This prints again cyan...")
|
||||
```
|
||||
|
||||
## Todo
|
||||
|
||||
* Save/Return previous values
|
||||
* Evaluate fmt.Formatter interface
|
||||
|
||||
|
||||
## Credits
|
||||
|
||||
* [Fatih Arslan](https://github.com/fatih)
|
||||
* Windows support via @mattn: [colorable](https://github.com/mattn/go-colorable)
|
||||
|
||||
## License
|
||||
|
||||
The MIT License (MIT) - see [`LICENSE.md`](https://github.com/fatih/color/blob/master/LICENSE.md) for more details
|
||||
|
|
@ -0,0 +1,603 @@
|
|||
package color
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/mattn/go-colorable"
|
||||
"github.com/mattn/go-isatty"
|
||||
)
|
||||
|
||||
var (
|
||||
// NoColor defines if the output is colorized or not. It's dynamically set to
|
||||
// false or true based on the stdout's file descriptor referring to a terminal
|
||||
// or not. This is a global option and affects all colors. For more control
|
||||
// over each color block use the methods DisableColor() individually.
|
||||
NoColor = os.Getenv("TERM") == "dumb" ||
|
||||
(!isatty.IsTerminal(os.Stdout.Fd()) && !isatty.IsCygwinTerminal(os.Stdout.Fd()))
|
||||
|
||||
// Output defines the standard output of the print functions. By default
|
||||
// os.Stdout is used.
|
||||
Output = colorable.NewColorableStdout()
|
||||
|
||||
// Error defines a color supporting writer for os.Stderr.
|
||||
Error = colorable.NewColorableStderr()
|
||||
|
||||
// colorsCache is used to reduce the count of created Color objects and
|
||||
// allows to reuse already created objects with required Attribute.
|
||||
colorsCache = make(map[Attribute]*Color)
|
||||
colorsCacheMu sync.Mutex // protects colorsCache
|
||||
)
|
||||
|
||||
// Color defines a custom color object which is defined by SGR parameters.
|
||||
type Color struct {
|
||||
params []Attribute
|
||||
noColor *bool
|
||||
}
|
||||
|
||||
// Attribute defines a single SGR Code
|
||||
type Attribute int
|
||||
|
||||
const escape = "\x1b"
|
||||
|
||||
// Base attributes
|
||||
const (
|
||||
Reset Attribute = iota
|
||||
Bold
|
||||
Faint
|
||||
Italic
|
||||
Underline
|
||||
BlinkSlow
|
||||
BlinkRapid
|
||||
ReverseVideo
|
||||
Concealed
|
||||
CrossedOut
|
||||
)
|
||||
|
||||
// Foreground text colors
|
||||
const (
|
||||
FgBlack Attribute = iota + 30
|
||||
FgRed
|
||||
FgGreen
|
||||
FgYellow
|
||||
FgBlue
|
||||
FgMagenta
|
||||
FgCyan
|
||||
FgWhite
|
||||
)
|
||||
|
||||
// Foreground Hi-Intensity text colors
|
||||
const (
|
||||
FgHiBlack Attribute = iota + 90
|
||||
FgHiRed
|
||||
FgHiGreen
|
||||
FgHiYellow
|
||||
FgHiBlue
|
||||
FgHiMagenta
|
||||
FgHiCyan
|
||||
FgHiWhite
|
||||
)
|
||||
|
||||
// Background text colors
|
||||
const (
|
||||
BgBlack Attribute = iota + 40
|
||||
BgRed
|
||||
BgGreen
|
||||
BgYellow
|
||||
BgBlue
|
||||
BgMagenta
|
||||
BgCyan
|
||||
BgWhite
|
||||
)
|
||||
|
||||
// Background Hi-Intensity text colors
|
||||
const (
|
||||
BgHiBlack Attribute = iota + 100
|
||||
BgHiRed
|
||||
BgHiGreen
|
||||
BgHiYellow
|
||||
BgHiBlue
|
||||
BgHiMagenta
|
||||
BgHiCyan
|
||||
BgHiWhite
|
||||
)
|
||||
|
||||
// New returns a newly created color object.
|
||||
func New(value ...Attribute) *Color {
|
||||
c := &Color{params: make([]Attribute, 0)}
|
||||
c.Add(value...)
|
||||
return c
|
||||
}
|
||||
|
||||
// Set sets the given parameters immediately. It will change the color of
|
||||
// output with the given SGR parameters until color.Unset() is called.
|
||||
func Set(p ...Attribute) *Color {
|
||||
c := New(p...)
|
||||
c.Set()
|
||||
return c
|
||||
}
|
||||
|
||||
// Unset resets all escape attributes and clears the output. Usually should
|
||||
// be called after Set().
|
||||
func Unset() {
|
||||
if NoColor {
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Fprintf(Output, "%s[%dm", escape, Reset)
|
||||
}
|
||||
|
||||
// Set sets the SGR sequence.
|
||||
func (c *Color) Set() *Color {
|
||||
if c.isNoColorSet() {
|
||||
return c
|
||||
}
|
||||
|
||||
fmt.Fprintf(Output, c.format())
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *Color) unset() {
|
||||
if c.isNoColorSet() {
|
||||
return
|
||||
}
|
||||
|
||||
Unset()
|
||||
}
|
||||
|
||||
func (c *Color) setWriter(w io.Writer) *Color {
|
||||
if c.isNoColorSet() {
|
||||
return c
|
||||
}
|
||||
|
||||
fmt.Fprintf(w, c.format())
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *Color) unsetWriter(w io.Writer) {
|
||||
if c.isNoColorSet() {
|
||||
return
|
||||
}
|
||||
|
||||
if NoColor {
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Fprintf(w, "%s[%dm", escape, Reset)
|
||||
}
|
||||
|
||||
// Add is used to chain SGR parameters. Use as many as parameters to combine
|
||||
// and create custom color objects. Example: Add(color.FgRed, color.Underline).
|
||||
func (c *Color) Add(value ...Attribute) *Color {
|
||||
c.params = append(c.params, value...)
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *Color) prepend(value Attribute) {
|
||||
c.params = append(c.params, 0)
|
||||
copy(c.params[1:], c.params[0:])
|
||||
c.params[0] = value
|
||||
}
|
||||
|
||||
// Fprint formats using the default formats for its operands and writes to w.
|
||||
// Spaces are added between operands when neither is a string.
|
||||
// It returns the number of bytes written and any write error encountered.
|
||||
// On Windows, users should wrap w with colorable.NewColorable() if w is of
|
||||
// type *os.File.
|
||||
func (c *Color) Fprint(w io.Writer, a ...interface{}) (n int, err error) {
|
||||
c.setWriter(w)
|
||||
defer c.unsetWriter(w)
|
||||
|
||||
return fmt.Fprint(w, a...)
|
||||
}
|
||||
|
||||
// Print formats using the default formats for its operands and writes to
|
||||
// standard output. Spaces are added between operands when neither is a
|
||||
// string. It returns the number of bytes written and any write error
|
||||
// encountered. This is the standard fmt.Print() method wrapped with the given
|
||||
// color.
|
||||
func (c *Color) Print(a ...interface{}) (n int, err error) {
|
||||
c.Set()
|
||||
defer c.unset()
|
||||
|
||||
return fmt.Fprint(Output, a...)
|
||||
}
|
||||
|
||||
// Fprintf formats according to a format specifier and writes to w.
|
||||
// It returns the number of bytes written and any write error encountered.
|
||||
// On Windows, users should wrap w with colorable.NewColorable() if w is of
|
||||
// type *os.File.
|
||||
func (c *Color) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) {
|
||||
c.setWriter(w)
|
||||
defer c.unsetWriter(w)
|
||||
|
||||
return fmt.Fprintf(w, format, a...)
|
||||
}
|
||||
|
||||
// Printf formats according to a format specifier and writes to standard output.
|
||||
// It returns the number of bytes written and any write error encountered.
|
||||
// This is the standard fmt.Printf() method wrapped with the given color.
|
||||
func (c *Color) Printf(format string, a ...interface{}) (n int, err error) {
|
||||
c.Set()
|
||||
defer c.unset()
|
||||
|
||||
return fmt.Fprintf(Output, format, a...)
|
||||
}
|
||||
|
||||
// Fprintln formats using the default formats for its operands and writes to w.
|
||||
// Spaces are always added between operands and a newline is appended.
|
||||
// On Windows, users should wrap w with colorable.NewColorable() if w is of
|
||||
// type *os.File.
|
||||
func (c *Color) Fprintln(w io.Writer, a ...interface{}) (n int, err error) {
|
||||
c.setWriter(w)
|
||||
defer c.unsetWriter(w)
|
||||
|
||||
return fmt.Fprintln(w, a...)
|
||||
}
|
||||
|
||||
// Println formats using the default formats for its operands and writes to
|
||||
// standard output. Spaces are always added between operands and a newline is
|
||||
// appended. It returns the number of bytes written and any write error
|
||||
// encountered. This is the standard fmt.Print() method wrapped with the given
|
||||
// color.
|
||||
func (c *Color) Println(a ...interface{}) (n int, err error) {
|
||||
c.Set()
|
||||
defer c.unset()
|
||||
|
||||
return fmt.Fprintln(Output, a...)
|
||||
}
|
||||
|
||||
// Sprint is just like Print, but returns a string instead of printing it.
|
||||
func (c *Color) Sprint(a ...interface{}) string {
|
||||
return c.wrap(fmt.Sprint(a...))
|
||||
}
|
||||
|
||||
// Sprintln is just like Println, but returns a string instead of printing it.
|
||||
func (c *Color) Sprintln(a ...interface{}) string {
|
||||
return c.wrap(fmt.Sprintln(a...))
|
||||
}
|
||||
|
||||
// Sprintf is just like Printf, but returns a string instead of printing it.
|
||||
func (c *Color) Sprintf(format string, a ...interface{}) string {
|
||||
return c.wrap(fmt.Sprintf(format, a...))
|
||||
}
|
||||
|
||||
// FprintFunc returns a new function that prints the passed arguments as
|
||||
// colorized with color.Fprint().
|
||||
func (c *Color) FprintFunc() func(w io.Writer, a ...interface{}) {
|
||||
return func(w io.Writer, a ...interface{}) {
|
||||
c.Fprint(w, a...)
|
||||
}
|
||||
}
|
||||
|
||||
// PrintFunc returns a new function that prints the passed arguments as
|
||||
// colorized with color.Print().
|
||||
func (c *Color) PrintFunc() func(a ...interface{}) {
|
||||
return func(a ...interface{}) {
|
||||
c.Print(a...)
|
||||
}
|
||||
}
|
||||
|
||||
// FprintfFunc returns a new function that prints the passed arguments as
|
||||
// colorized with color.Fprintf().
|
||||
func (c *Color) FprintfFunc() func(w io.Writer, format string, a ...interface{}) {
|
||||
return func(w io.Writer, format string, a ...interface{}) {
|
||||
c.Fprintf(w, format, a...)
|
||||
}
|
||||
}
|
||||
|
||||
// PrintfFunc returns a new function that prints the passed arguments as
|
||||
// colorized with color.Printf().
|
||||
func (c *Color) PrintfFunc() func(format string, a ...interface{}) {
|
||||
return func(format string, a ...interface{}) {
|
||||
c.Printf(format, a...)
|
||||
}
|
||||
}
|
||||
|
||||
// FprintlnFunc returns a new function that prints the passed arguments as
|
||||
// colorized with color.Fprintln().
|
||||
func (c *Color) FprintlnFunc() func(w io.Writer, a ...interface{}) {
|
||||
return func(w io.Writer, a ...interface{}) {
|
||||
c.Fprintln(w, a...)
|
||||
}
|
||||
}
|
||||
|
||||
// PrintlnFunc returns a new function that prints the passed arguments as
|
||||
// colorized with color.Println().
|
||||
func (c *Color) PrintlnFunc() func(a ...interface{}) {
|
||||
return func(a ...interface{}) {
|
||||
c.Println(a...)
|
||||
}
|
||||
}
|
||||
|
||||
// SprintFunc returns a new function that returns colorized strings for the
|
||||
// given arguments with fmt.Sprint(). Useful to put into or mix into other
|
||||
// string. Windows users should use this in conjunction with color.Output, example:
|
||||
//
|
||||
// put := New(FgYellow).SprintFunc()
|
||||
// fmt.Fprintf(color.Output, "This is a %s", put("warning"))
|
||||
func (c *Color) SprintFunc() func(a ...interface{}) string {
|
||||
return func(a ...interface{}) string {
|
||||
return c.wrap(fmt.Sprint(a...))
|
||||
}
|
||||
}
|
||||
|
||||
// SprintfFunc returns a new function that returns colorized strings for the
|
||||
// given arguments with fmt.Sprintf(). Useful to put into or mix into other
|
||||
// string. Windows users should use this in conjunction with color.Output.
|
||||
func (c *Color) SprintfFunc() func(format string, a ...interface{}) string {
|
||||
return func(format string, a ...interface{}) string {
|
||||
return c.wrap(fmt.Sprintf(format, a...))
|
||||
}
|
||||
}
|
||||
|
||||
// SprintlnFunc returns a new function that returns colorized strings for the
|
||||
// given arguments with fmt.Sprintln(). Useful to put into or mix into other
|
||||
// string. Windows users should use this in conjunction with color.Output.
|
||||
func (c *Color) SprintlnFunc() func(a ...interface{}) string {
|
||||
return func(a ...interface{}) string {
|
||||
return c.wrap(fmt.Sprintln(a...))
|
||||
}
|
||||
}
|
||||
|
||||
// sequence returns a formatted SGR sequence to be plugged into a "\x1b[...m"
|
||||
// an example output might be: "1;36" -> bold cyan
|
||||
func (c *Color) sequence() string {
|
||||
format := make([]string, len(c.params))
|
||||
for i, v := range c.params {
|
||||
format[i] = strconv.Itoa(int(v))
|
||||
}
|
||||
|
||||
return strings.Join(format, ";")
|
||||
}
|
||||
|
||||
// wrap wraps the s string with the colors attributes. The string is ready to
|
||||
// be printed.
|
||||
func (c *Color) wrap(s string) string {
|
||||
if c.isNoColorSet() {
|
||||
return s
|
||||
}
|
||||
|
||||
return c.format() + s + c.unformat()
|
||||
}
|
||||
|
||||
func (c *Color) format() string {
|
||||
return fmt.Sprintf("%s[%sm", escape, c.sequence())
|
||||
}
|
||||
|
||||
func (c *Color) unformat() string {
|
||||
return fmt.Sprintf("%s[%dm", escape, Reset)
|
||||
}
|
||||
|
||||
// DisableColor disables the color output. Useful to not change any existing
|
||||
// code and still being able to output. Can be used for flags like
|
||||
// "--no-color". To enable back use EnableColor() method.
|
||||
func (c *Color) DisableColor() {
|
||||
c.noColor = boolPtr(true)
|
||||
}
|
||||
|
||||
// EnableColor enables the color output. Use it in conjunction with
|
||||
// DisableColor(). Otherwise this method has no side effects.
|
||||
func (c *Color) EnableColor() {
|
||||
c.noColor = boolPtr(false)
|
||||
}
|
||||
|
||||
func (c *Color) isNoColorSet() bool {
|
||||
// check first if we have user setted action
|
||||
if c.noColor != nil {
|
||||
return *c.noColor
|
||||
}
|
||||
|
||||
// if not return the global option, which is disabled by default
|
||||
return NoColor
|
||||
}
|
||||
|
||||
// Equals returns a boolean value indicating whether two colors are equal.
|
||||
func (c *Color) Equals(c2 *Color) bool {
|
||||
if len(c.params) != len(c2.params) {
|
||||
return false
|
||||
}
|
||||
|
||||
for _, attr := range c.params {
|
||||
if !c2.attrExists(attr) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func (c *Color) attrExists(a Attribute) bool {
|
||||
for _, attr := range c.params {
|
||||
if attr == a {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func boolPtr(v bool) *bool {
|
||||
return &v
|
||||
}
|
||||
|
||||
func getCachedColor(p Attribute) *Color {
|
||||
colorsCacheMu.Lock()
|
||||
defer colorsCacheMu.Unlock()
|
||||
|
||||
c, ok := colorsCache[p]
|
||||
if !ok {
|
||||
c = New(p)
|
||||
colorsCache[p] = c
|
||||
}
|
||||
|
||||
return c
|
||||
}
|
||||
|
||||
func colorPrint(format string, p Attribute, a ...interface{}) {
|
||||
c := getCachedColor(p)
|
||||
|
||||
if !strings.HasSuffix(format, "\n") {
|
||||
format += "\n"
|
||||
}
|
||||
|
||||
if len(a) == 0 {
|
||||
c.Print(format)
|
||||
} else {
|
||||
c.Printf(format, a...)
|
||||
}
|
||||
}
|
||||
|
||||
func colorString(format string, p Attribute, a ...interface{}) string {
|
||||
c := getCachedColor(p)
|
||||
|
||||
if len(a) == 0 {
|
||||
return c.SprintFunc()(format)
|
||||
}
|
||||
|
||||
return c.SprintfFunc()(format, a...)
|
||||
}
|
||||
|
||||
// Black is a convenient helper function to print with black foreground. A
|
||||
// newline is appended to format by default.
|
||||
func Black(format string, a ...interface{}) { colorPrint(format, FgBlack, a...) }
|
||||
|
||||
// Red is a convenient helper function to print with red foreground. A
|
||||
// newline is appended to format by default.
|
||||
func Red(format string, a ...interface{}) { colorPrint(format, FgRed, a...) }
|
||||
|
||||
// Green is a convenient helper function to print with green foreground. A
|
||||
// newline is appended to format by default.
|
||||
func Green(format string, a ...interface{}) { colorPrint(format, FgGreen, a...) }
|
||||
|
||||
// Yellow is a convenient helper function to print with yellow foreground.
|
||||
// A newline is appended to format by default.
|
||||
func Yellow(format string, a ...interface{}) { colorPrint(format, FgYellow, a...) }
|
||||
|
||||
// Blue is a convenient helper function to print with blue foreground. A
|
||||
// newline is appended to format by default.
|
||||
func Blue(format string, a ...interface{}) { colorPrint(format, FgBlue, a...) }
|
||||
|
||||
// Magenta is a convenient helper function to print with magenta foreground.
|
||||
// A newline is appended to format by default.
|
||||
func Magenta(format string, a ...interface{}) { colorPrint(format, FgMagenta, a...) }
|
||||
|
||||
// Cyan is a convenient helper function to print with cyan foreground. A
|
||||
// newline is appended to format by default.
|
||||
func Cyan(format string, a ...interface{}) { colorPrint(format, FgCyan, a...) }
|
||||
|
||||
// White is a convenient helper function to print with white foreground. A
|
||||
// newline is appended to format by default.
|
||||
func White(format string, a ...interface{}) { colorPrint(format, FgWhite, a...) }
|
||||
|
||||
// BlackString is a convenient helper function to return a string with black
|
||||
// foreground.
|
||||
func BlackString(format string, a ...interface{}) string { return colorString(format, FgBlack, a...) }
|
||||
|
||||
// RedString is a convenient helper function to return a string with red
|
||||
// foreground.
|
||||
func RedString(format string, a ...interface{}) string { return colorString(format, FgRed, a...) }
|
||||
|
||||
// GreenString is a convenient helper function to return a string with green
|
||||
// foreground.
|
||||
func GreenString(format string, a ...interface{}) string { return colorString(format, FgGreen, a...) }
|
||||
|
||||
// YellowString is a convenient helper function to return a string with yellow
|
||||
// foreground.
|
||||
func YellowString(format string, a ...interface{}) string { return colorString(format, FgYellow, a...) }
|
||||
|
||||
// BlueString is a convenient helper function to return a string with blue
|
||||
// foreground.
|
||||
func BlueString(format string, a ...interface{}) string { return colorString(format, FgBlue, a...) }
|
||||
|
||||
// MagentaString is a convenient helper function to return a string with magenta
|
||||
// foreground.
|
||||
func MagentaString(format string, a ...interface{}) string {
|
||||
return colorString(format, FgMagenta, a...)
|
||||
}
|
||||
|
||||
// CyanString is a convenient helper function to return a string with cyan
|
||||
// foreground.
|
||||
func CyanString(format string, a ...interface{}) string { return colorString(format, FgCyan, a...) }
|
||||
|
||||
// WhiteString is a convenient helper function to return a string with white
|
||||
// foreground.
|
||||
func WhiteString(format string, a ...interface{}) string { return colorString(format, FgWhite, a...) }
|
||||
|
||||
// HiBlack is a convenient helper function to print with hi-intensity black foreground. A
|
||||
// newline is appended to format by default.
|
||||
func HiBlack(format string, a ...interface{}) { colorPrint(format, FgHiBlack, a...) }
|
||||
|
||||
// HiRed is a convenient helper function to print with hi-intensity red foreground. A
|
||||
// newline is appended to format by default.
|
||||
func HiRed(format string, a ...interface{}) { colorPrint(format, FgHiRed, a...) }
|
||||
|
||||
// HiGreen is a convenient helper function to print with hi-intensity green foreground. A
|
||||
// newline is appended to format by default.
|
||||
func HiGreen(format string, a ...interface{}) { colorPrint(format, FgHiGreen, a...) }
|
||||
|
||||
// HiYellow is a convenient helper function to print with hi-intensity yellow foreground.
|
||||
// A newline is appended to format by default.
|
||||
func HiYellow(format string, a ...interface{}) { colorPrint(format, FgHiYellow, a...) }
|
||||
|
||||
// HiBlue is a convenient helper function to print with hi-intensity blue foreground. A
|
||||
// newline is appended to format by default.
|
||||
func HiBlue(format string, a ...interface{}) { colorPrint(format, FgHiBlue, a...) }
|
||||
|
||||
// HiMagenta is a convenient helper function to print with hi-intensity magenta foreground.
|
||||
// A newline is appended to format by default.
|
||||
func HiMagenta(format string, a ...interface{}) { colorPrint(format, FgHiMagenta, a...) }
|
||||
|
||||
// HiCyan is a convenient helper function to print with hi-intensity cyan foreground. A
|
||||
// newline is appended to format by default.
|
||||
func HiCyan(format string, a ...interface{}) { colorPrint(format, FgHiCyan, a...) }
|
||||
|
||||
// HiWhite is a convenient helper function to print with hi-intensity white foreground. A
|
||||
// newline is appended to format by default.
|
||||
func HiWhite(format string, a ...interface{}) { colorPrint(format, FgHiWhite, a...) }
|
||||
|
||||
// HiBlackString is a convenient helper function to return a string with hi-intensity black
|
||||
// foreground.
|
||||
func HiBlackString(format string, a ...interface{}) string {
|
||||
return colorString(format, FgHiBlack, a...)
|
||||
}
|
||||
|
||||
// HiRedString is a convenient helper function to return a string with hi-intensity red
|
||||
// foreground.
|
||||
func HiRedString(format string, a ...interface{}) string { return colorString(format, FgHiRed, a...) }
|
||||
|
||||
// HiGreenString is a convenient helper function to return a string with hi-intensity green
|
||||
// foreground.
|
||||
func HiGreenString(format string, a ...interface{}) string {
|
||||
return colorString(format, FgHiGreen, a...)
|
||||
}
|
||||
|
||||
// HiYellowString is a convenient helper function to return a string with hi-intensity yellow
|
||||
// foreground.
|
||||
func HiYellowString(format string, a ...interface{}) string {
|
||||
return colorString(format, FgHiYellow, a...)
|
||||
}
|
||||
|
||||
// HiBlueString is a convenient helper function to return a string with hi-intensity blue
|
||||
// foreground.
|
||||
func HiBlueString(format string, a ...interface{}) string { return colorString(format, FgHiBlue, a...) }
|
||||
|
||||
// HiMagentaString is a convenient helper function to return a string with hi-intensity magenta
|
||||
// foreground.
|
||||
func HiMagentaString(format string, a ...interface{}) string {
|
||||
return colorString(format, FgHiMagenta, a...)
|
||||
}
|
||||
|
||||
// HiCyanString is a convenient helper function to return a string with hi-intensity cyan
|
||||
// foreground.
|
||||
func HiCyanString(format string, a ...interface{}) string { return colorString(format, FgHiCyan, a...) }
|
||||
|
||||
// HiWhiteString is a convenient helper function to return a string with hi-intensity white
|
||||
// foreground.
|
||||
func HiWhiteString(format string, a ...interface{}) string {
|
||||
return colorString(format, FgHiWhite, a...)
|
||||
}
|
|
@ -0,0 +1,133 @@
|
|||
/*
|
||||
Package color is an ANSI color package to output colorized or SGR defined
|
||||
output to the standard output. The API can be used in several way, pick one
|
||||
that suits you.
|
||||
|
||||
Use simple and default helper functions with predefined foreground colors:
|
||||
|
||||
color.Cyan("Prints text in cyan.")
|
||||
|
||||
// a newline will be appended automatically
|
||||
color.Blue("Prints %s in blue.", "text")
|
||||
|
||||
// More default foreground colors..
|
||||
color.Red("We have red")
|
||||
color.Yellow("Yellow color too!")
|
||||
color.Magenta("And many others ..")
|
||||
|
||||
// Hi-intensity colors
|
||||
color.HiGreen("Bright green color.")
|
||||
color.HiBlack("Bright black means gray..")
|
||||
color.HiWhite("Shiny white color!")
|
||||
|
||||
However there are times where custom color mixes are required. Below are some
|
||||
examples to create custom color objects and use the print functions of each
|
||||
separate color object.
|
||||
|
||||
// Create a new color object
|
||||
c := color.New(color.FgCyan).Add(color.Underline)
|
||||
c.Println("Prints cyan text with an underline.")
|
||||
|
||||
// Or just add them to New()
|
||||
d := color.New(color.FgCyan, color.Bold)
|
||||
d.Printf("This prints bold cyan %s\n", "too!.")
|
||||
|
||||
|
||||
// Mix up foreground and background colors, create new mixes!
|
||||
red := color.New(color.FgRed)
|
||||
|
||||
boldRed := red.Add(color.Bold)
|
||||
boldRed.Println("This will print text in bold red.")
|
||||
|
||||
whiteBackground := red.Add(color.BgWhite)
|
||||
whiteBackground.Println("Red text with White background.")
|
||||
|
||||
// Use your own io.Writer output
|
||||
color.New(color.FgBlue).Fprintln(myWriter, "blue color!")
|
||||
|
||||
blue := color.New(color.FgBlue)
|
||||
blue.Fprint(myWriter, "This will print text in blue.")
|
||||
|
||||
You can create PrintXxx functions to simplify even more:
|
||||
|
||||
// Create a custom print function for convenient
|
||||
red := color.New(color.FgRed).PrintfFunc()
|
||||
red("warning")
|
||||
red("error: %s", err)
|
||||
|
||||
// Mix up multiple attributes
|
||||
notice := color.New(color.Bold, color.FgGreen).PrintlnFunc()
|
||||
notice("don't forget this...")
|
||||
|
||||
You can also FprintXxx functions to pass your own io.Writer:
|
||||
|
||||
blue := color.New(FgBlue).FprintfFunc()
|
||||
blue(myWriter, "important notice: %s", stars)
|
||||
|
||||
// Mix up with multiple attributes
|
||||
success := color.New(color.Bold, color.FgGreen).FprintlnFunc()
|
||||
success(myWriter, don't forget this...")
|
||||
|
||||
|
||||
Or create SprintXxx functions to mix strings with other non-colorized strings:
|
||||
|
||||
yellow := New(FgYellow).SprintFunc()
|
||||
red := New(FgRed).SprintFunc()
|
||||
|
||||
fmt.Printf("this is a %s and this is %s.\n", yellow("warning"), red("error"))
|
||||
|
||||
info := New(FgWhite, BgGreen).SprintFunc()
|
||||
fmt.Printf("this %s rocks!\n", info("package"))
|
||||
|
||||
Windows support is enabled by default. All Print functions work as intended.
|
||||
However only for color.SprintXXX functions, user should use fmt.FprintXXX and
|
||||
set the output to color.Output:
|
||||
|
||||
fmt.Fprintf(color.Output, "Windows support: %s", color.GreenString("PASS"))
|
||||
|
||||
info := New(FgWhite, BgGreen).SprintFunc()
|
||||
fmt.Fprintf(color.Output, "this %s rocks!\n", info("package"))
|
||||
|
||||
Using with existing code is possible. Just use the Set() method to set the
|
||||
standard output to the given parameters. That way a rewrite of an existing
|
||||
code is not required.
|
||||
|
||||
// Use handy standard colors.
|
||||
color.Set(color.FgYellow)
|
||||
|
||||
fmt.Println("Existing text will be now in Yellow")
|
||||
fmt.Printf("This one %s\n", "too")
|
||||
|
||||
color.Unset() // don't forget to unset
|
||||
|
||||
// You can mix up parameters
|
||||
color.Set(color.FgMagenta, color.Bold)
|
||||
defer color.Unset() // use it in your function
|
||||
|
||||
fmt.Println("All text will be now bold magenta.")
|
||||
|
||||
There might be a case where you want to disable color output (for example to
|
||||
pipe the standard output of your app to somewhere else). `Color` has support to
|
||||
disable colors both globally and for single color definition. For example
|
||||
suppose you have a CLI app and a `--no-color` bool flag. You can easily disable
|
||||
the color output with:
|
||||
|
||||
var flagNoColor = flag.Bool("no-color", false, "Disable color output")
|
||||
|
||||
if *flagNoColor {
|
||||
color.NoColor = true // disables colorized output
|
||||
}
|
||||
|
||||
It also has support for single color definitions (local). You can
|
||||
disable/enable color output on the fly:
|
||||
|
||||
c := color.New(color.FgCyan)
|
||||
c.Println("Prints cyan text")
|
||||
|
||||
c.DisableColor()
|
||||
c.Println("This is printed without any color")
|
||||
|
||||
c.EnableColor()
|
||||
c.Println("This prints again cyan...")
|
||||
*/
|
||||
package color
|
|
@ -0,0 +1,8 @@
|
|||
module github.com/fatih/color
|
||||
|
||||
go 1.13
|
||||
|
||||
require (
|
||||
github.com/mattn/go-colorable v0.1.4
|
||||
github.com/mattn/go-isatty v0.0.11
|
||||
)
|
|
@ -0,0 +1,8 @@
|
|||
github.com/mattn/go-colorable v0.1.4 h1:snbPLB8fVfU9iwbbo30TPtbLRzwWu6aJS6Xh4eaaviA=
|
||||
github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
|
||||
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
|
||||
github.com/mattn/go-isatty v0.0.11 h1:FxPOTFNqGkuDUGi3H/qkUbQO4ZiBa2brKq5r0l8TGeM=
|
||||
github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE=
|
||||
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037 h1:YyJpGZS1sBuBCzLAR1VEpK193GlqGZbnPFnPV/5Rsb4=
|
||||
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
|
@ -0,0 +1,201 @@
|
|||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright {yyyy} {name of copyright owner}
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
|
@ -0,0 +1,36 @@
|
|||
# A more minimal logging API for Go
|
||||
|
||||
Before you consider this package, please read [this blog post by the inimitable
|
||||
Dave Cheney](http://dave.cheney.net/2015/11/05/lets-talk-about-logging). I
|
||||
really appreciate what he has to say, and it largely aligns with my own
|
||||
experiences. Too many choices of levels means inconsistent logs.
|
||||
|
||||
This package offers a purely abstract interface, based on these ideas but with
|
||||
a few twists. Code can depend on just this interface and have the actual
|
||||
logging implementation be injected from callers. Ideally only `main()` knows
|
||||
what logging implementation is being used.
|
||||
|
||||
# Differences from Dave's ideas
|
||||
|
||||
The main differences are:
|
||||
|
||||
1) Dave basically proposes doing away with the notion of a logging API in favor
|
||||
of `fmt.Printf()`. I disagree, especially when you consider things like output
|
||||
locations, timestamps, file and line decorations, and structured logging. I
|
||||
restrict the API to just 2 types of logs: info and error.
|
||||
|
||||
Info logs are things you want to tell the user which are not errors. Error
|
||||
logs are, well, errors. If your code receives an `error` from a subordinate
|
||||
function call and is logging that `error` *and not returning it*, use error
|
||||
logs.
|
||||
|
||||
2) Verbosity-levels on info logs. This gives developers a chance to indicate
|
||||
arbitrary grades of importance for info logs, without assigning names with
|
||||
semantic meaning such as "warning", "trace", and "debug". Superficially this
|
||||
may feel very similar, but the primary difference is the lack of semantics.
|
||||
Because verbosity is a numerical value, it's safe to assume that an app running
|
||||
with higher verbosity means more (and less important) logs will be generated.
|
||||
|
||||
This is a BETA grade API. I have implemented it for
|
||||
[glog](https://godoc.org/github.com/golang/glog). Until there is a significant
|
||||
2nd implementation, I don't really know how it will change.
|
|
@ -0,0 +1,151 @@
|
|||
// Package logr defines abstract interfaces for logging. Packages can depend on
|
||||
// these interfaces and callers can implement logging in whatever way is
|
||||
// appropriate.
|
||||
//
|
||||
// This design derives from Dave Cheney's blog:
|
||||
// http://dave.cheney.net/2015/11/05/lets-talk-about-logging
|
||||
//
|
||||
// This is a BETA grade API. Until there is a significant 2nd implementation,
|
||||
// I don't really know how it will change.
|
||||
//
|
||||
// The logging specifically makes it non-trivial to use format strings, to encourage
|
||||
// attaching structured information instead of unstructured format strings.
|
||||
//
|
||||
// Usage
|
||||
//
|
||||
// Logging is done using a Logger. Loggers can have name prefixes and named values
|
||||
// attached, so that all log messages logged with that Logger have some base context
|
||||
// associated.
|
||||
//
|
||||
// The term "key" is used to refer to the name associated with a particular value, to
|
||||
// disambiguate it from the general Logger name.
|
||||
//
|
||||
// For instance, suppose we're trying to reconcile the state of an object, and we want
|
||||
// to log that we've made some decision.
|
||||
//
|
||||
// With the traditional log package, we might write
|
||||
// log.Printf(
|
||||
// "decided to set field foo to value %q for object %s/%s",
|
||||
// targetValue, object.Namespace, object.Name)
|
||||
//
|
||||
// With logr's structured logging, we'd write
|
||||
// // elsewhere in the file, set up the logger to log with the prefix of "reconcilers",
|
||||
// // and the named value target-type=Foo, for extra context.
|
||||
// log := mainLogger.WithName("reconcilers").WithValues("target-type", "Foo")
|
||||
//
|
||||
// // later on...
|
||||
// log.Info("setting field foo on object", "value", targetValue, "object", object)
|
||||
//
|
||||
// Depending on our logging implementation, we could then make logging decisions based on field values
|
||||
// (like only logging such events for objects in a certain namespace), or copy the structured
|
||||
// information into a structured log store.
|
||||
//
|
||||
// For logging errors, Logger has a method called Error. Suppose we wanted to log an
|
||||
// error while reconciling. With the traditional log package, we might write
|
||||
// log.Errorf("unable to reconcile object %s/%s: %v", object.Namespace, object.Name, err)
|
||||
//
|
||||
// With logr, we'd instead write
|
||||
// // assuming the above setup for log
|
||||
// log.Error(err, "unable to reconcile object", "object", object)
|
||||
//
|
||||
// This functions similarly to:
|
||||
// log.Info("unable to reconcile object", "error", err, "object", object)
|
||||
//
|
||||
// However, it ensures that a standard key for the error value ("error") is used across all
|
||||
// error logging. Furthermore, certain implementations may choose to attach additional
|
||||
// information (such as stack traces) on calls to Error, so it's preferred to use Error
|
||||
// to log errors.
|
||||
//
|
||||
// Parts of a log line
|
||||
//
|
||||
// Each log message from a Logger has four types of context:
|
||||
// logger name, log verbosity, log message, and the named values.
|
||||
//
|
||||
// The Logger name constists of a series of name "segments" added by successive calls to WithName.
|
||||
// These name segments will be joined in some way by the underlying implementation. It is strongly
|
||||
// reccomended that name segements contain simple identifiers (letters, digits, and hyphen), and do
|
||||
// not contain characters that could muddle the log output or confuse the joining operation (e.g.
|
||||
// whitespace, commas, periods, slashes, brackets, quotes, etc).
|
||||
//
|
||||
// Log verbosity represents how little a log matters. Level zero, the default, matters most.
|
||||
// Increasing levels matter less and less. Try to avoid lots of different verbosity levels,
|
||||
// and instead provide useful keys, logger names, and log messages for users to filter on.
|
||||
// It's illegal to pass a log level below zero.
|
||||
//
|
||||
// The log message consists of a constant message attached to the the log line. This
|
||||
// should generally be a simple description of what's occuring, and should never be a format string.
|
||||
//
|
||||
// Variable information can then be attached using named values (key/value pairs). Keys are arbitrary
|
||||
// strings, while values may be any Go value.
|
||||
//
|
||||
// Key Naming Conventions
|
||||
//
|
||||
// While users are generally free to use key names of their choice, it's generally best to avoid
|
||||
// using the following keys, as they're frequently used by implementations:
|
||||
//
|
||||
// - `"error"`: the underlying error value in the `Error` method.
|
||||
// - `"stacktrace"`: the stack trace associated with a particular log line or error
|
||||
// (often from the `Error` message).
|
||||
// - `"caller"`: the calling information (file/line) of a particular log line.
|
||||
// - `"msg"`: the log message.
|
||||
// - `"level"`: the log level.
|
||||
// - `"ts"`: the timestamp for a log line.
|
||||
//
|
||||
// Implementations are encouraged to make use of these keys to represent the above
|
||||
// concepts, when neccessary (for example, in a pure-JSON output form, it would be
|
||||
// necessary to represent at least message and timestamp as ordinary named values).
|
||||
package logr
|
||||
|
||||
// TODO: consider adding back in format strings if they're really needed
|
||||
// TODO: consider other bits of zap/zapcore functionality like ObjectMarshaller (for arbitrary objects)
|
||||
// TODO: consider other bits of glog functionality like Flush, InfoDepth, OutputStats
|
||||
|
||||
// InfoLogger represents the ability to log non-error messages, at a particular verbosity.
|
||||
type InfoLogger interface {
|
||||
// Info logs a non-error message with the given key/value pairs as context.
|
||||
//
|
||||
// The msg argument should be used to add some constant description to
|
||||
// the log line. The key/value pairs can then be used to add additional
|
||||
// variable information. The key/value pairs should alternate string
|
||||
// keys and arbitrary values.
|
||||
Info(msg string, keysAndValues ...interface{})
|
||||
|
||||
// Enabled tests whether this InfoLogger is enabled. For example,
|
||||
// commandline flags might be used to set the logging verbosity and disable
|
||||
// some info logs.
|
||||
Enabled() bool
|
||||
}
|
||||
|
||||
// Logger represents the ability to log messages, both errors and not.
|
||||
type Logger interface {
|
||||
// All Loggers implement InfoLogger. Calling InfoLogger methods directly on
|
||||
// a Logger value is equivalent to calling them on a V(0) InfoLogger. For
|
||||
// example, logger.Info() produces the same result as logger.V(0).Info.
|
||||
InfoLogger
|
||||
|
||||
// Error logs an error, with the given message and key/value pairs as context.
|
||||
// It functions similarly to calling Info with the "error" named value, but may
|
||||
// have unique behavior, and should be preferred for logging errors (see the
|
||||
// package documentations for more information).
|
||||
//
|
||||
// The msg field should be used to add context to any underlying error,
|
||||
// while the err field should be used to attach the actual error that
|
||||
// triggered this log line, if present.
|
||||
Error(err error, msg string, keysAndValues ...interface{})
|
||||
|
||||
// V returns an InfoLogger value for a specific verbosity level. A higher
|
||||
// verbosity level means a log message is less important. It's illegal to
|
||||
// pass a log level less than zero.
|
||||
V(level int) InfoLogger
|
||||
|
||||
// WithValues adds some key-value pairs of context to a logger.
|
||||
// See Info for documentation on how key/value pairs work.
|
||||
WithValues(keysAndValues ...interface{}) Logger
|
||||
|
||||
// WithName adds a new element to the logger's name.
|
||||
// Successive calls with WithName continue to append
|
||||
// suffixes to the logger's name. It's strongly reccomended
|
||||
// that name segments contain only letters, digits, and hyphens
|
||||
// (see the package documentation for more information).
|
||||
WithName(name string) Logger
|
||||
}
|
|
@ -0,0 +1,29 @@
|
|||
*.log
|
||||
.DS_Store
|
||||
doc
|
||||
tmp
|
||||
pkg
|
||||
*.gem
|
||||
*.pid
|
||||
coverage
|
||||
coverage.data
|
||||
build/*
|
||||
*.pbxuser
|
||||
*.mode1v3
|
||||
.svn
|
||||
profile
|
||||
.console_history
|
||||
.sass-cache/*
|
||||
.rake_tasks~
|
||||
*.log.lck
|
||||
solr/
|
||||
.jhw-cache/
|
||||
jhw.*
|
||||
*.sublime*
|
||||
node_modules/
|
||||
dist/
|
||||
generated/
|
||||
.vendor/
|
||||
bin/*
|
||||
gin-bin
|
||||
.idea/
|
|
@ -0,0 +1,3 @@
|
|||
{
|
||||
"Enable": ["vet", "golint", "goimports", "deadcode", "gotype", "ineffassign", "misspell", "nakedret", "unconvert", "megacheck", "varcheck"]
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2019 Mark Bates
|
||||
|
||||
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.
|
|
@ -0,0 +1,61 @@
|
|||
TAGS ?= ""
|
||||
GO_BIN ?= "go"
|
||||
|
||||
install:
|
||||
$(GO_BIN) install -tags ${TAGS} -v .
|
||||
make tidy
|
||||
|
||||
tidy:
|
||||
ifeq ($(GO111MODULE),on)
|
||||
$(GO_BIN) mod tidy
|
||||
else
|
||||
echo skipping go mod tidy
|
||||
endif
|
||||
|
||||
deps:
|
||||
$(GO_BIN) get -tags ${TAGS} -t ./...
|
||||
make tidy
|
||||
|
||||
build:
|
||||
$(GO_BIN) build -v .
|
||||
make tidy
|
||||
|
||||
test:
|
||||
$(GO_BIN) test -cover -tags ${TAGS} ./...
|
||||
make tidy
|
||||
|
||||
ci-deps:
|
||||
$(GO_BIN) get -tags ${TAGS} -t ./...
|
||||
|
||||
ci-test:
|
||||
$(GO_BIN) test -tags ${TAGS} -race ./...
|
||||
|
||||
lint:
|
||||
go get github.com/golangci/golangci-lint/cmd/golangci-lint
|
||||
golangci-lint run --enable-all
|
||||
make tidy
|
||||
|
||||
update:
|
||||
ifeq ($(GO111MODULE),on)
|
||||
rm go.*
|
||||
$(GO_BIN) mod init
|
||||
$(GO_BIN) mod tidy
|
||||
else
|
||||
$(GO_BIN) get -u -tags ${TAGS}
|
||||
endif
|
||||
make test
|
||||
make install
|
||||
make tidy
|
||||
|
||||
release-test:
|
||||
$(GO_BIN) test -tags ${TAGS} -race ./...
|
||||
make tidy
|
||||
|
||||
release:
|
||||
$(GO_BIN) get github.com/gobuffalo/release
|
||||
make tidy
|
||||
release -y -f version.go --skip-packr
|
||||
make tidy
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
# Flect
|
||||
|
||||
<p align="center">
|
||||
<a href="https://godoc.org/github.com/gobuffalo/flect"><img src="https://godoc.org/github.com/gobuffalo/flect?status.svg" alt="GoDoc" /></a>
|
||||
<a href="https://dev.azure.com/markbates/buffalo/_build/latest?definitionId=51&branchName=master"><img src="https://dev.azure.com/markbates/buffalo/_apis/build/status/gobuffalo.flect?branchName=master" alt="CI" /></a>
|
||||
<a href="https://goreportcard.com/report/github.com/gobuffalo/flect"><img src="https://goreportcard.com/badge/github.com/gobuffalo/flect" alt="Go Report Card" /></a>
|
||||
</p>
|
||||
|
||||
This is a new inflection engine to replace [https://github.com/markbates/inflect](https://github.com/markbates/inflect) designed to be more modular, more readable, and easier to fix issues on than the original.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
$ go get -u -v github.com/gobuffalo/flect
|
||||
```
|
||||
|
||||
## `github.com/gobuffalo/flect`
|
||||
<a href="https://godoc.org/github.com/gobuffalo/flect"><img src="https://godoc.org/github.com/gobuffalo/flect?status.svg" alt="GoDoc" /></a>
|
||||
|
||||
The `github.com/gobuffalo/flect` package contains "basic" inflection tools, like pluralization, singularization, etc...
|
||||
|
||||
### The `Ident` Type
|
||||
|
||||
In addition to helpful methods that take in a `string` and return a `string`, there is an `Ident` type that can be used to create new, custom, inflection rules.
|
||||
|
||||
The `Ident` type contains two fields.
|
||||
|
||||
* `Original` - This is the original `string` that was used to create the `Ident`
|
||||
* `Parts` - This is a `[]string` that represents all of the "parts" of the string, that have been split apart, making the segments easier to work with
|
||||
|
||||
Examples of creating new inflection rules using `Ident` can be found in the `github.com/gobuffalo/flect/name` package.
|
||||
|
||||
## `github.com/gobuffalo/flect/name`
|
||||
<a href="https://godoc.org/github.com/gobuffalo/flect/name"><img src="https://godoc.org/github.com/gobuffalo/flect/name?status.svg" alt="GoDoc" /></a>
|
||||
|
||||
The `github.com/gobuffalo/flect/name` package contains more "business" inflection rules like creating proper names, table names, etc...
|
|
@ -0,0 +1,10 @@
|
|||
# github.com/gobuffalo/flect Stands on the Shoulders of Giants
|
||||
|
||||
github.com/gobuffalo/flect does not try to reinvent the wheel! Instead, it uses the already great wheels developed by the Go community and puts them all together in the best way possible. Without these giants, this project would not be possible. Please make sure to check them out and thank them for all of their hard work.
|
||||
|
||||
Thank you to the following **GIANTS**:
|
||||
|
||||
|
||||
* [github.com/davecgh/go-spew](https://godoc.org/github.com/davecgh/go-spew)
|
||||
|
||||
* [github.com/stretchr/testify](https://godoc.org/github.com/stretchr/testify)
|
|
@ -0,0 +1,152 @@
|
|||
package flect
|
||||
|
||||
import "sync"
|
||||
|
||||
var acronymsMoot = &sync.RWMutex{}
|
||||
|
||||
var baseAcronyms = map[string]bool{
|
||||
"OK": true,
|
||||
"UTF8": true,
|
||||
"HTML": true,
|
||||
"JSON": true,
|
||||
"JWT": true,
|
||||
"ID": true,
|
||||
"UUID": true,
|
||||
"SQL": true,
|
||||
"ACK": true,
|
||||
"ACL": true,
|
||||
"ADSL": true,
|
||||
"AES": true,
|
||||
"ANSI": true,
|
||||
"API": true,
|
||||
"ARP": true,
|
||||
"ATM": true,
|
||||
"BGP": true,
|
||||
"BSS": true,
|
||||
"CCITT": true,
|
||||
"CHAP": true,
|
||||
"CIDR": true,
|
||||
"CIR": true,
|
||||
"CLI": true,
|
||||
"CPE": true,
|
||||
"CPU": true,
|
||||
"CRC": true,
|
||||
"CRT": true,
|
||||
"CSMA": true,
|
||||
"CMOS": true,
|
||||
"DCE": true,
|
||||
"DEC": true,
|
||||
"DES": true,
|
||||
"DHCP": true,
|
||||
"DNS": true,
|
||||
"DRAM": true,
|
||||
"DSL": true,
|
||||
"DSLAM": true,
|
||||
"DTE": true,
|
||||
"DMI": true,
|
||||
"EHA": true,
|
||||
"EIA": true,
|
||||
"EIGRP": true,
|
||||
"EOF": true,
|
||||
"ESS": true,
|
||||
"FCC": true,
|
||||
"FCS": true,
|
||||
"FDDI": true,
|
||||
"FTP": true,
|
||||
"GBIC": true,
|
||||
"gbps": true,
|
||||
"GEPOF": true,
|
||||
"HDLC": true,
|
||||
"HTTP": true,
|
||||
"HTTPS": true,
|
||||
"IANA": true,
|
||||
"ICMP": true,
|
||||
"IDF": true,
|
||||
"IDS": true,
|
||||
"IEEE": true,
|
||||
"IETF": true,
|
||||
"IMAP": true,
|
||||
"IP": true,
|
||||
"IPS": true,
|
||||
"ISDN": true,
|
||||
"ISP": true,
|
||||
"kbps": true,
|
||||
"LACP": true,
|
||||
"LAN": true,
|
||||
"LAPB": true,
|
||||
"LAPF": true,
|
||||
"LLC": true,
|
||||
"MAC": true,
|
||||
"Mbps": true,
|
||||
"MC": true,
|
||||
"MDF": true,
|
||||
"MIB": true,
|
||||
"MoCA": true,
|
||||
"MPLS": true,
|
||||
"MTU": true,
|
||||
"NAC": true,
|
||||
"NAT": true,
|
||||
"NBMA": true,
|
||||
"NIC": true,
|
||||
"NRZ": true,
|
||||
"NRZI": true,
|
||||
"NVRAM": true,
|
||||
"OSI": true,
|
||||
"OSPF": true,
|
||||
"OUI": true,
|
||||
"PAP": true,
|
||||
"PAT": true,
|
||||
"PC": true,
|
||||
"PIM": true,
|
||||
"PCM": true,
|
||||
"PDU": true,
|
||||
"POP3": true,
|
||||
"POTS": true,
|
||||
"PPP": true,
|
||||
"PPTP": true,
|
||||
"PTT": true,
|
||||
"PVST": true,
|
||||
"RAM": true,
|
||||
"RARP": true,
|
||||
"RFC": true,
|
||||
"RIP": true,
|
||||
"RLL": true,
|
||||
"ROM": true,
|
||||
"RSTP": true,
|
||||
"RTP": true,
|
||||
"RCP": true,
|
||||
"SDLC": true,
|
||||
"SFD": true,
|
||||
"SFP": true,
|
||||
"SLARP": true,
|
||||
"SLIP": true,
|
||||
"SMTP": true,
|
||||
"SNA": true,
|
||||
"SNAP": true,
|
||||
"SNMP": true,
|
||||
"SOF": true,
|
||||
"SRAM": true,
|
||||
"SSH": true,
|
||||
"SSID": true,
|
||||
"STP": true,
|
||||
"SYN": true,
|
||||
"TDM": true,
|
||||
"TFTP": true,
|
||||
"TIA": true,
|
||||
"TOFU": true,
|
||||
"UDP": true,
|
||||
"URL": true,
|
||||
"URI": true,
|
||||
"USB": true,
|
||||
"UTP": true,
|
||||
"VC": true,
|
||||
"VLAN": true,
|
||||
"VLSM": true,
|
||||
"VPN": true,
|
||||
"W3C": true,
|
||||
"WAN": true,
|
||||
"WEP": true,
|
||||
"WiFi": true,
|
||||
"WPA": true,
|
||||
"WWW": true,
|
||||
}
|
|
@ -0,0 +1,48 @@
|
|||
package flect
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
// Camelize returns a camelize version of a string
|
||||
// bob dylan = bobDylan
|
||||
// widget_id = widgetID
|
||||
// WidgetID = widgetID
|
||||
func Camelize(s string) string {
|
||||
return New(s).Camelize().String()
|
||||
}
|
||||
|
||||
// Camelize returns a camelize version of a string
|
||||
// bob dylan = bobDylan
|
||||
// widget_id = widgetID
|
||||
// WidgetID = widgetID
|
||||
func (i Ident) Camelize() Ident {
|
||||
var out []string
|
||||
for i, part := range i.Parts {
|
||||
var x string
|
||||
var capped bool
|
||||
if strings.ToLower(part) == "id" {
|
||||
out = append(out, "ID")
|
||||
continue
|
||||
}
|
||||
for _, c := range part {
|
||||
if unicode.IsLetter(c) || unicode.IsDigit(c) {
|
||||
if i == 0 {
|
||||
x += string(unicode.ToLower(c))
|
||||
continue
|
||||
}
|
||||
if !capped {
|
||||
capped = true
|
||||
x += string(unicode.ToUpper(c))
|
||||
continue
|
||||
}
|
||||
x += string(c)
|
||||
}
|
||||
}
|
||||
if x != "" {
|
||||
out = append(out, x)
|
||||
}
|
||||
}
|
||||
return New(strings.Join(out, ""))
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
package flect
|
||||
|
||||
import "unicode"
|
||||
|
||||
// Capitalize will cap the first letter of string
|
||||
// user = User
|
||||
// bob dylan = Bob dylan
|
||||
// widget_id = Widget_id
|
||||
func Capitalize(s string) string {
|
||||
return New(s).Capitalize().String()
|
||||
}
|
||||
|
||||
// Capitalize will cap the first letter of string
|
||||
// user = User
|
||||
// bob dylan = Bob dylan
|
||||
// widget_id = Widget_id
|
||||
func (i Ident) Capitalize() Ident {
|
||||
var x string
|
||||
if len(i.Parts) == 0 {
|
||||
return New("")
|
||||
}
|
||||
x = string(unicode.ToTitle(rune(i.Original[0])))
|
||||
if len(i.Original) > 1 {
|
||||
x += i.Original[1:]
|
||||
}
|
||||
return New(x)
|
||||
}
|
|
@ -0,0 +1,83 @@
|
|||
package flect
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
func init() {
|
||||
loadCustomData("inflections.json", "INFLECT_PATH", "could not read inflection file", LoadInflections)
|
||||
loadCustomData("acronyms.json", "ACRONYMS_PATH", "could not read acronyms file", LoadAcronyms)
|
||||
}
|
||||
|
||||
//CustomDataParser are functions that parse data like acronyms or
|
||||
//plurals in the shape of a io.Reader it receives.
|
||||
type CustomDataParser func(io.Reader) error
|
||||
|
||||
func loadCustomData(defaultFile, env, readErrorMessage string, parser CustomDataParser) {
|
||||
pwd, _ := os.Getwd()
|
||||
path, found := os.LookupEnv(env)
|
||||
if !found {
|
||||
path = filepath.Join(pwd, defaultFile)
|
||||
}
|
||||
|
||||
if _, err := os.Stat(path); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
b, err := ioutil.ReadFile(path)
|
||||
if err != nil {
|
||||
fmt.Printf("%s %s (%s)\n", readErrorMessage, path, err)
|
||||
return
|
||||
}
|
||||
|
||||
if err = parser(bytes.NewReader(b)); err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
}
|
||||
|
||||
//LoadAcronyms loads rules from io.Reader param
|
||||
func LoadAcronyms(r io.Reader) error {
|
||||
m := []string{}
|
||||
err := json.NewDecoder(r).Decode(&m)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("could not decode acronyms JSON from reader: %s", err)
|
||||
}
|
||||
|
||||
acronymsMoot.Lock()
|
||||
defer acronymsMoot.Unlock()
|
||||
|
||||
for _, acronym := range m {
|
||||
baseAcronyms[acronym] = true
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
//LoadInflections loads rules from io.Reader param
|
||||
func LoadInflections(r io.Reader) error {
|
||||
m := map[string]string{}
|
||||
|
||||
err := json.NewDecoder(r).Decode(&m)
|
||||
if err != nil {
|
||||
return fmt.Errorf("could not decode inflection JSON from reader: %s", err)
|
||||
}
|
||||
|
||||
pluralMoot.Lock()
|
||||
defer pluralMoot.Unlock()
|
||||
singularMoot.Lock()
|
||||
defer singularMoot.Unlock()
|
||||
|
||||
for s, p := range m {
|
||||
singleToPlural[s] = p
|
||||
pluralToSingle[p] = s
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
package flect
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
// Dasherize returns an alphanumeric, lowercased, dashed string
|
||||
// Donald E. Knuth = donald-e-knuth
|
||||
// Test with + sign = test-with-sign
|
||||
// admin/WidgetID = admin-widget-id
|
||||
func Dasherize(s string) string {
|
||||
return New(s).Dasherize().String()
|
||||
}
|
||||
|
||||
// Dasherize returns an alphanumeric, lowercased, dashed string
|
||||
// Donald E. Knuth = donald-e-knuth
|
||||
// Test with + sign = test-with-sign
|
||||
// admin/WidgetID = admin-widget-id
|
||||
func (i Ident) Dasherize() Ident {
|
||||
var parts []string
|
||||
|
||||
for _, part := range i.Parts {
|
||||
var x string
|
||||
for _, c := range part {
|
||||
if unicode.IsLetter(c) || unicode.IsDigit(c) {
|
||||
x += string(c)
|
||||
}
|
||||
}
|
||||
parts = xappend(parts, x)
|
||||
}
|
||||
|
||||
return New(strings.ToLower(strings.Join(parts, "-")))
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
/*
|
||||
Package flect is a new inflection engine to replace [https://github.com/markbates/inflect](https://github.com/markbates/inflect) designed to be more modular, more readable, and easier to fix issues on than the original.
|
||||
*/
|
||||
package flect
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
var spaces = []rune{'_', ' ', ':', '-', '/'}
|
||||
|
||||
func isSpace(c rune) bool {
|
||||
for _, r := range spaces {
|
||||
if r == c {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return unicode.IsSpace(c)
|
||||
}
|
||||
|
||||
func xappend(a []string, ss ...string) []string {
|
||||
for _, s := range ss {
|
||||
s = strings.TrimSpace(s)
|
||||
for _, x := range spaces {
|
||||
s = strings.Trim(s, string(x))
|
||||
}
|
||||
if _, ok := baseAcronyms[strings.ToUpper(s)]; ok {
|
||||
s = strings.ToUpper(s)
|
||||
}
|
||||
if s != "" {
|
||||
a = append(a, s)
|
||||
}
|
||||
}
|
||||
return a
|
||||
}
|
||||
|
||||
func abs(x int) int {
|
||||
if x < 0 {
|
||||
return -x
|
||||
}
|
||||
return x
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
module github.com/gobuffalo/flect
|
||||
|
||||
go 1.13
|
||||
|
||||
require github.com/stretchr/testify v1.4.0
|
|
@ -0,0 +1,11 @@
|
|||
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
|
||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
|
@ -0,0 +1,35 @@
|
|||
package flect
|
||||
|
||||
import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Humanize returns first letter of sentence capitalized.
|
||||
// Common acronyms are capitalized as well.
|
||||
// Other capital letters in string are left as provided.
|
||||
// employee_salary = Employee salary
|
||||
// employee_id = employee ID
|
||||
// employee_mobile_number = Employee mobile number
|
||||
// first_Name = First Name
|
||||
// firstName = First Name
|
||||
func Humanize(s string) string {
|
||||
return New(s).Humanize().String()
|
||||
}
|
||||
|
||||
// Humanize First letter of sentence capitalized
|
||||
func (i Ident) Humanize() Ident {
|
||||
if len(i.Original) == 0 {
|
||||
return New("")
|
||||
}
|
||||
|
||||
var parts []string
|
||||
for index, part := range i.Parts {
|
||||
if index == 0 {
|
||||
part = strings.Title(i.Parts[0])
|
||||
}
|
||||
|
||||
parts = xappend(parts, part)
|
||||
}
|
||||
|
||||
return New(strings.Join(parts, " "))
|
||||
}
|
|
@ -0,0 +1,106 @@
|
|||
package flect
|
||||
|
||||
import (
|
||||
"encoding"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// Ident represents the string and it's parts
|
||||
type Ident struct {
|
||||
Original string
|
||||
Parts []string
|
||||
}
|
||||
|
||||
// String implements fmt.Stringer and returns the original string
|
||||
func (i Ident) String() string {
|
||||
return i.Original
|
||||
}
|
||||
|
||||
// New creates a new Ident from the string
|
||||
func New(s string) Ident {
|
||||
i := Ident{
|
||||
Original: s,
|
||||
Parts: toParts(s),
|
||||
}
|
||||
|
||||
return i
|
||||
}
|
||||
|
||||
func toParts(s string) []string {
|
||||
parts := []string{}
|
||||
s = strings.TrimSpace(s)
|
||||
if len(s) == 0 {
|
||||
return parts
|
||||
}
|
||||
if _, ok := baseAcronyms[strings.ToUpper(s)]; ok {
|
||||
return []string{strings.ToUpper(s)}
|
||||
}
|
||||
var prev rune
|
||||
var x string
|
||||
for _, c := range s {
|
||||
cs := string(c)
|
||||
// fmt.Println("### cs ->", cs)
|
||||
// fmt.Println("### unicode.IsControl(c) ->", unicode.IsControl(c))
|
||||
// fmt.Println("### unicode.IsDigit(c) ->", unicode.IsDigit(c))
|
||||
// fmt.Println("### unicode.IsGraphic(c) ->", unicode.IsGraphic(c))
|
||||
// fmt.Println("### unicode.IsLetter(c) ->", unicode.IsLetter(c))
|
||||
// fmt.Println("### unicode.IsLower(c) ->", unicode.IsLower(c))
|
||||
// fmt.Println("### unicode.IsMark(c) ->", unicode.IsMark(c))
|
||||
// fmt.Println("### unicode.IsPrint(c) ->", unicode.IsPrint(c))
|
||||
// fmt.Println("### unicode.IsPunct(c) ->", unicode.IsPunct(c))
|
||||
// fmt.Println("### unicode.IsSpace(c) ->", unicode.IsSpace(c))
|
||||
// fmt.Println("### unicode.IsTitle(c) ->", unicode.IsTitle(c))
|
||||
// fmt.Println("### unicode.IsUpper(c) ->", unicode.IsUpper(c))
|
||||
if !utf8.ValidRune(c) {
|
||||
continue
|
||||
}
|
||||
|
||||
if isSpace(c) {
|
||||
parts = xappend(parts, x)
|
||||
x = cs
|
||||
prev = c
|
||||
continue
|
||||
}
|
||||
|
||||
if unicode.IsUpper(c) && !unicode.IsUpper(prev) {
|
||||
parts = xappend(parts, x)
|
||||
x = cs
|
||||
prev = c
|
||||
continue
|
||||
}
|
||||
if unicode.IsUpper(c) && baseAcronyms[strings.ToUpper(x)] {
|
||||
parts = xappend(parts, x)
|
||||
x = cs
|
||||
prev = c
|
||||
continue
|
||||
}
|
||||
if unicode.IsLetter(c) || unicode.IsDigit(c) || unicode.IsPunct(c) || c == '`' {
|
||||
prev = c
|
||||
x += cs
|
||||
continue
|
||||
}
|
||||
|
||||
parts = xappend(parts, x)
|
||||
x = ""
|
||||
prev = c
|
||||
}
|
||||
parts = xappend(parts, x)
|
||||
|
||||
return parts
|
||||
}
|
||||
|
||||
var _ encoding.TextUnmarshaler = &Ident{}
|
||||
var _ encoding.TextMarshaler = &Ident{}
|
||||
|
||||
//UnmarshalText unmarshalls byte array into the Ident
|
||||
func (i *Ident) UnmarshalText(data []byte) error {
|
||||
(*i) = New(string(data))
|
||||
return nil
|
||||
}
|
||||
|
||||
//MarshalText marshals Ident into byte array
|
||||
func (i Ident) MarshalText() ([]byte, error) {
|
||||
return []byte(i.Original), nil
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
package flect
|
||||
|
||||
import "strings"
|
||||
|
||||
// ToUpper is a convience wrapper for strings.ToUpper
|
||||
func (i Ident) ToUpper() Ident {
|
||||
return New(strings.ToUpper(i.Original))
|
||||
}
|
||||
|
||||
// ToLower is a convience wrapper for strings.ToLower
|
||||
func (i Ident) ToLower() Ident {
|
||||
return New(strings.ToLower(i.Original))
|
||||
}
|
|
@ -0,0 +1,43 @@
|
|||
package flect
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// Ordinalize converts a number to an ordinal version
|
||||
// 42 = 42nd
|
||||
// 45 = 45th
|
||||
// 1 = 1st
|
||||
func Ordinalize(s string) string {
|
||||
return New(s).Ordinalize().String()
|
||||
}
|
||||
|
||||
// Ordinalize converts a number to an ordinal version
|
||||
// 42 = 42nd
|
||||
// 45 = 45th
|
||||
// 1 = 1st
|
||||
func (i Ident) Ordinalize() Ident {
|
||||
number, err := strconv.Atoi(i.Original)
|
||||
if err != nil {
|
||||
return i
|
||||
}
|
||||
var s string
|
||||
switch abs(number) % 100 {
|
||||
case 11, 12, 13:
|
||||
s = fmt.Sprintf("%dth", number)
|
||||
default:
|
||||
switch abs(number) % 10 {
|
||||
case 1:
|
||||
s = fmt.Sprintf("%dst", number)
|
||||
case 2:
|
||||
s = fmt.Sprintf("%dnd", number)
|
||||
case 3:
|
||||
s = fmt.Sprintf("%drd", number)
|
||||
}
|
||||
}
|
||||
if s != "" {
|
||||
return New(s)
|
||||
}
|
||||
return New(fmt.Sprintf("%dth", number))
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
package flect
|
||||
|
||||
import (
|
||||
"unicode"
|
||||
)
|
||||
|
||||
// Pascalize returns a string with each segment capitalized
|
||||
// user = User
|
||||
// bob dylan = BobDylan
|
||||
// widget_id = WidgetID
|
||||
func Pascalize(s string) string {
|
||||
return New(s).Pascalize().String()
|
||||
}
|
||||
|
||||
// Pascalize returns a string with each segment capitalized
|
||||
// user = User
|
||||
// bob dylan = BobDylan
|
||||
// widget_id = WidgetID
|
||||
func (i Ident) Pascalize() Ident {
|
||||
c := i.Camelize()
|
||||
if len(c.String()) == 0 {
|
||||
return c
|
||||
}
|
||||
return New(string(unicode.ToUpper(rune(c.Original[0]))) + c.Original[1:])
|
||||
}
|
|
@ -0,0 +1,286 @@
|
|||
package flect
|
||||
|
||||
var pluralRules = []rule{}
|
||||
|
||||
// AddPlural adds a rule that will replace the given suffix with the replacement suffix.
|
||||
func AddPlural(suffix string, repl string) {
|
||||
pluralMoot.Lock()
|
||||
defer pluralMoot.Unlock()
|
||||
pluralRules = append(pluralRules, rule{
|
||||
suffix: suffix,
|
||||
fn: func(s string) string {
|
||||
s = s[:len(s)-len(suffix)]
|
||||
return s + repl
|
||||
},
|
||||
})
|
||||
|
||||
pluralRules = append(pluralRules, rule{
|
||||
suffix: repl,
|
||||
fn: noop,
|
||||
})
|
||||
}
|
||||
|
||||
var singleToPlural = map[string]string{
|
||||
"aircraft": "aircraft",
|
||||
"alias": "aliases",
|
||||
"alumna": "alumnae",
|
||||
"alumnus": "alumni",
|
||||
"analysis": "analyses",
|
||||
"antenna": "antennas",
|
||||
"antithesis": "antitheses",
|
||||
"apex": "apexes",
|
||||
"appendix": "appendices",
|
||||
"axis": "axes",
|
||||
"bacillus": "bacilli",
|
||||
"bacterium": "bacteria",
|
||||
"basis": "bases",
|
||||
"beau": "beaus",
|
||||
"bison": "bison",
|
||||
"bureau": "bureaus",
|
||||
"bus": "buses",
|
||||
"campus": "campuses",
|
||||
"caucus": "caucuses",
|
||||
"child": "children",
|
||||
"château": "châteaux",
|
||||
"circus": "circuses",
|
||||
"codex": "codices",
|
||||
"concerto": "concertos",
|
||||
"corpus": "corpora",
|
||||
"crisis": "crises",
|
||||
"curriculum": "curriculums",
|
||||
"datum": "data",
|
||||
"dear": "dear",
|
||||
"deer": "deer",
|
||||
"diagnosis": "diagnoses",
|
||||
"die": "dice",
|
||||
"dwarf": "dwarves",
|
||||
"ellipsis": "ellipses",
|
||||
"equipment": "equipment",
|
||||
"erratum": "errata",
|
||||
"faux pas": "faux pas",
|
||||
"fez": "fezzes",
|
||||
"fish": "fish",
|
||||
"focus": "foci",
|
||||
"foo": "foos",
|
||||
"foot": "feet",
|
||||
"formula": "formulas",
|
||||
"fungus": "fungi",
|
||||
"genus": "genera",
|
||||
"goose": "geese",
|
||||
"graffito": "graffiti",
|
||||
"grouse": "grouse",
|
||||
"half": "halves",
|
||||
"halo": "halos",
|
||||
"hoof": "hooves",
|
||||
"human": "humans",
|
||||
"hypothesis": "hypotheses",
|
||||
"index": "indices",
|
||||
"information": "information",
|
||||
"jeans": "jeans",
|
||||
"larva": "larvae",
|
||||
"libretto": "librettos",
|
||||
"loaf": "loaves",
|
||||
"locus": "loci",
|
||||
"louse": "lice",
|
||||
"matrix": "matrices",
|
||||
"minutia": "minutiae",
|
||||
"money": "money",
|
||||
"moose": "moose",
|
||||
"mouse": "mice",
|
||||
"nebula": "nebulae",
|
||||
"news": "news",
|
||||
"nucleus": "nuclei",
|
||||
"oasis": "oases",
|
||||
"octopus": "octopi",
|
||||
"offspring": "offspring",
|
||||
"opus": "opera",
|
||||
"ovum": "ova",
|
||||
"ox": "oxen",
|
||||
"parenthesis": "parentheses",
|
||||
"phenomenon": "phenomena",
|
||||
"photo": "photos",
|
||||
"phylum": "phyla",
|
||||
"piano": "pianos",
|
||||
"plus": "pluses",
|
||||
"police": "police",
|
||||
"prognosis": "prognoses",
|
||||
"prometheus": "prometheuses",
|
||||
"quiz": "quizzes",
|
||||
"radius": "radiuses",
|
||||
"referendum": "referendums",
|
||||
"ress": "resses",
|
||||
"rice": "rice",
|
||||
"salmon": "salmon",
|
||||
"sex": "sexes",
|
||||
"series": "series",
|
||||
"sheep": "sheep",
|
||||
"shoe": "shoes",
|
||||
"shrimp": "shrimp",
|
||||
"species": "species",
|
||||
"stimulus": "stimuli",
|
||||
"stratum": "strata",
|
||||
"swine": "swine",
|
||||
"syllabus": "syllabi",
|
||||
"symposium": "symposiums",
|
||||
"synopsis": "synopses",
|
||||
"tableau": "tableaus",
|
||||
"testis": "testes",
|
||||
"thesis": "theses",
|
||||
"thief": "thieves",
|
||||
"tooth": "teeth",
|
||||
"trout": "trout",
|
||||
"tuna": "tuna",
|
||||
"vertebra": "vertebrae",
|
||||
"vertix": "vertices",
|
||||
"vita": "vitae",
|
||||
"vortex": "vortices",
|
||||
"wharf": "wharves",
|
||||
"wife": "wives",
|
||||
"woman": "women",
|
||||
"wolf": "wolves",
|
||||
"you": "you",
|
||||
}
|
||||
|
||||
var pluralToSingle = map[string]string{}
|
||||
|
||||
func init() {
|
||||
for k, v := range singleToPlural {
|
||||
pluralToSingle[v] = k
|
||||
}
|
||||
}
|
||||
|
||||
type singularToPluralSuffix struct {
|
||||
singular string
|
||||
plural string
|
||||
}
|
||||
|
||||
var singularToPluralSuffixList = []singularToPluralSuffix{
|
||||
{"iterion", "iteria"},
|
||||
{"campus", "campuses"},
|
||||
{"genera", "genus"},
|
||||
{"person", "people"},
|
||||
{"phylum", "phyla"},
|
||||
{"randum", "randa"},
|
||||
{"actus", "acti"},
|
||||
{"adium", "adia"},
|
||||
{"alias", "aliases"},
|
||||
{"basis", "basis"},
|
||||
{"child", "children"},
|
||||
{"chive", "chives"},
|
||||
{"focus", "foci"},
|
||||
{"hello", "hellos"},
|
||||
{"jeans", "jeans"},
|
||||
{"louse", "lice"},
|
||||
{"mouse", "mice"},
|
||||
{"movie", "movies"},
|
||||
{"oasis", "oasis"},
|
||||
{"atum", "ata"},
|
||||
{"atus", "atuses"},
|
||||
{"base", "bases"},
|
||||
{"cess", "cesses"},
|
||||
{"dium", "diums"},
|
||||
{"eses", "esis"},
|
||||
{"half", "halves"},
|
||||
{"hive", "hives"},
|
||||
{"iano", "ianos"},
|
||||
{"irus", "iri"},
|
||||
{"isis", "ises"},
|
||||
{"leus", "li"},
|
||||
{"mnus", "mni"},
|
||||
{"move", "moves"},
|
||||
{"news", "news"},
|
||||
{"odex", "odice"},
|
||||
{"oose", "eese"},
|
||||
{"ouse", "ouses"},
|
||||
{"ovum", "ova"},
|
||||
{"rion", "ria"},
|
||||
{"shoe", "shoes"},
|
||||
{"stis", "stes"},
|
||||
{"tive", "tives"},
|
||||
{"wife", "wives"},
|
||||
{"afe", "aves"},
|
||||
{"bfe", "bves"},
|
||||
{"box", "boxes"},
|
||||
{"cfe", "cves"},
|
||||
{"dfe", "dves"},
|
||||
{"dge", "dges"},
|
||||
{"efe", "eves"},
|
||||
{"gfe", "gves"},
|
||||
{"hfe", "hves"},
|
||||
{"ife", "ives"},
|
||||
{"itz", "itzes"},
|
||||
{"ium", "ia"},
|
||||
{"ize", "izes"},
|
||||
{"jfe", "jves"},
|
||||
{"kfe", "kves"},
|
||||
{"man", "men"},
|
||||
{"mfe", "mves"},
|
||||
{"nfe", "nves"},
|
||||
{"nna", "nnas"},
|
||||
{"oaf", "oaves"},
|
||||
{"oci", "ocus"},
|
||||
{"ode", "odes"},
|
||||
{"ofe", "oves"},
|
||||
{"oot", "eet"},
|
||||
{"pfe", "pves"},
|
||||
{"pse", "psis"},
|
||||
{"qfe", "qves"},
|
||||
{"quy", "quies"},
|
||||
{"rfe", "rves"},
|
||||
{"sfe", "sves"},
|
||||
{"tfe", "tves"},
|
||||
{"tum", "ta"},
|
||||
{"tus", "tuses"},
|
||||
{"ufe", "uves"},
|
||||
{"ula", "ulae"},
|
||||
{"ula", "ulas"},
|
||||
{"uli", "ulus"},
|
||||
{"use", "uses"},
|
||||
{"uss", "usses"},
|
||||
{"vfe", "vves"},
|
||||
{"wfe", "wves"},
|
||||
{"xfe", "xves"},
|
||||
{"yfe", "yves"},
|
||||
{"you", "you"},
|
||||
{"zfe", "zves"},
|
||||
{"by", "bies"},
|
||||
{"ch", "ches"},
|
||||
{"cy", "cies"},
|
||||
{"dy", "dies"},
|
||||
{"ex", "ices"},
|
||||
{"fy", "fies"},
|
||||
{"gy", "gies"},
|
||||
{"hy", "hies"},
|
||||
{"io", "ios"},
|
||||
{"jy", "jies"},
|
||||
{"ky", "kies"},
|
||||
{"lf", "lves"},
|
||||
{"ly", "lies"},
|
||||
{"my", "mies"},
|
||||
{"ny", "nies"},
|
||||
{"ox", "oxen"},
|
||||
{"py", "pies"},
|
||||
{"qy", "qies"},
|
||||
{"rf", "rves"},
|
||||
{"ry", "ries"},
|
||||
{"sh", "shes"},
|
||||
{"ss", "sses"},
|
||||
{"sy", "sies"},
|
||||
{"ty", "ties"},
|
||||
{"tz", "tzes"},
|
||||
{"va", "vae"},
|
||||
{"vy", "vies"},
|
||||
{"wy", "wies"},
|
||||
{"xy", "xies"},
|
||||
{"zy", "zies"},
|
||||
{"zz", "zzes"},
|
||||
{"o", "oes"},
|
||||
{"x", "xes"},
|
||||
}
|
||||
|
||||
func init() {
|
||||
for _, suffix := range singularToPluralSuffixList {
|
||||
AddPlural(suffix.singular, suffix.plural)
|
||||
AddSingular(suffix.plural, suffix.singular)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,49 @@
|
|||
package flect
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var pluralMoot = &sync.RWMutex{}
|
||||
|
||||
// Pluralize returns a plural version of the string
|
||||
// user = users
|
||||
// person = people
|
||||
// datum = data
|
||||
func Pluralize(s string) string {
|
||||
return New(s).Pluralize().String()
|
||||
}
|
||||
|
||||
// Pluralize returns a plural version of the string
|
||||
// user = users
|
||||
// person = people
|
||||
// datum = data
|
||||
func (i Ident) Pluralize() Ident {
|
||||
s := i.Original
|
||||
if len(s) == 0 {
|
||||
return New("")
|
||||
}
|
||||
|
||||
pluralMoot.RLock()
|
||||
defer pluralMoot.RUnlock()
|
||||
|
||||
ls := strings.ToLower(s)
|
||||
if _, ok := pluralToSingle[ls]; ok {
|
||||
return i
|
||||
}
|
||||
if p, ok := singleToPlural[ls]; ok {
|
||||
return New(p)
|
||||
}
|
||||
for _, r := range pluralRules {
|
||||
if strings.HasSuffix(ls, r.suffix) {
|
||||
return New(r.fn(s))
|
||||
}
|
||||
}
|
||||
|
||||
if strings.HasSuffix(ls, "s") {
|
||||
return i
|
||||
}
|
||||
|
||||
return New(i.String() + "s")
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
package flect
|
||||
|
||||
type ruleFn func(string) string
|
||||
|
||||
type rule struct {
|
||||
suffix string
|
||||
fn ruleFn
|
||||
}
|
||||
|
||||
func noop(s string) string { return s }
|
|
@ -0,0 +1,23 @@
|
|||
package flect
|
||||
|
||||
var singularRules = []rule{}
|
||||
|
||||
// AddSingular adds a rule that will replace the given suffix with the replacement suffix.
|
||||
func AddSingular(ext string, repl string) {
|
||||
singularMoot.Lock()
|
||||
defer singularMoot.Unlock()
|
||||
singularRules = append(singularRules, rule{
|
||||
suffix: ext,
|
||||
fn: func(s string) string {
|
||||
s = s[:len(s)-len(ext)]
|
||||
return s + repl
|
||||
},
|
||||
})
|
||||
|
||||
singularRules = append(singularRules, rule{
|
||||
suffix: repl,
|
||||
fn: func(s string) string {
|
||||
return s
|
||||
},
|
||||
})
|
||||
}
|
|
@ -0,0 +1,47 @@
|
|||
package flect
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var singularMoot = &sync.RWMutex{}
|
||||
|
||||
// Singularize returns a singular version of the string
|
||||
// users = user
|
||||
// data = datum
|
||||
// people = person
|
||||
func Singularize(s string) string {
|
||||
return New(s).Singularize().String()
|
||||
}
|
||||
|
||||
// Singularize returns a singular version of the string
|
||||
// users = user
|
||||
// data = datum
|
||||
// people = person
|
||||
func (i Ident) Singularize() Ident {
|
||||
s := i.Original
|
||||
if len(s) == 0 {
|
||||
return i
|
||||
}
|
||||
|
||||
singularMoot.RLock()
|
||||
defer singularMoot.RUnlock()
|
||||
ls := strings.ToLower(s)
|
||||
if p, ok := pluralToSingle[ls]; ok {
|
||||
return New(p)
|
||||
}
|
||||
if _, ok := singleToPlural[ls]; ok {
|
||||
return i
|
||||
}
|
||||
for _, r := range singularRules {
|
||||
if strings.HasSuffix(ls, r.suffix) {
|
||||
return New(r.fn(s))
|
||||
}
|
||||
}
|
||||
|
||||
if strings.HasSuffix(s, "s") {
|
||||
return New(s[:len(s)-1])
|
||||
}
|
||||
return i
|
||||
}
|
|
@ -0,0 +1,30 @@
|
|||
package flect
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
// Titleize will capitalize the start of each part
|
||||
// "Nice to see you!" = "Nice To See You!"
|
||||
// "i've read a book! have you?" = "I've Read A Book! Have You?"
|
||||
// "This is `code` ok" = "This Is `code` OK"
|
||||
func Titleize(s string) string {
|
||||
return New(s).Titleize().String()
|
||||
}
|
||||
|
||||
// Titleize will capitalize the start of each part
|
||||
// "Nice to see you!" = "Nice To See You!"
|
||||
// "i've read a book! have you?" = "I've Read A Book! Have You?"
|
||||
// "This is `code` ok" = "This Is `code` OK"
|
||||
func (i Ident) Titleize() Ident {
|
||||
var parts []string
|
||||
for _, part := range i.Parts {
|
||||
x := string(unicode.ToTitle(rune(part[0])))
|
||||
if len(part) > 1 {
|
||||
x += part[1:]
|
||||
}
|
||||
parts = append(parts, x)
|
||||
}
|
||||
return New(strings.Join(parts, " "))
|
||||
}
|
|
@ -0,0 +1,34 @@
|
|||
package flect
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
// Underscore a string
|
||||
// bob dylan = bob_dylan
|
||||
// Nice to see you! = nice_to_see_you
|
||||
// widgetID = widget_id
|
||||
func Underscore(s string) string {
|
||||
return New(s).Underscore().String()
|
||||
}
|
||||
|
||||
// Underscore a string
|
||||
// bob dylan = bob_dylan
|
||||
// Nice to see you! = nice_to_see_you
|
||||
// widgetID = widget_id
|
||||
func (i Ident) Underscore() Ident {
|
||||
var out []string
|
||||
for _, part := range i.Parts {
|
||||
var x string
|
||||
for _, c := range part {
|
||||
if unicode.IsLetter(c) || unicode.IsDigit(c) {
|
||||
x += string(c)
|
||||
}
|
||||
}
|
||||
if x != "" {
|
||||
out = append(out, x)
|
||||
}
|
||||
}
|
||||
return New(strings.ToLower(strings.Join(out, "_")))
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
package flect
|
||||
|
||||
//Version holds Flect version number
|
||||
const Version = "v0.1.6"
|
|
@ -1,3 +1 @@
|
|||
module github.com/google/uuid
|
||||
|
||||
go 1.14
|
||||
|
|
|
@ -1,7 +1,5 @@
|
|||
module github.com/gophercloud/gophercloud
|
||||
|
||||
go 1.14
|
||||
|
||||
require (
|
||||
golang.org/x/crypto v0.0.0-20191202143827-86a70503ff7e
|
||||
golang.org/x/net v0.0.0-20191126235420-ef20fe5d7933 // indirect
|
||||
|
@ -13,3 +11,4 @@ require (
|
|||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect
|
||||
gopkg.in/yaml.v2 v2.2.7
|
||||
)
|
||||
|
||||
|
|
|
@ -0,0 +1,23 @@
|
|||
# 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
|
|
@ -0,0 +1,223 @@
|
|||
package lru
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync"
|
||||
|
||||
"github.com/hashicorp/golang-lru/simplelru"
|
||||
)
|
||||
|
||||
const (
|
||||
// Default2QRecentRatio is the ratio of the 2Q cache dedicated
|
||||
// to recently added entries that have only been accessed once.
|
||||
Default2QRecentRatio = 0.25
|
||||
|
||||
// Default2QGhostEntries is the default ratio of ghost
|
||||
// entries kept to track entries recently evicted
|
||||
Default2QGhostEntries = 0.50
|
||||
)
|
||||
|
||||
// TwoQueueCache is a thread-safe fixed size 2Q cache.
|
||||
// 2Q is an enhancement over the standard LRU cache
|
||||
// in that it tracks both frequently and recently used
|
||||
// entries separately. This avoids a burst in access to new
|
||||
// entries from evicting frequently used entries. It adds some
|
||||
// additional tracking overhead to the standard LRU cache, and is
|
||||
// computationally about 2x the cost, and adds some metadata over
|
||||
// head. The ARCCache is similar, but does not require setting any
|
||||
// parameters.
|
||||
type TwoQueueCache struct {
|
||||
size int
|
||||
recentSize int
|
||||
|
||||
recent simplelru.LRUCache
|
||||
frequent simplelru.LRUCache
|
||||
recentEvict simplelru.LRUCache
|
||||
lock sync.RWMutex
|
||||
}
|
||||
|
||||
// New2Q creates a new TwoQueueCache using the default
|
||||
// values for the parameters.
|
||||
func New2Q(size int) (*TwoQueueCache, error) {
|
||||
return New2QParams(size, Default2QRecentRatio, Default2QGhostEntries)
|
||||
}
|
||||
|
||||
// New2QParams creates a new TwoQueueCache using the provided
|
||||
// parameter values.
|
||||
func New2QParams(size int, recentRatio float64, ghostRatio float64) (*TwoQueueCache, error) {
|
||||
if size <= 0 {
|
||||
return nil, fmt.Errorf("invalid size")
|
||||
}
|
||||
if recentRatio < 0.0 || recentRatio > 1.0 {
|
||||
return nil, fmt.Errorf("invalid recent ratio")
|
||||
}
|
||||
if ghostRatio < 0.0 || ghostRatio > 1.0 {
|
||||
return nil, fmt.Errorf("invalid ghost ratio")
|
||||
}
|
||||
|
||||
// Determine the sub-sizes
|
||||
recentSize := int(float64(size) * recentRatio)
|
||||
evictSize := int(float64(size) * ghostRatio)
|
||||
|
||||
// Allocate the LRUs
|
||||
recent, err := simplelru.NewLRU(size, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
frequent, err := simplelru.NewLRU(size, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
recentEvict, err := simplelru.NewLRU(evictSize, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Initialize the cache
|
||||
c := &TwoQueueCache{
|
||||
size: size,
|
||||
recentSize: recentSize,
|
||||
recent: recent,
|
||||
frequent: frequent,
|
||||
recentEvict: recentEvict,
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// Get looks up a key's value from the cache.
|
||||
func (c *TwoQueueCache) Get(key interface{}) (value interface{}, ok bool) {
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
|
||||
// Check if this is a frequent value
|
||||
if val, ok := c.frequent.Get(key); ok {
|
||||
return val, ok
|
||||
}
|
||||
|
||||
// If the value is contained in recent, then we
|
||||
// promote it to frequent
|
||||
if val, ok := c.recent.Peek(key); ok {
|
||||
c.recent.Remove(key)
|
||||
c.frequent.Add(key, val)
|
||||
return val, ok
|
||||
}
|
||||
|
||||
// No hit
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// Add adds a value to the cache.
|
||||
func (c *TwoQueueCache) Add(key, value interface{}) {
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
|
||||
// Check if the value is frequently used already,
|
||||
// and just update the value
|
||||
if c.frequent.Contains(key) {
|
||||
c.frequent.Add(key, value)
|
||||
return
|
||||
}
|
||||
|
||||
// Check if the value is recently used, and promote
|
||||
// the value into the frequent list
|
||||
if c.recent.Contains(key) {
|
||||
c.recent.Remove(key)
|
||||
c.frequent.Add(key, value)
|
||||
return
|
||||
}
|
||||
|
||||
// If the value was recently evicted, add it to the
|
||||
// frequently used list
|
||||
if c.recentEvict.Contains(key) {
|
||||
c.ensureSpace(true)
|
||||
c.recentEvict.Remove(key)
|
||||
c.frequent.Add(key, value)
|
||||
return
|
||||
}
|
||||
|
||||
// Add to the recently seen list
|
||||
c.ensureSpace(false)
|
||||
c.recent.Add(key, value)
|
||||
return
|
||||
}
|
||||
|
||||
// ensureSpace is used to ensure we have space in the cache
|
||||
func (c *TwoQueueCache) ensureSpace(recentEvict bool) {
|
||||
// If we have space, nothing to do
|
||||
recentLen := c.recent.Len()
|
||||
freqLen := c.frequent.Len()
|
||||
if recentLen+freqLen < c.size {
|
||||
return
|
||||
}
|
||||
|
||||
// If the recent buffer is larger than
|
||||
// the target, evict from there
|
||||
if recentLen > 0 && (recentLen > c.recentSize || (recentLen == c.recentSize && !recentEvict)) {
|
||||
k, _, _ := c.recent.RemoveOldest()
|
||||
c.recentEvict.Add(k, nil)
|
||||
return
|
||||
}
|
||||
|
||||
// Remove from the frequent list otherwise
|
||||
c.frequent.RemoveOldest()
|
||||
}
|
||||
|
||||
// Len returns the number of items in the cache.
|
||||
func (c *TwoQueueCache) Len() int {
|
||||
c.lock.RLock()
|
||||
defer c.lock.RUnlock()
|
||||
return c.recent.Len() + c.frequent.Len()
|
||||
}
|
||||
|
||||
// Keys returns a slice of the keys in the cache.
|
||||
// The frequently used keys are first in the returned slice.
|
||||
func (c *TwoQueueCache) Keys() []interface{} {
|
||||
c.lock.RLock()
|
||||
defer c.lock.RUnlock()
|
||||
k1 := c.frequent.Keys()
|
||||
k2 := c.recent.Keys()
|
||||
return append(k1, k2...)
|
||||
}
|
||||
|
||||
// Remove removes the provided key from the cache.
|
||||
func (c *TwoQueueCache) Remove(key interface{}) {
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
if c.frequent.Remove(key) {
|
||||
return
|
||||
}
|
||||
if c.recent.Remove(key) {
|
||||
return
|
||||
}
|
||||
if c.recentEvict.Remove(key) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Purge is used to completely clear the cache.
|
||||
func (c *TwoQueueCache) Purge() {
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
c.recent.Purge()
|
||||
c.frequent.Purge()
|
||||
c.recentEvict.Purge()
|
||||
}
|
||||
|
||||
// Contains is used to check if the cache contains a key
|
||||
// without updating recency or frequency.
|
||||
func (c *TwoQueueCache) Contains(key interface{}) bool {
|
||||
c.lock.RLock()
|
||||
defer c.lock.RUnlock()
|
||||
return c.frequent.Contains(key) || c.recent.Contains(key)
|
||||
}
|
||||
|
||||
// Peek is used to inspect the cache value of a key
|
||||
// without updating recency or frequency.
|
||||
func (c *TwoQueueCache) Peek(key interface{}) (value interface{}, ok bool) {
|
||||
c.lock.RLock()
|
||||
defer c.lock.RUnlock()
|
||||
if val, ok := c.frequent.Peek(key); ok {
|
||||
return val, ok
|
||||
}
|
||||
return c.recent.Peek(key)
|
||||
}
|
|
@ -0,0 +1,362 @@
|
|||
Mozilla Public License, version 2.0
|
||||
|
||||
1. Definitions
|
||||
|
||||
1.1. "Contributor"
|
||||
|
||||
means each individual or legal entity that creates, contributes to the
|
||||
creation of, or owns Covered Software.
|
||||
|
||||
1.2. "Contributor Version"
|
||||
|
||||
means the combination of the Contributions of others (if any) used by a
|
||||
Contributor and that particular Contributor's Contribution.
|
||||
|
||||
1.3. "Contribution"
|
||||
|
||||
means Covered Software of a particular Contributor.
|
||||
|
||||
1.4. "Covered Software"
|
||||
|
||||
means Source Code Form to which the initial Contributor has attached the
|
||||
notice in Exhibit A, the Executable Form of such Source Code Form, and
|
||||
Modifications of such Source Code Form, in each case including portions
|
||||
thereof.
|
||||
|
||||
1.5. "Incompatible With Secondary Licenses"
|
||||
means
|
||||
|
||||
a. that the initial Contributor has attached the notice described in
|
||||
Exhibit B to the Covered Software; or
|
||||
|
||||
b. that the Covered Software was made available under the terms of
|
||||
version 1.1 or earlier of the License, but not also under the terms of
|
||||
a Secondary License.
|
||||
|
||||
1.6. "Executable Form"
|
||||
|
||||
means any form of the work other than Source Code Form.
|
||||
|
||||
1.7. "Larger Work"
|
||||
|
||||
means a work that combines Covered Software with other material, in a
|
||||
separate file or files, that is not Covered Software.
|
||||
|
||||
1.8. "License"
|
||||
|
||||
means this document.
|
||||
|
||||
1.9. "Licensable"
|
||||
|
||||
means having the right to grant, to the maximum extent possible, whether
|
||||
at the time of the initial grant or subsequently, any and all of the
|
||||
rights conveyed by this License.
|
||||
|
||||
1.10. "Modifications"
|
||||
|
||||
means any of the following:
|
||||
|
||||
a. any file in Source Code Form that results from an addition to,
|
||||
deletion from, or modification of the contents of Covered Software; or
|
||||
|
||||
b. any new file in Source Code Form that contains any Covered Software.
|
||||
|
||||
1.11. "Patent Claims" of a Contributor
|
||||
|
||||
means any patent claim(s), including without limitation, method,
|
||||
process, and apparatus claims, in any patent Licensable by such
|
||||
Contributor that would be infringed, but for the grant of the License,
|
||||
by the making, using, selling, offering for sale, having made, import,
|
||||
or transfer of either its Contributions or its Contributor Version.
|
||||
|
||||
1.12. "Secondary License"
|
||||
|
||||
means either the GNU General Public License, Version 2.0, the GNU Lesser
|
||||
General Public License, Version 2.1, the GNU Affero General Public
|
||||
License, Version 3.0, or any later versions of those licenses.
|
||||
|
||||
1.13. "Source Code Form"
|
||||
|
||||
means the form of the work preferred for making modifications.
|
||||
|
||||
1.14. "You" (or "Your")
|
||||
|
||||
means an individual or a legal entity exercising rights under this
|
||||
License. For legal entities, "You" includes any entity that controls, is
|
||||
controlled by, or is under common control with You. For purposes of this
|
||||
definition, "control" means (a) the power, direct or indirect, to cause
|
||||
the direction or management of such entity, whether by contract or
|
||||
otherwise, or (b) ownership of more than fifty percent (50%) of the
|
||||
outstanding shares or beneficial ownership of such entity.
|
||||
|
||||
|
||||
2. License Grants and Conditions
|
||||
|
||||
2.1. Grants
|
||||
|
||||
Each Contributor hereby grants You a world-wide, royalty-free,
|
||||
non-exclusive license:
|
||||
|
||||
a. under intellectual property rights (other than patent or trademark)
|
||||
Licensable by such Contributor to use, reproduce, make available,
|
||||
modify, display, perform, distribute, and otherwise exploit its
|
||||
Contributions, either on an unmodified basis, with Modifications, or
|
||||
as part of a Larger Work; and
|
||||
|
||||
b. under Patent Claims of such Contributor to make, use, sell, offer for
|
||||
sale, have made, import, and otherwise transfer either its
|
||||
Contributions or its Contributor Version.
|
||||
|
||||
2.2. Effective Date
|
||||
|
||||
The licenses granted in Section 2.1 with respect to any Contribution
|
||||
become effective for each Contribution on the date the Contributor first
|
||||
distributes such Contribution.
|
||||
|
||||
2.3. Limitations on Grant Scope
|
||||
|
||||
The licenses granted in this Section 2 are the only rights granted under
|
||||
this License. No additional rights or licenses will be implied from the
|
||||
distribution or licensing of Covered Software under this License.
|
||||
Notwithstanding Section 2.1(b) above, no patent license is granted by a
|
||||
Contributor:
|
||||
|
||||
a. for any code that a Contributor has removed from Covered Software; or
|
||||
|
||||
b. for infringements caused by: (i) Your and any other third party's
|
||||
modifications of Covered Software, or (ii) the combination of its
|
||||
Contributions with other software (except as part of its Contributor
|
||||
Version); or
|
||||
|
||||
c. under Patent Claims infringed by Covered Software in the absence of
|
||||
its Contributions.
|
||||
|
||||
This License does not grant any rights in the trademarks, service marks,
|
||||
or logos of any Contributor (except as may be necessary to comply with
|
||||
the notice requirements in Section 3.4).
|
||||
|
||||
2.4. Subsequent Licenses
|
||||
|
||||
No Contributor makes additional grants as a result of Your choice to
|
||||
distribute the Covered Software under a subsequent version of this
|
||||
License (see Section 10.2) or under the terms of a Secondary License (if
|
||||
permitted under the terms of Section 3.3).
|
||||
|
||||
2.5. Representation
|
||||
|
||||
Each Contributor represents that the Contributor believes its
|
||||
Contributions are its original creation(s) or it has sufficient rights to
|
||||
grant the rights to its Contributions conveyed by this License.
|
||||
|
||||
2.6. Fair Use
|
||||
|
||||
This License is not intended to limit any rights You have under
|
||||
applicable copyright doctrines of fair use, fair dealing, or other
|
||||
equivalents.
|
||||
|
||||
2.7. Conditions
|
||||
|
||||
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
|
||||
Section 2.1.
|
||||
|
||||
|
||||
3. Responsibilities
|
||||
|
||||
3.1. Distribution of Source Form
|
||||
|
||||
All distribution of Covered Software in Source Code Form, including any
|
||||
Modifications that You create or to which You contribute, must be under
|
||||
the terms of this License. You must inform recipients that the Source
|
||||
Code Form of the Covered Software is governed by the terms of this
|
||||
License, and how they can obtain a copy of this License. You may not
|
||||
attempt to alter or restrict the recipients' rights in the Source Code
|
||||
Form.
|
||||
|
||||
3.2. Distribution of Executable Form
|
||||
|
||||
If You distribute Covered Software in Executable Form then:
|
||||
|
||||
a. such Covered Software must also be made available in Source Code Form,
|
||||
as described in Section 3.1, and You must inform recipients of the
|
||||
Executable Form how they can obtain a copy of such Source Code Form by
|
||||
reasonable means in a timely manner, at a charge no more than the cost
|
||||
of distribution to the recipient; and
|
||||
|
||||
b. You may distribute such Executable Form under the terms of this
|
||||
License, or sublicense it under different terms, provided that the
|
||||
license for the Executable Form does not attempt to limit or alter the
|
||||
recipients' rights in the Source Code Form under this License.
|
||||
|
||||
3.3. Distribution of a Larger Work
|
||||
|
||||
You may create and distribute a Larger Work under terms of Your choice,
|
||||
provided that You also comply with the requirements of this License for
|
||||
the Covered Software. If the Larger Work is a combination of Covered
|
||||
Software with a work governed by one or more Secondary Licenses, and the
|
||||
Covered Software is not Incompatible With Secondary Licenses, this
|
||||
License permits You to additionally distribute such Covered Software
|
||||
under the terms of such Secondary License(s), so that the recipient of
|
||||
the Larger Work may, at their option, further distribute the Covered
|
||||
Software under the terms of either this License or such Secondary
|
||||
License(s).
|
||||
|
||||
3.4. Notices
|
||||
|
||||
You may not remove or alter the substance of any license notices
|
||||
(including copyright notices, patent notices, disclaimers of warranty, or
|
||||
limitations of liability) contained within the Source Code Form of the
|
||||
Covered Software, except that You may alter any license notices to the
|
||||
extent required to remedy known factual inaccuracies.
|
||||
|
||||
3.5. Application of Additional Terms
|
||||
|
||||
You may choose to offer, and to charge a fee for, warranty, support,
|
||||
indemnity or liability obligations to one or more recipients of Covered
|
||||
Software. However, You may do so only on Your own behalf, and not on
|
||||
behalf of any Contributor. You must make it absolutely clear that any
|
||||
such warranty, support, indemnity, or liability obligation is offered by
|
||||
You alone, and You hereby agree to indemnify every Contributor for any
|
||||
liability incurred by such Contributor as a result of warranty, support,
|
||||
indemnity or liability terms You offer. You may include additional
|
||||
disclaimers of warranty and limitations of liability specific to any
|
||||
jurisdiction.
|
||||
|
||||
4. Inability to Comply Due to Statute or Regulation
|
||||
|
||||
If it is impossible for You to comply with any of the terms of this License
|
||||
with respect to some or all of the Covered Software due to statute,
|
||||
judicial order, or regulation then You must: (a) comply with the terms of
|
||||
this License to the maximum extent possible; and (b) describe the
|
||||
limitations and the code they affect. Such description must be placed in a
|
||||
text file included with all distributions of the Covered Software under
|
||||
this License. Except to the extent prohibited by statute or regulation,
|
||||
such description must be sufficiently detailed for a recipient of ordinary
|
||||
skill to be able to understand it.
|
||||
|
||||
5. Termination
|
||||
|
||||
5.1. The rights granted under this License will terminate automatically if You
|
||||
fail to comply with any of its terms. However, if You become compliant,
|
||||
then the rights granted under this License from a particular Contributor
|
||||
are reinstated (a) provisionally, unless and until such Contributor
|
||||
explicitly and finally terminates Your grants, and (b) on an ongoing
|
||||
basis, if such Contributor fails to notify You of the non-compliance by
|
||||
some reasonable means prior to 60 days after You have come back into
|
||||
compliance. Moreover, Your grants from a particular Contributor are
|
||||
reinstated on an ongoing basis if such Contributor notifies You of the
|
||||
non-compliance by some reasonable means, this is the first time You have
|
||||
received notice of non-compliance with this License from such
|
||||
Contributor, and You become compliant prior to 30 days after Your receipt
|
||||
of the notice.
|
||||
|
||||
5.2. If You initiate litigation against any entity by asserting a patent
|
||||
infringement claim (excluding declaratory judgment actions,
|
||||
counter-claims, and cross-claims) alleging that a Contributor Version
|
||||
directly or indirectly infringes any patent, then the rights granted to
|
||||
You by any and all Contributors for the Covered Software under Section
|
||||
2.1 of this License shall terminate.
|
||||
|
||||
5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
|
||||
license agreements (excluding distributors and resellers) which have been
|
||||
validly granted by You or Your distributors under this License prior to
|
||||
termination shall survive termination.
|
||||
|
||||
6. Disclaimer of Warranty
|
||||
|
||||
Covered Software is provided under this License on an "as is" basis,
|
||||
without warranty of any kind, either expressed, implied, or statutory,
|
||||
including, without limitation, warranties that the Covered Software is free
|
||||
of defects, merchantable, fit for a particular purpose or non-infringing.
|
||||
The entire risk as to the quality and performance of the Covered Software
|
||||
is with You. Should any Covered Software prove defective in any respect,
|
||||
You (not any Contributor) assume the cost of any necessary servicing,
|
||||
repair, or correction. This disclaimer of warranty constitutes an essential
|
||||
part of this License. No use of any Covered Software is authorized under
|
||||
this License except under this disclaimer.
|
||||
|
||||
7. Limitation of Liability
|
||||
|
||||
Under no circumstances and under no legal theory, whether tort (including
|
||||
negligence), contract, or otherwise, shall any Contributor, or anyone who
|
||||
distributes Covered Software as permitted above, be liable to You for any
|
||||
direct, indirect, special, incidental, or consequential damages of any
|
||||
character including, without limitation, damages for lost profits, loss of
|
||||
goodwill, work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses, even if such party shall have been
|
||||
informed of the possibility of such damages. This limitation of liability
|
||||
shall not apply to liability for death or personal injury resulting from
|
||||
such party's negligence to the extent applicable law prohibits such
|
||||
limitation. Some jurisdictions do not allow the exclusion or limitation of
|
||||
incidental or consequential damages, so this exclusion and limitation may
|
||||
not apply to You.
|
||||
|
||||
8. Litigation
|
||||
|
||||
Any litigation relating to this License may be brought only in the courts
|
||||
of a jurisdiction where the defendant maintains its principal place of
|
||||
business and such litigation shall be governed by laws of that
|
||||
jurisdiction, without reference to its conflict-of-law provisions. Nothing
|
||||
in this Section shall prevent a party's ability to bring cross-claims or
|
||||
counter-claims.
|
||||
|
||||
9. Miscellaneous
|
||||
|
||||
This License represents the complete agreement concerning the subject
|
||||
matter hereof. If any provision of this License is held to be
|
||||
unenforceable, such provision shall be reformed only to the extent
|
||||
necessary to make it enforceable. Any law or regulation which provides that
|
||||
the language of a contract shall be construed against the drafter shall not
|
||||
be used to construe this License against a Contributor.
|
||||
|
||||
|
||||
10. Versions of the License
|
||||
|
||||
10.1. New Versions
|
||||
|
||||
Mozilla Foundation is the license steward. Except as provided in Section
|
||||
10.3, no one other than the license steward has the right to modify or
|
||||
publish new versions of this License. Each version will be given a
|
||||
distinguishing version number.
|
||||
|
||||
10.2. Effect of New Versions
|
||||
|
||||
You may distribute the Covered Software under the terms of the version
|
||||
of the License under which You originally received the Covered Software,
|
||||
or under the terms of any subsequent version published by the license
|
||||
steward.
|
||||
|
||||
10.3. Modified Versions
|
||||
|
||||
If you create software not governed by this License, and you want to
|
||||
create a new license for such software, you may create and use a
|
||||
modified version of this License if you rename the license and remove
|
||||
any references to the name of the license steward (except to note that
|
||||
such modified license differs from this License).
|
||||
|
||||
10.4. Distributing Source Code Form that is Incompatible With Secondary
|
||||
Licenses If You choose to distribute Source Code Form that is
|
||||
Incompatible With Secondary Licenses under the terms of this version of
|
||||
the License, the notice described in Exhibit B of this License must be
|
||||
attached.
|
||||
|
||||
Exhibit A - Source Code Form License Notice
|
||||
|
||||
This Source Code Form is subject to the
|
||||
terms of the Mozilla Public License, v.
|
||||
2.0. If a copy of the MPL was not
|
||||
distributed with this file, You can
|
||||
obtain one at
|
||||
http://mozilla.org/MPL/2.0/.
|
||||
|
||||
If it is not possible or desirable to put the notice in a particular file,
|
||||
then You may include the notice in a location (such as a LICENSE file in a
|
||||
relevant directory) where a recipient would be likely to look for such a
|
||||
notice.
|
||||
|
||||
You may add additional accurate notices of copyright ownership.
|
||||
|
||||
Exhibit B - "Incompatible With Secondary Licenses" Notice
|
||||
|
||||
This Source Code Form is "Incompatible
|
||||
With Secondary Licenses", as defined by
|
||||
the Mozilla Public License, v. 2.0.
|
|
@ -0,0 +1,25 @@
|
|||
golang-lru
|
||||
==========
|
||||
|
||||
This provides the `lru` package which implements a fixed-size
|
||||
thread safe LRU cache. It is based on the cache in Groupcache.
|
||||
|
||||
Documentation
|
||||
=============
|
||||
|
||||
Full docs are available on [Godoc](http://godoc.org/github.com/hashicorp/golang-lru)
|
||||
|
||||
Example
|
||||
=======
|
||||
|
||||
Using the LRU is very simple:
|
||||
|
||||
```go
|
||||
l, _ := New(128)
|
||||
for i := 0; i < 256; i++ {
|
||||
l.Add(i, nil)
|
||||
}
|
||||
if l.Len() != 128 {
|
||||
panic(fmt.Sprintf("bad len: %v", l.Len()))
|
||||
}
|
||||
```
|
|
@ -0,0 +1,257 @@
|
|||
package lru
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/hashicorp/golang-lru/simplelru"
|
||||
)
|
||||
|
||||
// ARCCache is a thread-safe fixed size Adaptive Replacement Cache (ARC).
|
||||
// ARC is an enhancement over the standard LRU cache in that tracks both
|
||||
// frequency and recency of use. This avoids a burst in access to new
|
||||
// entries from evicting the frequently used older entries. It adds some
|
||||
// additional tracking overhead to a standard LRU cache, computationally
|
||||
// it is roughly 2x the cost, and the extra memory overhead is linear
|
||||
// with the size of the cache. ARC has been patented by IBM, but is
|
||||
// similar to the TwoQueueCache (2Q) which requires setting parameters.
|
||||
type ARCCache struct {
|
||||
size int // Size is the total capacity of the cache
|
||||
p int // P is the dynamic preference towards T1 or T2
|
||||
|
||||
t1 simplelru.LRUCache // T1 is the LRU for recently accessed items
|
||||
b1 simplelru.LRUCache // B1 is the LRU for evictions from t1
|
||||
|
||||
t2 simplelru.LRUCache // T2 is the LRU for frequently accessed items
|
||||
b2 simplelru.LRUCache // B2 is the LRU for evictions from t2
|
||||
|
||||
lock sync.RWMutex
|
||||
}
|
||||
|
||||
// NewARC creates an ARC of the given size
|
||||
func NewARC(size int) (*ARCCache, error) {
|
||||
// Create the sub LRUs
|
||||
b1, err := simplelru.NewLRU(size, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b2, err := simplelru.NewLRU(size, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t1, err := simplelru.NewLRU(size, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t2, err := simplelru.NewLRU(size, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Initialize the ARC
|
||||
c := &ARCCache{
|
||||
size: size,
|
||||
p: 0,
|
||||
t1: t1,
|
||||
b1: b1,
|
||||
t2: t2,
|
||||
b2: b2,
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// Get looks up a key's value from the cache.
|
||||
func (c *ARCCache) Get(key interface{}) (value interface{}, ok bool) {
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
|
||||
// If the value is contained in T1 (recent), then
|
||||
// promote it to T2 (frequent)
|
||||
if val, ok := c.t1.Peek(key); ok {
|
||||
c.t1.Remove(key)
|
||||
c.t2.Add(key, val)
|
||||
return val, ok
|
||||
}
|
||||
|
||||
// Check if the value is contained in T2 (frequent)
|
||||
if val, ok := c.t2.Get(key); ok {
|
||||
return val, ok
|
||||
}
|
||||
|
||||
// No hit
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// Add adds a value to the cache.
|
||||
func (c *ARCCache) Add(key, value interface{}) {
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
|
||||
// Check if the value is contained in T1 (recent), and potentially
|
||||
// promote it to frequent T2
|
||||
if c.t1.Contains(key) {
|
||||
c.t1.Remove(key)
|
||||
c.t2.Add(key, value)
|
||||
return
|
||||
}
|
||||
|
||||
// Check if the value is already in T2 (frequent) and update it
|
||||
if c.t2.Contains(key) {
|
||||
c.t2.Add(key, value)
|
||||
return
|
||||
}
|
||||
|
||||
// Check if this value was recently evicted as part of the
|
||||
// recently used list
|
||||
if c.b1.Contains(key) {
|
||||
// T1 set is too small, increase P appropriately
|
||||
delta := 1
|
||||
b1Len := c.b1.Len()
|
||||
b2Len := c.b2.Len()
|
||||
if b2Len > b1Len {
|
||||
delta = b2Len / b1Len
|
||||
}
|
||||
if c.p+delta >= c.size {
|
||||
c.p = c.size
|
||||
} else {
|
||||
c.p += delta
|
||||
}
|
||||
|
||||
// Potentially need to make room in the cache
|
||||
if c.t1.Len()+c.t2.Len() >= c.size {
|
||||
c.replace(false)
|
||||
}
|
||||
|
||||
// Remove from B1
|
||||
c.b1.Remove(key)
|
||||
|
||||
// Add the key to the frequently used list
|
||||
c.t2.Add(key, value)
|
||||
return
|
||||
}
|
||||
|
||||
// Check if this value was recently evicted as part of the
|
||||
// frequently used list
|
||||
if c.b2.Contains(key) {
|
||||
// T2 set is too small, decrease P appropriately
|
||||
delta := 1
|
||||
b1Len := c.b1.Len()
|
||||
b2Len := c.b2.Len()
|
||||
if b1Len > b2Len {
|
||||
delta = b1Len / b2Len
|
||||
}
|
||||
if delta >= c.p {
|
||||
c.p = 0
|
||||
} else {
|
||||
c.p -= delta
|
||||
}
|
||||
|
||||
// Potentially need to make room in the cache
|
||||
if c.t1.Len()+c.t2.Len() >= c.size {
|
||||
c.replace(true)
|
||||
}
|
||||
|
||||
// Remove from B2
|
||||
c.b2.Remove(key)
|
||||
|
||||
// Add the key to the frequently used list
|
||||
c.t2.Add(key, value)
|
||||
return
|
||||
}
|
||||
|
||||
// Potentially need to make room in the cache
|
||||
if c.t1.Len()+c.t2.Len() >= c.size {
|
||||
c.replace(false)
|
||||
}
|
||||
|
||||
// Keep the size of the ghost buffers trim
|
||||
if c.b1.Len() > c.size-c.p {
|
||||
c.b1.RemoveOldest()
|
||||
}
|
||||
if c.b2.Len() > c.p {
|
||||
c.b2.RemoveOldest()
|
||||
}
|
||||
|
||||
// Add to the recently seen list
|
||||
c.t1.Add(key, value)
|
||||
return
|
||||
}
|
||||
|
||||
// replace is used to adaptively evict from either T1 or T2
|
||||
// based on the current learned value of P
|
||||
func (c *ARCCache) replace(b2ContainsKey bool) {
|
||||
t1Len := c.t1.Len()
|
||||
if t1Len > 0 && (t1Len > c.p || (t1Len == c.p && b2ContainsKey)) {
|
||||
k, _, ok := c.t1.RemoveOldest()
|
||||
if ok {
|
||||
c.b1.Add(k, nil)
|
||||
}
|
||||
} else {
|
||||
k, _, ok := c.t2.RemoveOldest()
|
||||
if ok {
|
||||
c.b2.Add(k, nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Len returns the number of cached entries
|
||||
func (c *ARCCache) Len() int {
|
||||
c.lock.RLock()
|
||||
defer c.lock.RUnlock()
|
||||
return c.t1.Len() + c.t2.Len()
|
||||
}
|
||||
|
||||
// Keys returns all the cached keys
|
||||
func (c *ARCCache) Keys() []interface{} {
|
||||
c.lock.RLock()
|
||||
defer c.lock.RUnlock()
|
||||
k1 := c.t1.Keys()
|
||||
k2 := c.t2.Keys()
|
||||
return append(k1, k2...)
|
||||
}
|
||||
|
||||
// Remove is used to purge a key from the cache
|
||||
func (c *ARCCache) Remove(key interface{}) {
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
if c.t1.Remove(key) {
|
||||
return
|
||||
}
|
||||
if c.t2.Remove(key) {
|
||||
return
|
||||
}
|
||||
if c.b1.Remove(key) {
|
||||
return
|
||||
}
|
||||
if c.b2.Remove(key) {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Purge is used to clear the cache
|
||||
func (c *ARCCache) Purge() {
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
c.t1.Purge()
|
||||
c.t2.Purge()
|
||||
c.b1.Purge()
|
||||
c.b2.Purge()
|
||||
}
|
||||
|
||||
// Contains is used to check if the cache contains a key
|
||||
// without updating recency or frequency.
|
||||
func (c *ARCCache) Contains(key interface{}) bool {
|
||||
c.lock.RLock()
|
||||
defer c.lock.RUnlock()
|
||||
return c.t1.Contains(key) || c.t2.Contains(key)
|
||||
}
|
||||
|
||||
// Peek is used to inspect the cache value of a key
|
||||
// without updating recency or frequency.
|
||||
func (c *ARCCache) Peek(key interface{}) (value interface{}, ok bool) {
|
||||
c.lock.RLock()
|
||||
defer c.lock.RUnlock()
|
||||
if val, ok := c.t1.Peek(key); ok {
|
||||
return val, ok
|
||||
}
|
||||
return c.t2.Peek(key)
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
// Package lru provides three different LRU caches of varying sophistication.
|
||||
//
|
||||
// Cache is a simple LRU cache. It is based on the
|
||||
// LRU implementation in groupcache:
|
||||
// https://github.com/golang/groupcache/tree/master/lru
|
||||
//
|
||||
// TwoQueueCache tracks frequently used and recently used entries separately.
|
||||
// This avoids a burst of accesses from taking out frequently used entries,
|
||||
// at the cost of about 2x computational overhead and some extra bookkeeping.
|
||||
//
|
||||
// ARCCache is an adaptive replacement cache. It tracks recent evictions as
|
||||
// well as recent usage in both the frequent and recent caches. Its
|
||||
// computational overhead is comparable to TwoQueueCache, but the memory
|
||||
// overhead is linear with the size of the cache.
|
||||
//
|
||||
// ARC has been patented by IBM, so do not use it if that is problematic for
|
||||
// your program.
|
||||
//
|
||||
// All caches in this package take locks while operating, and are therefore
|
||||
// thread-safe for consumers.
|
||||
package lru
|
|
@ -0,0 +1,3 @@
|
|||
module github.com/hashicorp/golang-lru
|
||||
|
||||
go 1.12
|
|
@ -0,0 +1,150 @@
|
|||
package lru
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
"github.com/hashicorp/golang-lru/simplelru"
|
||||
)
|
||||
|
||||
// Cache is a thread-safe fixed size LRU cache.
|
||||
type Cache struct {
|
||||
lru simplelru.LRUCache
|
||||
lock sync.RWMutex
|
||||
}
|
||||
|
||||
// New creates an LRU of the given size.
|
||||
func New(size int) (*Cache, error) {
|
||||
return NewWithEvict(size, nil)
|
||||
}
|
||||
|
||||
// NewWithEvict constructs a fixed size cache with the given eviction
|
||||
// callback.
|
||||
func NewWithEvict(size int, onEvicted func(key interface{}, value interface{})) (*Cache, error) {
|
||||
lru, err := simplelru.NewLRU(size, simplelru.EvictCallback(onEvicted))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c := &Cache{
|
||||
lru: lru,
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// Purge is used to completely clear the cache.
|
||||
func (c *Cache) Purge() {
|
||||
c.lock.Lock()
|
||||
c.lru.Purge()
|
||||
c.lock.Unlock()
|
||||
}
|
||||
|
||||
// Add adds a value to the cache. Returns true if an eviction occurred.
|
||||
func (c *Cache) Add(key, value interface{}) (evicted bool) {
|
||||
c.lock.Lock()
|
||||
evicted = c.lru.Add(key, value)
|
||||
c.lock.Unlock()
|
||||
return evicted
|
||||
}
|
||||
|
||||
// Get looks up a key's value from the cache.
|
||||
func (c *Cache) Get(key interface{}) (value interface{}, ok bool) {
|
||||
c.lock.Lock()
|
||||
value, ok = c.lru.Get(key)
|
||||
c.lock.Unlock()
|
||||
return value, ok
|
||||
}
|
||||
|
||||
// Contains checks if a key is in the cache, without updating the
|
||||
// recent-ness or deleting it for being stale.
|
||||
func (c *Cache) Contains(key interface{}) bool {
|
||||
c.lock.RLock()
|
||||
containKey := c.lru.Contains(key)
|
||||
c.lock.RUnlock()
|
||||
return containKey
|
||||
}
|
||||
|
||||
// Peek returns the key value (or undefined if not found) without updating
|
||||
// the "recently used"-ness of the key.
|
||||
func (c *Cache) Peek(key interface{}) (value interface{}, ok bool) {
|
||||
c.lock.RLock()
|
||||
value, ok = c.lru.Peek(key)
|
||||
c.lock.RUnlock()
|
||||
return value, ok
|
||||
}
|
||||
|
||||
// ContainsOrAdd checks if a key is in the cache without updating the
|
||||
// recent-ness or deleting it for being stale, and if not, adds the value.
|
||||
// Returns whether found and whether an eviction occurred.
|
||||
func (c *Cache) ContainsOrAdd(key, value interface{}) (ok, evicted bool) {
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
|
||||
if c.lru.Contains(key) {
|
||||
return true, false
|
||||
}
|
||||
evicted = c.lru.Add(key, value)
|
||||
return false, evicted
|
||||
}
|
||||
|
||||
// PeekOrAdd checks if a key is in the cache without updating the
|
||||
// recent-ness or deleting it for being stale, and if not, adds the value.
|
||||
// Returns whether found and whether an eviction occurred.
|
||||
func (c *Cache) PeekOrAdd(key, value interface{}) (previous interface{}, ok, evicted bool) {
|
||||
c.lock.Lock()
|
||||
defer c.lock.Unlock()
|
||||
|
||||
previous, ok = c.lru.Peek(key)
|
||||
if ok {
|
||||
return previous, true, false
|
||||
}
|
||||
|
||||
evicted = c.lru.Add(key, value)
|
||||
return nil, false, evicted
|
||||
}
|
||||
|
||||
// Remove removes the provided key from the cache.
|
||||
func (c *Cache) Remove(key interface{}) (present bool) {
|
||||
c.lock.Lock()
|
||||
present = c.lru.Remove(key)
|
||||
c.lock.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
// Resize changes the cache size.
|
||||
func (c *Cache) Resize(size int) (evicted int) {
|
||||
c.lock.Lock()
|
||||
evicted = c.lru.Resize(size)
|
||||
c.lock.Unlock()
|
||||
return evicted
|
||||
}
|
||||
|
||||
// RemoveOldest removes the oldest item from the cache.
|
||||
func (c *Cache) RemoveOldest() (key interface{}, value interface{}, ok bool) {
|
||||
c.lock.Lock()
|
||||
key, value, ok = c.lru.RemoveOldest()
|
||||
c.lock.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
// GetOldest returns the oldest entry
|
||||
func (c *Cache) GetOldest() (key interface{}, value interface{}, ok bool) {
|
||||
c.lock.Lock()
|
||||
key, value, ok = c.lru.GetOldest()
|
||||
c.lock.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
// Keys returns a slice of the keys in the cache, from oldest to newest.
|
||||
func (c *Cache) Keys() []interface{} {
|
||||
c.lock.RLock()
|
||||
keys := c.lru.Keys()
|
||||
c.lock.RUnlock()
|
||||
return keys
|
||||
}
|
||||
|
||||
// Len returns the number of items in the cache.
|
||||
func (c *Cache) Len() int {
|
||||
c.lock.RLock()
|
||||
length := c.lru.Len()
|
||||
c.lock.RUnlock()
|
||||
return length
|
||||
}
|
177
vendor/github.com/hashicorp/golang-lru/simplelru/lru.go
сгенерированный
поставляемый
Normal file
177
vendor/github.com/hashicorp/golang-lru/simplelru/lru.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,177 @@
|
|||
package simplelru
|
||||
|
||||
import (
|
||||
"container/list"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// EvictCallback is used to get a callback when a cache entry is evicted
|
||||
type EvictCallback func(key interface{}, value interface{})
|
||||
|
||||
// LRU implements a non-thread safe fixed size LRU cache
|
||||
type LRU struct {
|
||||
size int
|
||||
evictList *list.List
|
||||
items map[interface{}]*list.Element
|
||||
onEvict EvictCallback
|
||||
}
|
||||
|
||||
// entry is used to hold a value in the evictList
|
||||
type entry struct {
|
||||
key interface{}
|
||||
value interface{}
|
||||
}
|
||||
|
||||
// NewLRU constructs an LRU of the given size
|
||||
func NewLRU(size int, onEvict EvictCallback) (*LRU, error) {
|
||||
if size <= 0 {
|
||||
return nil, errors.New("Must provide a positive size")
|
||||
}
|
||||
c := &LRU{
|
||||
size: size,
|
||||
evictList: list.New(),
|
||||
items: make(map[interface{}]*list.Element),
|
||||
onEvict: onEvict,
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// Purge is used to completely clear the cache.
|
||||
func (c *LRU) Purge() {
|
||||
for k, v := range c.items {
|
||||
if c.onEvict != nil {
|
||||
c.onEvict(k, v.Value.(*entry).value)
|
||||
}
|
||||
delete(c.items, k)
|
||||
}
|
||||
c.evictList.Init()
|
||||
}
|
||||
|
||||
// Add adds a value to the cache. Returns true if an eviction occurred.
|
||||
func (c *LRU) Add(key, value interface{}) (evicted bool) {
|
||||
// Check for existing item
|
||||
if ent, ok := c.items[key]; ok {
|
||||
c.evictList.MoveToFront(ent)
|
||||
ent.Value.(*entry).value = value
|
||||
return false
|
||||
}
|
||||
|
||||
// Add new item
|
||||
ent := &entry{key, value}
|
||||
entry := c.evictList.PushFront(ent)
|
||||
c.items[key] = entry
|
||||
|
||||
evict := c.evictList.Len() > c.size
|
||||
// Verify size not exceeded
|
||||
if evict {
|
||||
c.removeOldest()
|
||||
}
|
||||
return evict
|
||||
}
|
||||
|
||||
// Get looks up a key's value from the cache.
|
||||
func (c *LRU) Get(key interface{}) (value interface{}, ok bool) {
|
||||
if ent, ok := c.items[key]; ok {
|
||||
c.evictList.MoveToFront(ent)
|
||||
if ent.Value.(*entry) == nil {
|
||||
return nil, false
|
||||
}
|
||||
return ent.Value.(*entry).value, true
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Contains checks if a key is in the cache, without updating the recent-ness
|
||||
// or deleting it for being stale.
|
||||
func (c *LRU) Contains(key interface{}) (ok bool) {
|
||||
_, ok = c.items[key]
|
||||
return ok
|
||||
}
|
||||
|
||||
// Peek returns the key value (or undefined if not found) without updating
|
||||
// the "recently used"-ness of the key.
|
||||
func (c *LRU) Peek(key interface{}) (value interface{}, ok bool) {
|
||||
var ent *list.Element
|
||||
if ent, ok = c.items[key]; ok {
|
||||
return ent.Value.(*entry).value, true
|
||||
}
|
||||
return nil, ok
|
||||
}
|
||||
|
||||
// Remove removes the provided key from the cache, returning if the
|
||||
// key was contained.
|
||||
func (c *LRU) Remove(key interface{}) (present bool) {
|
||||
if ent, ok := c.items[key]; ok {
|
||||
c.removeElement(ent)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// RemoveOldest removes the oldest item from the cache.
|
||||
func (c *LRU) RemoveOldest() (key interface{}, value interface{}, ok bool) {
|
||||
ent := c.evictList.Back()
|
||||
if ent != nil {
|
||||
c.removeElement(ent)
|
||||
kv := ent.Value.(*entry)
|
||||
return kv.key, kv.value, true
|
||||
}
|
||||
return nil, nil, false
|
||||
}
|
||||
|
||||
// GetOldest returns the oldest entry
|
||||
func (c *LRU) GetOldest() (key interface{}, value interface{}, ok bool) {
|
||||
ent := c.evictList.Back()
|
||||
if ent != nil {
|
||||
kv := ent.Value.(*entry)
|
||||
return kv.key, kv.value, true
|
||||
}
|
||||
return nil, nil, false
|
||||
}
|
||||
|
||||
// Keys returns a slice of the keys in the cache, from oldest to newest.
|
||||
func (c *LRU) Keys() []interface{} {
|
||||
keys := make([]interface{}, len(c.items))
|
||||
i := 0
|
||||
for ent := c.evictList.Back(); ent != nil; ent = ent.Prev() {
|
||||
keys[i] = ent.Value.(*entry).key
|
||||
i++
|
||||
}
|
||||
return keys
|
||||
}
|
||||
|
||||
// Len returns the number of items in the cache.
|
||||
func (c *LRU) Len() int {
|
||||
return c.evictList.Len()
|
||||
}
|
||||
|
||||
// Resize changes the cache size.
|
||||
func (c *LRU) Resize(size int) (evicted int) {
|
||||
diff := c.Len() - size
|
||||
if diff < 0 {
|
||||
diff = 0
|
||||
}
|
||||
for i := 0; i < diff; i++ {
|
||||
c.removeOldest()
|
||||
}
|
||||
c.size = size
|
||||
return diff
|
||||
}
|
||||
|
||||
// removeOldest removes the oldest item from the cache.
|
||||
func (c *LRU) removeOldest() {
|
||||
ent := c.evictList.Back()
|
||||
if ent != nil {
|
||||
c.removeElement(ent)
|
||||
}
|
||||
}
|
||||
|
||||
// removeElement is used to remove a given list element from the cache
|
||||
func (c *LRU) removeElement(e *list.Element) {
|
||||
c.evictList.Remove(e)
|
||||
kv := e.Value.(*entry)
|
||||
delete(c.items, kv.key)
|
||||
if c.onEvict != nil {
|
||||
c.onEvict(kv.key, kv.value)
|
||||
}
|
||||
}
|
39
vendor/github.com/hashicorp/golang-lru/simplelru/lru_interface.go
сгенерированный
поставляемый
Normal file
39
vendor/github.com/hashicorp/golang-lru/simplelru/lru_interface.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,39 @@
|
|||
package simplelru
|
||||
|
||||
// LRUCache is the interface for simple LRU cache.
|
||||
type LRUCache interface {
|
||||
// Adds a value to the cache, returns true if an eviction occurred and
|
||||
// updates the "recently used"-ness of the key.
|
||||
Add(key, value interface{}) bool
|
||||
|
||||
// Returns key's value from the cache and
|
||||
// updates the "recently used"-ness of the key. #value, isFound
|
||||
Get(key interface{}) (value interface{}, ok bool)
|
||||
|
||||
// Checks if a key exists in cache without updating the recent-ness.
|
||||
Contains(key interface{}) (ok bool)
|
||||
|
||||
// Returns key's value without updating the "recently used"-ness of the key.
|
||||
Peek(key interface{}) (value interface{}, ok bool)
|
||||
|
||||
// Removes a key from the cache.
|
||||
Remove(key interface{}) bool
|
||||
|
||||
// Removes the oldest entry from cache.
|
||||
RemoveOldest() (interface{}, interface{}, bool)
|
||||
|
||||
// Returns the oldest entry from the cache. #key, value, isFound
|
||||
GetOldest() (interface{}, interface{}, bool)
|
||||
|
||||
// Returns a slice of the keys in the cache, from oldest to newest.
|
||||
Keys() []interface{}
|
||||
|
||||
// Returns the number of items in the cache.
|
||||
Len() int
|
||||
|
||||
// Clears all cache entries.
|
||||
Purge()
|
||||
|
||||
// Resizes cache, returning number evicted
|
||||
Resize(int) int
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
Copyright 2014 Alan Shreve
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
|
@ -0,0 +1,23 @@
|
|||
# mousetrap
|
||||
|
||||
mousetrap is a tiny library that answers a single question.
|
||||
|
||||
On a Windows machine, was the process invoked by someone double clicking on
|
||||
the executable file while browsing in explorer?
|
||||
|
||||
### Motivation
|
||||
|
||||
Windows developers unfamiliar with command line tools will often "double-click"
|
||||
the executable for a tool. Because most CLI tools print the help and then exit
|
||||
when invoked without arguments, this is often very frustrating for those users.
|
||||
|
||||
mousetrap provides a way to detect these invocations so that you can provide
|
||||
more helpful behavior and instructions on how to run the CLI tool. To see what
|
||||
this looks like, both from an organizational and a technical perspective, see
|
||||
https://inconshreveable.com/09-09-2014/sweat-the-small-stuff/
|
||||
|
||||
### The interface
|
||||
|
||||
The library exposes a single interface:
|
||||
|
||||
func StartedByExplorer() (bool)
|
15
vendor/github.com/inconshreveable/mousetrap/trap_others.go
сгенерированный
поставляемый
Normal file
15
vendor/github.com/inconshreveable/mousetrap/trap_others.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,15 @@
|
|||
// +build !windows
|
||||
|
||||
package mousetrap
|
||||
|
||||
// StartedByExplorer returns true if the program was invoked by the user
|
||||
// double-clicking on the executable from explorer.exe
|
||||
//
|
||||
// It is conservative and returns false if any of the internal calls fail.
|
||||
// It does not guarantee that the program was run from a terminal. It only can tell you
|
||||
// whether it was launched from explorer.exe
|
||||
//
|
||||
// On non-Windows platforms, it always returns false.
|
||||
func StartedByExplorer() bool {
|
||||
return false
|
||||
}
|
98
vendor/github.com/inconshreveable/mousetrap/trap_windows.go
сгенерированный
поставляемый
Normal file
98
vendor/github.com/inconshreveable/mousetrap/trap_windows.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,98 @@
|
|||
// +build windows
|
||||
// +build !go1.4
|
||||
|
||||
package mousetrap
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
// defined by the Win32 API
|
||||
th32cs_snapprocess uintptr = 0x2
|
||||
)
|
||||
|
||||
var (
|
||||
kernel = syscall.MustLoadDLL("kernel32.dll")
|
||||
CreateToolhelp32Snapshot = kernel.MustFindProc("CreateToolhelp32Snapshot")
|
||||
Process32First = kernel.MustFindProc("Process32FirstW")
|
||||
Process32Next = kernel.MustFindProc("Process32NextW")
|
||||
)
|
||||
|
||||
// ProcessEntry32 structure defined by the Win32 API
|
||||
type processEntry32 struct {
|
||||
dwSize uint32
|
||||
cntUsage uint32
|
||||
th32ProcessID uint32
|
||||
th32DefaultHeapID int
|
||||
th32ModuleID uint32
|
||||
cntThreads uint32
|
||||
th32ParentProcessID uint32
|
||||
pcPriClassBase int32
|
||||
dwFlags uint32
|
||||
szExeFile [syscall.MAX_PATH]uint16
|
||||
}
|
||||
|
||||
func getProcessEntry(pid int) (pe *processEntry32, err error) {
|
||||
snapshot, _, e1 := CreateToolhelp32Snapshot.Call(th32cs_snapprocess, uintptr(0))
|
||||
if snapshot == uintptr(syscall.InvalidHandle) {
|
||||
err = fmt.Errorf("CreateToolhelp32Snapshot: %v", e1)
|
||||
return
|
||||
}
|
||||
defer syscall.CloseHandle(syscall.Handle(snapshot))
|
||||
|
||||
var processEntry processEntry32
|
||||
processEntry.dwSize = uint32(unsafe.Sizeof(processEntry))
|
||||
ok, _, e1 := Process32First.Call(snapshot, uintptr(unsafe.Pointer(&processEntry)))
|
||||
if ok == 0 {
|
||||
err = fmt.Errorf("Process32First: %v", e1)
|
||||
return
|
||||
}
|
||||
|
||||
for {
|
||||
if processEntry.th32ProcessID == uint32(pid) {
|
||||
pe = &processEntry
|
||||
return
|
||||
}
|
||||
|
||||
ok, _, e1 = Process32Next.Call(snapshot, uintptr(unsafe.Pointer(&processEntry)))
|
||||
if ok == 0 {
|
||||
err = fmt.Errorf("Process32Next: %v", e1)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func getppid() (pid int, err error) {
|
||||
pe, err := getProcessEntry(os.Getpid())
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
pid = int(pe.th32ParentProcessID)
|
||||
return
|
||||
}
|
||||
|
||||
// StartedByExplorer returns true if the program was invoked by the user double-clicking
|
||||
// on the executable from explorer.exe
|
||||
//
|
||||
// It is conservative and returns false if any of the internal calls fail.
|
||||
// It does not guarantee that the program was run from a terminal. It only can tell you
|
||||
// whether it was launched from explorer.exe
|
||||
func StartedByExplorer() bool {
|
||||
ppid, err := getppid()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
pe, err := getProcessEntry(ppid)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
name := syscall.UTF16ToString(pe.szExeFile[:])
|
||||
return name == "explorer.exe"
|
||||
}
|
46
vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go
сгенерированный
поставляемый
Normal file
46
vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,46 @@
|
|||
// +build windows
|
||||
// +build go1.4
|
||||
|
||||
package mousetrap
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func getProcessEntry(pid int) (*syscall.ProcessEntry32, error) {
|
||||
snapshot, err := syscall.CreateToolhelp32Snapshot(syscall.TH32CS_SNAPPROCESS, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer syscall.CloseHandle(snapshot)
|
||||
var procEntry syscall.ProcessEntry32
|
||||
procEntry.Size = uint32(unsafe.Sizeof(procEntry))
|
||||
if err = syscall.Process32First(snapshot, &procEntry); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for {
|
||||
if procEntry.ProcessID == uint32(pid) {
|
||||
return &procEntry, nil
|
||||
}
|
||||
err = syscall.Process32Next(snapshot, &procEntry)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// StartedByExplorer returns true if the program was invoked by the user double-clicking
|
||||
// on the executable from explorer.exe
|
||||
//
|
||||
// It is conservative and returns false if any of the internal calls fail.
|
||||
// It does not guarantee that the program was run from a terminal. It only can tell you
|
||||
// whether it was launched from explorer.exe
|
||||
func StartedByExplorer() bool {
|
||||
pe, err := getProcessEntry(os.Getppid())
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return "explorer.exe" == syscall.UTF16ToString(pe.ExeFile[:])
|
||||
}
|
|
@ -1,3 +1 @@
|
|||
module github.com/konsorten/go-windows-terminal-sequences
|
||||
|
||||
go 1.14
|
||||
|
|
|
@ -1,5 +1,3 @@
|
|||
module github.com/mattn/go-colorable
|
||||
|
||||
go 1.14
|
||||
|
||||
require github.com/mattn/go-isatty v0.0.8
|
||||
|
|
|
@ -1,5 +1,4 @@
|
|||
github.com/mattn/go-isatty v0.0.5 h1:tHXDdz1cpzGaovsTB+TVB8q90WEokoVmfMqoVcrLUgw=
|
||||
github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
|
||||
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
|
||||
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223 h1:DH4skfRX4EBpamg7iV4ZlCpblAHI6s6TDM39bFZumv8=
|
||||
golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
|
|
|
@ -1,3 +1 @@
|
|||
module github.com/mitchellh/go-homedir
|
||||
|
||||
go 1.14
|
||||
|
|
|
@ -1,7 +1,5 @@
|
|||
module github.com/onsi/gomega
|
||||
|
||||
go 1.14
|
||||
|
||||
require (
|
||||
github.com/fsnotify/fsnotify v1.4.7 // indirect
|
||||
github.com/golang/protobuf v1.2.0
|
||||
|
@ -15,3 +13,4 @@ require (
|
|||
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect
|
||||
gopkg.in/yaml.v2 v2.2.4
|
||||
)
|
||||
|
||||
|
|
201
vendor/github.com/operator-framework/operator-sdk/LICENSE
сгенерированный
поставляемый
Normal file
201
vendor/github.com/operator-framework/operator-sdk/LICENSE
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,201 @@
|
|||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
189
vendor/github.com/operator-framework/operator-sdk/pkg/status/conditions.go
сгенерированный
поставляемый
Normal file
189
vendor/github.com/operator-framework/operator-sdk/pkg/status/conditions.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,189 @@
|
|||
// Copyright 2020 The Operator-SDK Authors
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package status
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"sort"
|
||||
|
||||
corev1 "k8s.io/api/core/v1"
|
||||
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
kubeclock "k8s.io/apimachinery/pkg/util/clock"
|
||||
)
|
||||
|
||||
// clock is used to set status condition timestamps.
|
||||
// This variable makes it easier to test conditions.
|
||||
var clock kubeclock.Clock = &kubeclock.RealClock{}
|
||||
|
||||
// ConditionType is the type of the condition and is typically a CamelCased
|
||||
// word or short phrase.
|
||||
//
|
||||
// Condition types should indicate state in the "abnormal-true" polarity. For
|
||||
// example, if the condition indicates when a policy is invalid, the "is valid"
|
||||
// case is probably the norm, so the condition should be called "Invalid".
|
||||
type ConditionType string
|
||||
|
||||
// ConditionReason is intended to be a one-word, CamelCase representation of
|
||||
// the category of cause of the current status. It is intended to be used in
|
||||
// concise output, such as one-line kubectl get output, and in summarizing
|
||||
// occurrences of causes.
|
||||
type ConditionReason string
|
||||
|
||||
// Condition represents an observation of an object's state. Conditions are an
|
||||
// extension mechanism intended to be used when the details of an observation
|
||||
// are not a priori known or would not apply to all instances of a given Kind.
|
||||
//
|
||||
// Conditions should be added to explicitly convey properties that users and
|
||||
// components care about rather than requiring those properties to be inferred
|
||||
// from other observations. Once defined, the meaning of a Condition can not be
|
||||
// changed arbitrarily - it becomes part of the API, and has the same
|
||||
// backwards- and forwards-compatibility concerns of any other part of the API.
|
||||
type Condition struct {
|
||||
Type ConditionType `json:"type"`
|
||||
Status corev1.ConditionStatus `json:"status"`
|
||||
Reason ConditionReason `json:"reason,omitempty"`
|
||||
Message string `json:"message,omitempty"`
|
||||
LastTransitionTime metav1.Time `json:"lastTransitionTime,omitempty"`
|
||||
}
|
||||
|
||||
// IsTrue Condition whether the condition status is "True".
|
||||
func (c Condition) IsTrue() bool {
|
||||
return c.Status == corev1.ConditionTrue
|
||||
}
|
||||
|
||||
// IsFalse returns whether the condition status is "False".
|
||||
func (c Condition) IsFalse() bool {
|
||||
return c.Status == corev1.ConditionFalse
|
||||
}
|
||||
|
||||
// IsUnknown returns whether the condition status is "Unknown".
|
||||
func (c Condition) IsUnknown() bool {
|
||||
return c.Status == corev1.ConditionUnknown
|
||||
}
|
||||
|
||||
// DeepCopyInto copies in into out.
|
||||
func (c *Condition) DeepCopyInto(cpy *Condition) {
|
||||
*cpy = *c
|
||||
}
|
||||
|
||||
// Conditions is a set of Condition instances.
|
||||
type Conditions []Condition
|
||||
|
||||
// NewConditions initializes a set of conditions with the given list of
|
||||
// conditions.
|
||||
func NewConditions(conds ...Condition) Conditions {
|
||||
conditions := Conditions{}
|
||||
for _, c := range conds {
|
||||
conditions.SetCondition(c)
|
||||
}
|
||||
return conditions
|
||||
}
|
||||
|
||||
// IsTrueFor searches the set of conditions for a condition with the given
|
||||
// ConditionType. If found, it returns `condition.IsTrue()`. If not found,
|
||||
// it returns false.
|
||||
func (conditions Conditions) IsTrueFor(t ConditionType) bool {
|
||||
for _, condition := range conditions {
|
||||
if condition.Type == t {
|
||||
return condition.IsTrue()
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsFalseFor searches the set of conditions for a condition with the given
|
||||
// ConditionType. If found, it returns `condition.IsFalse()`. If not found,
|
||||
// it returns false.
|
||||
func (conditions Conditions) IsFalseFor(t ConditionType) bool {
|
||||
for _, condition := range conditions {
|
||||
if condition.Type == t {
|
||||
return condition.IsFalse()
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsUnknownFor searches the set of conditions for a condition with the given
|
||||
// ConditionType. If found, it returns `condition.IsUnknown()`. If not found,
|
||||
// it returns true.
|
||||
func (conditions Conditions) IsUnknownFor(t ConditionType) bool {
|
||||
for _, condition := range conditions {
|
||||
if condition.Type == t {
|
||||
return condition.IsUnknown()
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// SetCondition adds (or updates) the set of conditions with the given
|
||||
// condition. It returns a boolean value indicating whether the set condition
|
||||
// is new or was a change to the existing condition with the same type.
|
||||
func (conditions *Conditions) SetCondition(newCond Condition) bool {
|
||||
newCond.LastTransitionTime = metav1.Time{Time: clock.Now()}
|
||||
|
||||
for i, condition := range *conditions {
|
||||
if condition.Type == newCond.Type {
|
||||
if condition.Status == newCond.Status {
|
||||
newCond.LastTransitionTime = condition.LastTransitionTime
|
||||
}
|
||||
changed := condition.Status != newCond.Status ||
|
||||
condition.Reason != newCond.Reason ||
|
||||
condition.Message != newCond.Message
|
||||
(*conditions)[i] = newCond
|
||||
return changed
|
||||
}
|
||||
}
|
||||
*conditions = append(*conditions, newCond)
|
||||
return true
|
||||
}
|
||||
|
||||
// GetCondition searches the set of conditions for the condition with the given
|
||||
// ConditionType and returns it. If the matching condition is not found,
|
||||
// GetCondition returns nil.
|
||||
func (conditions Conditions) GetCondition(t ConditionType) *Condition {
|
||||
for _, condition := range conditions {
|
||||
if condition.Type == t {
|
||||
return &condition
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RemoveCondition removes the condition with the given ConditionType from
|
||||
// the conditions set. If no condition with that type is found, RemoveCondition
|
||||
// returns without performing any action. If the passed condition type is not
|
||||
// found in the set of conditions, RemoveCondition returns false.
|
||||
func (conditions *Conditions) RemoveCondition(t ConditionType) bool {
|
||||
if conditions == nil {
|
||||
return false
|
||||
}
|
||||
for i, condition := range *conditions {
|
||||
if condition.Type == t {
|
||||
*conditions = append((*conditions)[:i], (*conditions)[i+1:]...)
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// MarshalJSON marshals the set of conditions as a JSON array, sorted by
|
||||
// condition type.
|
||||
func (conditions Conditions) MarshalJSON() ([]byte, error) {
|
||||
conds := []Condition(conditions)
|
||||
sort.Slice(conds, func(a, b int) bool {
|
||||
return conds[a].Type < conds[b].Type
|
||||
})
|
||||
return json.Marshal(conds)
|
||||
}
|
|
@ -1,7 +1,5 @@
|
|||
module github.com/sirupsen/logrus
|
||||
|
||||
go 1.14
|
||||
|
||||
require (
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1
|
||||
|
|
|
@ -0,0 +1,39 @@
|
|||
# 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
|
||||
|
||||
# Vim files https://github.com/github/gitignore/blob/master/Global/Vim.gitignore
|
||||
# swap
|
||||
[._]*.s[a-w][a-z]
|
||||
[._]s[a-w][a-z]
|
||||
# session
|
||||
Session.vim
|
||||
# temporary
|
||||
.netrwhist
|
||||
*~
|
||||
# auto-generated tag files
|
||||
tags
|
||||
|
||||
*.exe
|
||||
cobra.test
|
||||
bin
|
||||
|
||||
.idea/
|
||||
*.iml
|
|
@ -0,0 +1,3 @@
|
|||
Steve Francia <steve.francia@gmail.com>
|
||||
Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
|
||||
Fabiano Franz <ffranz@redhat.com> <contact@fabianofranz.com>
|
|
@ -0,0 +1,29 @@
|
|||
language: go
|
||||
|
||||
stages:
|
||||
- diff
|
||||
- test
|
||||
- build
|
||||
|
||||
go:
|
||||
- 1.12.x
|
||||
- 1.13.x
|
||||
- tip
|
||||
|
||||
before_install:
|
||||
- go get -u github.com/kyoh86/richgo
|
||||
- go get -u github.com/mitchellh/gox
|
||||
|
||||
matrix:
|
||||
allow_failures:
|
||||
- go: tip
|
||||
include:
|
||||
- stage: diff
|
||||
go: 1.13.x
|
||||
script: make fmt
|
||||
- stage: build
|
||||
go: 1.13.x
|
||||
script: make cobra_generator
|
||||
|
||||
script:
|
||||
- make test
|
|
@ -0,0 +1,174 @@
|
|||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
|
@ -0,0 +1,36 @@
|
|||
BIN="./bin"
|
||||
SRC=$(shell find . -name "*.go")
|
||||
|
||||
ifeq (, $(shell which richgo))
|
||||
$(warning "could not find richgo in $(PATH), run: go get github.com/kyoh86/richgo")
|
||||
endif
|
||||
|
||||
.PHONY: fmt vet test cobra_generator install_deps clean
|
||||
|
||||
default: all
|
||||
|
||||
all: fmt vet test cobra_generator
|
||||
|
||||
fmt:
|
||||
$(info ******************** checking formatting ********************)
|
||||
@test -z $(shell gofmt -l $(SRC)) || (gofmt -d $(SRC); exit 1)
|
||||
|
||||
test: install_deps vet
|
||||
$(info ******************** running tests ********************)
|
||||
richgo test -v ./...
|
||||
|
||||
cobra_generator: install_deps
|
||||
$(info ******************** building generator ********************)
|
||||
mkdir -p $(BIN)
|
||||
make -C cobra all
|
||||
|
||||
install_deps:
|
||||
$(info ******************** downloading dependencies ********************)
|
||||
go get -v ./...
|
||||
|
||||
vet:
|
||||
$(info ******************** vetting ********************)
|
||||
go vet ./...
|
||||
|
||||
clean:
|
||||
rm -rf $(BIN)
|
|
@ -0,0 +1,770 @@
|
|||
![cobra logo](https://cloud.githubusercontent.com/assets/173412/10886352/ad566232-814f-11e5-9cd0-aa101788c117.png)
|
||||
|
||||
Cobra is both a library for creating powerful modern CLI applications as well as a program to generate applications and command files.
|
||||
|
||||
Many of the most widely used Go projects are built using Cobra, such as:
|
||||
[Kubernetes](http://kubernetes.io/),
|
||||
[Hugo](http://gohugo.io),
|
||||
[rkt](https://github.com/coreos/rkt),
|
||||
[etcd](https://github.com/coreos/etcd),
|
||||
[Moby (former Docker)](https://github.com/moby/moby),
|
||||
[Docker (distribution)](https://github.com/docker/distribution),
|
||||
[OpenShift](https://www.openshift.com/),
|
||||
[Delve](https://github.com/derekparker/delve),
|
||||
[GopherJS](http://www.gopherjs.org/),
|
||||
[CockroachDB](http://www.cockroachlabs.com/),
|
||||
[Bleve](http://www.blevesearch.com/),
|
||||
[ProjectAtomic (enterprise)](http://www.projectatomic.io/),
|
||||
[Giant Swarm's gsctl](https://github.com/giantswarm/gsctl),
|
||||
[Nanobox](https://github.com/nanobox-io/nanobox)/[Nanopack](https://github.com/nanopack),
|
||||
[rclone](http://rclone.org/),
|
||||
[nehm](https://github.com/bogem/nehm),
|
||||
[Pouch](https://github.com/alibaba/pouch),
|
||||
[Istio](https://istio.io),
|
||||
[Prototool](https://github.com/uber/prototool),
|
||||
[mattermost-server](https://github.com/mattermost/mattermost-server),
|
||||
[Gardener](https://github.com/gardener/gardenctl),
|
||||
[Linkerd](https://linkerd.io/),
|
||||
[Github CLI](https://github.com/cli/cli)
|
||||
etc.
|
||||
|
||||
[![Build Status](https://travis-ci.org/spf13/cobra.svg "Travis CI status")](https://travis-ci.org/spf13/cobra)
|
||||
[![GoDoc](https://godoc.org/github.com/spf13/cobra?status.svg)](https://godoc.org/github.com/spf13/cobra)
|
||||
[![Go Report Card](https://goreportcard.com/badge/github.com/spf13/cobra)](https://goreportcard.com/report/github.com/spf13/cobra)
|
||||
|
||||
# Table of Contents
|
||||
|
||||
- [Overview](#overview)
|
||||
- [Concepts](#concepts)
|
||||
* [Commands](#commands)
|
||||
* [Flags](#flags)
|
||||
- [Installing](#installing)
|
||||
- [Getting Started](#getting-started)
|
||||
* [Using the Cobra Generator](#using-the-cobra-generator)
|
||||
* [Using the Cobra Library](#using-the-cobra-library)
|
||||
* [Working with Flags](#working-with-flags)
|
||||
* [Positional and Custom Arguments](#positional-and-custom-arguments)
|
||||
* [Example](#example)
|
||||
* [Help Command](#help-command)
|
||||
* [Usage Message](#usage-message)
|
||||
* [PreRun and PostRun Hooks](#prerun-and-postrun-hooks)
|
||||
* [Suggestions when "unknown command" happens](#suggestions-when-unknown-command-happens)
|
||||
* [Generating documentation for your command](#generating-documentation-for-your-command)
|
||||
* [Generating bash completions](#generating-bash-completions)
|
||||
* [Generating zsh completions](#generating-zsh-completions)
|
||||
- [Contributing](#contributing)
|
||||
- [License](#license)
|
||||
|
||||
# Overview
|
||||
|
||||
Cobra is a library providing a simple interface to create powerful modern CLI
|
||||
interfaces similar to git & go tools.
|
||||
|
||||
Cobra is also an application that will generate your application scaffolding to rapidly
|
||||
develop a Cobra-based application.
|
||||
|
||||
Cobra provides:
|
||||
* Easy subcommand-based CLIs: `app server`, `app fetch`, etc.
|
||||
* Fully POSIX-compliant flags (including short & long versions)
|
||||
* Nested subcommands
|
||||
* Global, local and cascading flags
|
||||
* Easy generation of applications & commands with `cobra init appname` & `cobra add cmdname`
|
||||
* Intelligent suggestions (`app srver`... did you mean `app server`?)
|
||||
* Automatic help generation for commands and flags
|
||||
* Automatic help flag recognition of `-h`, `--help`, etc.
|
||||
* Automatically generated bash autocomplete for your application
|
||||
* Automatically generated man pages for your application
|
||||
* Command aliases so you can change things without breaking them
|
||||
* The flexibility to define your own help, usage, etc.
|
||||
* Optional tight integration with [viper](http://github.com/spf13/viper) for 12-factor apps
|
||||
|
||||
# Concepts
|
||||
|
||||
Cobra is built on a structure of commands, arguments & flags.
|
||||
|
||||
**Commands** represent actions, **Args** are things and **Flags** are modifiers for those actions.
|
||||
|
||||
The best applications will read like sentences when used. Users will know how
|
||||
to use the application because they will natively understand how to use it.
|
||||
|
||||
The pattern to follow is
|
||||
`APPNAME VERB NOUN --ADJECTIVE.`
|
||||
or
|
||||
`APPNAME COMMAND ARG --FLAG`
|
||||
|
||||
A few good real world examples may better illustrate this point.
|
||||
|
||||
In the following example, 'server' is a command, and 'port' is a flag:
|
||||
|
||||
hugo server --port=1313
|
||||
|
||||
In this command we are telling Git to clone the url bare.
|
||||
|
||||
git clone URL --bare
|
||||
|
||||
## Commands
|
||||
|
||||
Command is the central point of the application. Each interaction that
|
||||
the application supports will be contained in a Command. A command can
|
||||
have children commands and optionally run an action.
|
||||
|
||||
In the example above, 'server' is the command.
|
||||
|
||||
[More about cobra.Command](https://godoc.org/github.com/spf13/cobra#Command)
|
||||
|
||||
## Flags
|
||||
|
||||
A flag is a way to modify the behavior of a command. Cobra supports
|
||||
fully POSIX-compliant flags as well as the Go [flag package](https://golang.org/pkg/flag/).
|
||||
A Cobra command can define flags that persist through to children commands
|
||||
and flags that are only available to that command.
|
||||
|
||||
In the example above, 'port' is the flag.
|
||||
|
||||
Flag functionality is provided by the [pflag
|
||||
library](https://github.com/spf13/pflag), a fork of the flag standard library
|
||||
which maintains the same interface while adding POSIX compliance.
|
||||
|
||||
# Installing
|
||||
Using Cobra is easy. First, use `go get` to install the latest version
|
||||
of the library. This command will install the `cobra` generator executable
|
||||
along with the library and its dependencies:
|
||||
|
||||
go get -u github.com/spf13/cobra/cobra
|
||||
|
||||
Next, include Cobra in your application:
|
||||
|
||||
```go
|
||||
import "github.com/spf13/cobra"
|
||||
```
|
||||
|
||||
# Getting Started
|
||||
|
||||
While you are welcome to provide your own organization, typically a Cobra-based
|
||||
application will follow the following organizational structure:
|
||||
|
||||
```
|
||||
▾ appName/
|
||||
▾ cmd/
|
||||
add.go
|
||||
your.go
|
||||
commands.go
|
||||
here.go
|
||||
main.go
|
||||
```
|
||||
|
||||
In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra.
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"{pathToYourApp}/cmd"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cmd.Execute()
|
||||
}
|
||||
```
|
||||
|
||||
## Using the Cobra Generator
|
||||
|
||||
Cobra provides its own program that will create your application and add any
|
||||
commands you want. It's the easiest way to incorporate Cobra into your application.
|
||||
|
||||
[Here](https://github.com/spf13/cobra/blob/master/cobra/README.md) you can find more information about it.
|
||||
|
||||
## Using the Cobra Library
|
||||
|
||||
To manually implement Cobra you need to create a bare main.go file and a rootCmd file.
|
||||
You will optionally provide additional commands as you see fit.
|
||||
|
||||
### Create rootCmd
|
||||
|
||||
Cobra doesn't require any special constructors. Simply create your commands.
|
||||
|
||||
Ideally you place this in app/cmd/root.go:
|
||||
|
||||
```go
|
||||
var rootCmd = &cobra.Command{
|
||||
Use: "hugo",
|
||||
Short: "Hugo is a very fast static site generator",
|
||||
Long: `A Fast and Flexible Static Site Generator built with
|
||||
love by spf13 and friends in Go.
|
||||
Complete documentation is available at http://hugo.spf13.com`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
// Do Stuff Here
|
||||
},
|
||||
}
|
||||
|
||||
func Execute() {
|
||||
if err := rootCmd.Execute(); err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
You will additionally define flags and handle configuration in your init() function.
|
||||
|
||||
For example cmd/root.go:
|
||||
|
||||
```go
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
homedir "github.com/mitchellh/go-homedir"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var (
|
||||
// Used for flags.
|
||||
cfgFile string
|
||||
userLicense string
|
||||
|
||||
rootCmd = &cobra.Command{
|
||||
Use: "cobra",
|
||||
Short: "A generator for Cobra based Applications",
|
||||
Long: `Cobra is a CLI library for Go that empowers applications.
|
||||
This application is a tool to generate the needed files
|
||||
to quickly create a Cobra application.`,
|
||||
}
|
||||
)
|
||||
|
||||
// Execute executes the root command.
|
||||
func Execute() error {
|
||||
return rootCmd.Execute()
|
||||
}
|
||||
|
||||
func init() {
|
||||
cobra.OnInitialize(initConfig)
|
||||
|
||||
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
|
||||
rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution")
|
||||
rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project")
|
||||
rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration")
|
||||
viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
|
||||
viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper"))
|
||||
viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")
|
||||
viper.SetDefault("license", "apache")
|
||||
|
||||
rootCmd.AddCommand(addCmd)
|
||||
rootCmd.AddCommand(initCmd)
|
||||
}
|
||||
|
||||
func er(msg interface{}) {
|
||||
fmt.Println("Error:", msg)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
func initConfig() {
|
||||
if cfgFile != "" {
|
||||
// Use config file from the flag.
|
||||
viper.SetConfigFile(cfgFile)
|
||||
} else {
|
||||
// Find home directory.
|
||||
home, err := homedir.Dir()
|
||||
if err != nil {
|
||||
er(err)
|
||||
}
|
||||
|
||||
// Search config in home directory with name ".cobra" (without extension).
|
||||
viper.AddConfigPath(home)
|
||||
viper.SetConfigName(".cobra")
|
||||
}
|
||||
|
||||
viper.AutomaticEnv()
|
||||
|
||||
if err := viper.ReadInConfig(); err == nil {
|
||||
fmt.Println("Using config file:", viper.ConfigFileUsed())
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Create your main.go
|
||||
|
||||
With the root command you need to have your main function execute it.
|
||||
Execute should be run on the root for clarity, though it can be called on any command.
|
||||
|
||||
In a Cobra app, typically the main.go file is very bare. It serves, one purpose, to initialize Cobra.
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"{pathToYourApp}/cmd"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cmd.Execute()
|
||||
}
|
||||
```
|
||||
|
||||
### Create additional commands
|
||||
|
||||
Additional commands can be defined and typically are each given their own file
|
||||
inside of the cmd/ directory.
|
||||
|
||||
If you wanted to create a version command you would create cmd/version.go and
|
||||
populate it with the following:
|
||||
|
||||
```go
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(versionCmd)
|
||||
}
|
||||
|
||||
var versionCmd = &cobra.Command{
|
||||
Use: "version",
|
||||
Short: "Print the version number of Hugo",
|
||||
Long: `All software has versions. This is Hugo's`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Println("Hugo Static Site Generator v0.9 -- HEAD")
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
## Working with Flags
|
||||
|
||||
Flags provide modifiers to control how the action command operates.
|
||||
|
||||
### Assign flags to a command
|
||||
|
||||
Since the flags are defined and used in different locations, we need to
|
||||
define a variable outside with the correct scope to assign the flag to
|
||||
work with.
|
||||
|
||||
```go
|
||||
var Verbose bool
|
||||
var Source string
|
||||
```
|
||||
|
||||
There are two different approaches to assign a flag.
|
||||
|
||||
### Persistent Flags
|
||||
|
||||
A flag can be 'persistent' meaning that this flag will be available to the
|
||||
command it's assigned to as well as every command under that command. For
|
||||
global flags, assign a flag as a persistent flag on the root.
|
||||
|
||||
```go
|
||||
rootCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")
|
||||
```
|
||||
|
||||
### Local Flags
|
||||
|
||||
A flag can also be assigned locally which will only apply to that specific command.
|
||||
|
||||
```go
|
||||
localCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")
|
||||
```
|
||||
|
||||
### Local Flag on Parent Commands
|
||||
|
||||
By default Cobra only parses local flags on the target command, any local flags on
|
||||
parent commands are ignored. By enabling `Command.TraverseChildren` Cobra will
|
||||
parse local flags on each command before executing the target command.
|
||||
|
||||
```go
|
||||
command := cobra.Command{
|
||||
Use: "print [OPTIONS] [COMMANDS]",
|
||||
TraverseChildren: true,
|
||||
}
|
||||
```
|
||||
|
||||
### Bind Flags with Config
|
||||
|
||||
You can also bind your flags with [viper](https://github.com/spf13/viper):
|
||||
```go
|
||||
var author string
|
||||
|
||||
func init() {
|
||||
rootCmd.PersistentFlags().StringVar(&author, "author", "YOUR NAME", "Author name for copyright attribution")
|
||||
viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
|
||||
}
|
||||
```
|
||||
|
||||
In this example the persistent flag `author` is bound with `viper`.
|
||||
**Note**, that the variable `author` will not be set to the value from config,
|
||||
when the `--author` flag is not provided by user.
|
||||
|
||||
More in [viper documentation](https://github.com/spf13/viper#working-with-flags).
|
||||
|
||||
### Required flags
|
||||
|
||||
Flags are optional by default. If instead you wish your command to report an error
|
||||
when a flag has not been set, mark it as required:
|
||||
```go
|
||||
rootCmd.Flags().StringVarP(&Region, "region", "r", "", "AWS region (required)")
|
||||
rootCmd.MarkFlagRequired("region")
|
||||
```
|
||||
|
||||
## Positional and Custom Arguments
|
||||
|
||||
Validation of positional arguments can be specified using the `Args` field
|
||||
of `Command`.
|
||||
|
||||
The following validators are built in:
|
||||
|
||||
- `NoArgs` - the command will report an error if there are any positional args.
|
||||
- `ArbitraryArgs` - the command will accept any args.
|
||||
- `OnlyValidArgs` - the command will report an error if there are any positional args that are not in the `ValidArgs` field of `Command`.
|
||||
- `MinimumNArgs(int)` - the command will report an error if there are not at least N positional args.
|
||||
- `MaximumNArgs(int)` - the command will report an error if there are more than N positional args.
|
||||
- `ExactArgs(int)` - the command will report an error if there are not exactly N positional args.
|
||||
- `ExactValidArgs(int)` - the command will report an error if there are not exactly N positional args OR if there are any positional args that are not in the `ValidArgs` field of `Command`
|
||||
- `RangeArgs(min, max)` - the command will report an error if the number of args is not between the minimum and maximum number of expected args.
|
||||
|
||||
An example of setting the custom validator:
|
||||
|
||||
```go
|
||||
var cmd = &cobra.Command{
|
||||
Short: "hello",
|
||||
Args: func(cmd *cobra.Command, args []string) error {
|
||||
if len(args) < 1 {
|
||||
return errors.New("requires a color argument")
|
||||
}
|
||||
if myapp.IsValidColor(args[0]) {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("invalid color specified: %s", args[0])
|
||||
},
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Println("Hello, World!")
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
## Example
|
||||
|
||||
In the example below, we have defined three commands. Two are at the top level
|
||||
and one (cmdTimes) is a child of one of the top commands. In this case the root
|
||||
is not executable meaning that a subcommand is required. This is accomplished
|
||||
by not providing a 'Run' for the 'rootCmd'.
|
||||
|
||||
We have only defined one flag for a single command.
|
||||
|
||||
More documentation about flags is available at https://github.com/spf13/pflag
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var echoTimes int
|
||||
|
||||
var cmdPrint = &cobra.Command{
|
||||
Use: "print [string to print]",
|
||||
Short: "Print anything to the screen",
|
||||
Long: `print is for printing anything back to the screen.
|
||||
For many years people have printed back to the screen.`,
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Println("Print: " + strings.Join(args, " "))
|
||||
},
|
||||
}
|
||||
|
||||
var cmdEcho = &cobra.Command{
|
||||
Use: "echo [string to echo]",
|
||||
Short: "Echo anything to the screen",
|
||||
Long: `echo is for echoing anything back.
|
||||
Echo works a lot like print, except it has a child command.`,
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Println("Echo: " + strings.Join(args, " "))
|
||||
},
|
||||
}
|
||||
|
||||
var cmdTimes = &cobra.Command{
|
||||
Use: "times [string to echo]",
|
||||
Short: "Echo anything to the screen more times",
|
||||
Long: `echo things multiple times back to the user by providing
|
||||
a count and a string.`,
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
for i := 0; i < echoTimes; i++ {
|
||||
fmt.Println("Echo: " + strings.Join(args, " "))
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input")
|
||||
|
||||
var rootCmd = &cobra.Command{Use: "app"}
|
||||
rootCmd.AddCommand(cmdPrint, cmdEcho)
|
||||
cmdEcho.AddCommand(cmdTimes)
|
||||
rootCmd.Execute()
|
||||
}
|
||||
```
|
||||
|
||||
For a more complete example of a larger application, please checkout [Hugo](http://gohugo.io/).
|
||||
|
||||
## Help Command
|
||||
|
||||
Cobra automatically adds a help command to your application when you have subcommands.
|
||||
This will be called when a user runs 'app help'. Additionally, help will also
|
||||
support all other commands as input. Say, for instance, you have a command called
|
||||
'create' without any additional configuration; Cobra will work when 'app help
|
||||
create' is called. Every command will automatically have the '--help' flag added.
|
||||
|
||||
### Example
|
||||
|
||||
The following output is automatically generated by Cobra. Nothing beyond the
|
||||
command and flag definitions are needed.
|
||||
|
||||
$ cobra help
|
||||
|
||||
Cobra is a CLI library for Go that empowers applications.
|
||||
This application is a tool to generate the needed files
|
||||
to quickly create a Cobra application.
|
||||
|
||||
Usage:
|
||||
cobra [command]
|
||||
|
||||
Available Commands:
|
||||
add Add a command to a Cobra Application
|
||||
help Help about any command
|
||||
init Initialize a Cobra Application
|
||||
|
||||
Flags:
|
||||
-a, --author string author name for copyright attribution (default "YOUR NAME")
|
||||
--config string config file (default is $HOME/.cobra.yaml)
|
||||
-h, --help help for cobra
|
||||
-l, --license string name of license for the project
|
||||
--viper use Viper for configuration (default true)
|
||||
|
||||
Use "cobra [command] --help" for more information about a command.
|
||||
|
||||
|
||||
Help is just a command like any other. There is no special logic or behavior
|
||||
around it. In fact, you can provide your own if you want.
|
||||
|
||||
### Defining your own help
|
||||
|
||||
You can provide your own Help command or your own template for the default command to use
|
||||
with following functions:
|
||||
|
||||
```go
|
||||
cmd.SetHelpCommand(cmd *Command)
|
||||
cmd.SetHelpFunc(f func(*Command, []string))
|
||||
cmd.SetHelpTemplate(s string)
|
||||
```
|
||||
|
||||
The latter two will also apply to any children commands.
|
||||
|
||||
## Usage Message
|
||||
|
||||
When the user provides an invalid flag or invalid command, Cobra responds by
|
||||
showing the user the 'usage'.
|
||||
|
||||
### Example
|
||||
You may recognize this from the help above. That's because the default help
|
||||
embeds the usage as part of its output.
|
||||
|
||||
$ cobra --invalid
|
||||
Error: unknown flag: --invalid
|
||||
Usage:
|
||||
cobra [command]
|
||||
|
||||
Available Commands:
|
||||
add Add a command to a Cobra Application
|
||||
help Help about any command
|
||||
init Initialize a Cobra Application
|
||||
|
||||
Flags:
|
||||
-a, --author string author name for copyright attribution (default "YOUR NAME")
|
||||
--config string config file (default is $HOME/.cobra.yaml)
|
||||
-h, --help help for cobra
|
||||
-l, --license string name of license for the project
|
||||
--viper use Viper for configuration (default true)
|
||||
|
||||
Use "cobra [command] --help" for more information about a command.
|
||||
|
||||
### Defining your own usage
|
||||
You can provide your own usage function or template for Cobra to use.
|
||||
Like help, the function and template are overridable through public methods:
|
||||
|
||||
```go
|
||||
cmd.SetUsageFunc(f func(*Command) error)
|
||||
cmd.SetUsageTemplate(s string)
|
||||
```
|
||||
|
||||
## Version Flag
|
||||
|
||||
Cobra adds a top-level '--version' flag if the Version field is set on the root command.
|
||||
Running an application with the '--version' flag will print the version to stdout using
|
||||
the version template. The template can be customized using the
|
||||
`cmd.SetVersionTemplate(s string)` function.
|
||||
|
||||
## PreRun and PostRun Hooks
|
||||
|
||||
It is possible to run functions before or after the main `Run` function of your command. The `PersistentPreRun` and `PreRun` functions will be executed before `Run`. `PersistentPostRun` and `PostRun` will be executed after `Run`. The `Persistent*Run` functions will be inherited by children if they do not declare their own. These functions are run in the following order:
|
||||
|
||||
- `PersistentPreRun`
|
||||
- `PreRun`
|
||||
- `Run`
|
||||
- `PostRun`
|
||||
- `PersistentPostRun`
|
||||
|
||||
An example of two commands which use all of these features is below. When the subcommand is executed, it will run the root command's `PersistentPreRun` but not the root command's `PersistentPostRun`:
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
var rootCmd = &cobra.Command{
|
||||
Use: "root [sub]",
|
||||
Short: "My root command",
|
||||
PersistentPreRun: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args)
|
||||
},
|
||||
PreRun: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside rootCmd PreRun with args: %v\n", args)
|
||||
},
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside rootCmd Run with args: %v\n", args)
|
||||
},
|
||||
PostRun: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside rootCmd PostRun with args: %v\n", args)
|
||||
},
|
||||
PersistentPostRun: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args)
|
||||
},
|
||||
}
|
||||
|
||||
var subCmd = &cobra.Command{
|
||||
Use: "sub [no options!]",
|
||||
Short: "My subcommand",
|
||||
PreRun: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside subCmd PreRun with args: %v\n", args)
|
||||
},
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside subCmd Run with args: %v\n", args)
|
||||
},
|
||||
PostRun: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside subCmd PostRun with args: %v\n", args)
|
||||
},
|
||||
PersistentPostRun: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args)
|
||||
},
|
||||
}
|
||||
|
||||
rootCmd.AddCommand(subCmd)
|
||||
|
||||
rootCmd.SetArgs([]string{""})
|
||||
rootCmd.Execute()
|
||||
fmt.Println()
|
||||
rootCmd.SetArgs([]string{"sub", "arg1", "arg2"})
|
||||
rootCmd.Execute()
|
||||
}
|
||||
```
|
||||
|
||||
Output:
|
||||
```
|
||||
Inside rootCmd PersistentPreRun with args: []
|
||||
Inside rootCmd PreRun with args: []
|
||||
Inside rootCmd Run with args: []
|
||||
Inside rootCmd PostRun with args: []
|
||||
Inside rootCmd PersistentPostRun with args: []
|
||||
|
||||
Inside rootCmd PersistentPreRun with args: [arg1 arg2]
|
||||
Inside subCmd PreRun with args: [arg1 arg2]
|
||||
Inside subCmd Run with args: [arg1 arg2]
|
||||
Inside subCmd PostRun with args: [arg1 arg2]
|
||||
Inside subCmd PersistentPostRun with args: [arg1 arg2]
|
||||
```
|
||||
|
||||
## Suggestions when "unknown command" happens
|
||||
|
||||
Cobra will print automatic suggestions when "unknown command" errors happen. This allows Cobra to behave similarly to the `git` command when a typo happens. For example:
|
||||
|
||||
```
|
||||
$ hugo srever
|
||||
Error: unknown command "srever" for "hugo"
|
||||
|
||||
Did you mean this?
|
||||
server
|
||||
|
||||
Run 'hugo --help' for usage.
|
||||
```
|
||||
|
||||
Suggestions are automatic based on every subcommand registered and use an implementation of [Levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance). Every registered command that matches a minimum distance of 2 (ignoring case) will be displayed as a suggestion.
|
||||
|
||||
If you need to disable suggestions or tweak the string distance in your command, use:
|
||||
|
||||
```go
|
||||
command.DisableSuggestions = true
|
||||
```
|
||||
|
||||
or
|
||||
|
||||
```go
|
||||
command.SuggestionsMinimumDistance = 1
|
||||
```
|
||||
|
||||
You can also explicitly set names for which a given command will be suggested using the `SuggestFor` attribute. This allows suggestions for strings that are not close in terms of string distance, but makes sense in your set of commands and for some which you don't want aliases. Example:
|
||||
|
||||
```
|
||||
$ kubectl remove
|
||||
Error: unknown command "remove" for "kubectl"
|
||||
|
||||
Did you mean this?
|
||||
delete
|
||||
|
||||
Run 'kubectl help' for usage.
|
||||
```
|
||||
|
||||
## Generating documentation for your command
|
||||
|
||||
Cobra can generate documentation based on subcommands, flags, etc. in the following formats:
|
||||
|
||||
- [Markdown](doc/md_docs.md)
|
||||
- [ReStructured Text](doc/rest_docs.md)
|
||||
- [Man Page](doc/man_docs.md)
|
||||
|
||||
## Generating bash completions
|
||||
|
||||
Cobra can generate a bash-completion file. If you add more information to your command, these completions can be amazingly powerful and flexible. Read more about it in [Bash Completions](bash_completions.md).
|
||||
|
||||
## Generating zsh completions
|
||||
|
||||
Cobra can generate zsh-completion file. Read more about it in
|
||||
[Zsh Completions](zsh_completions.md).
|
||||
|
||||
# Contributing
|
||||
|
||||
1. Fork it
|
||||
2. Download your fork to your PC (`git clone https://github.com/your_username/cobra && cd cobra`)
|
||||
3. Create your feature branch (`git checkout -b my-new-feature`)
|
||||
4. Make changes and add them (`git add .`)
|
||||
5. Commit your changes (`git commit -m 'Add some feature'`)
|
||||
6. Push to the branch (`git push origin my-new-feature`)
|
||||
7. Create new pull request
|
||||
|
||||
# License
|
||||
|
||||
Cobra is released under the Apache 2.0 license. See [LICENSE.txt](https://github.com/spf13/cobra/blob/master/LICENSE.txt)
|
|
@ -0,0 +1,109 @@
|
|||
package cobra
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type PositionalArgs func(cmd *Command, args []string) error
|
||||
|
||||
// Legacy arg validation has the following behaviour:
|
||||
// - root commands with no subcommands can take arbitrary arguments
|
||||
// - root commands with subcommands will do subcommand validity checking
|
||||
// - subcommands will always accept arbitrary arguments
|
||||
func legacyArgs(cmd *Command, args []string) error {
|
||||
// no subcommand, always take args
|
||||
if !cmd.HasSubCommands() {
|
||||
return nil
|
||||
}
|
||||
|
||||
// root command with subcommands, do subcommand checking.
|
||||
if !cmd.HasParent() && len(args) > 0 {
|
||||
return fmt.Errorf("unknown command %q for %q%s", args[0], cmd.CommandPath(), cmd.findSuggestions(args[0]))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// NoArgs returns an error if any args are included.
|
||||
func NoArgs(cmd *Command, args []string) error {
|
||||
if len(args) > 0 {
|
||||
return fmt.Errorf("unknown command %q for %q", args[0], cmd.CommandPath())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// OnlyValidArgs returns an error if any args are not in the list of ValidArgs.
|
||||
func OnlyValidArgs(cmd *Command, args []string) error {
|
||||
if len(cmd.ValidArgs) > 0 {
|
||||
// Remove any description that may be included in ValidArgs.
|
||||
// A description is following a tab character.
|
||||
var validArgs []string
|
||||
for _, v := range cmd.ValidArgs {
|
||||
validArgs = append(validArgs, strings.Split(v, "\t")[0])
|
||||
}
|
||||
|
||||
for _, v := range args {
|
||||
if !stringInSlice(v, validArgs) {
|
||||
return fmt.Errorf("invalid argument %q for %q%s", v, cmd.CommandPath(), cmd.findSuggestions(args[0]))
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ArbitraryArgs never returns an error.
|
||||
func ArbitraryArgs(cmd *Command, args []string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// MinimumNArgs returns an error if there is not at least N args.
|
||||
func MinimumNArgs(n int) PositionalArgs {
|
||||
return func(cmd *Command, args []string) error {
|
||||
if len(args) < n {
|
||||
return fmt.Errorf("requires at least %d arg(s), only received %d", n, len(args))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// MaximumNArgs returns an error if there are more than N args.
|
||||
func MaximumNArgs(n int) PositionalArgs {
|
||||
return func(cmd *Command, args []string) error {
|
||||
if len(args) > n {
|
||||
return fmt.Errorf("accepts at most %d arg(s), received %d", n, len(args))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExactArgs returns an error if there are not exactly n args.
|
||||
func ExactArgs(n int) PositionalArgs {
|
||||
return func(cmd *Command, args []string) error {
|
||||
if len(args) != n {
|
||||
return fmt.Errorf("accepts %d arg(s), received %d", n, len(args))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// ExactValidArgs returns an error if
|
||||
// there are not exactly N positional args OR
|
||||
// there are any positional args that are not in the `ValidArgs` field of `Command`
|
||||
func ExactValidArgs(n int) PositionalArgs {
|
||||
return func(cmd *Command, args []string) error {
|
||||
if err := ExactArgs(n)(cmd, args); err != nil {
|
||||
return err
|
||||
}
|
||||
return OnlyValidArgs(cmd, args)
|
||||
}
|
||||
}
|
||||
|
||||
// RangeArgs returns an error if the number of args is not within the expected range.
|
||||
func RangeArgs(min int, max int) PositionalArgs {
|
||||
return func(cmd *Command, args []string) error {
|
||||
if len(args) < min || len(args) > max {
|
||||
return fmt.Errorf("accepts between %d and %d arg(s), received %d", min, max, len(args))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
|
@ -0,0 +1,641 @@
|
|||
package cobra
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
// Annotations for Bash completion.
|
||||
const (
|
||||
BashCompFilenameExt = "cobra_annotation_bash_completion_filename_extensions"
|
||||
BashCompCustom = "cobra_annotation_bash_completion_custom"
|
||||
BashCompOneRequiredFlag = "cobra_annotation_bash_completion_one_required_flag"
|
||||
BashCompSubdirsInDir = "cobra_annotation_bash_completion_subdirs_in_dir"
|
||||
)
|
||||
|
||||
func writePreamble(buf *bytes.Buffer, name string) {
|
||||
buf.WriteString(fmt.Sprintf("# bash completion for %-36s -*- shell-script -*-\n", name))
|
||||
buf.WriteString(fmt.Sprintf(`
|
||||
__%[1]s_debug()
|
||||
{
|
||||
if [[ -n ${BASH_COMP_DEBUG_FILE} ]]; then
|
||||
echo "$*" >> "${BASH_COMP_DEBUG_FILE}"
|
||||
fi
|
||||
}
|
||||
|
||||
# Homebrew on Macs have version 1.3 of bash-completion which doesn't include
|
||||
# _init_completion. This is a very minimal version of that function.
|
||||
__%[1]s_init_completion()
|
||||
{
|
||||
COMPREPLY=()
|
||||
_get_comp_words_by_ref "$@" cur prev words cword
|
||||
}
|
||||
|
||||
__%[1]s_index_of_word()
|
||||
{
|
||||
local w word=$1
|
||||
shift
|
||||
index=0
|
||||
for w in "$@"; do
|
||||
[[ $w = "$word" ]] && return
|
||||
index=$((index+1))
|
||||
done
|
||||
index=-1
|
||||
}
|
||||
|
||||
__%[1]s_contains_word()
|
||||
{
|
||||
local w word=$1; shift
|
||||
for w in "$@"; do
|
||||
[[ $w = "$word" ]] && return
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
__%[1]s_handle_go_custom_completion()
|
||||
{
|
||||
__%[1]s_debug "${FUNCNAME[0]}: cur is ${cur}, words[*] is ${words[*]}, #words[@] is ${#words[@]}"
|
||||
|
||||
local out requestComp lastParam lastChar comp directive args
|
||||
|
||||
# Prepare the command to request completions for the program.
|
||||
# Calling ${words[0]} instead of directly %[1]s allows to handle aliases
|
||||
args=("${words[@]:1}")
|
||||
requestComp="${words[0]} %[2]s ${args[*]}"
|
||||
|
||||
lastParam=${words[$((${#words[@]}-1))]}
|
||||
lastChar=${lastParam:$((${#lastParam}-1)):1}
|
||||
__%[1]s_debug "${FUNCNAME[0]}: lastParam ${lastParam}, lastChar ${lastChar}"
|
||||
|
||||
if [ -z "${cur}" ] && [ "${lastChar}" != "=" ]; then
|
||||
# If the last parameter is complete (there is a space following it)
|
||||
# We add an extra empty parameter so we can indicate this to the go method.
|
||||
__%[1]s_debug "${FUNCNAME[0]}: Adding extra empty parameter"
|
||||
requestComp="${requestComp} \"\""
|
||||
fi
|
||||
|
||||
__%[1]s_debug "${FUNCNAME[0]}: calling ${requestComp}"
|
||||
# Use eval to handle any environment variables and such
|
||||
out=$(eval "${requestComp}" 2>/dev/null)
|
||||
|
||||
# Extract the directive integer at the very end of the output following a colon (:)
|
||||
directive=${out##*:}
|
||||
# Remove the directive
|
||||
out=${out%%:*}
|
||||
if [ "${directive}" = "${out}" ]; then
|
||||
# There is not directive specified
|
||||
directive=0
|
||||
fi
|
||||
__%[1]s_debug "${FUNCNAME[0]}: the completion directive is: ${directive}"
|
||||
__%[1]s_debug "${FUNCNAME[0]}: the completions are: ${out[*]}"
|
||||
|
||||
if [ $((directive & %[3]d)) -ne 0 ]; then
|
||||
# Error code. No completion.
|
||||
__%[1]s_debug "${FUNCNAME[0]}: received error from custom completion go code"
|
||||
return
|
||||
else
|
||||
if [ $((directive & %[4]d)) -ne 0 ]; then
|
||||
if [[ $(type -t compopt) = "builtin" ]]; then
|
||||
__%[1]s_debug "${FUNCNAME[0]}: activating no space"
|
||||
compopt -o nospace
|
||||
fi
|
||||
fi
|
||||
if [ $((directive & %[5]d)) -ne 0 ]; then
|
||||
if [[ $(type -t compopt) = "builtin" ]]; then
|
||||
__%[1]s_debug "${FUNCNAME[0]}: activating no file completion"
|
||||
compopt +o default
|
||||
fi
|
||||
fi
|
||||
|
||||
while IFS='' read -r comp; do
|
||||
COMPREPLY+=("$comp")
|
||||
done < <(compgen -W "${out[*]}" -- "$cur")
|
||||
fi
|
||||
}
|
||||
|
||||
__%[1]s_handle_reply()
|
||||
{
|
||||
__%[1]s_debug "${FUNCNAME[0]}"
|
||||
local comp
|
||||
case $cur in
|
||||
-*)
|
||||
if [[ $(type -t compopt) = "builtin" ]]; then
|
||||
compopt -o nospace
|
||||
fi
|
||||
local allflags
|
||||
if [ ${#must_have_one_flag[@]} -ne 0 ]; then
|
||||
allflags=("${must_have_one_flag[@]}")
|
||||
else
|
||||
allflags=("${flags[*]} ${two_word_flags[*]}")
|
||||
fi
|
||||
while IFS='' read -r comp; do
|
||||
COMPREPLY+=("$comp")
|
||||
done < <(compgen -W "${allflags[*]}" -- "$cur")
|
||||
if [[ $(type -t compopt) = "builtin" ]]; then
|
||||
[[ "${COMPREPLY[0]}" == *= ]] || compopt +o nospace
|
||||
fi
|
||||
|
||||
# complete after --flag=abc
|
||||
if [[ $cur == *=* ]]; then
|
||||
if [[ $(type -t compopt) = "builtin" ]]; then
|
||||
compopt +o nospace
|
||||
fi
|
||||
|
||||
local index flag
|
||||
flag="${cur%%=*}"
|
||||
__%[1]s_index_of_word "${flag}" "${flags_with_completion[@]}"
|
||||
COMPREPLY=()
|
||||
if [[ ${index} -ge 0 ]]; then
|
||||
PREFIX=""
|
||||
cur="${cur#*=}"
|
||||
${flags_completion[${index}]}
|
||||
if [ -n "${ZSH_VERSION}" ]; then
|
||||
# zsh completion needs --flag= prefix
|
||||
eval "COMPREPLY=( \"\${COMPREPLY[@]/#/${flag}=}\" )"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
return 0;
|
||||
;;
|
||||
esac
|
||||
|
||||
# check if we are handling a flag with special work handling
|
||||
local index
|
||||
__%[1]s_index_of_word "${prev}" "${flags_with_completion[@]}"
|
||||
if [[ ${index} -ge 0 ]]; then
|
||||
${flags_completion[${index}]}
|
||||
return
|
||||
fi
|
||||
|
||||
# we are parsing a flag and don't have a special handler, no completion
|
||||
if [[ ${cur} != "${words[cword]}" ]]; then
|
||||
return
|
||||
fi
|
||||
|
||||
local completions
|
||||
completions=("${commands[@]}")
|
||||
if [[ ${#must_have_one_noun[@]} -ne 0 ]]; then
|
||||
completions=("${must_have_one_noun[@]}")
|
||||
elif [[ -n "${has_completion_function}" ]]; then
|
||||
# if a go completion function is provided, defer to that function
|
||||
completions=()
|
||||
__%[1]s_handle_go_custom_completion
|
||||
fi
|
||||
if [[ ${#must_have_one_flag[@]} -ne 0 ]]; then
|
||||
completions+=("${must_have_one_flag[@]}")
|
||||
fi
|
||||
while IFS='' read -r comp; do
|
||||
COMPREPLY+=("$comp")
|
||||
done < <(compgen -W "${completions[*]}" -- "$cur")
|
||||
|
||||
if [[ ${#COMPREPLY[@]} -eq 0 && ${#noun_aliases[@]} -gt 0 && ${#must_have_one_noun[@]} -ne 0 ]]; then
|
||||
while IFS='' read -r comp; do
|
||||
COMPREPLY+=("$comp")
|
||||
done < <(compgen -W "${noun_aliases[*]}" -- "$cur")
|
||||
fi
|
||||
|
||||
if [[ ${#COMPREPLY[@]} -eq 0 ]]; then
|
||||
if declare -F __%[1]s_custom_func >/dev/null; then
|
||||
# try command name qualified custom func
|
||||
__%[1]s_custom_func
|
||||
else
|
||||
# otherwise fall back to unqualified for compatibility
|
||||
declare -F __custom_func >/dev/null && __custom_func
|
||||
fi
|
||||
fi
|
||||
|
||||
# available in bash-completion >= 2, not always present on macOS
|
||||
if declare -F __ltrim_colon_completions >/dev/null; then
|
||||
__ltrim_colon_completions "$cur"
|
||||
fi
|
||||
|
||||
# If there is only 1 completion and it is a flag with an = it will be completed
|
||||
# but we don't want a space after the =
|
||||
if [[ "${#COMPREPLY[@]}" -eq "1" ]] && [[ $(type -t compopt) = "builtin" ]] && [[ "${COMPREPLY[0]}" == --*= ]]; then
|
||||
compopt -o nospace
|
||||
fi
|
||||
}
|
||||
|
||||
# The arguments should be in the form "ext1|ext2|extn"
|
||||
__%[1]s_handle_filename_extension_flag()
|
||||
{
|
||||
local ext="$1"
|
||||
_filedir "@(${ext})"
|
||||
}
|
||||
|
||||
__%[1]s_handle_subdirs_in_dir_flag()
|
||||
{
|
||||
local dir="$1"
|
||||
pushd "${dir}" >/dev/null 2>&1 && _filedir -d && popd >/dev/null 2>&1 || return
|
||||
}
|
||||
|
||||
__%[1]s_handle_flag()
|
||||
{
|
||||
__%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
|
||||
|
||||
# if a command required a flag, and we found it, unset must_have_one_flag()
|
||||
local flagname=${words[c]}
|
||||
local flagvalue
|
||||
# if the word contained an =
|
||||
if [[ ${words[c]} == *"="* ]]; then
|
||||
flagvalue=${flagname#*=} # take in as flagvalue after the =
|
||||
flagname=${flagname%%=*} # strip everything after the =
|
||||
flagname="${flagname}=" # but put the = back
|
||||
fi
|
||||
__%[1]s_debug "${FUNCNAME[0]}: looking for ${flagname}"
|
||||
if __%[1]s_contains_word "${flagname}" "${must_have_one_flag[@]}"; then
|
||||
must_have_one_flag=()
|
||||
fi
|
||||
|
||||
# if you set a flag which only applies to this command, don't show subcommands
|
||||
if __%[1]s_contains_word "${flagname}" "${local_nonpersistent_flags[@]}"; then
|
||||
commands=()
|
||||
fi
|
||||
|
||||
# keep flag value with flagname as flaghash
|
||||
# flaghash variable is an associative array which is only supported in bash > 3.
|
||||
if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then
|
||||
if [ -n "${flagvalue}" ] ; then
|
||||
flaghash[${flagname}]=${flagvalue}
|
||||
elif [ -n "${words[ $((c+1)) ]}" ] ; then
|
||||
flaghash[${flagname}]=${words[ $((c+1)) ]}
|
||||
else
|
||||
flaghash[${flagname}]="true" # pad "true" for bool flag
|
||||
fi
|
||||
fi
|
||||
|
||||
# skip the argument to a two word flag
|
||||
if [[ ${words[c]} != *"="* ]] && __%[1]s_contains_word "${words[c]}" "${two_word_flags[@]}"; then
|
||||
__%[1]s_debug "${FUNCNAME[0]}: found a flag ${words[c]}, skip the next argument"
|
||||
c=$((c+1))
|
||||
# if we are looking for a flags value, don't show commands
|
||||
if [[ $c -eq $cword ]]; then
|
||||
commands=()
|
||||
fi
|
||||
fi
|
||||
|
||||
c=$((c+1))
|
||||
|
||||
}
|
||||
|
||||
__%[1]s_handle_noun()
|
||||
{
|
||||
__%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
|
||||
|
||||
if __%[1]s_contains_word "${words[c]}" "${must_have_one_noun[@]}"; then
|
||||
must_have_one_noun=()
|
||||
elif __%[1]s_contains_word "${words[c]}" "${noun_aliases[@]}"; then
|
||||
must_have_one_noun=()
|
||||
fi
|
||||
|
||||
nouns+=("${words[c]}")
|
||||
c=$((c+1))
|
||||
}
|
||||
|
||||
__%[1]s_handle_command()
|
||||
{
|
||||
__%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
|
||||
|
||||
local next_command
|
||||
if [[ -n ${last_command} ]]; then
|
||||
next_command="_${last_command}_${words[c]//:/__}"
|
||||
else
|
||||
if [[ $c -eq 0 ]]; then
|
||||
next_command="_%[1]s_root_command"
|
||||
else
|
||||
next_command="_${words[c]//:/__}"
|
||||
fi
|
||||
fi
|
||||
c=$((c+1))
|
||||
__%[1]s_debug "${FUNCNAME[0]}: looking for ${next_command}"
|
||||
declare -F "$next_command" >/dev/null && $next_command
|
||||
}
|
||||
|
||||
__%[1]s_handle_word()
|
||||
{
|
||||
if [[ $c -ge $cword ]]; then
|
||||
__%[1]s_handle_reply
|
||||
return
|
||||
fi
|
||||
__%[1]s_debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
|
||||
if [[ "${words[c]}" == -* ]]; then
|
||||
__%[1]s_handle_flag
|
||||
elif __%[1]s_contains_word "${words[c]}" "${commands[@]}"; then
|
||||
__%[1]s_handle_command
|
||||
elif [[ $c -eq 0 ]]; then
|
||||
__%[1]s_handle_command
|
||||
elif __%[1]s_contains_word "${words[c]}" "${command_aliases[@]}"; then
|
||||
# aliashash variable is an associative array which is only supported in bash > 3.
|
||||
if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then
|
||||
words[c]=${aliashash[${words[c]}]}
|
||||
__%[1]s_handle_command
|
||||
else
|
||||
__%[1]s_handle_noun
|
||||
fi
|
||||
else
|
||||
__%[1]s_handle_noun
|
||||
fi
|
||||
__%[1]s_handle_word
|
||||
}
|
||||
|
||||
`, name, ShellCompNoDescRequestCmd, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp))
|
||||
}
|
||||
|
||||
func writePostscript(buf *bytes.Buffer, name string) {
|
||||
name = strings.Replace(name, ":", "__", -1)
|
||||
buf.WriteString(fmt.Sprintf("__start_%s()\n", name))
|
||||
buf.WriteString(fmt.Sprintf(`{
|
||||
local cur prev words cword
|
||||
declare -A flaghash 2>/dev/null || :
|
||||
declare -A aliashash 2>/dev/null || :
|
||||
if declare -F _init_completion >/dev/null 2>&1; then
|
||||
_init_completion -s || return
|
||||
else
|
||||
__%[1]s_init_completion -n "=" || return
|
||||
fi
|
||||
|
||||
local c=0
|
||||
local flags=()
|
||||
local two_word_flags=()
|
||||
local local_nonpersistent_flags=()
|
||||
local flags_with_completion=()
|
||||
local flags_completion=()
|
||||
local commands=("%[1]s")
|
||||
local must_have_one_flag=()
|
||||
local must_have_one_noun=()
|
||||
local has_completion_function
|
||||
local last_command
|
||||
local nouns=()
|
||||
|
||||
__%[1]s_handle_word
|
||||
}
|
||||
|
||||
`, name))
|
||||
buf.WriteString(fmt.Sprintf(`if [[ $(type -t compopt) = "builtin" ]]; then
|
||||
complete -o default -F __start_%s %s
|
||||
else
|
||||
complete -o default -o nospace -F __start_%s %s
|
||||
fi
|
||||
|
||||
`, name, name, name, name))
|
||||
buf.WriteString("# ex: ts=4 sw=4 et filetype=sh\n")
|
||||
}
|
||||
|
||||
func writeCommands(buf *bytes.Buffer, cmd *Command) {
|
||||
buf.WriteString(" commands=()\n")
|
||||
for _, c := range cmd.Commands() {
|
||||
if !c.IsAvailableCommand() || c == cmd.helpCommand {
|
||||
continue
|
||||
}
|
||||
buf.WriteString(fmt.Sprintf(" commands+=(%q)\n", c.Name()))
|
||||
writeCmdAliases(buf, c)
|
||||
}
|
||||
buf.WriteString("\n")
|
||||
}
|
||||
|
||||
func writeFlagHandler(buf *bytes.Buffer, name string, annotations map[string][]string, cmd *Command) {
|
||||
for key, value := range annotations {
|
||||
switch key {
|
||||
case BashCompFilenameExt:
|
||||
buf.WriteString(fmt.Sprintf(" flags_with_completion+=(%q)\n", name))
|
||||
|
||||
var ext string
|
||||
if len(value) > 0 {
|
||||
ext = fmt.Sprintf("__%s_handle_filename_extension_flag ", cmd.Root().Name()) + strings.Join(value, "|")
|
||||
} else {
|
||||
ext = "_filedir"
|
||||
}
|
||||
buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", ext))
|
||||
case BashCompCustom:
|
||||
buf.WriteString(fmt.Sprintf(" flags_with_completion+=(%q)\n", name))
|
||||
if len(value) > 0 {
|
||||
handlers := strings.Join(value, "; ")
|
||||
buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", handlers))
|
||||
} else {
|
||||
buf.WriteString(" flags_completion+=(:)\n")
|
||||
}
|
||||
case BashCompSubdirsInDir:
|
||||
buf.WriteString(fmt.Sprintf(" flags_with_completion+=(%q)\n", name))
|
||||
|
||||
var ext string
|
||||
if len(value) == 1 {
|
||||
ext = fmt.Sprintf("__%s_handle_subdirs_in_dir_flag ", cmd.Root().Name()) + value[0]
|
||||
} else {
|
||||
ext = "_filedir -d"
|
||||
}
|
||||
buf.WriteString(fmt.Sprintf(" flags_completion+=(%q)\n", ext))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func writeShortFlag(buf *bytes.Buffer, flag *pflag.Flag, cmd *Command) {
|
||||
name := flag.Shorthand
|
||||
format := " "
|
||||
if len(flag.NoOptDefVal) == 0 {
|
||||
format += "two_word_"
|
||||
}
|
||||
format += "flags+=(\"-%s\")\n"
|
||||
buf.WriteString(fmt.Sprintf(format, name))
|
||||
writeFlagHandler(buf, "-"+name, flag.Annotations, cmd)
|
||||
}
|
||||
|
||||
func writeFlag(buf *bytes.Buffer, flag *pflag.Flag, cmd *Command) {
|
||||
name := flag.Name
|
||||
format := " flags+=(\"--%s"
|
||||
if len(flag.NoOptDefVal) == 0 {
|
||||
format += "="
|
||||
}
|
||||
format += "\")\n"
|
||||
buf.WriteString(fmt.Sprintf(format, name))
|
||||
if len(flag.NoOptDefVal) == 0 {
|
||||
format = " two_word_flags+=(\"--%s\")\n"
|
||||
buf.WriteString(fmt.Sprintf(format, name))
|
||||
}
|
||||
writeFlagHandler(buf, "--"+name, flag.Annotations, cmd)
|
||||
}
|
||||
|
||||
func writeLocalNonPersistentFlag(buf *bytes.Buffer, flag *pflag.Flag) {
|
||||
name := flag.Name
|
||||
format := " local_nonpersistent_flags+=(\"--%s"
|
||||
if len(flag.NoOptDefVal) == 0 {
|
||||
format += "="
|
||||
}
|
||||
format += "\")\n"
|
||||
buf.WriteString(fmt.Sprintf(format, name))
|
||||
}
|
||||
|
||||
// Setup annotations for go completions for registered flags
|
||||
func prepareCustomAnnotationsForFlags(cmd *Command) {
|
||||
for flag := range flagCompletionFunctions {
|
||||
// Make sure the completion script calls the __*_go_custom_completion function for
|
||||
// every registered flag. We need to do this here (and not when the flag was registered
|
||||
// for completion) so that we can know the root command name for the prefix
|
||||
// of __<prefix>_go_custom_completion
|
||||
if flag.Annotations == nil {
|
||||
flag.Annotations = map[string][]string{}
|
||||
}
|
||||
flag.Annotations[BashCompCustom] = []string{fmt.Sprintf("__%[1]s_handle_go_custom_completion", cmd.Root().Name())}
|
||||
}
|
||||
}
|
||||
|
||||
func writeFlags(buf *bytes.Buffer, cmd *Command) {
|
||||
prepareCustomAnnotationsForFlags(cmd)
|
||||
buf.WriteString(` flags=()
|
||||
two_word_flags=()
|
||||
local_nonpersistent_flags=()
|
||||
flags_with_completion=()
|
||||
flags_completion=()
|
||||
|
||||
`)
|
||||
localNonPersistentFlags := cmd.LocalNonPersistentFlags()
|
||||
cmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {
|
||||
if nonCompletableFlag(flag) {
|
||||
return
|
||||
}
|
||||
writeFlag(buf, flag, cmd)
|
||||
if len(flag.Shorthand) > 0 {
|
||||
writeShortFlag(buf, flag, cmd)
|
||||
}
|
||||
if localNonPersistentFlags.Lookup(flag.Name) != nil {
|
||||
writeLocalNonPersistentFlag(buf, flag)
|
||||
}
|
||||
})
|
||||
cmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {
|
||||
if nonCompletableFlag(flag) {
|
||||
return
|
||||
}
|
||||
writeFlag(buf, flag, cmd)
|
||||
if len(flag.Shorthand) > 0 {
|
||||
writeShortFlag(buf, flag, cmd)
|
||||
}
|
||||
})
|
||||
|
||||
buf.WriteString("\n")
|
||||
}
|
||||
|
||||
func writeRequiredFlag(buf *bytes.Buffer, cmd *Command) {
|
||||
buf.WriteString(" must_have_one_flag=()\n")
|
||||
flags := cmd.NonInheritedFlags()
|
||||
flags.VisitAll(func(flag *pflag.Flag) {
|
||||
if nonCompletableFlag(flag) {
|
||||
return
|
||||
}
|
||||
for key := range flag.Annotations {
|
||||
switch key {
|
||||
case BashCompOneRequiredFlag:
|
||||
format := " must_have_one_flag+=(\"--%s"
|
||||
if flag.Value.Type() != "bool" {
|
||||
format += "="
|
||||
}
|
||||
format += "\")\n"
|
||||
buf.WriteString(fmt.Sprintf(format, flag.Name))
|
||||
|
||||
if len(flag.Shorthand) > 0 {
|
||||
buf.WriteString(fmt.Sprintf(" must_have_one_flag+=(\"-%s\")\n", flag.Shorthand))
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func writeRequiredNouns(buf *bytes.Buffer, cmd *Command) {
|
||||
buf.WriteString(" must_have_one_noun=()\n")
|
||||
sort.Sort(sort.StringSlice(cmd.ValidArgs))
|
||||
for _, value := range cmd.ValidArgs {
|
||||
// Remove any description that may be included following a tab character.
|
||||
// Descriptions are not supported by bash completion.
|
||||
value = strings.Split(value, "\t")[0]
|
||||
buf.WriteString(fmt.Sprintf(" must_have_one_noun+=(%q)\n", value))
|
||||
}
|
||||
if cmd.ValidArgsFunction != nil {
|
||||
buf.WriteString(" has_completion_function=1\n")
|
||||
}
|
||||
}
|
||||
|
||||
func writeCmdAliases(buf *bytes.Buffer, cmd *Command) {
|
||||
if len(cmd.Aliases) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
sort.Sort(sort.StringSlice(cmd.Aliases))
|
||||
|
||||
buf.WriteString(fmt.Sprint(` if [[ -z "${BASH_VERSION}" || "${BASH_VERSINFO[0]}" -gt 3 ]]; then`, "\n"))
|
||||
for _, value := range cmd.Aliases {
|
||||
buf.WriteString(fmt.Sprintf(" command_aliases+=(%q)\n", value))
|
||||
buf.WriteString(fmt.Sprintf(" aliashash[%q]=%q\n", value, cmd.Name()))
|
||||
}
|
||||
buf.WriteString(` fi`)
|
||||
buf.WriteString("\n")
|
||||
}
|
||||
func writeArgAliases(buf *bytes.Buffer, cmd *Command) {
|
||||
buf.WriteString(" noun_aliases=()\n")
|
||||
sort.Sort(sort.StringSlice(cmd.ArgAliases))
|
||||
for _, value := range cmd.ArgAliases {
|
||||
buf.WriteString(fmt.Sprintf(" noun_aliases+=(%q)\n", value))
|
||||
}
|
||||
}
|
||||
|
||||
func gen(buf *bytes.Buffer, cmd *Command) {
|
||||
for _, c := range cmd.Commands() {
|
||||
if !c.IsAvailableCommand() || c == cmd.helpCommand {
|
||||
continue
|
||||
}
|
||||
gen(buf, c)
|
||||
}
|
||||
commandName := cmd.CommandPath()
|
||||
commandName = strings.Replace(commandName, " ", "_", -1)
|
||||
commandName = strings.Replace(commandName, ":", "__", -1)
|
||||
|
||||
if cmd.Root() == cmd {
|
||||
buf.WriteString(fmt.Sprintf("_%s_root_command()\n{\n", commandName))
|
||||
} else {
|
||||
buf.WriteString(fmt.Sprintf("_%s()\n{\n", commandName))
|
||||
}
|
||||
|
||||
buf.WriteString(fmt.Sprintf(" last_command=%q\n", commandName))
|
||||
buf.WriteString("\n")
|
||||
buf.WriteString(" command_aliases=()\n")
|
||||
buf.WriteString("\n")
|
||||
|
||||
writeCommands(buf, cmd)
|
||||
writeFlags(buf, cmd)
|
||||
writeRequiredFlag(buf, cmd)
|
||||
writeRequiredNouns(buf, cmd)
|
||||
writeArgAliases(buf, cmd)
|
||||
buf.WriteString("}\n\n")
|
||||
}
|
||||
|
||||
// GenBashCompletion generates bash completion file and writes to the passed writer.
|
||||
func (c *Command) GenBashCompletion(w io.Writer) error {
|
||||
buf := new(bytes.Buffer)
|
||||
writePreamble(buf, c.Name())
|
||||
if len(c.BashCompletionFunction) > 0 {
|
||||
buf.WriteString(c.BashCompletionFunction + "\n")
|
||||
}
|
||||
gen(buf, c)
|
||||
writePostscript(buf, c.Name())
|
||||
|
||||
_, err := buf.WriteTo(w)
|
||||
return err
|
||||
}
|
||||
|
||||
func nonCompletableFlag(flag *pflag.Flag) bool {
|
||||
return flag.Hidden || len(flag.Deprecated) > 0
|
||||
}
|
||||
|
||||
// GenBashCompletionFile generates bash completion file.
|
||||
func (c *Command) GenBashCompletionFile(filename string) error {
|
||||
outFile, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer outFile.Close()
|
||||
|
||||
return c.GenBashCompletion(outFile)
|
||||
}
|
|
@ -0,0 +1,383 @@
|
|||
# Generating Bash Completions For Your Own cobra.Command
|
||||
|
||||
If you are using the generator you can create a completion command by running
|
||||
|
||||
```bash
|
||||
cobra add completion
|
||||
```
|
||||
|
||||
Update the help text show how to install the bash_completion Linux show here [Kubectl docs show mac options](https://kubernetes.io/docs/tasks/tools/install-kubectl/#enabling-shell-autocompletion)
|
||||
|
||||
Writing the shell script to stdout allows the most flexible use.
|
||||
|
||||
```go
|
||||
// completionCmd represents the completion command
|
||||
var completionCmd = &cobra.Command{
|
||||
Use: "completion",
|
||||
Short: "Generates bash completion scripts",
|
||||
Long: `To load completion run
|
||||
|
||||
. <(bitbucket completion)
|
||||
|
||||
To configure your bash shell to load completions for each session add to your bashrc
|
||||
|
||||
# ~/.bashrc or ~/.profile
|
||||
. <(bitbucket completion)
|
||||
`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
rootCmd.GenBashCompletion(os.Stdout);
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** The cobra generator may include messages printed to stdout for example if the config file is loaded, this will break the auto complete script
|
||||
|
||||
|
||||
## Example from kubectl
|
||||
|
||||
Generating bash completions from a cobra command is incredibly easy. An actual program which does so for the kubernetes kubectl binary is as follows:
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"os"
|
||||
|
||||
"k8s.io/kubernetes/pkg/kubectl/cmd"
|
||||
"k8s.io/kubernetes/pkg/kubectl/cmd/util"
|
||||
)
|
||||
|
||||
func main() {
|
||||
kubectl := cmd.NewKubectlCommand(util.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
|
||||
kubectl.GenBashCompletionFile("out.sh")
|
||||
}
|
||||
```
|
||||
|
||||
`out.sh` will get you completions of subcommands and flags. Copy it to `/etc/bash_completion.d/` as described [here](https://debian-administration.org/article/316/An_introduction_to_bash_completion_part_1) and reset your terminal to use autocompletion. If you make additional annotations to your code, you can get even more intelligent and flexible behavior.
|
||||
|
||||
## Have the completions code complete your 'nouns'
|
||||
|
||||
### Static completion of nouns
|
||||
|
||||
This method allows you to provide a pre-defined list of completion choices for your nouns using the `validArgs` field.
|
||||
For example, if you want `kubectl get [tab][tab]` to show a list of valid "nouns" you have to set them. Simplified code from `kubectl get` looks like:
|
||||
|
||||
```go
|
||||
validArgs []string = { "pod", "node", "service", "replicationcontroller" }
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)",
|
||||
Short: "Display one or many resources",
|
||||
Long: get_long,
|
||||
Example: get_example,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
err := RunGet(f, out, cmd, args)
|
||||
util.CheckErr(err)
|
||||
},
|
||||
ValidArgs: validArgs,
|
||||
}
|
||||
```
|
||||
|
||||
Notice we put the "ValidArgs" on the "get" subcommand. Doing so will give results like
|
||||
|
||||
```bash
|
||||
# kubectl get [tab][tab]
|
||||
node pod replicationcontroller service
|
||||
```
|
||||
|
||||
### Plural form and shortcuts for nouns
|
||||
|
||||
If your nouns have a number of aliases, you can define them alongside `ValidArgs` using `ArgAliases`:
|
||||
|
||||
```go
|
||||
argAliases []string = { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" }
|
||||
|
||||
cmd := &cobra.Command{
|
||||
...
|
||||
ValidArgs: validArgs,
|
||||
ArgAliases: argAliases
|
||||
}
|
||||
```
|
||||
|
||||
The aliases are not shown to the user on tab completion, but they are accepted as valid nouns by
|
||||
the completion algorithm if entered manually, e.g. in:
|
||||
|
||||
```bash
|
||||
# kubectl get rc [tab][tab]
|
||||
backend frontend database
|
||||
```
|
||||
|
||||
Note that without declaring `rc` as an alias, the completion algorithm would show the list of nouns
|
||||
in this example again instead of the replication controllers.
|
||||
|
||||
### Dynamic completion of nouns
|
||||
|
||||
In some cases it is not possible to provide a list of possible completions in advance. Instead, the list of completions must be determined at execution-time. Cobra provides two ways of defining such dynamic completion of nouns. Note that both these methods can be used along-side each other as long as they are not both used for the same command.
|
||||
|
||||
**Note**: *Custom Completions written in Go* will automatically work for other shell-completion scripts (e.g., Fish shell), while *Custom Completions written in Bash* will only work for Bash shell-completion. It is therefore recommended to use *Custom Completions written in Go*.
|
||||
|
||||
#### 1. Custom completions of nouns written in Go
|
||||
|
||||
In a similar fashion as for static completions, you can use the `ValidArgsFunction` field to provide a Go function that Cobra will execute when it needs the list of completion choices for the nouns of a command. Note that either `ValidArgs` or `ValidArgsFunction` can be used for a single cobra command, but not both.
|
||||
Simplified code from `helm status` looks like:
|
||||
|
||||
```go
|
||||
cmd := &cobra.Command{
|
||||
Use: "status RELEASE_NAME",
|
||||
Short: "Display the status of the named release",
|
||||
Long: status_long,
|
||||
RunE: func(cmd *cobra.Command, args []string) {
|
||||
RunGet(args[0])
|
||||
},
|
||||
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
if len(args) != 0 {
|
||||
return nil, cobra.ShellCompDirectiveNoFileComp
|
||||
}
|
||||
return getReleasesFromCluster(toComplete), cobra.ShellCompDirectiveNoFileComp
|
||||
},
|
||||
}
|
||||
```
|
||||
Where `getReleasesFromCluster()` is a Go function that obtains the list of current Helm releases running on the Kubernetes cluster.
|
||||
Notice we put the `ValidArgsFunction` on the `status` subcommand. Let's assume the Helm releases on the cluster are: `harbor`, `notary`, `rook` and `thanos` then this dynamic completion will give results like
|
||||
|
||||
```bash
|
||||
# helm status [tab][tab]
|
||||
harbor notary rook thanos
|
||||
```
|
||||
You may have noticed the use of `cobra.ShellCompDirective`. These directives are bit fields allowing to control some shell completion behaviors for your particular completion. You can combine them with the bit-or operator such as `cobra.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveNoFileComp`
|
||||
```go
|
||||
// Indicates an error occurred and completions should be ignored.
|
||||
ShellCompDirectiveError
|
||||
// Indicates that the shell should not add a space after the completion,
|
||||
// even if there is a single completion provided.
|
||||
ShellCompDirectiveNoSpace
|
||||
// Indicates that the shell should not provide file completion even when
|
||||
// no completion is provided.
|
||||
// This currently does not work for zsh or bash < 4
|
||||
ShellCompDirectiveNoFileComp
|
||||
// Indicates that the shell will perform its default behavior after completions
|
||||
// have been provided (this implies !ShellCompDirectiveNoSpace && !ShellCompDirectiveNoFileComp).
|
||||
ShellCompDirectiveDefault
|
||||
```
|
||||
|
||||
When using the `ValidArgsFunction`, Cobra will call your registered function after having parsed all flags and arguments provided in the command-line. You therefore don't need to do this parsing yourself. For example, when a user calls `helm status --namespace my-rook-ns [tab][tab]`, Cobra will call your registered `ValidArgsFunction` after having parsed the `--namespace` flag, as it would have done when calling the `RunE` function.
|
||||
|
||||
##### Debugging
|
||||
|
||||
Cobra achieves dynamic completions written in Go through the use of a hidden command called by the completion script. To debug your Go completion code, you can call this hidden command directly:
|
||||
```bash
|
||||
# helm __complete status har<ENTER>
|
||||
harbor
|
||||
:4
|
||||
Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr
|
||||
```
|
||||
***Important:*** If the noun to complete is empty, you must pass an empty parameter to the `__complete` command:
|
||||
```bash
|
||||
# helm __complete status ""<ENTER>
|
||||
harbor
|
||||
notary
|
||||
rook
|
||||
thanos
|
||||
:4
|
||||
Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr
|
||||
```
|
||||
Calling the `__complete` command directly allows you to run the Go debugger to troubleshoot your code. You can also add printouts to your code; Cobra provides the following functions to use for printouts in Go completion code:
|
||||
```go
|
||||
// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE
|
||||
// is set to a file path) and optionally prints to stderr.
|
||||
cobra.CompDebug(msg string, printToStdErr bool) {
|
||||
cobra.CompDebugln(msg string, printToStdErr bool)
|
||||
|
||||
// Prints to the completion script debug file (if BASH_COMP_DEBUG_FILE
|
||||
// is set to a file path) and to stderr.
|
||||
cobra.CompError(msg string)
|
||||
cobra.CompErrorln(msg string)
|
||||
```
|
||||
***Important:*** You should **not** leave traces that print to stdout in your completion code as they will be interpreted as completion choices by the completion script. Instead, use the cobra-provided debugging traces functions mentioned above.
|
||||
|
||||
#### 2. Custom completions of nouns written in Bash
|
||||
|
||||
This method allows you to inject bash functions into the completion script. Those bash functions are responsible for providing the completion choices for your own completions.
|
||||
|
||||
Some more actual code that works in kubernetes:
|
||||
|
||||
```bash
|
||||
const (
|
||||
bash_completion_func = `__kubectl_parse_get()
|
||||
{
|
||||
local kubectl_output out
|
||||
if kubectl_output=$(kubectl get --no-headers "$1" 2>/dev/null); then
|
||||
out=($(echo "${kubectl_output}" | awk '{print $1}'))
|
||||
COMPREPLY=( $( compgen -W "${out[*]}" -- "$cur" ) )
|
||||
fi
|
||||
}
|
||||
|
||||
__kubectl_get_resource()
|
||||
{
|
||||
if [[ ${#nouns[@]} -eq 0 ]]; then
|
||||
return 1
|
||||
fi
|
||||
__kubectl_parse_get ${nouns[${#nouns[@]} -1]}
|
||||
if [[ $? -eq 0 ]]; then
|
||||
return 0
|
||||
fi
|
||||
}
|
||||
|
||||
__kubectl_custom_func() {
|
||||
case ${last_command} in
|
||||
kubectl_get | kubectl_describe | kubectl_delete | kubectl_stop)
|
||||
__kubectl_get_resource
|
||||
return
|
||||
;;
|
||||
*)
|
||||
;;
|
||||
esac
|
||||
}
|
||||
`)
|
||||
```
|
||||
|
||||
And then I set that in my command definition:
|
||||
|
||||
```go
|
||||
cmds := &cobra.Command{
|
||||
Use: "kubectl",
|
||||
Short: "kubectl controls the Kubernetes cluster manager",
|
||||
Long: `kubectl controls the Kubernetes cluster manager.
|
||||
|
||||
Find more information at https://github.com/GoogleCloudPlatform/kubernetes.`,
|
||||
Run: runHelp,
|
||||
BashCompletionFunction: bash_completion_func,
|
||||
}
|
||||
```
|
||||
|
||||
The `BashCompletionFunction` option is really only valid/useful on the root command. Doing the above will cause `__kubectl_custom_func()` (`__<command-use>_custom_func()`) to be called when the built in processor was unable to find a solution. In the case of kubernetes a valid command might look something like `kubectl get pod [mypod]`. If you type `kubectl get pod [tab][tab]` the `__kubectl_customc_func()` will run because the cobra.Command only understood "kubectl" and "get." `__kubectl_custom_func()` will see that the cobra.Command is "kubectl_get" and will thus call another helper `__kubectl_get_resource()`. `__kubectl_get_resource` will look at the 'nouns' collected. In our example the only noun will be `pod`. So it will call `__kubectl_parse_get pod`. `__kubectl_parse_get` will actually call out to kubernetes and get any pods. It will then set `COMPREPLY` to valid pods!
|
||||
|
||||
## Mark flags as required
|
||||
|
||||
Most of the time completions will only show subcommands. But if a flag is required to make a subcommand work, you probably want it to show up when the user types [tab][tab]. Marking a flag as 'Required' is incredibly easy.
|
||||
|
||||
```go
|
||||
cmd.MarkFlagRequired("pod")
|
||||
cmd.MarkFlagRequired("container")
|
||||
```
|
||||
|
||||
and you'll get something like
|
||||
|
||||
```bash
|
||||
# kubectl exec [tab][tab][tab]
|
||||
-c --container= -p --pod=
|
||||
```
|
||||
|
||||
# Specify valid filename extensions for flags that take a filename
|
||||
|
||||
In this example we use --filename= and expect to get a json or yaml file as the argument. To make this easier we annotate the --filename flag with valid filename extensions.
|
||||
|
||||
```go
|
||||
annotations := []string{"json", "yaml", "yml"}
|
||||
annotation := make(map[string][]string)
|
||||
annotation[cobra.BashCompFilenameExt] = annotations
|
||||
|
||||
flag := &pflag.Flag{
|
||||
Name: "filename",
|
||||
Shorthand: "f",
|
||||
Usage: usage,
|
||||
Value: value,
|
||||
DefValue: value.String(),
|
||||
Annotations: annotation,
|
||||
}
|
||||
cmd.Flags().AddFlag(flag)
|
||||
```
|
||||
|
||||
Now when you run a command with this filename flag you'll get something like
|
||||
|
||||
```bash
|
||||
# kubectl create -f
|
||||
test/ example/ rpmbuild/
|
||||
hello.yml test.json
|
||||
```
|
||||
|
||||
So while there are many other files in the CWD it only shows me subdirs and those with valid extensions.
|
||||
|
||||
# Specify custom flag completion
|
||||
|
||||
As for nouns, Cobra provides two ways of defining dynamic completion of flags. Note that both these methods can be used along-side each other as long as they are not both used for the same flag.
|
||||
|
||||
**Note**: *Custom Completions written in Go* will automatically work for other shell-completion scripts (e.g., Fish shell), while *Custom Completions written in Bash* will only work for Bash shell-completion. It is therefore recommended to use *Custom Completions written in Go*.
|
||||
|
||||
## 1. Custom completions of flags written in Go
|
||||
|
||||
To provide a Go function that Cobra will execute when it needs the list of completion choices for a flag, you must register the function in the following manner:
|
||||
|
||||
```go
|
||||
flagName := "output"
|
||||
cmd.RegisterFlagCompletionFunc(flagName, func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
|
||||
return []string{"json", "table", "yaml"}, cobra.ShellCompDirectiveDefault
|
||||
})
|
||||
```
|
||||
Notice that calling `RegisterFlagCompletionFunc()` is done through the `command` with which the flag is associated. In our example this dynamic completion will give results like so:
|
||||
|
||||
```bash
|
||||
# helm status --output [tab][tab]
|
||||
json table yaml
|
||||
```
|
||||
|
||||
### Debugging
|
||||
|
||||
You can also easily debug your Go completion code for flags:
|
||||
```bash
|
||||
# helm __complete status --output ""
|
||||
json
|
||||
table
|
||||
yaml
|
||||
:4
|
||||
Completion ended with directive: ShellCompDirectiveNoFileComp # This is on stderr
|
||||
```
|
||||
***Important:*** You should **not** leave traces that print to stdout in your completion code as they will be interpreted as completion choices by the completion script. Instead, use the cobra-provided debugging traces functions mentioned in the above section.
|
||||
|
||||
## 2. Custom completions of flags written in Bash
|
||||
|
||||
Alternatively, you can use bash code for flag custom completion. Similar to the filename
|
||||
completion and filtering using `cobra.BashCompFilenameExt`, you can specify
|
||||
a custom flag completion bash function with `cobra.BashCompCustom`:
|
||||
|
||||
```go
|
||||
annotation := make(map[string][]string)
|
||||
annotation[cobra.BashCompCustom] = []string{"__kubectl_get_namespaces"}
|
||||
|
||||
flag := &pflag.Flag{
|
||||
Name: "namespace",
|
||||
Usage: usage,
|
||||
Annotations: annotation,
|
||||
}
|
||||
cmd.Flags().AddFlag(flag)
|
||||
```
|
||||
|
||||
In addition add the `__kubectl_get_namespaces` implementation in the `BashCompletionFunction`
|
||||
value, e.g.:
|
||||
|
||||
```bash
|
||||
__kubectl_get_namespaces()
|
||||
{
|
||||
local template
|
||||
template="{{ range .items }}{{ .metadata.name }} {{ end }}"
|
||||
local kubectl_out
|
||||
if kubectl_out=$(kubectl get -o template --template="${template}" namespace 2>/dev/null); then
|
||||
COMPREPLY=( $( compgen -W "${kubectl_out}[*]" -- "$cur" ) )
|
||||
fi
|
||||
}
|
||||
```
|
||||
# Using bash aliases for commands
|
||||
|
||||
You can also configure the `bash aliases` for the commands and they will also support completions.
|
||||
|
||||
```bash
|
||||
alias aliasname=origcommand
|
||||
complete -o default -F __start_origcommand aliasname
|
||||
|
||||
# and now when you run `aliasname` completion will make
|
||||
# suggestions as it did for `origcommand`.
|
||||
|
||||
$) aliasname <tab><tab>
|
||||
completion firstcommand secondcommand
|
||||
```
|
|
@ -0,0 +1,207 @@
|
|||
// Copyright © 2013 Steve Francia <spf@spf13.com>.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
// Commands similar to git, go tools and other modern CLI tools
|
||||
// inspired by go, go-Commander, gh and subcommand
|
||||
|
||||
package cobra
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"text/template"
|
||||
"time"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
var templateFuncs = template.FuncMap{
|
||||
"trim": strings.TrimSpace,
|
||||
"trimRightSpace": trimRightSpace,
|
||||
"trimTrailingWhitespaces": trimRightSpace,
|
||||
"appendIfNotPresent": appendIfNotPresent,
|
||||
"rpad": rpad,
|
||||
"gt": Gt,
|
||||
"eq": Eq,
|
||||
}
|
||||
|
||||
var initializers []func()
|
||||
|
||||
// EnablePrefixMatching allows to set automatic prefix matching. Automatic prefix matching can be a dangerous thing
|
||||
// to automatically enable in CLI tools.
|
||||
// Set this to true to enable it.
|
||||
var EnablePrefixMatching = false
|
||||
|
||||
// EnableCommandSorting controls sorting of the slice of commands, which is turned on by default.
|
||||
// To disable sorting, set it to false.
|
||||
var EnableCommandSorting = true
|
||||
|
||||
// MousetrapHelpText enables an information splash screen on Windows
|
||||
// if the CLI is started from explorer.exe.
|
||||
// To disable the mousetrap, just set this variable to blank string ("").
|
||||
// Works only on Microsoft Windows.
|
||||
var MousetrapHelpText = `This is a command line tool.
|
||||
|
||||
You need to open cmd.exe and run it from there.
|
||||
`
|
||||
|
||||
// MousetrapDisplayDuration controls how long the MousetrapHelpText message is displayed on Windows
|
||||
// if the CLI is started from explorer.exe. Set to 0 to wait for the return key to be pressed.
|
||||
// To disable the mousetrap, just set MousetrapHelpText to blank string ("").
|
||||
// Works only on Microsoft Windows.
|
||||
var MousetrapDisplayDuration = 5 * time.Second
|
||||
|
||||
// AddTemplateFunc adds a template function that's available to Usage and Help
|
||||
// template generation.
|
||||
func AddTemplateFunc(name string, tmplFunc interface{}) {
|
||||
templateFuncs[name] = tmplFunc
|
||||
}
|
||||
|
||||
// AddTemplateFuncs adds multiple template functions that are available to Usage and
|
||||
// Help template generation.
|
||||
func AddTemplateFuncs(tmplFuncs template.FuncMap) {
|
||||
for k, v := range tmplFuncs {
|
||||
templateFuncs[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
// OnInitialize sets the passed functions to be run when each command's
|
||||
// Execute method is called.
|
||||
func OnInitialize(y ...func()) {
|
||||
initializers = append(initializers, y...)
|
||||
}
|
||||
|
||||
// FIXME Gt is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.
|
||||
|
||||
// Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans,
|
||||
// Maps and Slices, Gt will compare their lengths. Ints are compared directly while strings are first parsed as
|
||||
// ints and then compared.
|
||||
func Gt(a interface{}, b interface{}) bool {
|
||||
var left, right int64
|
||||
av := reflect.ValueOf(a)
|
||||
|
||||
switch av.Kind() {
|
||||
case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
|
||||
left = int64(av.Len())
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
left = av.Int()
|
||||
case reflect.String:
|
||||
left, _ = strconv.ParseInt(av.String(), 10, 64)
|
||||
}
|
||||
|
||||
bv := reflect.ValueOf(b)
|
||||
|
||||
switch bv.Kind() {
|
||||
case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
|
||||
right = int64(bv.Len())
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
right = bv.Int()
|
||||
case reflect.String:
|
||||
right, _ = strconv.ParseInt(bv.String(), 10, 64)
|
||||
}
|
||||
|
||||
return left > right
|
||||
}
|
||||
|
||||
// FIXME Eq is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.
|
||||
|
||||
// Eq takes two types and checks whether they are equal. Supported types are int and string. Unsupported types will panic.
|
||||
func Eq(a interface{}, b interface{}) bool {
|
||||
av := reflect.ValueOf(a)
|
||||
bv := reflect.ValueOf(b)
|
||||
|
||||
switch av.Kind() {
|
||||
case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
|
||||
panic("Eq called on unsupported type")
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
return av.Int() == bv.Int()
|
||||
case reflect.String:
|
||||
return av.String() == bv.String()
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func trimRightSpace(s string) string {
|
||||
return strings.TrimRightFunc(s, unicode.IsSpace)
|
||||
}
|
||||
|
||||
// FIXME appendIfNotPresent is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.
|
||||
|
||||
// appendIfNotPresent will append stringToAppend to the end of s, but only if it's not yet present in s.
|
||||
func appendIfNotPresent(s, stringToAppend string) string {
|
||||
if strings.Contains(s, stringToAppend) {
|
||||
return s
|
||||
}
|
||||
return s + " " + stringToAppend
|
||||
}
|
||||
|
||||
// rpad adds padding to the right of a string.
|
||||
func rpad(s string, padding int) string {
|
||||
template := fmt.Sprintf("%%-%ds", padding)
|
||||
return fmt.Sprintf(template, s)
|
||||
}
|
||||
|
||||
// tmpl executes the given template text on data, writing the result to w.
|
||||
func tmpl(w io.Writer, text string, data interface{}) error {
|
||||
t := template.New("top")
|
||||
t.Funcs(templateFuncs)
|
||||
template.Must(t.Parse(text))
|
||||
return t.Execute(w, data)
|
||||
}
|
||||
|
||||
// ld compares two strings and returns the levenshtein distance between them.
|
||||
func ld(s, t string, ignoreCase bool) int {
|
||||
if ignoreCase {
|
||||
s = strings.ToLower(s)
|
||||
t = strings.ToLower(t)
|
||||
}
|
||||
d := make([][]int, len(s)+1)
|
||||
for i := range d {
|
||||
d[i] = make([]int, len(t)+1)
|
||||
}
|
||||
for i := range d {
|
||||
d[i][0] = i
|
||||
}
|
||||
for j := range d[0] {
|
||||
d[0][j] = j
|
||||
}
|
||||
for j := 1; j <= len(t); j++ {
|
||||
for i := 1; i <= len(s); i++ {
|
||||
if s[i-1] == t[j-1] {
|
||||
d[i][j] = d[i-1][j-1]
|
||||
} else {
|
||||
min := d[i-1][j]
|
||||
if d[i][j-1] < min {
|
||||
min = d[i][j-1]
|
||||
}
|
||||
if d[i-1][j-1] < min {
|
||||
min = d[i-1][j-1]
|
||||
}
|
||||
d[i][j] = min + 1
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
return d[len(s)][len(t)]
|
||||
}
|
||||
|
||||
func stringInSlice(a string, list []string) bool {
|
||||
for _, b := range list {
|
||||
if b == a {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
202
vendor/github.com/spf13/cobra/cobra/cmd/testdata/LICENSE.golden
сгенерированный
поставляемый
Normal file
202
vendor/github.com/spf13/cobra/cobra/cmd/testdata/LICENSE.golden
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,202 @@
|
|||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
|
@ -0,0 +1,5 @@
|
|||
// +build !windows
|
||||
|
||||
package cobra
|
||||
|
||||
var preExecHookFn func(*Command)
|
|
@ -0,0 +1,26 @@
|
|||
// +build windows
|
||||
|
||||
package cobra
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/inconshreveable/mousetrap"
|
||||
)
|
||||
|
||||
var preExecHookFn = preExecHook
|
||||
|
||||
func preExecHook(c *Command) {
|
||||
if MousetrapHelpText != "" && mousetrap.StartedByExplorer() {
|
||||
c.Print(MousetrapHelpText)
|
||||
if MousetrapDisplayDuration > 0 {
|
||||
time.Sleep(MousetrapDisplayDuration)
|
||||
} else {
|
||||
c.Println("Press return to continue...")
|
||||
fmt.Scanln()
|
||||
}
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
|
@ -0,0 +1,384 @@
|
|||
package cobra
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
const (
|
||||
// ShellCompRequestCmd is the name of the hidden command that is used to request
|
||||
// completion results from the program. It is used by the shell completion scripts.
|
||||
ShellCompRequestCmd = "__complete"
|
||||
// ShellCompNoDescRequestCmd is the name of the hidden command that is used to request
|
||||
// completion results without their description. It is used by the shell completion scripts.
|
||||
ShellCompNoDescRequestCmd = "__completeNoDesc"
|
||||
)
|
||||
|
||||
// Global map of flag completion functions.
|
||||
var flagCompletionFunctions = map[*pflag.Flag]func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective){}
|
||||
|
||||
// ShellCompDirective is a bit map representing the different behaviors the shell
|
||||
// can be instructed to have once completions have been provided.
|
||||
type ShellCompDirective int
|
||||
|
||||
const (
|
||||
// ShellCompDirectiveError indicates an error occurred and completions should be ignored.
|
||||
ShellCompDirectiveError ShellCompDirective = 1 << iota
|
||||
|
||||
// ShellCompDirectiveNoSpace indicates that the shell should not add a space
|
||||
// after the completion even if there is a single completion provided.
|
||||
ShellCompDirectiveNoSpace
|
||||
|
||||
// ShellCompDirectiveNoFileComp indicates that the shell should not provide
|
||||
// file completion even when no completion is provided.
|
||||
// This currently does not work for zsh or bash < 4
|
||||
ShellCompDirectiveNoFileComp
|
||||
|
||||
// ShellCompDirectiveDefault indicates to let the shell perform its default
|
||||
// behavior after completions have been provided.
|
||||
ShellCompDirectiveDefault ShellCompDirective = 0
|
||||
)
|
||||
|
||||
// RegisterFlagCompletionFunc should be called to register a function to provide completion for a flag.
|
||||
func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)) error {
|
||||
flag := c.Flag(flagName)
|
||||
if flag == nil {
|
||||
return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' does not exist", flagName)
|
||||
}
|
||||
if _, exists := flagCompletionFunctions[flag]; exists {
|
||||
return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' already registered", flagName)
|
||||
}
|
||||
flagCompletionFunctions[flag] = f
|
||||
return nil
|
||||
}
|
||||
|
||||
// Returns a string listing the different directive enabled in the specified parameter
|
||||
func (d ShellCompDirective) string() string {
|
||||
var directives []string
|
||||
if d&ShellCompDirectiveError != 0 {
|
||||
directives = append(directives, "ShellCompDirectiveError")
|
||||
}
|
||||
if d&ShellCompDirectiveNoSpace != 0 {
|
||||
directives = append(directives, "ShellCompDirectiveNoSpace")
|
||||
}
|
||||
if d&ShellCompDirectiveNoFileComp != 0 {
|
||||
directives = append(directives, "ShellCompDirectiveNoFileComp")
|
||||
}
|
||||
if len(directives) == 0 {
|
||||
directives = append(directives, "ShellCompDirectiveDefault")
|
||||
}
|
||||
|
||||
if d > ShellCompDirectiveError+ShellCompDirectiveNoSpace+ShellCompDirectiveNoFileComp {
|
||||
return fmt.Sprintf("ERROR: unexpected ShellCompDirective value: %d", d)
|
||||
}
|
||||
return strings.Join(directives, ", ")
|
||||
}
|
||||
|
||||
// Adds a special hidden command that can be used to request custom completions.
|
||||
func (c *Command) initCompleteCmd(args []string) {
|
||||
completeCmd := &Command{
|
||||
Use: fmt.Sprintf("%s [command-line]", ShellCompRequestCmd),
|
||||
Aliases: []string{ShellCompNoDescRequestCmd},
|
||||
DisableFlagsInUseLine: true,
|
||||
Hidden: true,
|
||||
DisableFlagParsing: true,
|
||||
Args: MinimumNArgs(1),
|
||||
Short: "Request shell completion choices for the specified command-line",
|
||||
Long: fmt.Sprintf("%[2]s is a special command that is used by the shell completion logic\n%[1]s",
|
||||
"to request completion choices for the specified command-line.", ShellCompRequestCmd),
|
||||
Run: func(cmd *Command, args []string) {
|
||||
finalCmd, completions, directive, err := cmd.getCompletions(args)
|
||||
if err != nil {
|
||||
CompErrorln(err.Error())
|
||||
// Keep going for multiple reasons:
|
||||
// 1- There could be some valid completions even though there was an error
|
||||
// 2- Even without completions, we need to print the directive
|
||||
}
|
||||
|
||||
noDescriptions := (cmd.CalledAs() == ShellCompNoDescRequestCmd)
|
||||
for _, comp := range completions {
|
||||
if noDescriptions {
|
||||
// Remove any description that may be included following a tab character.
|
||||
comp = strings.Split(comp, "\t")[0]
|
||||
}
|
||||
// Print each possible completion to stdout for the completion script to consume.
|
||||
fmt.Fprintln(finalCmd.OutOrStdout(), comp)
|
||||
}
|
||||
|
||||
if directive > ShellCompDirectiveError+ShellCompDirectiveNoSpace+ShellCompDirectiveNoFileComp {
|
||||
directive = ShellCompDirectiveDefault
|
||||
}
|
||||
|
||||
// As the last printout, print the completion directive for the completion script to parse.
|
||||
// The directive integer must be that last character following a single colon (:).
|
||||
// The completion script expects :<directive>
|
||||
fmt.Fprintf(finalCmd.OutOrStdout(), ":%d\n", directive)
|
||||
|
||||
// Print some helpful info to stderr for the user to understand.
|
||||
// Output from stderr must be ignored by the completion script.
|
||||
fmt.Fprintf(finalCmd.ErrOrStderr(), "Completion ended with directive: %s\n", directive.string())
|
||||
},
|
||||
}
|
||||
c.AddCommand(completeCmd)
|
||||
subCmd, _, err := c.Find(args)
|
||||
if err != nil || subCmd.Name() != ShellCompRequestCmd {
|
||||
// Only create this special command if it is actually being called.
|
||||
// This reduces possible side-effects of creating such a command;
|
||||
// for example, having this command would cause problems to a
|
||||
// cobra program that only consists of the root command, since this
|
||||
// command would cause the root command to suddenly have a subcommand.
|
||||
c.RemoveCommand(completeCmd)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDirective, error) {
|
||||
var completions []string
|
||||
|
||||
// The last argument, which is not completely typed by the user,
|
||||
// should not be part of the list of arguments
|
||||
toComplete := args[len(args)-1]
|
||||
trimmedArgs := args[:len(args)-1]
|
||||
|
||||
// Find the real command for which completion must be performed
|
||||
finalCmd, finalArgs, err := c.Root().Find(trimmedArgs)
|
||||
if err != nil {
|
||||
// Unable to find the real command. E.g., <program> someInvalidCmd <TAB>
|
||||
return c, completions, ShellCompDirectiveDefault, fmt.Errorf("Unable to find a command for arguments: %v", trimmedArgs)
|
||||
}
|
||||
|
||||
// When doing completion of a flag name, as soon as an argument starts with
|
||||
// a '-' we know it is a flag. We cannot use isFlagArg() here as it requires
|
||||
// the flag to be complete
|
||||
if len(toComplete) > 0 && toComplete[0] == '-' && !strings.Contains(toComplete, "=") {
|
||||
// We are completing a flag name
|
||||
finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {
|
||||
completions = append(completions, getFlagNameCompletions(flag, toComplete)...)
|
||||
})
|
||||
finalCmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {
|
||||
completions = append(completions, getFlagNameCompletions(flag, toComplete)...)
|
||||
})
|
||||
|
||||
directive := ShellCompDirectiveDefault
|
||||
if len(completions) > 0 {
|
||||
if strings.HasSuffix(completions[0], "=") {
|
||||
directive = ShellCompDirectiveNoSpace
|
||||
}
|
||||
}
|
||||
return finalCmd, completions, directive, nil
|
||||
}
|
||||
|
||||
var flag *pflag.Flag
|
||||
if !finalCmd.DisableFlagParsing {
|
||||
// We only do flag completion if we are allowed to parse flags
|
||||
// This is important for commands which have requested to do their own flag completion.
|
||||
flag, finalArgs, toComplete, err = checkIfFlagCompletion(finalCmd, finalArgs, toComplete)
|
||||
if err != nil {
|
||||
// Error while attempting to parse flags
|
||||
return finalCmd, completions, ShellCompDirectiveDefault, err
|
||||
}
|
||||
}
|
||||
|
||||
if flag == nil {
|
||||
// Complete subcommand names
|
||||
for _, subCmd := range finalCmd.Commands() {
|
||||
if subCmd.IsAvailableCommand() && strings.HasPrefix(subCmd.Name(), toComplete) {
|
||||
completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))
|
||||
}
|
||||
}
|
||||
|
||||
if len(finalCmd.ValidArgs) > 0 {
|
||||
// Always complete ValidArgs, even if we are completing a subcommand name.
|
||||
// This is for commands that have both subcommands and ValidArgs.
|
||||
for _, validArg := range finalCmd.ValidArgs {
|
||||
if strings.HasPrefix(validArg, toComplete) {
|
||||
completions = append(completions, validArg)
|
||||
}
|
||||
}
|
||||
|
||||
// If there are ValidArgs specified (even if they don't match), we stop completion.
|
||||
// Only one of ValidArgs or ValidArgsFunction can be used for a single command.
|
||||
return finalCmd, completions, ShellCompDirectiveNoFileComp, nil
|
||||
}
|
||||
|
||||
// Always let the logic continue so as to add any ValidArgsFunction completions,
|
||||
// even if we already found sub-commands.
|
||||
// This is for commands that have subcommands but also specify a ValidArgsFunction.
|
||||
}
|
||||
|
||||
// Parse the flags and extract the arguments to prepare for calling the completion function
|
||||
if err = finalCmd.ParseFlags(finalArgs); err != nil {
|
||||
return finalCmd, completions, ShellCompDirectiveDefault, fmt.Errorf("Error while parsing flags from args %v: %s", finalArgs, err.Error())
|
||||
}
|
||||
|
||||
// We only remove the flags from the arguments if DisableFlagParsing is not set.
|
||||
// This is important for commands which have requested to do their own flag completion.
|
||||
if !finalCmd.DisableFlagParsing {
|
||||
finalArgs = finalCmd.Flags().Args()
|
||||
}
|
||||
|
||||
// Find the completion function for the flag or command
|
||||
var completionFn func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)
|
||||
if flag != nil {
|
||||
completionFn = flagCompletionFunctions[flag]
|
||||
} else {
|
||||
completionFn = finalCmd.ValidArgsFunction
|
||||
}
|
||||
if completionFn == nil {
|
||||
// Go custom completion not supported/needed for this flag or command
|
||||
return finalCmd, completions, ShellCompDirectiveDefault, nil
|
||||
}
|
||||
|
||||
// Call the registered completion function to get the completions
|
||||
comps, directive := completionFn(finalCmd, finalArgs, toComplete)
|
||||
completions = append(completions, comps...)
|
||||
return finalCmd, completions, directive, nil
|
||||
}
|
||||
|
||||
func getFlagNameCompletions(flag *pflag.Flag, toComplete string) []string {
|
||||
if nonCompletableFlag(flag) {
|
||||
return []string{}
|
||||
}
|
||||
|
||||
var completions []string
|
||||
flagName := "--" + flag.Name
|
||||
if strings.HasPrefix(flagName, toComplete) {
|
||||
// Flag without the =
|
||||
completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))
|
||||
|
||||
if len(flag.NoOptDefVal) == 0 {
|
||||
// Flag requires a value, so it can be suffixed with =
|
||||
flagName += "="
|
||||
completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))
|
||||
}
|
||||
}
|
||||
|
||||
flagName = "-" + flag.Shorthand
|
||||
if len(flag.Shorthand) > 0 && strings.HasPrefix(flagName, toComplete) {
|
||||
completions = append(completions, fmt.Sprintf("%s\t%s", flagName, flag.Usage))
|
||||
}
|
||||
|
||||
return completions
|
||||
}
|
||||
|
||||
func checkIfFlagCompletion(finalCmd *Command, args []string, lastArg string) (*pflag.Flag, []string, string, error) {
|
||||
var flagName string
|
||||
trimmedArgs := args
|
||||
flagWithEqual := false
|
||||
if isFlagArg(lastArg) {
|
||||
if index := strings.Index(lastArg, "="); index >= 0 {
|
||||
flagName = strings.TrimLeft(lastArg[:index], "-")
|
||||
lastArg = lastArg[index+1:]
|
||||
flagWithEqual = true
|
||||
} else {
|
||||
return nil, nil, "", errors.New("Unexpected completion request for flag")
|
||||
}
|
||||
}
|
||||
|
||||
if len(flagName) == 0 {
|
||||
if len(args) > 0 {
|
||||
prevArg := args[len(args)-1]
|
||||
if isFlagArg(prevArg) {
|
||||
// Only consider the case where the flag does not contain an =.
|
||||
// If the flag contains an = it means it has already been fully processed,
|
||||
// so we don't need to deal with it here.
|
||||
if index := strings.Index(prevArg, "="); index < 0 {
|
||||
flagName = strings.TrimLeft(prevArg, "-")
|
||||
|
||||
// Remove the uncompleted flag or else there could be an error created
|
||||
// for an invalid value for that flag
|
||||
trimmedArgs = args[:len(args)-1]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(flagName) == 0 {
|
||||
// Not doing flag completion
|
||||
return nil, trimmedArgs, lastArg, nil
|
||||
}
|
||||
|
||||
flag := findFlag(finalCmd, flagName)
|
||||
if flag == nil {
|
||||
// Flag not supported by this command, nothing to complete
|
||||
err := fmt.Errorf("Subcommand '%s' does not support flag '%s'", finalCmd.Name(), flagName)
|
||||
return nil, nil, "", err
|
||||
}
|
||||
|
||||
if !flagWithEqual {
|
||||
if len(flag.NoOptDefVal) != 0 {
|
||||
// We had assumed dealing with a two-word flag but the flag is a boolean flag.
|
||||
// In that case, there is no value following it, so we are not really doing flag completion.
|
||||
// Reset everything to do noun completion.
|
||||
trimmedArgs = args
|
||||
flag = nil
|
||||
}
|
||||
}
|
||||
|
||||
return flag, trimmedArgs, lastArg, nil
|
||||
}
|
||||
|
||||
func findFlag(cmd *Command, name string) *pflag.Flag {
|
||||
flagSet := cmd.Flags()
|
||||
if len(name) == 1 {
|
||||
// First convert the short flag into a long flag
|
||||
// as the cmd.Flag() search only accepts long flags
|
||||
if short := flagSet.ShorthandLookup(name); short != nil {
|
||||
name = short.Name
|
||||
} else {
|
||||
set := cmd.InheritedFlags()
|
||||
if short = set.ShorthandLookup(name); short != nil {
|
||||
name = short.Name
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return cmd.Flag(name)
|
||||
}
|
||||
|
||||
// CompDebug prints the specified string to the same file as where the
|
||||
// completion script prints its logs.
|
||||
// Note that completion printouts should never be on stdout as they would
|
||||
// be wrongly interpreted as actual completion choices by the completion script.
|
||||
func CompDebug(msg string, printToStdErr bool) {
|
||||
msg = fmt.Sprintf("[Debug] %s", msg)
|
||||
|
||||
// Such logs are only printed when the user has set the environment
|
||||
// variable BASH_COMP_DEBUG_FILE to the path of some file to be used.
|
||||
if path := os.Getenv("BASH_COMP_DEBUG_FILE"); path != "" {
|
||||
f, err := os.OpenFile(path,
|
||||
os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
|
||||
if err == nil {
|
||||
defer f.Close()
|
||||
f.WriteString(msg)
|
||||
}
|
||||
}
|
||||
|
||||
if printToStdErr {
|
||||
// Must print to stderr for this not to be read by the completion script.
|
||||
fmt.Fprintf(os.Stderr, msg)
|
||||
}
|
||||
}
|
||||
|
||||
// CompDebugln prints the specified string with a newline at the end
|
||||
// to the same file as where the completion script prints its logs.
|
||||
// Such logs are only printed when the user has set the environment
|
||||
// variable BASH_COMP_DEBUG_FILE to the path of some file to be used.
|
||||
func CompDebugln(msg string, printToStdErr bool) {
|
||||
CompDebug(fmt.Sprintf("%s\n", msg), printToStdErr)
|
||||
}
|
||||
|
||||
// CompError prints the specified completion message to stderr.
|
||||
func CompError(msg string) {
|
||||
msg = fmt.Sprintf("[Error] %s", msg)
|
||||
CompDebug(msg, true)
|
||||
}
|
||||
|
||||
// CompErrorln prints the specified completion message to stderr with a newline at the end.
|
||||
func CompErrorln(msg string) {
|
||||
CompError(fmt.Sprintf("%s\n", msg))
|
||||
}
|
|
@ -0,0 +1,172 @@
|
|||
package cobra
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
func genFishComp(buf *bytes.Buffer, name string, includeDesc bool) {
|
||||
compCmd := ShellCompRequestCmd
|
||||
if !includeDesc {
|
||||
compCmd = ShellCompNoDescRequestCmd
|
||||
}
|
||||
buf.WriteString(fmt.Sprintf("# fish completion for %-36s -*- shell-script -*-\n", name))
|
||||
buf.WriteString(fmt.Sprintf(`
|
||||
function __%[1]s_debug
|
||||
set file "$BASH_COMP_DEBUG_FILE"
|
||||
if test -n "$file"
|
||||
echo "$argv" >> $file
|
||||
end
|
||||
end
|
||||
|
||||
function __%[1]s_perform_completion
|
||||
__%[1]s_debug "Starting __%[1]s_perform_completion with: $argv"
|
||||
|
||||
set args (string split -- " " "$argv")
|
||||
set lastArg "$args[-1]"
|
||||
|
||||
__%[1]s_debug "args: $args"
|
||||
__%[1]s_debug "last arg: $lastArg"
|
||||
|
||||
set emptyArg ""
|
||||
if test -z "$lastArg"
|
||||
__%[1]s_debug "Setting emptyArg"
|
||||
set emptyArg \"\"
|
||||
end
|
||||
__%[1]s_debug "emptyArg: $emptyArg"
|
||||
|
||||
set requestComp "$args[1] %[2]s $args[2..-1] $emptyArg"
|
||||
__%[1]s_debug "Calling $requestComp"
|
||||
|
||||
set results (eval $requestComp 2> /dev/null)
|
||||
set comps $results[1..-2]
|
||||
set directiveLine $results[-1]
|
||||
|
||||
# For Fish, when completing a flag with an = (e.g., <program> -n=<TAB>)
|
||||
# completions must be prefixed with the flag
|
||||
set flagPrefix (string match -r -- '-.*=' "$lastArg")
|
||||
|
||||
__%[1]s_debug "Comps: $comps"
|
||||
__%[1]s_debug "DirectiveLine: $directiveLine"
|
||||
__%[1]s_debug "flagPrefix: $flagPrefix"
|
||||
|
||||
for comp in $comps
|
||||
printf "%%s%%s\n" "$flagPrefix" "$comp"
|
||||
end
|
||||
|
||||
printf "%%s\n" "$directiveLine"
|
||||
end
|
||||
|
||||
# This function does three things:
|
||||
# 1- Obtain the completions and store them in the global __%[1]s_comp_results
|
||||
# 2- Set the __%[1]s_comp_do_file_comp flag if file completion should be performed
|
||||
# and unset it otherwise
|
||||
# 3- Return true if the completion results are not empty
|
||||
function __%[1]s_prepare_completions
|
||||
# Start fresh
|
||||
set --erase __%[1]s_comp_do_file_comp
|
||||
set --erase __%[1]s_comp_results
|
||||
|
||||
# Check if the command-line is already provided. This is useful for testing.
|
||||
if not set --query __%[1]s_comp_commandLine
|
||||
set __%[1]s_comp_commandLine (commandline)
|
||||
end
|
||||
__%[1]s_debug "commandLine is: $__%[1]s_comp_commandLine"
|
||||
|
||||
set results (__%[1]s_perform_completion "$__%[1]s_comp_commandLine")
|
||||
set --erase __%[1]s_comp_commandLine
|
||||
__%[1]s_debug "Completion results: $results"
|
||||
|
||||
if test -z "$results"
|
||||
__%[1]s_debug "No completion, probably due to a failure"
|
||||
# Might as well do file completion, in case it helps
|
||||
set --global __%[1]s_comp_do_file_comp 1
|
||||
return 0
|
||||
end
|
||||
|
||||
set directive (string sub --start 2 $results[-1])
|
||||
set --global __%[1]s_comp_results $results[1..-2]
|
||||
|
||||
__%[1]s_debug "Completions are: $__%[1]s_comp_results"
|
||||
__%[1]s_debug "Directive is: $directive"
|
||||
|
||||
if test -z "$directive"
|
||||
set directive 0
|
||||
end
|
||||
|
||||
set compErr (math (math --scale 0 $directive / %[3]d) %% 2)
|
||||
if test $compErr -eq 1
|
||||
__%[1]s_debug "Received error directive: aborting."
|
||||
# Might as well do file completion, in case it helps
|
||||
set --global __%[1]s_comp_do_file_comp 1
|
||||
return 0
|
||||
end
|
||||
|
||||
set nospace (math (math --scale 0 $directive / %[4]d) %% 2)
|
||||
set nofiles (math (math --scale 0 $directive / %[5]d) %% 2)
|
||||
|
||||
__%[1]s_debug "nospace: $nospace, nofiles: $nofiles"
|
||||
|
||||
# Important not to quote the variable for count to work
|
||||
set numComps (count $__%[1]s_comp_results)
|
||||
__%[1]s_debug "numComps: $numComps"
|
||||
|
||||
if test $numComps -eq 1; and test $nospace -ne 0
|
||||
# To support the "nospace" directive we trick the shell
|
||||
# by outputting an extra, longer completion.
|
||||
__%[1]s_debug "Adding second completion to perform nospace directive"
|
||||
set --append __%[1]s_comp_results $__%[1]s_comp_results[1].
|
||||
end
|
||||
|
||||
if test $numComps -eq 0; and test $nofiles -eq 0
|
||||
__%[1]s_debug "Requesting file completion"
|
||||
set --global __%[1]s_comp_do_file_comp 1
|
||||
end
|
||||
|
||||
# If we don't want file completion, we must return true even if there
|
||||
# are no completions found. This is because fish will perform the last
|
||||
# completion command, even if its condition is false, if no other
|
||||
# completion command was triggered
|
||||
return (not set --query __%[1]s_comp_do_file_comp)
|
||||
end
|
||||
|
||||
# Remove any pre-existing completions for the program since we will be handling all of them
|
||||
# TODO this cleanup is not sufficient. Fish completions are only loaded once the user triggers
|
||||
# them, so the below deletion will not work as it is run too early. What else can we do?
|
||||
complete -c %[1]s -e
|
||||
|
||||
# The order in which the below two lines are defined is very important so that __%[1]s_prepare_completions
|
||||
# is called first. It is __%[1]s_prepare_completions that sets up the __%[1]s_comp_do_file_comp variable.
|
||||
#
|
||||
# This completion will be run second as complete commands are added FILO.
|
||||
# It triggers file completion choices when __%[1]s_comp_do_file_comp is set.
|
||||
complete -c %[1]s -n 'set --query __%[1]s_comp_do_file_comp'
|
||||
|
||||
# This completion will be run first as complete commands are added FILO.
|
||||
# The call to __%[1]s_prepare_completions will setup both __%[1]s_comp_results abd __%[1]s_comp_do_file_comp.
|
||||
# It provides the program's completion choices.
|
||||
complete -c %[1]s -n '__%[1]s_prepare_completions' -f -a '$__%[1]s_comp_results'
|
||||
|
||||
`, name, compCmd, ShellCompDirectiveError, ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp))
|
||||
}
|
||||
|
||||
// GenFishCompletion generates fish completion file and writes to the passed writer.
|
||||
func (c *Command) GenFishCompletion(w io.Writer, includeDesc bool) error {
|
||||
buf := new(bytes.Buffer)
|
||||
genFishComp(buf, c.Name(), includeDesc)
|
||||
_, err := buf.WriteTo(w)
|
||||
return err
|
||||
}
|
||||
|
||||
// GenFishCompletionFile generates fish completion file.
|
||||
func (c *Command) GenFishCompletionFile(filename string, includeDesc bool) error {
|
||||
outFile, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer outFile.Close()
|
||||
|
||||
return c.GenFishCompletion(outFile, includeDesc)
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
## Generating Fish Completions for your own cobra.Command
|
||||
|
||||
Cobra supports native Fish completions generated from the root `cobra.Command`. You can use the `command.GenFishCompletion()` or `command.GenFishCompletionFile()` functions. You must provide these functions with a parameter indicating if the completions should be annotated with a description; Cobra will provide the description automatically based on usage information. You can choose to make this option configurable by your users.
|
||||
|
||||
### Limitations
|
||||
|
||||
* Custom completions implemented using the `ValidArgsFunction` and `RegisterFlagCompletionFunc()` are supported automatically but the ones implemented in Bash scripting are not.
|
|
@ -0,0 +1,12 @@
|
|||
module github.com/spf13/cobra
|
||||
|
||||
go 1.12
|
||||
|
||||
require (
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.0
|
||||
github.com/inconshreveable/mousetrap v1.0.0
|
||||
github.com/mitchellh/go-homedir v1.1.0
|
||||
github.com/spf13/pflag v1.0.3
|
||||
github.com/spf13/viper v1.4.0
|
||||
gopkg.in/yaml.v2 v2.2.2
|
||||
)
|
|
@ -0,0 +1,149 @@
|
|||
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
|
||||
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
|
||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
|
||||
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
|
||||
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
|
||||
github.com/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8=
|
||||
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
|
||||
github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
|
||||
github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc=
|
||||
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
|
||||
github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk=
|
||||
github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE=
|
||||
github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
|
||||
github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
|
||||
github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.0 h1:EoUDS0afbrsXAZ9YQ9jdu/mZ2sXgT1/2yyNng4PGlyM=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
|
||||
github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no=
|
||||
github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
|
||||
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
|
||||
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
|
||||
github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
|
||||
github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
|
||||
github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
|
||||
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
|
||||
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
|
||||
github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4=
|
||||
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
|
||||
github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
|
||||
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
|
||||
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
|
||||
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
|
||||
github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
|
||||
github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs=
|
||||
github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk=
|
||||
github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY=
|
||||
github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
|
||||
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
|
||||
github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
|
||||
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
|
||||
github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo=
|
||||
github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
|
||||
github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q=
|
||||
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
|
||||
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/magiconair/properties v1.8.0 h1:LLgXmsheXeRoUOBOjtwPQCWIYqM/LU1ayDtDePerRcY=
|
||||
github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
|
||||
github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
|
||||
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
|
||||
github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE=
|
||||
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
|
||||
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
|
||||
github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U=
|
||||
github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc=
|
||||
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
|
||||
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
|
||||
github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso=
|
||||
github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
|
||||
github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
|
||||
github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro=
|
||||
github.com/prometheus/common v0.4.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4=
|
||||
github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
|
||||
github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
|
||||
github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU=
|
||||
github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg=
|
||||
github.com/russross/blackfriday/v2 v2.0.1 h1:lPqVAte+HuHNfhJ/0LC98ESWRz8afy9tM/0RK8m9o+Q=
|
||||
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo=
|
||||
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
|
||||
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
|
||||
github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM=
|
||||
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
|
||||
github.com/spf13/afero v1.1.2 h1:m8/z1t7/fwjysjQRYbP0RD+bUIF/8tJwPdEZsI83ACI=
|
||||
github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ=
|
||||
github.com/spf13/cast v1.3.0 h1:oget//CVOEoFewqQxwr0Ej5yjygnqGkvggSE/gB35Q8=
|
||||
github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
|
||||
github.com/spf13/jwalterweatherman v1.0.0 h1:XHEdyB+EcvlqZamSM4ZOMGlc93t6AcsBEu9Gc1vn7yk=
|
||||
github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo=
|
||||
github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg=
|
||||
github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
|
||||
github.com/spf13/viper v1.4.0 h1:yXHLWeravcrgGyFSyCgdYpXQ9dR9c/WED3pg1RhxqEU=
|
||||
github.com/spf13/viper v1.4.0/go.mod h1:PTJ7Z/lr49W6bUbkmS1V3by4uWynFiR9p7+dSq/yZzE=
|
||||
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=
|
||||
github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc=
|
||||
github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU=
|
||||
github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q=
|
||||
go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU=
|
||||
go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
|
||||
go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0=
|
||||
go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
|
||||
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
|
||||
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190522155817-f3200d17e092/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a h1:1BGLXjeY4akVXGgbC9HugT3Jv3hCI0z56oJR5vAMgBU=
|
||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
|
||||
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
|
||||
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
|
||||
google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
|
||||
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo=
|
||||
gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74=
|
||||
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
100
vendor/github.com/spf13/cobra/powershell_completions.go
сгенерированный
поставляемый
Normal file
100
vendor/github.com/spf13/cobra/powershell_completions.go
сгенерированный
поставляемый
Normal file
|
@ -0,0 +1,100 @@
|
|||
// PowerShell completions are based on the amazing work from clap:
|
||||
// https://github.com/clap-rs/clap/blob/3294d18efe5f264d12c9035f404c7d189d4824e1/src/completions/powershell.rs
|
||||
//
|
||||
// The generated scripts require PowerShell v5.0+ (which comes Windows 10, but
|
||||
// can be downloaded separately for windows 7 or 8.1).
|
||||
|
||||
package cobra
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
var powerShellCompletionTemplate = `using namespace System.Management.Automation
|
||||
using namespace System.Management.Automation.Language
|
||||
Register-ArgumentCompleter -Native -CommandName '%s' -ScriptBlock {
|
||||
param($wordToComplete, $commandAst, $cursorPosition)
|
||||
$commandElements = $commandAst.CommandElements
|
||||
$command = @(
|
||||
'%s'
|
||||
for ($i = 1; $i -lt $commandElements.Count; $i++) {
|
||||
$element = $commandElements[$i]
|
||||
if ($element -isnot [StringConstantExpressionAst] -or
|
||||
$element.StringConstantType -ne [StringConstantType]::BareWord -or
|
||||
$element.Value.StartsWith('-')) {
|
||||
break
|
||||
}
|
||||
$element.Value
|
||||
}
|
||||
) -join ';'
|
||||
$completions = @(switch ($command) {%s
|
||||
})
|
||||
$completions.Where{ $_.CompletionText -like "$wordToComplete*" } |
|
||||
Sort-Object -Property ListItemText
|
||||
}`
|
||||
|
||||
func generatePowerShellSubcommandCases(out io.Writer, cmd *Command, previousCommandName string) {
|
||||
var cmdName string
|
||||
if previousCommandName == "" {
|
||||
cmdName = cmd.Name()
|
||||
} else {
|
||||
cmdName = fmt.Sprintf("%s;%s", previousCommandName, cmd.Name())
|
||||
}
|
||||
|
||||
fmt.Fprintf(out, "\n '%s' {", cmdName)
|
||||
|
||||
cmd.Flags().VisitAll(func(flag *pflag.Flag) {
|
||||
if nonCompletableFlag(flag) {
|
||||
return
|
||||
}
|
||||
usage := escapeStringForPowerShell(flag.Usage)
|
||||
if len(flag.Shorthand) > 0 {
|
||||
fmt.Fprintf(out, "\n [CompletionResult]::new('-%s', '%s', [CompletionResultType]::ParameterName, '%s')", flag.Shorthand, flag.Shorthand, usage)
|
||||
}
|
||||
fmt.Fprintf(out, "\n [CompletionResult]::new('--%s', '%s', [CompletionResultType]::ParameterName, '%s')", flag.Name, flag.Name, usage)
|
||||
})
|
||||
|
||||
for _, subCmd := range cmd.Commands() {
|
||||
usage := escapeStringForPowerShell(subCmd.Short)
|
||||
fmt.Fprintf(out, "\n [CompletionResult]::new('%s', '%s', [CompletionResultType]::ParameterValue, '%s')", subCmd.Name(), subCmd.Name(), usage)
|
||||
}
|
||||
|
||||
fmt.Fprint(out, "\n break\n }")
|
||||
|
||||
for _, subCmd := range cmd.Commands() {
|
||||
generatePowerShellSubcommandCases(out, subCmd, cmdName)
|
||||
}
|
||||
}
|
||||
|
||||
func escapeStringForPowerShell(s string) string {
|
||||
return strings.Replace(s, "'", "''", -1)
|
||||
}
|
||||
|
||||
// GenPowerShellCompletion generates PowerShell completion file and writes to the passed writer.
|
||||
func (c *Command) GenPowerShellCompletion(w io.Writer) error {
|
||||
buf := new(bytes.Buffer)
|
||||
|
||||
var subCommandCases bytes.Buffer
|
||||
generatePowerShellSubcommandCases(&subCommandCases, c, "")
|
||||
fmt.Fprintf(buf, powerShellCompletionTemplate, c.Name(), c.Name(), subCommandCases.String())
|
||||
|
||||
_, err := buf.WriteTo(w)
|
||||
return err
|
||||
}
|
||||
|
||||
// GenPowerShellCompletionFile generates PowerShell completion file.
|
||||
func (c *Command) GenPowerShellCompletionFile(filename string) error {
|
||||
outFile, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer outFile.Close()
|
||||
|
||||
return c.GenPowerShellCompletion(outFile)
|
||||
}
|
|
@ -0,0 +1,14 @@
|
|||
# Generating PowerShell Completions For Your Own cobra.Command
|
||||
|
||||
Cobra can generate PowerShell completion scripts. Users need PowerShell version 5.0 or above, which comes with Windows 10 and can be downloaded separately for Windows 7 or 8.1. They can then write the completions to a file and source this file from their PowerShell profile, which is referenced by the `$Profile` environment variable. See `Get-Help about_Profiles` for more info about PowerShell profiles.
|
||||
|
||||
# What's supported
|
||||
|
||||
- Completion for subcommands using their `.Short` description
|
||||
- Completion for non-hidden flags using their `.Name` and `.Shorthand`
|
||||
|
||||
# What's not yet supported
|
||||
|
||||
- Command aliases
|
||||
- Required, filename or custom flags (they will work like normal flags)
|
||||
- Custom completion scripts
|
|
@ -0,0 +1,85 @@
|
|||
package cobra
|
||||
|
||||
import (
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
// MarkFlagRequired adds the BashCompOneRequiredFlag annotation to the named flag if it exists,
|
||||
// and causes your command to report an error if invoked without the flag.
|
||||
func (c *Command) MarkFlagRequired(name string) error {
|
||||
return MarkFlagRequired(c.Flags(), name)
|
||||
}
|
||||
|
||||
// MarkPersistentFlagRequired adds the BashCompOneRequiredFlag annotation to the named persistent flag if it exists,
|
||||
// and causes your command to report an error if invoked without the flag.
|
||||
func (c *Command) MarkPersistentFlagRequired(name string) error {
|
||||
return MarkFlagRequired(c.PersistentFlags(), name)
|
||||
}
|
||||
|
||||
// MarkFlagRequired adds the BashCompOneRequiredFlag annotation to the named flag if it exists,
|
||||
// and causes your command to report an error if invoked without the flag.
|
||||
func MarkFlagRequired(flags *pflag.FlagSet, name string) error {
|
||||
return flags.SetAnnotation(name, BashCompOneRequiredFlag, []string{"true"})
|
||||
}
|
||||
|
||||
// MarkFlagFilename adds the BashCompFilenameExt annotation to the named flag, if it exists.
|
||||
// Generated bash autocompletion will select filenames for the flag, limiting to named extensions if provided.
|
||||
func (c *Command) MarkFlagFilename(name string, extensions ...string) error {
|
||||
return MarkFlagFilename(c.Flags(), name, extensions...)
|
||||
}
|
||||
|
||||
// MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists.
|
||||
// Generated bash autocompletion will call the bash function f for the flag.
|
||||
func (c *Command) MarkFlagCustom(name string, f string) error {
|
||||
return MarkFlagCustom(c.Flags(), name, f)
|
||||
}
|
||||
|
||||
// MarkPersistentFlagFilename instructs the various shell completion
|
||||
// implementations to limit completions for this persistent flag to the
|
||||
// specified extensions (patterns).
|
||||
//
|
||||
// Shell Completion compatibility matrix: bash, zsh
|
||||
func (c *Command) MarkPersistentFlagFilename(name string, extensions ...string) error {
|
||||
return MarkFlagFilename(c.PersistentFlags(), name, extensions...)
|
||||
}
|
||||
|
||||
// MarkFlagFilename instructs the various shell completion implementations to
|
||||
// limit completions for this flag to the specified extensions (patterns).
|
||||
//
|
||||
// Shell Completion compatibility matrix: bash, zsh
|
||||
func MarkFlagFilename(flags *pflag.FlagSet, name string, extensions ...string) error {
|
||||
return flags.SetAnnotation(name, BashCompFilenameExt, extensions)
|
||||
}
|
||||
|
||||
// MarkFlagCustom instructs the various shell completion implementations to
|
||||
// limit completions for this flag to the specified extensions (patterns).
|
||||
//
|
||||
// Shell Completion compatibility matrix: bash, zsh
|
||||
func MarkFlagCustom(flags *pflag.FlagSet, name string, f string) error {
|
||||
return flags.SetAnnotation(name, BashCompCustom, []string{f})
|
||||
}
|
||||
|
||||
// MarkFlagDirname instructs the various shell completion implementations to
|
||||
// complete only directories with this named flag.
|
||||
//
|
||||
// Shell Completion compatibility matrix: zsh
|
||||
func (c *Command) MarkFlagDirname(name string) error {
|
||||
return MarkFlagDirname(c.Flags(), name)
|
||||
}
|
||||
|
||||
// MarkPersistentFlagDirname instructs the various shell completion
|
||||
// implementations to complete only directories with this persistent named flag.
|
||||
//
|
||||
// Shell Completion compatibility matrix: zsh
|
||||
func (c *Command) MarkPersistentFlagDirname(name string) error {
|
||||
return MarkFlagDirname(c.PersistentFlags(), name)
|
||||
}
|
||||
|
||||
// MarkFlagDirname instructs the various shell completion implementations to
|
||||
// complete only directories with this specified flag.
|
||||
//
|
||||
// Shell Completion compatibility matrix: zsh
|
||||
func MarkFlagDirname(flags *pflag.FlagSet, name string) error {
|
||||
zshPattern := "-(/)"
|
||||
return flags.SetAnnotation(name, zshCompDirname, []string{zshPattern})
|
||||
}
|
|
@ -0,0 +1,336 @@
|
|||
package cobra
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
"text/template"
|
||||
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
const (
|
||||
zshCompArgumentAnnotation = "cobra_annotations_zsh_completion_argument_annotation"
|
||||
zshCompArgumentFilenameComp = "cobra_annotations_zsh_completion_argument_file_completion"
|
||||
zshCompArgumentWordComp = "cobra_annotations_zsh_completion_argument_word_completion"
|
||||
zshCompDirname = "cobra_annotations_zsh_dirname"
|
||||
)
|
||||
|
||||
var (
|
||||
zshCompFuncMap = template.FuncMap{
|
||||
"genZshFuncName": zshCompGenFuncName,
|
||||
"extractFlags": zshCompExtractFlag,
|
||||
"genFlagEntryForZshArguments": zshCompGenFlagEntryForArguments,
|
||||
"extractArgsCompletions": zshCompExtractArgumentCompletionHintsForRendering,
|
||||
}
|
||||
zshCompletionText = `
|
||||
{{/* should accept Command (that contains subcommands) as parameter */}}
|
||||
{{define "argumentsC" -}}
|
||||
{{ $cmdPath := genZshFuncName .}}
|
||||
function {{$cmdPath}} {
|
||||
local -a commands
|
||||
|
||||
_arguments -C \{{- range extractFlags .}}
|
||||
{{genFlagEntryForZshArguments .}} \{{- end}}
|
||||
"1: :->cmnds" \
|
||||
"*::arg:->args"
|
||||
|
||||
case $state in
|
||||
cmnds)
|
||||
commands=({{range .Commands}}{{if not .Hidden}}
|
||||
"{{.Name}}:{{.Short}}"{{end}}{{end}}
|
||||
)
|
||||
_describe "command" commands
|
||||
;;
|
||||
esac
|
||||
|
||||
case "$words[1]" in {{- range .Commands}}{{if not .Hidden}}
|
||||
{{.Name}})
|
||||
{{$cmdPath}}_{{.Name}}
|
||||
;;{{end}}{{end}}
|
||||
esac
|
||||
}
|
||||
{{range .Commands}}{{if not .Hidden}}
|
||||
{{template "selectCmdTemplate" .}}
|
||||
{{- end}}{{end}}
|
||||
{{- end}}
|
||||
|
||||
{{/* should accept Command without subcommands as parameter */}}
|
||||
{{define "arguments" -}}
|
||||
function {{genZshFuncName .}} {
|
||||
{{" _arguments"}}{{range extractFlags .}} \
|
||||
{{genFlagEntryForZshArguments . -}}
|
||||
{{end}}{{range extractArgsCompletions .}} \
|
||||
{{.}}{{end}}
|
||||
}
|
||||
{{end}}
|
||||
|
||||
{{/* dispatcher for commands with or without subcommands */}}
|
||||
{{define "selectCmdTemplate" -}}
|
||||
{{if .Hidden}}{{/* ignore hidden*/}}{{else -}}
|
||||
{{if .Commands}}{{template "argumentsC" .}}{{else}}{{template "arguments" .}}{{end}}
|
||||
{{- end}}
|
||||
{{- end}}
|
||||
|
||||
{{/* template entry point */}}
|
||||
{{define "Main" -}}
|
||||
#compdef _{{.Name}} {{.Name}}
|
||||
|
||||
{{template "selectCmdTemplate" .}}
|
||||
{{end}}
|
||||
`
|
||||
)
|
||||
|
||||
// zshCompArgsAnnotation is used to encode/decode zsh completion for
|
||||
// arguments to/from Command.Annotations.
|
||||
type zshCompArgsAnnotation map[int]zshCompArgHint
|
||||
|
||||
type zshCompArgHint struct {
|
||||
// Indicates the type of the completion to use. One of:
|
||||
// zshCompArgumentFilenameComp or zshCompArgumentWordComp
|
||||
Tipe string `json:"type"`
|
||||
|
||||
// A value for the type above (globs for file completion or words)
|
||||
Options []string `json:"options"`
|
||||
}
|
||||
|
||||
// GenZshCompletionFile generates zsh completion file.
|
||||
func (c *Command) GenZshCompletionFile(filename string) error {
|
||||
outFile, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer outFile.Close()
|
||||
|
||||
return c.GenZshCompletion(outFile)
|
||||
}
|
||||
|
||||
// GenZshCompletion generates a zsh completion file and writes to the passed
|
||||
// writer. The completion always run on the root command regardless of the
|
||||
// command it was called from.
|
||||
func (c *Command) GenZshCompletion(w io.Writer) error {
|
||||
tmpl, err := template.New("Main").Funcs(zshCompFuncMap).Parse(zshCompletionText)
|
||||
if err != nil {
|
||||
return fmt.Errorf("error creating zsh completion template: %v", err)
|
||||
}
|
||||
return tmpl.Execute(w, c.Root())
|
||||
}
|
||||
|
||||
// MarkZshCompPositionalArgumentFile marks the specified argument (first
|
||||
// argument is 1) as completed by file selection. patterns (e.g. "*.txt") are
|
||||
// optional - if not provided the completion will search for all files.
|
||||
func (c *Command) MarkZshCompPositionalArgumentFile(argPosition int, patterns ...string) error {
|
||||
if argPosition < 1 {
|
||||
return fmt.Errorf("Invalid argument position (%d)", argPosition)
|
||||
}
|
||||
annotation, err := c.zshCompGetArgsAnnotations()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if c.zshcompArgsAnnotationnIsDuplicatePosition(annotation, argPosition) {
|
||||
return fmt.Errorf("Duplicate annotation for positional argument at index %d", argPosition)
|
||||
}
|
||||
annotation[argPosition] = zshCompArgHint{
|
||||
Tipe: zshCompArgumentFilenameComp,
|
||||
Options: patterns,
|
||||
}
|
||||
return c.zshCompSetArgsAnnotations(annotation)
|
||||
}
|
||||
|
||||
// MarkZshCompPositionalArgumentWords marks the specified positional argument
|
||||
// (first argument is 1) as completed by the provided words. At east one word
|
||||
// must be provided, spaces within words will be offered completion with
|
||||
// "word\ word".
|
||||
func (c *Command) MarkZshCompPositionalArgumentWords(argPosition int, words ...string) error {
|
||||
if argPosition < 1 {
|
||||
return fmt.Errorf("Invalid argument position (%d)", argPosition)
|
||||
}
|
||||
if len(words) == 0 {
|
||||
return fmt.Errorf("Trying to set empty word list for positional argument %d", argPosition)
|
||||
}
|
||||
annotation, err := c.zshCompGetArgsAnnotations()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if c.zshcompArgsAnnotationnIsDuplicatePosition(annotation, argPosition) {
|
||||
return fmt.Errorf("Duplicate annotation for positional argument at index %d", argPosition)
|
||||
}
|
||||
annotation[argPosition] = zshCompArgHint{
|
||||
Tipe: zshCompArgumentWordComp,
|
||||
Options: words,
|
||||
}
|
||||
return c.zshCompSetArgsAnnotations(annotation)
|
||||
}
|
||||
|
||||
func zshCompExtractArgumentCompletionHintsForRendering(c *Command) ([]string, error) {
|
||||
var result []string
|
||||
annotation, err := c.zshCompGetArgsAnnotations()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for k, v := range annotation {
|
||||
s, err := zshCompRenderZshCompArgHint(k, v)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, s)
|
||||
}
|
||||
if len(c.ValidArgs) > 0 {
|
||||
if _, positionOneExists := annotation[1]; !positionOneExists {
|
||||
s, err := zshCompRenderZshCompArgHint(1, zshCompArgHint{
|
||||
Tipe: zshCompArgumentWordComp,
|
||||
Options: c.ValidArgs,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, s)
|
||||
}
|
||||
}
|
||||
sort.Strings(result)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func zshCompRenderZshCompArgHint(i int, z zshCompArgHint) (string, error) {
|
||||
switch t := z.Tipe; t {
|
||||
case zshCompArgumentFilenameComp:
|
||||
var globs []string
|
||||
for _, g := range z.Options {
|
||||
globs = append(globs, fmt.Sprintf(`-g "%s"`, g))
|
||||
}
|
||||
return fmt.Sprintf(`'%d: :_files %s'`, i, strings.Join(globs, " ")), nil
|
||||
case zshCompArgumentWordComp:
|
||||
var words []string
|
||||
for _, w := range z.Options {
|
||||
words = append(words, fmt.Sprintf("%q", w))
|
||||
}
|
||||
return fmt.Sprintf(`'%d: :(%s)'`, i, strings.Join(words, " ")), nil
|
||||
default:
|
||||
return "", fmt.Errorf("Invalid zsh argument completion annotation: %s", t)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Command) zshcompArgsAnnotationnIsDuplicatePosition(annotation zshCompArgsAnnotation, position int) bool {
|
||||
_, dup := annotation[position]
|
||||
return dup
|
||||
}
|
||||
|
||||
func (c *Command) zshCompGetArgsAnnotations() (zshCompArgsAnnotation, error) {
|
||||
annotation := make(zshCompArgsAnnotation)
|
||||
annotationString, ok := c.Annotations[zshCompArgumentAnnotation]
|
||||
if !ok {
|
||||
return annotation, nil
|
||||
}
|
||||
err := json.Unmarshal([]byte(annotationString), &annotation)
|
||||
if err != nil {
|
||||
return annotation, fmt.Errorf("Error unmarshaling zsh argument annotation: %v", err)
|
||||
}
|
||||
return annotation, nil
|
||||
}
|
||||
|
||||
func (c *Command) zshCompSetArgsAnnotations(annotation zshCompArgsAnnotation) error {
|
||||
jsn, err := json.Marshal(annotation)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Error marshaling zsh argument annotation: %v", err)
|
||||
}
|
||||
if c.Annotations == nil {
|
||||
c.Annotations = make(map[string]string)
|
||||
}
|
||||
c.Annotations[zshCompArgumentAnnotation] = string(jsn)
|
||||
return nil
|
||||
}
|
||||
|
||||
func zshCompGenFuncName(c *Command) string {
|
||||
if c.HasParent() {
|
||||
return zshCompGenFuncName(c.Parent()) + "_" + c.Name()
|
||||
}
|
||||
return "_" + c.Name()
|
||||
}
|
||||
|
||||
func zshCompExtractFlag(c *Command) []*pflag.Flag {
|
||||
var flags []*pflag.Flag
|
||||
c.LocalFlags().VisitAll(func(f *pflag.Flag) {
|
||||
if !f.Hidden {
|
||||
flags = append(flags, f)
|
||||
}
|
||||
})
|
||||
c.InheritedFlags().VisitAll(func(f *pflag.Flag) {
|
||||
if !f.Hidden {
|
||||
flags = append(flags, f)
|
||||
}
|
||||
})
|
||||
return flags
|
||||
}
|
||||
|
||||
// zshCompGenFlagEntryForArguments returns an entry that matches _arguments
|
||||
// zsh-completion parameters. It's too complicated to generate in a template.
|
||||
func zshCompGenFlagEntryForArguments(f *pflag.Flag) string {
|
||||
if f.Name == "" || f.Shorthand == "" {
|
||||
return zshCompGenFlagEntryForSingleOptionFlag(f)
|
||||
}
|
||||
return zshCompGenFlagEntryForMultiOptionFlag(f)
|
||||
}
|
||||
|
||||
func zshCompGenFlagEntryForSingleOptionFlag(f *pflag.Flag) string {
|
||||
var option, multiMark, extras string
|
||||
|
||||
if zshCompFlagCouldBeSpecifiedMoreThenOnce(f) {
|
||||
multiMark = "*"
|
||||
}
|
||||
|
||||
option = "--" + f.Name
|
||||
if option == "--" {
|
||||
option = "-" + f.Shorthand
|
||||
}
|
||||
extras = zshCompGenFlagEntryExtras(f)
|
||||
|
||||
return fmt.Sprintf(`'%s%s[%s]%s'`, multiMark, option, zshCompQuoteFlagDescription(f.Usage), extras)
|
||||
}
|
||||
|
||||
func zshCompGenFlagEntryForMultiOptionFlag(f *pflag.Flag) string {
|
||||
var options, parenMultiMark, curlyMultiMark, extras string
|
||||
|
||||
if zshCompFlagCouldBeSpecifiedMoreThenOnce(f) {
|
||||
parenMultiMark = "*"
|
||||
curlyMultiMark = "\\*"
|
||||
}
|
||||
|
||||
options = fmt.Sprintf(`'(%s-%s %s--%s)'{%s-%s,%s--%s}`,
|
||||
parenMultiMark, f.Shorthand, parenMultiMark, f.Name, curlyMultiMark, f.Shorthand, curlyMultiMark, f.Name)
|
||||
extras = zshCompGenFlagEntryExtras(f)
|
||||
|
||||
return fmt.Sprintf(`%s'[%s]%s'`, options, zshCompQuoteFlagDescription(f.Usage), extras)
|
||||
}
|
||||
|
||||
func zshCompGenFlagEntryExtras(f *pflag.Flag) string {
|
||||
if f.NoOptDefVal != "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
extras := ":" // allow options for flag (even without assistance)
|
||||
for key, values := range f.Annotations {
|
||||
switch key {
|
||||
case zshCompDirname:
|
||||
extras = fmt.Sprintf(":filename:_files -g %q", values[0])
|
||||
case BashCompFilenameExt:
|
||||
extras = ":filename:_files"
|
||||
for _, pattern := range values {
|
||||
extras = extras + fmt.Sprintf(` -g "%s"`, pattern)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return extras
|
||||
}
|
||||
|
||||
func zshCompFlagCouldBeSpecifiedMoreThenOnce(f *pflag.Flag) bool {
|
||||
return strings.Contains(f.Value.Type(), "Slice") ||
|
||||
strings.Contains(f.Value.Type(), "Array")
|
||||
}
|
||||
|
||||
func zshCompQuoteFlagDescription(s string) string {
|
||||
return strings.Replace(s, "'", `'\''`, -1)
|
||||
}
|
|
@ -0,0 +1,39 @@
|
|||
## Generating Zsh Completion for your cobra.Command
|
||||
|
||||
Cobra supports native Zsh completion generated from the root `cobra.Command`.
|
||||
The generated completion script should be put somewhere in your `$fpath` named
|
||||
`_<YOUR COMMAND>`.
|
||||
|
||||
### What's Supported
|
||||
|
||||
* Completion for all non-hidden subcommands using their `.Short` description.
|
||||
* Completion for all non-hidden flags using the following rules:
|
||||
* Filename completion works by marking the flag with `cmd.MarkFlagFilename...`
|
||||
family of commands.
|
||||
* The requirement for argument to the flag is decided by the `.NoOptDefVal`
|
||||
flag value - if it's empty then completion will expect an argument.
|
||||
* Flags of one of the various `*Array` and `*Slice` types supports multiple
|
||||
specifications (with or without argument depending on the specific type).
|
||||
* Completion of positional arguments using the following rules:
|
||||
* Argument position for all options below starts at `1`. If argument position
|
||||
`0` is requested it will raise an error.
|
||||
* Use `command.MarkZshCompPositionalArgumentFile` to complete filenames. Glob
|
||||
patterns (e.g. `"*.log"`) are optional - if not specified it will offer to
|
||||
complete all file types.
|
||||
* Use `command.MarkZshCompPositionalArgumentWords` to offer specific words for
|
||||
completion. At least one word is required.
|
||||
* It's possible to specify completion for some arguments and leave some
|
||||
unspecified (e.g. offer words for second argument but nothing for first
|
||||
argument). This will cause no completion for first argument but words
|
||||
completion for second argument.
|
||||
* If no argument completion was specified for 1st argument (but optionally was
|
||||
specified for 2nd) and the command has `ValidArgs` it will be used as
|
||||
completion options for 1st argument.
|
||||
* Argument completions only offered for commands with no subcommands.
|
||||
|
||||
### What's not yet Supported
|
||||
|
||||
* Custom completion scripts are not supported yet (We should probably create zsh
|
||||
specific one, doesn't make sense to re-use the bash one as the functions will
|
||||
be different).
|
||||
* Whatever other feature you're looking for and doesn't exist :)
|
|
@ -1,5 +1,5 @@
|
|||
module github.com/ugorji/go/codec
|
||||
|
||||
go 1.14
|
||||
|
||||
require github.com/ugorji/go v1.1.7
|
||||
require (
|
||||
github.com/ugorji/go v1.1.7
|
||||
)
|
||||
|
|
|
@ -1,2 +0,0 @@
|
|||
github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw=
|
||||
github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY=
|
|
@ -1,3 +1 @@
|
|||
module github.com/ulikunitz/xz
|
||||
|
||||
go 1.14
|
||||
|
|
|
@ -0,0 +1,67 @@
|
|||
// Package imports implements a Go pretty-printer (like package "go/format")
|
||||
// that also adds or removes import statements as necessary.
|
||||
package imports // import "golang.org/x/tools/imports"
|
||||
|
||||
import (
|
||||
"go/build"
|
||||
"os"
|
||||
|
||||
intimp "golang.org/x/tools/internal/imports"
|
||||
)
|
||||
|
||||
// Options specifies options for processing files.
|
||||
type Options struct {
|
||||
Fragment bool // Accept fragment of a source file (no package statement)
|
||||
AllErrors bool // Report all errors (not just the first 10 on different lines)
|
||||
|
||||
Comments bool // Print comments (true if nil *Options provided)
|
||||
TabIndent bool // Use tabs for indent (true if nil *Options provided)
|
||||
TabWidth int // Tab width (8 if nil *Options provided)
|
||||
|
||||
FormatOnly bool // Disable the insertion and deletion of imports
|
||||
}
|
||||
|
||||
// Debug controls verbose logging.
|
||||
var Debug = false
|
||||
|
||||
// LocalPrefix is a comma-separated string of import path prefixes, which, if
|
||||
// set, instructs Process to sort the import paths with the given prefixes
|
||||
// into another group after 3rd-party packages.
|
||||
var LocalPrefix string
|
||||
|
||||
// Process formats and adjusts imports for the provided file.
|
||||
// If opt is nil the defaults are used.
|
||||
//
|
||||
// Note that filename's directory influences which imports can be chosen,
|
||||
// so it is important that filename be accurate.
|
||||
// To process data ``as if'' it were in filename, pass the data as a non-nil src.
|
||||
func Process(filename string, src []byte, opt *Options) ([]byte, error) {
|
||||
if opt == nil {
|
||||
opt = &Options{Comments: true, TabIndent: true, TabWidth: 8}
|
||||
}
|
||||
intopt := &intimp.Options{
|
||||
Env: &intimp.ProcessEnv{
|
||||
GOPATH: build.Default.GOPATH,
|
||||
GOROOT: build.Default.GOROOT,
|
||||
GOFLAGS: os.Getenv("GOFLAGS"),
|
||||
GO111MODULE: os.Getenv("GO111MODULE"),
|
||||
GOPROXY: os.Getenv("GOPROXY"),
|
||||
GOSUMDB: os.Getenv("GOSUMDB"),
|
||||
Debug: Debug,
|
||||
LocalPrefix: LocalPrefix,
|
||||
},
|
||||
AllErrors: opt.AllErrors,
|
||||
Comments: opt.Comments,
|
||||
FormatOnly: opt.FormatOnly,
|
||||
Fragment: opt.Fragment,
|
||||
TabIndent: opt.TabIndent,
|
||||
TabWidth: opt.TabWidth,
|
||||
}
|
||||
return intimp.Process(filename, src, intopt)
|
||||
}
|
||||
|
||||
// VendorlessPath returns the devendorized version of the import path ipath.
|
||||
// For example, VendorlessPath("foo/bar/vendor/a/b") returns "a/b".
|
||||
func VendorlessPath(ipath string) string {
|
||||
return intimp.VendorlessPath(ipath)
|
||||
}
|
|
@ -0,0 +1,202 @@
|
|||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright {yyyy} {name of copyright owner}
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
module gomodules.xyz/jsonpatch/v2
|
||||
|
||||
go 1.12
|
||||
|
||||
require (
|
||||
github.com/evanphx/json-patch v4.5.0+incompatible
|
||||
github.com/pkg/errors v0.8.1 // indirect
|
||||
github.com/stretchr/testify v1.3.0
|
||||
)
|
|
@ -0,0 +1,11 @@
|
|||
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/evanphx/json-patch v4.5.0+incompatible h1:ouOWdg56aJriqS0huScTkVXPC5IcNrDCXZ6OoTAWu7M=
|
||||
github.com/evanphx/json-patch v4.5.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk=
|
||||
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
|
||||
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
|
@ -0,0 +1,336 @@
|
|||
package jsonpatch
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var errBadJSONDoc = fmt.Errorf("invalid JSON Document")
|
||||
|
||||
type JsonPatchOperation = Operation
|
||||
|
||||
type Operation struct {
|
||||
Operation string `json:"op"`
|
||||
Path string `json:"path"`
|
||||
Value interface{} `json:"value,omitempty"`
|
||||
}
|
||||
|
||||
func (j *Operation) Json() string {
|
||||
b, _ := json.Marshal(j)
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func (j *Operation) MarshalJSON() ([]byte, error) {
|
||||
var b bytes.Buffer
|
||||
b.WriteString("{")
|
||||
b.WriteString(fmt.Sprintf(`"op":"%s"`, j.Operation))
|
||||
b.WriteString(fmt.Sprintf(`,"path":"%s"`, j.Path))
|
||||
// Consider omitting Value for non-nullable operations.
|
||||
if j.Value != nil || j.Operation == "replace" || j.Operation == "add" {
|
||||
v, err := json.Marshal(j.Value)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b.WriteString(`,"value":`)
|
||||
b.Write(v)
|
||||
}
|
||||
b.WriteString("}")
|
||||
return b.Bytes(), nil
|
||||
}
|
||||
|
||||
type ByPath []Operation
|
||||
|
||||
func (a ByPath) Len() int { return len(a) }
|
||||
func (a ByPath) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
|
||||
func (a ByPath) Less(i, j int) bool { return a[i].Path < a[j].Path }
|
||||
|
||||
func NewOperation(op, path string, value interface{}) Operation {
|
||||
return Operation{Operation: op, Path: path, Value: value}
|
||||
}
|
||||
|
||||
// CreatePatch creates a patch as specified in http://jsonpatch.com/
|
||||
//
|
||||
// 'a' is original, 'b' is the modified document. Both are to be given as json encoded content.
|
||||
// The function will return an array of JsonPatchOperations
|
||||
//
|
||||
// An error will be returned if any of the two documents are invalid.
|
||||
func CreatePatch(a, b []byte) ([]Operation, error) {
|
||||
var aI interface{}
|
||||
var bI interface{}
|
||||
err := json.Unmarshal(a, &aI)
|
||||
if err != nil {
|
||||
return nil, errBadJSONDoc
|
||||
}
|
||||
err = json.Unmarshal(b, &bI)
|
||||
if err != nil {
|
||||
return nil, errBadJSONDoc
|
||||
}
|
||||
return handleValues(aI, bI, "", []Operation{})
|
||||
}
|
||||
|
||||
// Returns true if the values matches (must be json types)
|
||||
// The types of the values must match, otherwise it will always return false
|
||||
// If two map[string]interface{} are given, all elements must match.
|
||||
func matchesValue(av, bv interface{}) bool {
|
||||
if reflect.TypeOf(av) != reflect.TypeOf(bv) {
|
||||
return false
|
||||
}
|
||||
switch at := av.(type) {
|
||||
case string:
|
||||
bt, ok := bv.(string)
|
||||
if ok && bt == at {
|
||||
return true
|
||||
}
|
||||
case float64:
|
||||
bt, ok := bv.(float64)
|
||||
if ok && bt == at {
|
||||
return true
|
||||
}
|
||||
case bool:
|
||||
bt, ok := bv.(bool)
|
||||
if ok && bt == at {
|
||||
return true
|
||||
}
|
||||
case map[string]interface{}:
|
||||
bt, ok := bv.(map[string]interface{})
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
for key := range at {
|
||||
if !matchesValue(at[key], bt[key]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
for key := range bt {
|
||||
if !matchesValue(at[key], bt[key]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
case []interface{}:
|
||||
bt, ok := bv.([]interface{})
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
if len(bt) != len(at) {
|
||||
return false
|
||||
}
|
||||
for key := range at {
|
||||
if !matchesValue(at[key], bt[key]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
for key := range bt {
|
||||
if !matchesValue(at[key], bt[key]) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// From http://tools.ietf.org/html/rfc6901#section-4 :
|
||||
//
|
||||
// Evaluation of each reference token begins by decoding any escaped
|
||||
// character sequence. This is performed by first transforming any
|
||||
// occurrence of the sequence '~1' to '/', and then transforming any
|
||||
// occurrence of the sequence '~0' to '~'.
|
||||
// TODO decode support:
|
||||
// var rfc6901Decoder = strings.NewReplacer("~1", "/", "~0", "~")
|
||||
|
||||
var rfc6901Encoder = strings.NewReplacer("~", "~0", "/", "~1")
|
||||
|
||||
func makePath(path string, newPart interface{}) string {
|
||||
key := rfc6901Encoder.Replace(fmt.Sprintf("%v", newPart))
|
||||
if path == "" {
|
||||
return "/" + key
|
||||
}
|
||||
if strings.HasSuffix(path, "/") {
|
||||
return path + key
|
||||
}
|
||||
return path + "/" + key
|
||||
}
|
||||
|
||||
// diff returns the (recursive) difference between a and b as an array of JsonPatchOperations.
|
||||
func diff(a, b map[string]interface{}, path string, patch []Operation) ([]Operation, error) {
|
||||
for key, bv := range b {
|
||||
p := makePath(path, key)
|
||||
av, ok := a[key]
|
||||
// value was added
|
||||
if !ok {
|
||||
patch = append(patch, NewOperation("add", p, bv))
|
||||
continue
|
||||
}
|
||||
// Types are the same, compare values
|
||||
var err error
|
||||
patch, err = handleValues(av, bv, p, patch)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
// Now add all deleted values as nil
|
||||
for key := range a {
|
||||
_, found := b[key]
|
||||
if !found {
|
||||
p := makePath(path, key)
|
||||
|
||||
patch = append(patch, NewOperation("remove", p, nil))
|
||||
}
|
||||
}
|
||||
return patch, nil
|
||||
}
|
||||
|
||||
func handleValues(av, bv interface{}, p string, patch []Operation) ([]Operation, error) {
|
||||
{
|
||||
at := reflect.TypeOf(av)
|
||||
bt := reflect.TypeOf(bv)
|
||||
if at == nil && bt == nil {
|
||||
// do nothing
|
||||
return patch, nil
|
||||
} else if at == nil && bt != nil {
|
||||
return append(patch, NewOperation("add", p, bv)), nil
|
||||
} else if at != bt {
|
||||
// If types have changed, replace completely (preserves null in destination)
|
||||
return append(patch, NewOperation("replace", p, bv)), nil
|
||||
}
|
||||
}
|
||||
|
||||
var err error
|
||||
switch at := av.(type) {
|
||||
case map[string]interface{}:
|
||||
bt := bv.(map[string]interface{})
|
||||
patch, err = diff(at, bt, p, patch)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case string, float64, bool:
|
||||
if !matchesValue(av, bv) {
|
||||
patch = append(patch, NewOperation("replace", p, bv))
|
||||
}
|
||||
case []interface{}:
|
||||
bt := bv.([]interface{})
|
||||
if isSimpleArray(at) && isSimpleArray(bt) {
|
||||
patch = append(patch, compareEditDistance(at, bt, p)...)
|
||||
} else {
|
||||
n := min(len(at), len(bt))
|
||||
for i := len(at) - 1; i >= n; i-- {
|
||||
patch = append(patch, NewOperation("remove", makePath(p, i), nil))
|
||||
}
|
||||
for i := n; i < len(bt); i++ {
|
||||
patch = append(patch, NewOperation("add", makePath(p, i), bt[i]))
|
||||
}
|
||||
for i := 0; i < n; i++ {
|
||||
var err error
|
||||
patch, err = handleValues(at[i], bt[i], makePath(p, i), patch)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
default:
|
||||
panic(fmt.Sprintf("Unknown type:%T ", av))
|
||||
}
|
||||
return patch, nil
|
||||
}
|
||||
|
||||
func isBasicType(a interface{}) bool {
|
||||
switch a.(type) {
|
||||
case string, float64, bool:
|
||||
default:
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func isSimpleArray(a []interface{}) bool {
|
||||
for i := range a {
|
||||
switch a[i].(type) {
|
||||
case string, float64, bool:
|
||||
default:
|
||||
val := reflect.ValueOf(a[i])
|
||||
if val.Kind() == reflect.Map {
|
||||
for _, k := range val.MapKeys() {
|
||||
av := val.MapIndex(k)
|
||||
if av.Kind() == reflect.Ptr || av.Kind() == reflect.Interface {
|
||||
if av.IsNil() {
|
||||
continue
|
||||
}
|
||||
av = av.Elem()
|
||||
}
|
||||
if av.Kind() != reflect.String && av.Kind() != reflect.Float64 && av.Kind() != reflect.Bool {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// https://en.wikipedia.org/wiki/Wagner%E2%80%93Fischer_algorithm
|
||||
// Adapted from https://github.com/texttheater/golang-levenshtein
|
||||
func compareEditDistance(s, t []interface{}, p string) []Operation {
|
||||
m := len(s)
|
||||
n := len(t)
|
||||
|
||||
d := make([][]int, m+1)
|
||||
for i := 0; i <= m; i++ {
|
||||
d[i] = make([]int, n+1)
|
||||
d[i][0] = i
|
||||
}
|
||||
for j := 0; j <= n; j++ {
|
||||
d[0][j] = j
|
||||
}
|
||||
|
||||
for j := 1; j <= n; j++ {
|
||||
for i := 1; i <= m; i++ {
|
||||
if reflect.DeepEqual(s[i-1], t[j-1]) {
|
||||
d[i][j] = d[i-1][j-1] // no op required
|
||||
} else {
|
||||
del := d[i-1][j] + 1
|
||||
add := d[i][j-1] + 1
|
||||
rep := d[i-1][j-1] + 1
|
||||
d[i][j] = min(rep, min(add, del))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return backtrace(s, t, p, m, n, d)
|
||||
}
|
||||
|
||||
func min(x int, y int) int {
|
||||
if y < x {
|
||||
return y
|
||||
}
|
||||
return x
|
||||
}
|
||||
|
||||
func backtrace(s, t []interface{}, p string, i int, j int, matrix [][]int) []Operation {
|
||||
if i > 0 && matrix[i-1][j]+1 == matrix[i][j] {
|
||||
op := NewOperation("remove", makePath(p, i-1), nil)
|
||||
return append([]Operation{op}, backtrace(s, t, p, i-1, j, matrix)...)
|
||||
}
|
||||
if j > 0 && matrix[i][j-1]+1 == matrix[i][j] {
|
||||
op := NewOperation("add", makePath(p, i), t[j-1])
|
||||
return append([]Operation{op}, backtrace(s, t, p, i, j-1, matrix)...)
|
||||
}
|
||||
if i > 0 && j > 0 && matrix[i-1][j-1]+1 == matrix[i][j] {
|
||||
if isBasicType(s[0]) {
|
||||
op := NewOperation("replace", makePath(p, i-1), t[j-1])
|
||||
return append([]Operation{op}, backtrace(s, t, p, i-1, j-1, matrix)...)
|
||||
}
|
||||
|
||||
p2, _ := handleValues(s[i-1], t[j-1], makePath(p, i-1), []Operation{})
|
||||
return append(p2, backtrace(s, t, p, i-1, j-1, matrix)...)
|
||||
}
|
||||
if i > 0 && j > 0 && matrix[i-1][j-1] == matrix[i][j] {
|
||||
return backtrace(s, t, p, i-1, j-1, matrix)
|
||||
}
|
||||
return []Operation{}
|
||||
}
|
|
@ -1,5 +1,5 @@
|
|||
module gopkg.in/yaml.v2
|
||||
module "gopkg.in/yaml.v2"
|
||||
|
||||
go 1.14
|
||||
|
||||
require gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405
|
||||
require (
|
||||
"gopkg.in/check.v1" v0.0.0-20161208181325-20d25e280405
|
||||
)
|
||||
|
|
|
@ -1 +0,0 @@
|
|||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше
Загрузка…
Ссылка в новой задаче