diff --git a/README.md b/README.md index 64c7fa04..9b762976 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,5 @@ +*NOTE* see https://githib.com/knative-sandbox for all knative client plugins and extensions + ## Knative Client Contributions This repository is the place for curated contributions for the [Knative client](https://github.com/knative/client), especially Knative plugins diff --git a/plugins/source-github/cmd/main.go b/plugins/source-github/cmd/main.go index bb4d1a78..1a6665b5 100644 --- a/plugins/source-github/cmd/main.go +++ b/plugins/source-github/cmd/main.go @@ -16,8 +16,24 @@ package main import ( "fmt" + "os" + + "github.com/maximilien/kn-source-github/pkg/factories" + "github.com/maximilien/kn-source-pkg/pkg/core" ) func main() { - fmt.Printf("This is placeholder code to get the dependencies merged. Sudsequent PRs will have kn-source-guthub code\n") + ghSourceFactory := factories.NewGHSourceFactory() + + ghCommandFactory := factories.NewGHCommandFactory(ghSourceFactory) + ghFlagsFactory := factories.NewGHFlagsFactory(ghSourceFactory) + ghRunEFactory := factories.NewGHRunEFactory(ghSourceFactory) + + err := core.NewKnSourceCommand(ghSourceFactory, ghCommandFactory, ghFlagsFactory, ghRunEFactory).Execute() + if err != nil { + if err.Error() != "subcommand is required" { + fmt.Fprintln(os.Stderr, err) + } + os.Exit(1) + } } diff --git a/plugins/source-github/go.mod b/plugins/source-github/go.mod index 3214d3ba..9a36091c 100644 --- a/plugins/source-github/go.mod +++ b/plugins/source-github/go.mod @@ -3,8 +3,16 @@ module github.com/maximilien/kn-source-github go 1.13 require ( - github.com/maximilien/kn-source-pkg v0.4.0 - github.com/spf13/cobra v1.0.0 // indirect - knative.dev/eventing-contrib v0.14.0 + github.com/maximilien/kn-source-pkg v0.4.7 + github.com/spf13/cobra v1.0.0 + github.com/spf13/pflag v1.0.5 + gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 // indirect + gotest.tools v2.2.0+incompatible + k8s.io/api v0.17.4 + k8s.io/apimachinery v0.17.4 + k8s.io/client-go v0.17.4 + knative.dev/client v0.14.0 + knative.dev/eventing-contrib v0.14.1 + knative.dev/pkg v0.0.0-20200414233146-0eed424fa4ee knative.dev/test-infra v0.0.0-20200413202711-9cf64fb1b912 ) diff --git a/plugins/source-github/go.sum b/plugins/source-github/go.sum index 33e1d37c..f5d3e088 100644 --- a/plugins/source-github/go.sum +++ b/plugins/source-github/go.sum @@ -11,8 +11,8 @@ contrib.go.opencensus.io/exporter/ocagent v0.6.0 h1:Z1n6UAyr0QwM284yUuh5Zd8JlvxU contrib.go.opencensus.io/exporter/ocagent v0.6.0/go.mod h1:zmKjrJcdo0aYcVS7bmEeSEBLPA9YJp5bjrofdU3pIXs= contrib.go.opencensus.io/exporter/prometheus v0.1.0 h1:SByaIoWwNgMdPSgl5sMqM2KDE5H/ukPWBRo314xiDvg= contrib.go.opencensus.io/exporter/prometheus v0.1.0/go.mod h1:cGFniUXGZlKRjzOyuZJ6mgB+PgBcCIa79kEKR8YCW+A= -contrib.go.opencensus.io/exporter/stackdriver v0.13.0 h1:Jaz7WbqjtfoCPa1KbfisCX+P5aM3DizEY9pQMU0oAQo= -contrib.go.opencensus.io/exporter/stackdriver v0.13.0/go.mod h1:z2tyTZtPmQ2HvWH4cOmVDgtY+1lomfKdbLnkJvZdc8c= +contrib.go.opencensus.io/exporter/stackdriver v0.13.1 h1:RX9W6FelAqTVnBi/bRXJLXr9n18v4QkQwZYIdnNS51I= +contrib.go.opencensus.io/exporter/stackdriver v0.13.1/go.mod h1:z2tyTZtPmQ2HvWH4cOmVDgtY+1lomfKdbLnkJvZdc8c= github.com/Azure/azure-sdk-for-go v35.0.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= github.com/Azure/azure-sdk-for-go v38.0.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78/go.mod h1:LmzpDX56iTiv29bbRTIsUNlaFfuhWRQBWjQdVyAevI8= @@ -163,8 +163,8 @@ github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5a github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1 h1:Xye71clBPdm5HgqGwUkwhbynsUJZhDbS20FvLhQ2izg= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-containerregistry v0.0.0-20200304201134-fcc8ea80e26f h1:tc00QCOHwGF/IyStWQnJN7zmrPP9LBJTKyulXzApCfw= -github.com/google/go-containerregistry v0.0.0-20200304201134-fcc8ea80e26f/go.mod h1:m8YvHwSOuBCq25yrj1DaX/fIMrv6ec3CNg8jY8+5PEA= +github.com/google/go-containerregistry v0.0.0-20200413145205-82d30a103c0a h1:XNvUa41C0oOgPmTmZKrWKhOCCFPLnOwLfm+pWU75sNs= +github.com/google/go-containerregistry v0.0.0-20200413145205-82d30a103c0a/go.mod h1:pD1UFYs7MCAx+ZLShBdttcaOSbyc8F9Na/9IZLNwJeA= github.com/google/gofuzz v0.0.0-20161122191042-44d81051d367/go.mod h1:HP5RmnzzSNb993RKQDq4+1A4ia9nllfqcQFTQJedwGI= github.com/google/gofuzz v1.0.0 h1:A8PeW59pxE9IoFRqBp37U+mSNaQoZ46F1f0f863XSXw= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= @@ -246,9 +246,10 @@ github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNx github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/maxbrunsfeld/counterfeiter/v6 v6.2.2 h1:g+4J5sZg6osfvEfkRZxJ1em0VT95/UOZgi/l7zi1/oE= github.com/maxbrunsfeld/counterfeiter/v6 v6.2.2/go.mod h1:eD9eIE7cdwcMi9rYluz88Jz2VyhSmden33/aXg4oVIY= -github.com/maximilien/kn-source-pkg v0.4.0 h1:YmSHyu3dfQ3K736fn8J3dSCZRNkm2RJaC/DQ7QnIcsg= -github.com/maximilien/kn-source-pkg v0.4.0/go.mod h1:EDa7rFyEq3i2X02NaP1/pnrg+yVUlWPOS4CCZaZwCx0= +github.com/maximilien/kn-source-pkg v0.4.7 h1:IhabIU8yz9k9Ii6lyIkgaAdNlmsvgdZttvQ0LwTopAU= +github.com/maximilien/kn-source-pkg v0.4.7/go.mod h1:zsncYNwuLplBjtxr5vPZ0+2OSpxwJLN+8oMaJVpqCTE= 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= @@ -368,7 +369,7 @@ github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1 github.com/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc= github.com/ugorji/go/codec v0.0.0-20181204163529-d75b2dcb6bc8/go.mod h1:VFNgLljTbGfSG7qAOspJ7OScBnGdDN/yBr0sguwnwf0= github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= -github.com/vdemeester/k8s-pkg-credentialprovider v0.0.0-20200107171650-7c61ffa44238/go.mod h1:JwQJCMWpUDqjZrB5jpw0f5VbN7U95zxFy1ZDpoEarGo= +github.com/vdemeester/k8s-pkg-credentialprovider v1.17.4/go.mod h1:inCTmtUdr5KJbreVojo06krnTgaeAz/Z7lynpPk/Q2c= github.com/vmware/govmomi v0.20.3/go.mod h1:URlwyTFZX72RmxtxuaFL2Uj3fD1JTvZdx59bHWk6aFU= 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= @@ -397,6 +398,8 @@ golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8U golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191206172530-e9b2fee46413 h1:ULYEB3JvPRE/IfO+9uO7vKV/xzVTO7XPAwm8xbf4w2g= golang.org/x/crypto v0.0.0-20191206172530-e9b2fee46413/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20200220183623-bac4c82f6975 h1:/Tl7pH94bvbAAHBdZJT947M/+gp0+CqQXDtMRC0fseo= +golang.org/x/crypto v0.0.0-20200220183623-bac4c82f6975/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190125153040-c74c464bbbf2/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190312203227-4b39c73a6495/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -407,9 +410,9 @@ golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvx golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= -golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee h1:WG0RUwxtNT4qqaXX3DPA8zHFNm/D9xaBpxzHt1WcA/E= golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/net v0.0.0-20170114055629-f2499483f923/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -496,9 +499,10 @@ golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgw golang.org/x/tools v0.0.0-20190706070813-72ffa07ba3db/go.mod h1:jcCCGcm9btYwXyDqrUWc6MKQKKGJCWEQ3AfLSRIbEuI= golang.org/x/tools v0.0.0-20190920225731-5eefd052ad72/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20191010075000-0337d82405ff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= -golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200210192313-1ace956b0e17 h1:a/Fd23DJvg1CaeDH0dYHahE+hCI0v9rFgxSNIThoUcM= golang.org/x/tools v0.0.0-20200210192313-1ace956b0e17/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898 h1:/atklqdjdhuosWIl6AIbOeHJjicWYPqR9bpxqxYG2pA= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gomodules.xyz/jsonpatch/v2 v2.1.0 h1:Phva6wqu+xR//Njw6iorylFFgn/z547tw5Ne3HZPQ+k= gomodules.xyz/jsonpatch/v2 v2.1.0/go.mod h1:IhYNNY4jnS53ZnfE4PAmpKtDpTCj1JFXc+3mwe7XcUU= @@ -560,6 +564,8 @@ gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.4 h1:/eiJrUcujPVeJ3xlSWaiNi3uSVmDGBK1pDHUHAnao1I= gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo= gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= @@ -569,17 +575,23 @@ honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWh honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= k8s.io/api v0.17.0 h1:H9d/lw+VkZKEVIUc8F3wgiQ+FUXTTr21M87jXLU7yqM= k8s.io/api v0.17.0/go.mod h1:npsyOePkeP0CPwyGfXDHxvypiYMJxBWAMpQxCaJ4ZxI= +k8s.io/api v0.17.4 h1:HbwOhDapkguO8lTAE8OX3hdF2qp8GtpC9CW/MQATXXo= +k8s.io/api v0.17.4/go.mod h1:5qxx6vjmwUVG2nHQTKGlLts8Tbok8PzHl4vHtVFuZCA= k8s.io/apimachinery v0.17.0 h1:xRBnuie9rXcPxUkDizUsGvPf1cnlZCFu210op7J7LJo= k8s.io/apimachinery v0.17.0/go.mod h1:b9qmWdKlLuU9EBh+06BtLcSf/Mu89rWL33naRxs1uZg= -k8s.io/apiserver v0.17.0/go.mod h1:ABM+9x/prjINN6iiffRVNCBR2Wk7uY4z+EtEGZD48cg= +k8s.io/apimachinery v0.17.4 h1:UzM+38cPUJnzqSQ+E1PY4YxMHIzQyCg29LOoGfo79Zw= +k8s.io/apimachinery v0.17.4/go.mod h1:gxLnyZcGNdZTCLnq3fgzyg2A5BVCHTNDFrw8AmuJ+0g= +k8s.io/apiserver v0.17.4/go.mod h1:5ZDQ6Xr5MNBxyi3iUZXS84QOhZl+W7Oq2us/29c0j9I= k8s.io/cli-runtime v0.17.0 h1:XEuStbJBHCQlEKFyTQmceDKEWOSYHZkcYWKp3SsQ9Hk= k8s.io/cli-runtime v0.17.0/go.mod h1:1E5iQpMODZq2lMWLUJELwRu2MLWIzwvMgDBpn3Y81Qo= k8s.io/client-go v0.17.0 h1:8QOGvUGdqDMFrm9sD6IUFl256BcffynGoe80sxgTEDg= k8s.io/client-go v0.17.0/go.mod h1:TYgR6EUHs6k45hb6KWjVD6jFZvJV4gHDikv/It0xz+k= -k8s.io/cloud-provider v0.17.0/go.mod h1:Ze4c3w2C0bRsjkBUoHpFi+qWe3ob1wI2/7cUn+YQIDE= +k8s.io/client-go v0.17.4 h1:VVdVbpTY70jiNHS1eiFkUt7ZIJX3txd29nDxxXH4en8= +k8s.io/client-go v0.17.4/go.mod h1:ouF6o5pz3is8qU0/qYL2RnoxOPqgfuidYLowytyLJmc= +k8s.io/cloud-provider v0.17.4/go.mod h1:XEjKDzfD+b9MTLXQFlDGkk6Ho8SGMpaU8Uugx/KNK9U= k8s.io/code-generator v0.17.2/go.mod h1:DVmfPQgxQENqDIzVR2ddLXMH34qeszkKSdH/N+s+38s= -k8s.io/component-base v0.17.0/go.mod h1:rKuRAokNMY2nn2A6LP/MiwpoaMRHpfRnrPaUJJj1Yoc= -k8s.io/csi-translation-lib v0.17.0/go.mod h1:HEF7MEz7pOLJCnxabi45IPkhSsE/KmxPQksuCrHKWls= +k8s.io/component-base v0.17.4/go.mod h1:5BRqHMbbQPm2kKu35v3G+CpVq4K0RJKC7TRioF0I9lE= +k8s.io/csi-translation-lib v0.17.4/go.mod h1:CsxmjwxEI0tTNMzffIAcgR9lX4wOh6AKHdxQrT7L0oo= k8s.io/gengo v0.0.0-20190128074634-0689ccc1d7d6/go.mod h1:ezvh/TsK7cY6rbqRK0oQQ8IAqLxYwwyPxAX1Pzy0ii0= k8s.io/gengo v0.0.0-20190822140433-26a664648505/go.mod h1:ezvh/TsK7cY6rbqRK0oQQ8IAqLxYwwyPxAX1Pzy0ii0= k8s.io/klog v0.0.0-20181102134211-b9b56d5dfc92/go.mod h1:Gq+BEi5rUBO/HRz0bTSXDUcqjScdoY3a9IHpCEIOOfk= @@ -588,20 +600,19 @@ k8s.io/klog v1.0.0 h1:Pt+yjF5aB1xDSVbau4VsWe+dQNzA0qv1LlXdC2dF6Q8= k8s.io/klog v1.0.0/go.mod h1:4Bi6QPql/J/LkTDqv7R/cd3hPo4k2DG6Ptcz060Ez5I= k8s.io/kube-openapi v0.0.0-20191107075043-30be4d16710a h1:UcxjrRMyNx/i/y8G7kPvLyy7rfbeuf1PYyBf973pgyU= k8s.io/kube-openapi v0.0.0-20191107075043-30be4d16710a/go.mod h1:1TqjTSzOxsLGIKfj0lK8EeCP7K1iUG65v09OM0/WG5E= -k8s.io/legacy-cloud-providers v0.17.0/go.mod h1:DdzaepJ3RtRy+e5YhNtrCYwlgyK87j/5+Yfp0L9Syp8= +k8s.io/legacy-cloud-providers v0.17.4/go.mod h1:FikRNoD64ECjkxO36gkDgJeiQWwyZTuBkhu+yxOc1Js= k8s.io/utils v0.0.0-20191114184206-e782cd3c129f h1:GiPwtSzdP43eI1hpPCbROQCCIgCuiMMNF8YUVLF3vJo= k8s.io/utils v0.0.0-20191114184206-e782cd3c129f/go.mod h1:sZAwmy6armz5eXlNoLmJcl4F1QuKu7sr+mFQ0byX7Ew= -knative.dev/client v0.13.1-0.20200406212659-8a60d2ebf8e2 h1:fr3KOo5KOM4PMc7DovHr2XzUY01UBWVeS8xcgng2wCA= -knative.dev/client v0.13.1-0.20200406212659-8a60d2ebf8e2/go.mod h1:FaXTcYIZbzoA6yfisrN0c8GLleqk6+D9jmYcHTgvf8M= -knative.dev/eventing v0.13.5 h1:+iihvTcV2QH0Mgu237fG/z0GptDxQxbXOAtcKveJBjI= -knative.dev/eventing v0.13.5/go.mod h1:UxweNv8yXhsdHJitcb9R6rmfNaUD2DFi9GWwNRyIs58= -knative.dev/eventing-contrib v0.14.0 h1:KrDufWSbngkPI7436JqKbd/FPU1XmzZnsy4SWXb5UCY= -knative.dev/eventing-contrib v0.14.0/go.mod h1:SnXZgSGgMSMLNFTwTnpaOH7hXDzTFtw0J8OmHflNx3g= -knative.dev/pkg v0.0.0-20200404181734-92cdec5b3593 h1:ubDiFWWncTD4TkA3hDH/JgGOYJlp3qyUjXf2rEIRLiM= -knative.dev/pkg v0.0.0-20200404181734-92cdec5b3593/go.mod h1:pgODObA1dTyhNoFxPZTTjNWfx6F0aKsKzn+vaT9XO/Q= -knative.dev/serving v0.13.1-0.20200403170819-0e8f7a9e34f0 h1:Vg92uLJq34mq7DDO1CnTNbjb40Ktk4UDgexICYDWvek= -knative.dev/serving v0.13.1-0.20200403170819-0e8f7a9e34f0/go.mod h1:x2n255JS2XBI39tmjZ8CwTxIf9EKNMCrkVuiOttLRm0= -knative.dev/test-infra v0.0.0-20200403181419-e84f0d1a3647/go.mod h1:xcdUkMJrLlBswIZqL5zCuBFOC22WIPMQoVX1L35i0vQ= +knative.dev/client v0.14.0 h1:QHA1WlzwL8YjLc1KRUJIi1UmSvQljTp0uDWvkEee8hc= +knative.dev/client v0.14.0/go.mod h1:r7Y5gp8Yt6cuJvN6r7+gOmNosVoLkOt01EDKn2A07wU= +knative.dev/eventing v0.14.1 h1:YmnEl3IBVRkBcVYWPMWZegRGifeI7ibcA9xuhHWvAaw= +knative.dev/eventing v0.14.1/go.mod h1:UxweNv8yXhsdHJitcb9R6rmfNaUD2DFi9GWwNRyIs58= +knative.dev/eventing-contrib v0.14.1 h1:lo3ejCNhV9YqByZwmi11JMYVEeTeczlvIKlM81JRLF8= +knative.dev/eventing-contrib v0.14.1/go.mod h1:SnXZgSGgMSMLNFTwTnpaOH7hXDzTFtw0J8OmHflNx3g= +knative.dev/pkg v0.0.0-20200414233146-0eed424fa4ee h1:G1QedLB/RxF4QTyL1Pq9M1QK1uj8khQgTypofUXrG20= +knative.dev/pkg v0.0.0-20200414233146-0eed424fa4ee/go.mod h1:pgODObA1dTyhNoFxPZTTjNWfx6F0aKsKzn+vaT9XO/Q= +knative.dev/serving v0.14.0 h1:9iDyOqTciNuAh2D5KJP0soOq23FDR4HQHdIQNBQ/rAE= +knative.dev/serving v0.14.0/go.mod h1:x2n255JS2XBI39tmjZ8CwTxIf9EKNMCrkVuiOttLRm0= knative.dev/test-infra v0.0.0-20200413202711-9cf64fb1b912 h1:RZJe3OFkal3m9lorMSS2BaEnBs4OPj2o5/Oiw0JXlQY= knative.dev/test-infra v0.0.0-20200413202711-9cf64fb1b912/go.mod h1:xcdUkMJrLlBswIZqL5zCuBFOC22WIPMQoVX1L35i0vQ= modernc.org/cc v1.0.0/go.mod h1:1Sk4//wdnYJiUIxnW8ddKpaOJCF37yAdqYnkxUpaYxw= diff --git a/plugins/source-github/hack/build.sh b/plugins/source-github/hack/build.sh index 693a4431..9c9efc4d 100755 --- a/plugins/source-github/hack/build.sh +++ b/plugins/source-github/hack/build.sh @@ -27,6 +27,9 @@ fi set -eu +# counterfeiter +COUNTERFEITER=github.com/maxbrunsfeld/counterfeiter/v6 + # Run build run() { # Switch on modules unconditionally @@ -54,18 +57,27 @@ run() { fi # Fast mode: Only compile and maybe run test - if $(has_flag --fast -f); then + if $(has_flag --compile --fast -f); then go_build if $(has_flag --test -t); then go_test fi + + if $(has_flag --e2e); then + go_e2e + fi exit 0 fi # Run only tests if $(has_flag --test -t); then go_test + exit 0 + fi + + # Run only e2e tests + if $(has_flag --e2e); then go_e2e exit 0 fi @@ -103,6 +115,12 @@ codegen() { # Check for license headers check_license + + # Generate fakes + generate_fakes + + # Generate fakes + generate_docs } go_fmt() { @@ -188,7 +206,7 @@ check_license() { local check_output=$(mktemp /tmp/kn-source_github-licence-check.XXXXXX) for ext in "${extensions_to_check[@]}"; do - find . -name "*.$ext" -a \! -path "./vendor/*" -a \! -path "./.*" -print0 | + find . -name "*.$ext" -a \! -path "./vendor/*" -a \! -path "./pkg/*fakes*" -a \! -path "./.*" -print0 | while IFS= read -r -d '' path; do for rword in "${required_keywords[@]}"; do if ! grep -q "$rword" "$path"; then @@ -221,6 +239,41 @@ generate_docs() { go run "./hack/generate_docs.go" "." } +generate_fakes() { + echo "🎭 Fakes (pkg/types)" + mkdir -p ./pkg/types/typesfakes + genfakes=false + for f in ./pkg/types/*.go + do + if [ "$f" -nt ./pkg/types/typesfakes ]; then + echo "Found newer file: $f, generating new fakes" + genfakes=true + fi + done + if $genfakes ; then + rm -rf "./pkg/types/typesfakes" + mkdir -p "./pkg/types/typesfakes" + go generate ./pkg/types/... + fi + + echo "🎭 Fakes (3rd parties)" + mkdir -p "./pkg/fakes" + + TYPES_PACKAGE=knative.dev/eventing-contrib/github/pkg/client/clientset/versioned/typed/sources/v1alpha1 + TYPES=( SourcesV1alpha1Interface GitHubSourcesGetter GitHubSourceInterface ) + FILES=( ./vendor/knative.dev/eventing-contrib/github/pkg/client/clientset/versioned/typed/sources ) + CFILES=( fake_sources_v1alpha1interface.go fake_sources_githubsourcesgetter.go fake_sources_githubsourceinterface.go ) + + i=0 + for t in ${TYPES[@]} + do + if [[ ${FILES[0]} -nt ./pkg/fakes/${CFILES[$i]} ]]; then + go run $COUNTERFEITER -o ./pkg/fakes/${CFILES[$i]} $TYPES_PACKAGE.$t + fi + i=$((i+1)) + done +} + watch() { local command="./hack/build.sh --fast" local fswatch_opts='-e "^\..*$" -o pkg cmd' @@ -334,7 +387,7 @@ Usage: $(basename $BASH_SOURCE) [... options ...] with the following options: --f --fast Only compile (without dep update, formatting, testing, doc gen) +-f --fast, --compile Only compile (without dep update, formatting, testing, doc gen) -t --test Run tests when used with --fast or --watch -e --e2e Run the e2e tests when used with --fast or --watch -c --codegen Runs formatting, doc gen and update without compiling/testing @@ -357,6 +410,7 @@ Examples: * Run only tests: .................... build.sh --test * Run only e2e tests: ................ build.sh --e2e * Compile with tests: ................ build.sh -f -t +* Generate fakes: .................... build.sh --codegen * Automatic recompilation: ........... build.sh --watch * Build cross platform binaries: ..... build.sh --all EOT diff --git a/plugins/source-github/hack/generate_docs.go b/plugins/source-github/hack/generate_docs.go index 75749242..719a80f8 100644 --- a/plugins/source-github/hack/generate_docs.go +++ b/plugins/source-github/hack/generate_docs.go @@ -16,8 +16,25 @@ package main import ( "fmt" + "os" + + "github.com/maximilien/kn-source-github/pkg/factories" + + "github.com/maximilien/kn-source-pkg/pkg/core" + "github.com/maximilien/kn-source-pkg/pkg/util" ) func main() { - fmt.Printf("This is placeholder code to get the dependencies merged. Sudsequent PRs will have kn-source-guthub code\n") + ghSourceFactory := factories.NewGHSourceFactory() + + ghCommandFactory := factories.NewGHCommandFactory(ghSourceFactory) + ghFlagsFactory := factories.NewGHFlagsFactory(ghSourceFactory) + ghRunEFactory := factories.NewGHRunEFactory(ghSourceFactory) + + rootCmd := core.NewKnSourceCommand(ghSourceFactory, ghCommandFactory, ghFlagsFactory, ghRunEFactory) + err := util.ReadmeGenerator(rootCmd) + if err != nil { + fmt.Fprintln(os.Stdout, err) + os.Exit(1) + } } \ No newline at end of file diff --git a/plugins/source-github/pkg/client/client.go b/plugins/source-github/pkg/client/client.go new file mode 100644 index 00000000..0ed0d3f4 --- /dev/null +++ b/plugins/source-github/pkg/client/client.go @@ -0,0 +1,140 @@ +// Copyright © 2019 The Knative 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 client + +import ( + "github.com/maximilien/kn-source-github/pkg/types" + + sourceclient "github.com/maximilien/kn-source-pkg/pkg/client" + sourcetypes "github.com/maximilien/kn-source-pkg/pkg/types" + + knerrors "knative.dev/client/pkg/errors" + + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + "k8s.io/client-go/rest" + + v1alpha1 "knative.dev/eventing-contrib/github/pkg/apis/sources/v1alpha1" + clientv1alpha1 "knative.dev/eventing-contrib/github/pkg/client/clientset/versioned/typed/sources/v1alpha1" +) + +type ghSourceClient struct { + namespace string + ghSourceParams *types.GHSourceParams + knSourceClient sourcetypes.KnSourceClient + ghSourcesV1 clientv1alpha1.SourcesV1alpha1Interface +} + +func NewGHSourceClient(ghSourceParams *types.GHSourceParams, namespace string) types.GHSourceClient { + return &ghSourceClient{ + namespace: namespace, + ghSourceParams: ghSourceParams, + knSourceClient: sourceclient.NewKnSourceClient(ghSourceParams.KnSourceParams, namespace), + } +} + +// Namespace for this client +func (client *ghSourceClient) Namespace() string { + return client.knSourceClient.Namespace() +} + +// RestConfig the REST cconfig +func (client *ghSourceClient) RestConfig() *rest.Config { + return client.knSourceClient.RestConfig() +} + +// KnSourceClient interface for this client +func (client *ghSourceClient) KnSourceClient() sourcetypes.KnSourceClient { + return client +} + +// KnSourceParams for common Kn source parameters +func (client *ghSourceClient) KnSourceParams() *sourcetypes.KnSourceParams { + return client.GHSourceParams().KnSourceParams +} + +// GHSourceParams for GitHub source specific parameters +func (client *ghSourceClient) GHSourceParams() *types.GHSourceParams { + return client.ghSourceParams +} + +// GetGHSource is used to create and initialize an GHSource +func (client *ghSourceClient) GetGHSource(name string) (*v1alpha1.GitHubSource, error) { + ghSourcesV1, err := client.GHSourcesV1() + if err != nil { + return nil, knerrors.GetError(err) + } + + getGHSource, err := ghSourcesV1.GitHubSources(client.namespace).Get(name, v1.GetOptions{}) + if err != nil { + return nil, knerrors.GetError(err) + } + return getGHSource, nil +} + +// CreateGHSource is used to create and initialize an GHSource +func (client *ghSourceClient) CreateGHSource(ghSource *v1alpha1.GitHubSource) (*v1alpha1.GitHubSource, error) { + ghSourcesV1, err := client.GHSourcesV1() + if err != nil { + return nil, knerrors.GetError(err) + } + + createGHSource, err := ghSourcesV1.GitHubSources(client.namespace).Create(ghSource) + if err != nil { + return nil, knerrors.GetError(err) + } + return createGHSource, nil +} + +// UpdateGHSource is used to update a GHSource +func (client *ghSourceClient) UpdateGHSource(ghSource *v1alpha1.GitHubSource) (*v1alpha1.GitHubSource, error) { + ghSourcesV1, err := client.GHSourcesV1() + if err != nil { + return nil, knerrors.GetError(err) + } + + updateGHSource, err := ghSourcesV1.GitHubSources(client.namespace).Update(ghSource) + if err != nil { + return nil, knerrors.GetError(err) + } + return updateGHSource, nil +} + +// DeleteGHSource is used to delete an GHSource +func (client *ghSourceClient) DeleteGHSource(name string) error { + ghSourcesV1, err := client.GHSourcesV1() + if err != nil { + return knerrors.GetError(err) + } + + err = ghSourcesV1.GitHubSources(client.namespace).Delete(name, &v1.DeleteOptions{}) + if err != nil { + return knerrors.GetError(err) + } + + return nil +} + +// Private +func (client *ghSourceClient) GHSourcesV1() (clientv1alpha1.SourcesV1alpha1Interface, error) { + var err error + if client.ghSourcesV1 == nil { + client.ghSourcesV1, err = clientv1alpha1.NewForConfig(client.RestConfig()) + if err != nil { + return nil, err + } + } + return client.ghSourcesV1, nil +} diff --git a/plugins/source-github/pkg/client/client_test.go b/plugins/source-github/pkg/client/client_test.go new file mode 100644 index 00000000..f904aa68 --- /dev/null +++ b/plugins/source-github/pkg/client/client_test.go @@ -0,0 +1,78 @@ +// Copyright © 2019 The Knative 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 client + +import ( + "testing" + + "gotest.tools/assert" + + "knative.dev/eventing-contrib/github/pkg/apis/sources/v1alpha1" +) + +func TestKnSourceParams(t *testing.T) { + ghSourceParams := NewFakeGHSourceParams() + ghSourceClient := NewFakeGHSourceClient(ghSourceParams, &v1alpha1.GitHubSource{}) + + assert.Equal(t, ghSourceClient.KnSourceParams(), ghSourceParams.KnSourceParams) +} + +func TestGHSourceParams(t *testing.T) { + ghSourceParams := NewFakeGHSourceParams() + ghSourceClient := NewFakeGHSourceClient(ghSourceParams, &v1alpha1.GitHubSource{}) + + assert.Equal(t, ghSourceClient.GHSourceParams(), ghSourceParams) +} + +func TestNamespace(t *testing.T) { + ghSourceClient := NewFakeGHSourceClient(NewFakeGHSourceParams(), &v1alpha1.GitHubSource{}) + assert.Equal(t, ghSourceClient.Namespace(), "fake-namespace") +} + +func TestRestConfig(t *testing.T) { + ghSourceClient := NewFakeGHSourceClient(NewFakeGHSourceParams(), &v1alpha1.GitHubSource{}) + assert.Assert(t, ghSourceClient.RestConfig() != nil) +} + +func TestGetGHSource(t *testing.T) { + fakeGHSource := &v1alpha1.GitHubSource{} + ghSourceClient := NewFakeGHSourceClient(NewFakeGHSourceParams(), fakeGHSource) + ghSource, err := ghSourceClient.GetGHSource("fake-name") + assert.Assert(t, err == nil) + assert.Assert(t, ghSource == fakeGHSource) +} + +func TestCreateGHSource(t *testing.T) { + fakeGHSource := &v1alpha1.GitHubSource{} + ghSourceClient := NewFakeGHSourceClient(NewFakeGHSourceParams(), fakeGHSource) + ghSource, err := ghSourceClient.CreateGHSource(fakeGHSource) + assert.Assert(t, err == nil) + assert.Assert(t, ghSource == fakeGHSource) +} + +func TestUpdateGHSource(t *testing.T) { + fakeGHSource := &v1alpha1.GitHubSource{} + ghSourceClient := NewFakeGHSourceClient(NewFakeGHSourceParams(), fakeGHSource) + ghSource, err := ghSourceClient.UpdateGHSource(fakeGHSource) + assert.Assert(t, err == nil) + assert.Assert(t, ghSource == fakeGHSource) +} + +func TestDeleteGHSource(t *testing.T) { + fakeGHSource := &v1alpha1.GitHubSource{} + ghSourceClient := NewFakeGHSourceClient(NewFakeGHSourceParams(), fakeGHSource) + err := ghSourceClient.DeleteGHSource("fake-name") + assert.Assert(t, err == nil) +} diff --git a/plugins/source-github/pkg/client/github_source_builder.go b/plugins/source-github/pkg/client/github_source_builder.go new file mode 100644 index 00000000..fd61705a --- /dev/null +++ b/plugins/source-github/pkg/client/github_source_builder.go @@ -0,0 +1,84 @@ +// Copyright © 2019 The Knative 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 client + +import ( + "fmt" + + v1alpha1 "knative.dev/eventing-contrib/github/pkg/apis/sources/v1alpha1" + + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + duckv1 "knative.dev/pkg/apis/duck/v1" +) + +// GitHubSourceBuilder is for building the source +type GitHubSourceBuilder struct { + ghSource *v1alpha1.GitHubSource +} + +// NewGitHubSourceBuilder for building ApiServer source object +func NewGitHubSourceBuilder(name string) *GitHubSourceBuilder { + return &GitHubSourceBuilder{ + ghSource: &v1alpha1.GitHubSource{ + ObjectMeta: metav1.ObjectMeta{ + Name: name, + }, + }, + } +} + +// OrgRepo sets the org/owner and repository +func (b *GitHubSourceBuilder) OrgRepo(org, repo string) *GitHubSourceBuilder { + b.ghSource.Spec.OwnerAndRepository = fmt.Sprintf("%s/%s", org, repo) + return b +} + +// APIURL to set the value of the GitHub APIURL +func (b *GitHubSourceBuilder) APIURL(apiURL string) *GitHubSourceBuilder { + b.ghSource.Spec.GitHubAPIURL = apiURL + return b +} + +// AccessToken the access-token to use for this GitHub source +func (b *GitHubSourceBuilder) AccessToken(accessToken string) *GitHubSourceBuilder { + b.ghSource.Spec.AccessToken = v1alpha1.SecretValueFromSource{ + SecretKeyRef: &corev1.SecretKeySelector{ + Key: accessToken, + }, + } + return b +} + +// SecretToken the secret-token to use for this GitHub source +func (b *GitHubSourceBuilder) SecretToken(secretToken string) *GitHubSourceBuilder { + b.ghSource.Spec.SecretToken = v1alpha1.SecretValueFromSource{ + SecretKeyRef: &corev1.SecretKeySelector{ + Key: secretToken, + }, + } + return b +} + +// Sink or destination of the source +func (b *GitHubSourceBuilder) Sink(sink *duckv1.Destination) *GitHubSourceBuilder { + b.ghSource.Spec.Sink = sink + return b +} + +// Build the GitHubSource object +func (b *GitHubSourceBuilder) Build() *v1alpha1.GitHubSource { + return b.ghSource +} diff --git a/plugins/source-github/pkg/client/github_source_builder_test.go b/plugins/source-github/pkg/client/github_source_builder_test.go new file mode 100644 index 00000000..20a0ce89 --- /dev/null +++ b/plugins/source-github/pkg/client/github_source_builder_test.go @@ -0,0 +1,63 @@ +// Copyright © 2019 The Knative 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 client + +import ( + "fmt" + "testing" + + "gotest.tools/assert" + + duckv1 "knative.dev/pkg/apis/duck/v1" +) + +var builder *GitHubSourceBuilder + +func TestNewGitHubSourceBuilder(t *testing.T) { + setup(t) + assert.Assert(t, builder.ghSource.ObjectMeta.Name == "fake-builder") +} + +func TestOrgRepo(t *testing.T) { + setup(t) + builder = builder.OrgRepo("fake-org", "fake-repo") + assert.Assert(t, builder.ghSource.Spec.OwnerAndRepository == fmt.Sprintf("fake-org/fake-repo")) +} + +func TestAPIURL(t *testing.T) { + setup(t) + builder = builder.APIURL("https://fake-api-url") + assert.Assert(t, builder.ghSource.Spec.GitHubAPIURL == fmt.Sprintf("https://fake-api-url")) +} + +func TestSink(t *testing.T) { + setup(t) + fakeSink := &duckv1.Destination{} + builder := builder.Sink(fakeSink) + assert.Assert(t, builder.ghSource.Spec.Sink == fakeSink) +} + +func TestBuild(t *testing.T) { + setup(t) + build := builder.Build() + assert.Assert(t, builder.ghSource == build) +} + +// Private + +func setup(t *testing.T) { + builder = NewGitHubSourceBuilder("fake-builder") + assert.Assert(t, builder != nil) +} diff --git a/plugins/source-github/pkg/client/test_utils.go b/plugins/source-github/pkg/client/test_utils.go new file mode 100644 index 00000000..41a926dd --- /dev/null +++ b/plugins/source-github/pkg/client/test_utils.go @@ -0,0 +1,64 @@ +// Copyright © 2019 The Knative 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 client + +import ( + "k8s.io/client-go/rest" + + "knative.dev/eventing-contrib/github/pkg/apis/sources/v1alpha1" + + "github.com/maximilien/kn-source-github/pkg/types" + + sourcestypes "github.com/maximilien/kn-source-pkg/pkg/types" + + fakes "github.com/maximilien/kn-source-github/pkg/fakes" + sourcestypesfakes "github.com/maximilien/kn-source-pkg/pkg/types/typesfakes" +) + +func NewFakeGHSourceParams() *types.GHSourceParams { + return &types.GHSourceParams{ + KnSourceParams: &sourcestypes.KnSourceParams{}, + + Org: "fake-org", + Repo: "fake-repo", + + APIURL: "https://fake-api-url", + SecretToken: "fake-secret-token", + AccessToken: "fake-access-token", + } +} + +func NewFakeGHSourceClient(ghSourceParams *types.GHSourceParams, ghSource *v1alpha1.GitHubSource) types.GHSourceClient { + fakeGitHubSources := &fakes.FakeGitHubSourceInterface{} + fakeGitHubSources.GetReturns(ghSource, nil) + fakeGitHubSources.CreateReturns(ghSource, nil) + fakeGitHubSources.UpdateReturns(ghSource, nil) + fakeGitHubSources.DeleteReturns(nil) + + fakeGHSourcesV1 := &fakes.FakeSourcesV1alpha1Interface{} + fakeGHSourcesV1.GitHubSourcesReturns(fakeGitHubSources) + + knSourceClient := &sourcestypesfakes.FakeKnSourceClient{} + knSourceClient.KnSourceParamsReturns(ghSourceParams.KnSourceParams) + knSourceClient.NamespaceReturns("fake-namespace") + knSourceClient.RestConfigReturns(&rest.Config{}) + + return &ghSourceClient{ + namespace: "fake-namespace", + ghSourceParams: ghSourceParams, + knSourceClient: knSourceClient, + ghSourcesV1: fakeGHSourcesV1, + } +} diff --git a/plugins/source-github/pkg/factories/boilerplate.go b/plugins/source-github/pkg/factories/boilerplate.go new file mode 100644 index 00000000..4bb33ea3 --- /dev/null +++ b/plugins/source-github/pkg/factories/boilerplate.go @@ -0,0 +1,99 @@ +// Copyright © 2018 The Knative 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 factories + +import ( + "github.com/maximilien/kn-source-github/pkg/types" + + sourcetypes "github.com/maximilien/kn-source-pkg/pkg/types" +) + +// GHSourceFactory + +func (f *ghSourceFactory) KnSourceParams() *sourcetypes.KnSourceParams { + if f.ghSourceParams == nil { + f.initGHSourceParams() + } + return f.ghSourceParams.KnSourceParams +} + +func (f *ghSourceFactory) GHSourceParams() *types.GHSourceParams { + if f.ghSourceParams == nil { + f.initGHSourceParams() + } + return f.ghSourceParams +} + +func (f *ghSourceFactory) GHSourceClient() types.GHSourceClient { + return f.ghSourceClient +} + +// CommandFactory + +func (f *ghCommandFactory) KnSourceFactory() sourcetypes.KnSourceFactory { + return f.ghSourceFactory +} + +func (f *ghCommandFactory) GHSourceFactory() types.GHSourceFactory { + return f.ghSourceFactory +} + +func (f *ghCommandFactory) GHSourceParams() *types.GHSourceParams { + return f.ghSourceFactory.GHSourceParams() +} + +func (f *ghCommandFactory) KnSourceParams() *sourcetypes.KnSourceParams { + return f.ghSourceFactory.KnSourceParams() +} + +// FlagsFactory + +func (f *ghFlagsFactory) KnSourceFactory() sourcetypes.KnSourceFactory { + return f.ghSourceFactory +} + +func (f *ghFlagsFactory) KnSourceParams() *sourcetypes.KnSourceParams { + return f.ghSourceFactory.KnSourceParams() +} + +func (f *ghFlagsFactory) GHSourceParams() *types.GHSourceParams { + return f.ghSourceFactory.GHSourceParams() +} + +func (f *ghFlagsFactory) GHSourceFactory() types.GHSourceFactory { + return f.ghSourceFactory +} + +// RunEFactory + +func (f *ghRunEFactory) KnSourceParams() *sourcetypes.KnSourceParams { + return f.GHSourceFactory().KnSourceParams() +} + +func (f *ghRunEFactory) KnSourceClient(namespace string) sourcetypes.KnSourceClient { + return f.GHSourceFactory().CreateGHSourceClient(namespace) +} + +func (f *ghRunEFactory) GHSourceClient(namespace string) types.GHSourceClient { + return f.GHSourceFactory().CreateGHSourceClient(namespace) +} + +func (f *ghRunEFactory) KnSourceFactory() sourcetypes.KnSourceFactory { + return f.GHSourceFactory() +} + +func (f *ghRunEFactory) GHSourceFactory() types.GHSourceFactory { + return f.ghSourceFactory +} diff --git a/plugins/source-github/pkg/factories/boilerplate_test.go b/plugins/source-github/pkg/factories/boilerplate_test.go new file mode 100644 index 00000000..4612ceec --- /dev/null +++ b/plugins/source-github/pkg/factories/boilerplate_test.go @@ -0,0 +1,95 @@ +// Copyright © 2020 The Knative 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 factories + +import ( + "testing" + + "gotest.tools/assert" +) + +// KnSourceFactory + +func TestGHSourceFactory_KnSourceParams(t *testing.T) { + ghSourceFactory := NewGHSourceFactory() + + knSourceParams := ghSourceFactory.KnSourceParams() + assert.Assert(t, knSourceParams != nil) + + knSourceParams = ghSourceFactory.CreateKnSourceParams() + assert.Equal(t, ghSourceFactory.KnSourceParams(), knSourceParams) +} + +func TestGHSourceFactory_GHSourceParams(t *testing.T) { + ghSourceFactory := NewGHSourceFactory() + + ghSourceParams := ghSourceFactory.GHSourceParams() + assert.Assert(t, ghSourceParams != nil) + + ghSourceParams = ghSourceFactory.CreateGHSourceParams() + assert.Equal(t, ghSourceFactory.GHSourceParams(), ghSourceParams) +} + +// CommandFactory + +func TestCommandFactory_GHSourceFactory(t *testing.T) { + ghSourceFactory := NewGHSourceFactory() + commandFactory := NewGHCommandFactory(ghSourceFactory) + + assert.Equal(t, commandFactory.GHSourceFactory(), ghSourceFactory) +} + +// FlagsFactory + +func TestFlagsFactory_KnSourceFactory(t *testing.T) { + ghSourceFactory := NewGHSourceFactory() + flagsFactory := NewGHFlagsFactory(ghSourceFactory) + + assert.Equal(t, flagsFactory.KnSourceFactory(), ghSourceFactory) +} + +func TestFlagsFactory_GHSourceFactory(t *testing.T) { + ghSourceFactory := NewGHSourceFactory() + flagsFactory := NewGHFlagsFactory(ghSourceFactory) + + assert.Equal(t, flagsFactory.GHSourceFactory(), ghSourceFactory) +} + +// RunEFactory + +func TestRunEFactory_GHSourceClient(t *testing.T) { + runEFactory := NewGHRunEFactory(createFakeGHSourceFactory()) + + ghSourceClient := runEFactory.GHSourceClient("fake_namespace") + assert.Assert(t, ghSourceClient != nil) +} + +func TestRunEFactory_KnSourceParams(t *testing.T) { + runEFactory := NewGHRunEFactory(createFakeGHSourceFactory()) + + assert.Assert(t, runEFactory.GHSourceFactory().KnSourceParams() != nil) +} + +func TestRunEFactory_GHSourceParams(t *testing.T) { + runEFactory := NewGHRunEFactory(createFakeGHSourceFactory()) + + assert.Assert(t, runEFactory.GHSourceFactory().GHSourceParams() != nil) +} + +func TestRunEFactory_GHSourceClientFactory(t *testing.T) { + runEFactory := NewGHRunEFactory(createFakeGHSourceFactory()) + + assert.Assert(t, runEFactory.GHSourceFactory() != nil) +} diff --git a/plugins/source-github/pkg/factories/command_factory.go b/plugins/source-github/pkg/factories/command_factory.go new file mode 100644 index 00000000..da9a665b --- /dev/null +++ b/plugins/source-github/pkg/factories/command_factory.go @@ -0,0 +1,83 @@ +// Copyright © 2018 The Knative 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 factories + +import ( + "github.com/maximilien/kn-source-github/pkg/types" + + sourcefactories "github.com/maximilien/kn-source-pkg/pkg/factories" + sourcetypes "github.com/maximilien/kn-source-pkg/pkg/types" + + "github.com/spf13/cobra" +) + +type ghCommandFactory struct { + ghSourceFactory types.GHSourceFactory + defaultCommandFactory sourcetypes.CommandFactory +} + +func NewGHCommandFactory(ghSourceFactory types.GHSourceFactory) types.GHCommandFactory { + return &ghCommandFactory{ + ghSourceFactory: ghSourceFactory, + defaultCommandFactory: sourcefactories.NewDefaultCommandFactory(ghSourceFactory), + } +} + +func (f *ghCommandFactory) SourceCommand() *cobra.Command { + sourceCmd := f.defaultCommandFactory.SourceCommand() + sourceCmd.Use = "github" + sourceCmd.Short = "Knative eventing GitHub source plugin" + sourceCmd.Long = "Manage your Knative GitHub eventing sources" + return sourceCmd +} + +func (f *ghCommandFactory) CreateCommand() *cobra.Command { + createCmd := f.defaultCommandFactory.CreateCommand() + createCmd.Short = "create NAME" + createCmd.Long = "create a GitHub source" + createCmd.Example = `# Creates a new GitHub source with NAME using credentials +kn source github create NAME --access-token $MY_ACCESS_TOKEN --secret-token $MY_SECRET_TOKEN + +# Creates a new GitHub source with NAME with specified organization and repository using credentials +kn source github create NAME --org knative --repo client-contrib --access-token $MY_ACCESS_TOKEN --secret-token $MY_SECRET_TOKEN` + return createCmd +} + +func (f *ghCommandFactory) DeleteCommand() *cobra.Command { + deleteCmd := f.defaultCommandFactory.DeleteCommand() + deleteCmd.Short = "delete NAME" + deleteCmd.Long = "delete a GitHub source" + deleteCmd.Example = `# Deletes a GitHub source with NAME +kn source github delete NAME` + return deleteCmd +} + +func (f *ghCommandFactory) UpdateCommand() *cobra.Command { + updateCmd := f.defaultCommandFactory.UpdateCommand() + updateCmd.Short = "update NAME" + updateCmd.Long = "update a GitHub source" + updateCmd.Example = `# Updates a GitHub source with NAME +kn source github update NAME` + return updateCmd +} + +func (f *ghCommandFactory) DescribeCommand() *cobra.Command { + describeCmd := f.defaultCommandFactory.DescribeCommand() + describeCmd.Short = "describe NAME" + describeCmd.Long = "update a GitHub source" + describeCmd.Example = `# Describes a GitHub source with NAME +kn source github describe NAME` + return describeCmd +} diff --git a/plugins/source-github/pkg/factories/command_factory_test.go b/plugins/source-github/pkg/factories/command_factory_test.go new file mode 100644 index 00000000..b3718190 --- /dev/null +++ b/plugins/source-github/pkg/factories/command_factory_test.go @@ -0,0 +1,90 @@ +// Copyright © 2020 The Knative 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 factories + +import ( + "testing" + + "gotest.tools/assert" +) + +func TestNewGHCommandFactory(t *testing.T) { + knSourceFactory := NewGHSourceFactory() + commandFactory := NewGHCommandFactory(knSourceFactory) + + assert.Assert(t, commandFactory != nil) +} + +func TestSourceCommand(t *testing.T) { + commandFactory := NewGHCommandFactory(NewGHSourceFactory()) + + sourceCmd := commandFactory.SourceCommand() + assert.Assert(t, sourceCmd != nil) + + assert.Equal(t, sourceCmd.Use, "github") + assert.Equal(t, sourceCmd.Short, "Knative eventing GitHub source plugin") + assert.Equal(t, sourceCmd.Long, "Manage your Knative GitHub eventing sources") +} + +func TestCreateCommand(t *testing.T) { + commandFactory := NewGHCommandFactory(NewGHSourceFactory()) + + createCmd := commandFactory.CreateCommand() + assert.Assert(t, createCmd != nil) + + assert.Equal(t, createCmd.Short, "create NAME") + assert.Equal(t, createCmd.Long, "create a GitHub source") + assert.Equal(t, createCmd.Example, `# Creates a new GitHub source with NAME using credentials +kn source github create NAME --access-token $MY_ACCESS_TOKEN --secret-token $MY_SECRET_TOKEN + +# Creates a new GitHub source with NAME with specified organization and repository using credentials +kn source github create NAME --org knative --repo client-contrib --access-token $MY_ACCESS_TOKEN --secret-token $MY_SECRET_TOKEN`) +} + +func TestDeleteCommand(t *testing.T) { + commandFactory := NewGHCommandFactory(NewGHSourceFactory()) + + deleteCmd := commandFactory.DeleteCommand() + assert.Assert(t, deleteCmd != nil) + + assert.Equal(t, deleteCmd.Short, "delete NAME") + assert.Equal(t, deleteCmd.Long, "delete a GitHub source") + assert.Equal(t, deleteCmd.Example, `# Deletes a GitHub source with NAME +kn source github delete NAME`) +} + +func TestUpdateCommand(t *testing.T) { + commandFactory := NewGHCommandFactory(NewGHSourceFactory()) + + updateCmd := commandFactory.UpdateCommand() + assert.Assert(t, updateCmd != nil) + + assert.Equal(t, updateCmd.Short, "update NAME") + assert.Equal(t, updateCmd.Long, "update a GitHub source") + assert.Equal(t, updateCmd.Example, `# Updates a GitHub source with NAME +kn source github update NAME`) +} + +func TestDescribeCommand(t *testing.T) { + commandFactory := NewGHCommandFactory(NewGHSourceFactory()) + + describeCmd := commandFactory.DescribeCommand() + assert.Assert(t, describeCmd != nil) + + assert.Equal(t, describeCmd.Short, "describe NAME") + assert.Equal(t, describeCmd.Long, "update a GitHub source") + assert.Equal(t, describeCmd.Example, `# Describes a GitHub source with NAME +kn source github describe NAME`) +} diff --git a/plugins/source-github/pkg/factories/flags_factory.go b/plugins/source-github/pkg/factories/flags_factory.go new file mode 100644 index 00000000..a73e62e1 --- /dev/null +++ b/plugins/source-github/pkg/factories/flags_factory.go @@ -0,0 +1,66 @@ +// Copyright © 2018 The Knative 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 factories + +import ( + sourcefactories "github.com/maximilien/kn-source-pkg/pkg/factories" + sourcetypes "github.com/maximilien/kn-source-pkg/pkg/types" + + "github.com/maximilien/kn-source-github/pkg/types" + + "github.com/spf13/pflag" +) + +type ghFlagsFactory struct { + defaultFlagsFactory sourcetypes.FlagsFactory + ghSourceFactory types.GHSourceFactory +} + +func NewGHFlagsFactory(ghSourceFactory types.GHSourceFactory) types.GHFlagsFactory { + return &ghFlagsFactory{ + defaultFlagsFactory: sourcefactories.NewDefaultFlagsFactory(ghSourceFactory), + ghSourceFactory: ghSourceFactory, + } +} + +func (f *ghFlagsFactory) CreateFlags() *pflag.FlagSet { + flagSet := f.defaultFlagsFactory.CreateFlags() + flagSet.StringVar(&f.GHSourceParams().Org, "org", "", "The GitHub organization or username") + flagSet.StringVar(&f.GHSourceParams().Repo, "repo", "", "Repository name to consume messages from") + flagSet.StringVar(&f.GHSourceParams().APIURL, "api-url", "https://api.github.com", "The GitHub API URL to use") + flagSet.StringVar(&f.GHSourceParams().SecretToken, "secret-token", "", "The GitHub secret-token to use") + flagSet.StringVar(&f.GHSourceParams().AccessToken, "access-token", "", "The GitHub access-token to use") + return flagSet +} + +func (f *ghFlagsFactory) DeleteFlags() *pflag.FlagSet { + flagSet := f.defaultFlagsFactory.DeleteFlags() + return flagSet +} + +func (f *ghFlagsFactory) UpdateFlags() *pflag.FlagSet { + flagSet := f.defaultFlagsFactory.UpdateFlags() + flagSet.StringVar(&f.GHSourceParams().Org, "org", "", "The GitHub organization or username") + flagSet.StringVar(&f.GHSourceParams().Repo, "repo", "", "Repository name to consume messages from") + flagSet.StringVar(&f.GHSourceParams().APIURL, "api-url", "https://api.github.com", "The GitHub API URL to use") + flagSet.StringVar(&f.GHSourceParams().SecretToken, "secret-token", "", "The GitHub secret-token to use") + flagSet.StringVar(&f.GHSourceParams().AccessToken, "access-token", "", "The GitHub access-token to use") + return flagSet +} + +func (f *ghFlagsFactory) DescribeFlags() *pflag.FlagSet { + flagSet := f.defaultFlagsFactory.DescribeFlags() + return flagSet +} diff --git a/plugins/source-github/pkg/factories/flags_factory_test.go b/plugins/source-github/pkg/factories/flags_factory_test.go new file mode 100644 index 00000000..d14b710c --- /dev/null +++ b/plugins/source-github/pkg/factories/flags_factory_test.go @@ -0,0 +1,84 @@ +// Copyright © 2020 The Knative 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 factories + +import ( + "testing" + + "gotest.tools/assert" + + "github.com/spf13/pflag" +) + +func TestNewGHFlagsFactory(t *testing.T) { + flagsFactory := NewGHFlagsFactory(NewGHSourceFactory()) + assert.Assert(t, flagsFactory != nil) +} + +func TestCreateFlags(t *testing.T) { + flagsFactory := NewGHFlagsFactory(NewGHSourceFactory()) + + createFlags := flagsFactory.CreateFlags() + assert.Assert(t, createFlags != nil) + + testCreateUpdateFlags(t, createFlags) +} + +func TestDeleteFlags(t *testing.T) { + flagsFactory := NewGHFlagsFactory(NewGHSourceFactory()) + + deleteFlags := flagsFactory.DescribeFlags() + assert.Assert(t, deleteFlags != nil) +} + +func TestUpdateFlags(t *testing.T) { + flagsFactory := NewGHFlagsFactory(NewGHSourceFactory()) + + updateFlags := flagsFactory.CreateFlags() + assert.Assert(t, updateFlags != nil) + + testCreateUpdateFlags(t, updateFlags) +} + +func TestDescribeFlags(t *testing.T) { + flagsFactory := NewGHFlagsFactory(NewGHSourceFactory()) + + describeFlags := flagsFactory.DescribeFlags() + assert.Assert(t, describeFlags != nil) +} + +// Private + +func testCreateUpdateFlags(t *testing.T, flagSet *pflag.FlagSet) { + orgFlag, err := flagSet.GetString("org") + assert.NilError(t, err) + assert.Assert(t, orgFlag == "") + + repoFlag, err := flagSet.GetString("repo") + assert.NilError(t, err) + assert.Assert(t, repoFlag == "") + + apiURLFlag, err := flagSet.GetString("api-url") + assert.NilError(t, err) + assert.Assert(t, apiURLFlag == "https://api.github.com") + + secretTokenFlag, err := flagSet.GetString("secret-token") + assert.NilError(t, err) + assert.Assert(t, secretTokenFlag == "") + + accessTokenFlag, err := flagSet.GetString("access-token") + assert.NilError(t, err) + assert.Assert(t, accessTokenFlag == "") +} diff --git a/plugins/source-github/pkg/factories/rune_factory.go b/plugins/source-github/pkg/factories/rune_factory.go new file mode 100644 index 00000000..25348c31 --- /dev/null +++ b/plugins/source-github/pkg/factories/rune_factory.go @@ -0,0 +1,199 @@ +// Copyright © 2018 The Knative 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 factories + +import ( + "errors" + "fmt" + + "github.com/spf13/cobra" + + "github.com/maximilien/kn-source-github/pkg/client" + "github.com/maximilien/kn-source-github/pkg/types" + + sourcetypes "github.com/maximilien/kn-source-pkg/pkg/types" +) + +type ghRunEFactory struct { + ghSourceFactory types.GHSourceFactory +} + +func NewGHRunEFactory(ghSourceFactory types.GHSourceFactory) types.GHRunEFactory { + return &ghRunEFactory{ + ghSourceFactory: ghSourceFactory, + } +} + +func (f *ghRunEFactory) CreateRunE() sourcetypes.RunE { + return func(cmd *cobra.Command, args []string) error { + namespace, err := f.KnSourceParams().GetNamespace(cmd) + if err != nil { + return err + } + + if len(args) != 1 { + return errors.New("requires the NAME of the source to create as single argument") + } + + ghSourceClient := f.GHSourceClient(namespace) + + name := args[0] + + // client, err := servingv1client.NewForConfig(ghSourceClient.RestConfig()) + // if err != nil { + // return err + // } + + dynamicClient, err := f.KnSourceParams().KnParams.NewDynamicClient(namespace) + if err != nil { + return err + } + + fmt.Printf("f.KnSourceParams(): %#v\n", f.KnSourceParams()) + + objectRef, err := f.KnSourceParams().SinkFlag.ResolveSink(dynamicClient, namespace) + if err != nil { + return fmt.Errorf("cannot create GitHub source '%s' in namespace '%s' because: %s", + name, namespace, err.Error()) + } + + builder := client.NewGitHubSourceBuilder(name). + OrgRepo(ghSourceClient.GHSourceParams().Org, ghSourceClient.GHSourceParams().Repo). + APIURL(ghSourceClient.GHSourceParams().APIURL). + AccessToken(ghSourceClient.GHSourceParams().AccessToken). + SecretToken(ghSourceClient.GHSourceParams().SecretToken). + Sink(objectRef) + + _, err = ghSourceClient.CreateGHSource(builder.Build()) + if err != nil { + return fmt.Errorf( + "cannot create GitHub source '%s' in namespace '%s' because: %s", + name, namespace, err.Error()) + } else { + fmt.Fprintf(cmd.OutOrStdout(), "GitHub source '%s' created in namespace '%s'.\n", name, namespace) + } + + return nil + } +} + +func (f *ghRunEFactory) DeleteRunE() sourcetypes.RunE { + return func(cmd *cobra.Command, args []string) error { + namespace, err := f.KnSourceParams().GetNamespace(cmd) + if err != nil { + return err + } + + ghSourceClient := f.GHSourceClient(namespace) + + if len(args) != 1 { + return errors.New("requires the NAME of the source to `delete` as single argument") + } + + name := args[0] + + err = ghSourceClient.DeleteGHSource(name) + if err != nil { + return fmt.Errorf( + "cannot delete GitHub source '%s' in namespace '%s' because: %s", + name, namespace, err.Error()) + } else { + fmt.Fprintf(cmd.OutOrStdout(), "GitHub source '%s' deleted in namespace '%s'.\n", name, namespace) + } + + return nil + } +} + +func (f *ghRunEFactory) UpdateRunE() sourcetypes.RunE { + return func(cmd *cobra.Command, args []string) error { + namespace, err := f.KnSourceParams().GetNamespace(cmd) + if err != nil { + return err + } + + ghSourceClient := f.GHSourceClient(namespace) + + if len(args) != 1 { + return errors.New("requires the NAME of the source to update as single argument") + } + + name := args[0] + + dynamicClient, err := f.KnSourceParams().KnParams.NewDynamicClient(namespace) + if err != nil { + return err + } + + objectRef, err := f.KnSourceParams().SinkFlag.ResolveSink(dynamicClient, namespace) + if err != nil { + return fmt.Errorf("cannot update GitHub source '%s' in namespace '%s' because: %s", + name, namespace, err.Error()) + } + + builder := client.NewGitHubSourceBuilder(name). + OrgRepo(ghSourceClient.GHSourceParams().Org, ghSourceClient.GHSourceParams().Repo). + APIURL(ghSourceClient.GHSourceParams().APIURL). + AccessToken(ghSourceClient.GHSourceParams().AccessToken). + SecretToken(ghSourceClient.GHSourceParams().SecretToken). + Sink(objectRef) + + _, err = ghSourceClient.UpdateGHSource(builder.Build()) + if err != nil { + return fmt.Errorf( + "cannot update GitHub source '%s' in namespace '%s' because: %s", + name, namespace, err.Error()) + } else { + fmt.Fprintf(cmd.OutOrStdout(), "GitHub source '%s' updated in namespace '%s'.\n", name, namespace) + } + + return nil + } +} + +func (f *ghRunEFactory) DescribeRunE() sourcetypes.RunE { + return func(cmd *cobra.Command, args []string) error { + namespace, err := f.KnSourceParams().GetNamespace(cmd) + if err != nil { + return err + } + + ghSourceClient := f.GHSourceClient(namespace) + + if len(args) != 1 { + return errors.New("requires the NAME of the source to `describe` as single argument") + } + + name := args[0] + + ghSource, err := ghSourceClient.GetGHSource(name) + if err != nil { + return fmt.Errorf( + "cannot describe GitHub source '%s' in namespace '%s' because: %s", + name, namespace, err.Error()) + } else { + fmt.Fprintf(cmd.OutOrStdout(), "GitHub source '%s' in namespace '%s'.\n", name, namespace) + fmt.Fprintf(cmd.OutOrStdout(), " service account name: %s", ghSource.Spec.ServiceAccountName) + fmt.Fprintf(cmd.OutOrStdout(), " owner and repository: %s\n", ghSource.Spec.OwnerAndRepository) + fmt.Fprintf(cmd.OutOrStdout(), " event types list : %s\n", ghSource.Spec.EventTypes) + fmt.Fprintf(cmd.OutOrStdout(), " access token : %s\n", ghSource.Spec.AccessToken) + fmt.Fprintf(cmd.OutOrStdout(), " secret token : %s\n", ghSource.Spec.SecretToken) + fmt.Fprintf(cmd.OutOrStdout(), " GitHub API URL : %s\n", ghSource.Spec.GitHubAPIURL) + fmt.Fprintf(cmd.OutOrStdout(), " secure : %b\n", ghSource.Spec.Secure) + } + + return nil + } +} diff --git a/plugins/source-github/pkg/factories/rune_factory_test.go b/plugins/source-github/pkg/factories/rune_factory_test.go new file mode 100644 index 00000000..e5545c1e --- /dev/null +++ b/plugins/source-github/pkg/factories/rune_factory_test.go @@ -0,0 +1,54 @@ +// Copyright © 2020 The Knative 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 factories + +import ( + "testing" + + "gotest.tools/assert" +) + +func TestNewGHRunEFactory(t *testing.T) { + runEFactory := NewGHRunEFactory(createFakeGHSourceFactory()) + assert.Assert(t, runEFactory != nil) +} + +func TestCreateRunE(t *testing.T) { + runEFactory := NewGHRunEFactory(createFakeGHSourceFactory()) + + createRunE := runEFactory.CreateRunE() + assert.Assert(t, createRunE != nil) +} + +func TestDeleteRunE(t *testing.T) { + runEFactory := NewGHRunEFactory(createFakeGHSourceFactory()) + + deleteRunE := runEFactory.DeleteRunE() + assert.Assert(t, deleteRunE != nil) +} + +func TestUpdateRunE(t *testing.T) { + runEFactory := NewGHRunEFactory(createFakeGHSourceFactory()) + + updateRunE := runEFactory.UpdateRunE() + assert.Assert(t, updateRunE != nil) +} + +func TestDescribeRunE(t *testing.T) { + runEFactory := NewGHRunEFactory(createFakeGHSourceFactory()) + + describeRunE := runEFactory.DescribeRunE() + assert.Assert(t, describeRunE != nil) +} diff --git a/plugins/source-github/pkg/factories/source_factory.go b/plugins/source-github/pkg/factories/source_factory.go new file mode 100644 index 00000000..9ef8ded3 --- /dev/null +++ b/plugins/source-github/pkg/factories/source_factory.go @@ -0,0 +1,84 @@ +// Copyright © 2018 The Knative 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 factories + +import ( + "github.com/maximilien/kn-source-github/pkg/client" + "github.com/maximilien/kn-source-github/pkg/types" + + "knative.dev/client/pkg/kn/commands/flags" + + sourcefactories "github.com/maximilien/kn-source-pkg/pkg/factories" + sourcetypes "github.com/maximilien/kn-source-pkg/pkg/types" +) + +type ghSourceFactory struct { + ghSourceParams *types.GHSourceParams + ghSourceClient types.GHSourceClient + + knSourceFactory sourcetypes.KnSourceFactory +} + +func NewGHSourceFactory() types.GHSourceFactory { + return &ghSourceFactory{ + ghSourceParams: nil, + ghSourceClient: nil, + knSourceFactory: sourcefactories.NewDefaultKnSourceFactory(), + } +} + +func (f *ghSourceFactory) CreateKnSourceParams() *sourcetypes.KnSourceParams { + if f.ghSourceParams == nil { + f.initGHSourceParams() + } + return f.ghSourceParams.KnSourceParams +} + +func (f *ghSourceFactory) CreateGHSourceParams() *types.GHSourceParams { + if f.ghSourceParams == nil { + f.initGHSourceParams() + } + return f.ghSourceParams +} + +func (f *ghSourceFactory) CreateKnSourceClient(namespace string) sourcetypes.KnSourceClient { + return f.CreateGHSourceClient(namespace) +} + +func (f *ghSourceFactory) CreateGHSourceClient(namespace string) types.GHSourceClient { + if f.ghSourceClient == nil { + f.initGHSourceClient(namespace) + } + return f.ghSourceClient +} + +// Private + +func (f *ghSourceFactory) initGHSourceClient(namespace string) { + if f.ghSourceClient == nil { + f.ghSourceClient = client.NewGHSourceClient(f.GHSourceParams(), namespace) + } +} + +// Private + +func (f *ghSourceFactory) initGHSourceParams() { + f.ghSourceParams = &types.GHSourceParams{ + KnSourceParams: &sourcetypes.KnSourceParams{ + SinkFlag: flags.SinkFlags{}, + }, + } + f.ghSourceParams.KnSourceParams.Initialize() +} diff --git a/plugins/source-github/pkg/factories/source_factory_test.go b/plugins/source-github/pkg/factories/source_factory_test.go new file mode 100644 index 00000000..f48d7486 --- /dev/null +++ b/plugins/source-github/pkg/factories/source_factory_test.go @@ -0,0 +1,77 @@ +// Copyright © 2020 The Knative 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 factories + +import ( + "testing" + + "github.com/maximilien/kn-source-github/pkg/client" + "github.com/maximilien/kn-source-github/pkg/types" + + "knative.dev/eventing-contrib/github/pkg/apis/sources/v1alpha1" + + "gotest.tools/assert" + + sourcetypes "github.com/maximilien/kn-source-pkg/pkg/types" +) + +func TestNewGHSourceFactory(t *testing.T) { + ghSourceFactory := createFakeGHSourceFactory() + + assert.Assert(t, ghSourceFactory != nil) +} + +func TestCreateKnSourceParams(t *testing.T) { + ghSourceFactory := createFakeGHSourceFactory() + + ghSourceParams := ghSourceFactory.CreateKnSourceParams() + assert.Assert(t, ghSourceParams != nil) +} + +func TestCreateGHSourceParams(t *testing.T) { + ghSourceFactory := createFakeGHSourceFactory() + + ghSourceParams := ghSourceFactory.CreateGHSourceParams() + assert.Assert(t, ghSourceParams != nil) +} + +func TestCreateKnSourceClient(t *testing.T) { + ghSourceFactory := createFakeGHSourceFactory() + client := ghSourceFactory.CreateKnSourceClient("fake-namespace") + + assert.Assert(t, client != nil) + assert.Equal(t, client.Namespace(), "fake-namespace") +} + +func TestCreateGHSourceClient(t *testing.T) { + ghSourceFactory := createFakeGHSourceFactory() + client := ghSourceFactory.CreateGHSourceClient("fake-namespace") + + assert.Assert(t, client != nil) + assert.Equal(t, client.Namespace(), "fake-namespace") +} + +// Private + +func createFakeGHSourceFactory() types.GHSourceFactory { + fakeGHSourceClient := client.NewFakeGHSourceClient(client.NewFakeGHSourceParams(), &v1alpha1.GitHubSource{}) + + return &ghSourceFactory{ + ghSourceParams: &types.GHSourceParams{ + KnSourceParams: &sourcetypes.KnSourceParams{}, + }, + ghSourceClient: fakeGHSourceClient, + } +} diff --git a/plugins/source-github/pkg/fakes/fake_sources_githubsourceinterface.go b/plugins/source-github/pkg/fakes/fake_sources_githubsourceinterface.go new file mode 100644 index 00000000..59a31a11 --- /dev/null +++ b/plugins/source-github/pkg/fakes/fake_sources_githubsourceinterface.go @@ -0,0 +1,750 @@ +// Code generated by counterfeiter. DO NOT EDIT. +package fakes + +import ( + "sync" + + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/watch" + v1alpha1a "knative.dev/eventing-contrib/github/pkg/apis/sources/v1alpha1" + "knative.dev/eventing-contrib/github/pkg/client/clientset/versioned/typed/sources/v1alpha1" +) + +type FakeGitHubSourceInterface struct { + CreateStub func(*v1alpha1a.GitHubSource) (*v1alpha1a.GitHubSource, error) + createMutex sync.RWMutex + createArgsForCall []struct { + arg1 *v1alpha1a.GitHubSource + } + createReturns struct { + result1 *v1alpha1a.GitHubSource + result2 error + } + createReturnsOnCall map[int]struct { + result1 *v1alpha1a.GitHubSource + result2 error + } + DeleteStub func(string, *v1.DeleteOptions) error + deleteMutex sync.RWMutex + deleteArgsForCall []struct { + arg1 string + arg2 *v1.DeleteOptions + } + deleteReturns struct { + result1 error + } + deleteReturnsOnCall map[int]struct { + result1 error + } + DeleteCollectionStub func(*v1.DeleteOptions, v1.ListOptions) error + deleteCollectionMutex sync.RWMutex + deleteCollectionArgsForCall []struct { + arg1 *v1.DeleteOptions + arg2 v1.ListOptions + } + deleteCollectionReturns struct { + result1 error + } + deleteCollectionReturnsOnCall map[int]struct { + result1 error + } + GetStub func(string, v1.GetOptions) (*v1alpha1a.GitHubSource, error) + getMutex sync.RWMutex + getArgsForCall []struct { + arg1 string + arg2 v1.GetOptions + } + getReturns struct { + result1 *v1alpha1a.GitHubSource + result2 error + } + getReturnsOnCall map[int]struct { + result1 *v1alpha1a.GitHubSource + result2 error + } + ListStub func(v1.ListOptions) (*v1alpha1a.GitHubSourceList, error) + listMutex sync.RWMutex + listArgsForCall []struct { + arg1 v1.ListOptions + } + listReturns struct { + result1 *v1alpha1a.GitHubSourceList + result2 error + } + listReturnsOnCall map[int]struct { + result1 *v1alpha1a.GitHubSourceList + result2 error + } + PatchStub func(string, types.PatchType, []byte, ...string) (*v1alpha1a.GitHubSource, error) + patchMutex sync.RWMutex + patchArgsForCall []struct { + arg1 string + arg2 types.PatchType + arg3 []byte + arg4 []string + } + patchReturns struct { + result1 *v1alpha1a.GitHubSource + result2 error + } + patchReturnsOnCall map[int]struct { + result1 *v1alpha1a.GitHubSource + result2 error + } + UpdateStub func(*v1alpha1a.GitHubSource) (*v1alpha1a.GitHubSource, error) + updateMutex sync.RWMutex + updateArgsForCall []struct { + arg1 *v1alpha1a.GitHubSource + } + updateReturns struct { + result1 *v1alpha1a.GitHubSource + result2 error + } + updateReturnsOnCall map[int]struct { + result1 *v1alpha1a.GitHubSource + result2 error + } + UpdateStatusStub func(*v1alpha1a.GitHubSource) (*v1alpha1a.GitHubSource, error) + updateStatusMutex sync.RWMutex + updateStatusArgsForCall []struct { + arg1 *v1alpha1a.GitHubSource + } + updateStatusReturns struct { + result1 *v1alpha1a.GitHubSource + result2 error + } + updateStatusReturnsOnCall map[int]struct { + result1 *v1alpha1a.GitHubSource + result2 error + } + WatchStub func(v1.ListOptions) (watch.Interface, error) + watchMutex sync.RWMutex + watchArgsForCall []struct { + arg1 v1.ListOptions + } + watchReturns struct { + result1 watch.Interface + result2 error + } + watchReturnsOnCall map[int]struct { + result1 watch.Interface + result2 error + } + invocations map[string][][]interface{} + invocationsMutex sync.RWMutex +} + +func (fake *FakeGitHubSourceInterface) Create(arg1 *v1alpha1a.GitHubSource) (*v1alpha1a.GitHubSource, error) { + fake.createMutex.Lock() + ret, specificReturn := fake.createReturnsOnCall[len(fake.createArgsForCall)] + fake.createArgsForCall = append(fake.createArgsForCall, struct { + arg1 *v1alpha1a.GitHubSource + }{arg1}) + fake.recordInvocation("Create", []interface{}{arg1}) + fake.createMutex.Unlock() + if fake.CreateStub != nil { + return fake.CreateStub(arg1) + } + if specificReturn { + return ret.result1, ret.result2 + } + fakeReturns := fake.createReturns + return fakeReturns.result1, fakeReturns.result2 +} + +func (fake *FakeGitHubSourceInterface) CreateCallCount() int { + fake.createMutex.RLock() + defer fake.createMutex.RUnlock() + return len(fake.createArgsForCall) +} + +func (fake *FakeGitHubSourceInterface) CreateCalls(stub func(*v1alpha1a.GitHubSource) (*v1alpha1a.GitHubSource, error)) { + fake.createMutex.Lock() + defer fake.createMutex.Unlock() + fake.CreateStub = stub +} + +func (fake *FakeGitHubSourceInterface) CreateArgsForCall(i int) *v1alpha1a.GitHubSource { + fake.createMutex.RLock() + defer fake.createMutex.RUnlock() + argsForCall := fake.createArgsForCall[i] + return argsForCall.arg1 +} + +func (fake *FakeGitHubSourceInterface) CreateReturns(result1 *v1alpha1a.GitHubSource, result2 error) { + fake.createMutex.Lock() + defer fake.createMutex.Unlock() + fake.CreateStub = nil + fake.createReturns = struct { + result1 *v1alpha1a.GitHubSource + result2 error + }{result1, result2} +} + +func (fake *FakeGitHubSourceInterface) CreateReturnsOnCall(i int, result1 *v1alpha1a.GitHubSource, result2 error) { + fake.createMutex.Lock() + defer fake.createMutex.Unlock() + fake.CreateStub = nil + if fake.createReturnsOnCall == nil { + fake.createReturnsOnCall = make(map[int]struct { + result1 *v1alpha1a.GitHubSource + result2 error + }) + } + fake.createReturnsOnCall[i] = struct { + result1 *v1alpha1a.GitHubSource + result2 error + }{result1, result2} +} + +func (fake *FakeGitHubSourceInterface) Delete(arg1 string, arg2 *v1.DeleteOptions) error { + fake.deleteMutex.Lock() + ret, specificReturn := fake.deleteReturnsOnCall[len(fake.deleteArgsForCall)] + fake.deleteArgsForCall = append(fake.deleteArgsForCall, struct { + arg1 string + arg2 *v1.DeleteOptions + }{arg1, arg2}) + fake.recordInvocation("Delete", []interface{}{arg1, arg2}) + fake.deleteMutex.Unlock() + if fake.DeleteStub != nil { + return fake.DeleteStub(arg1, arg2) + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.deleteReturns + return fakeReturns.result1 +} + +func (fake *FakeGitHubSourceInterface) DeleteCallCount() int { + fake.deleteMutex.RLock() + defer fake.deleteMutex.RUnlock() + return len(fake.deleteArgsForCall) +} + +func (fake *FakeGitHubSourceInterface) DeleteCalls(stub func(string, *v1.DeleteOptions) error) { + fake.deleteMutex.Lock() + defer fake.deleteMutex.Unlock() + fake.DeleteStub = stub +} + +func (fake *FakeGitHubSourceInterface) DeleteArgsForCall(i int) (string, *v1.DeleteOptions) { + fake.deleteMutex.RLock() + defer fake.deleteMutex.RUnlock() + argsForCall := fake.deleteArgsForCall[i] + return argsForCall.arg1, argsForCall.arg2 +} + +func (fake *FakeGitHubSourceInterface) DeleteReturns(result1 error) { + fake.deleteMutex.Lock() + defer fake.deleteMutex.Unlock() + fake.DeleteStub = nil + fake.deleteReturns = struct { + result1 error + }{result1} +} + +func (fake *FakeGitHubSourceInterface) DeleteReturnsOnCall(i int, result1 error) { + fake.deleteMutex.Lock() + defer fake.deleteMutex.Unlock() + fake.DeleteStub = nil + if fake.deleteReturnsOnCall == nil { + fake.deleteReturnsOnCall = make(map[int]struct { + result1 error + }) + } + fake.deleteReturnsOnCall[i] = struct { + result1 error + }{result1} +} + +func (fake *FakeGitHubSourceInterface) DeleteCollection(arg1 *v1.DeleteOptions, arg2 v1.ListOptions) error { + fake.deleteCollectionMutex.Lock() + ret, specificReturn := fake.deleteCollectionReturnsOnCall[len(fake.deleteCollectionArgsForCall)] + fake.deleteCollectionArgsForCall = append(fake.deleteCollectionArgsForCall, struct { + arg1 *v1.DeleteOptions + arg2 v1.ListOptions + }{arg1, arg2}) + fake.recordInvocation("DeleteCollection", []interface{}{arg1, arg2}) + fake.deleteCollectionMutex.Unlock() + if fake.DeleteCollectionStub != nil { + return fake.DeleteCollectionStub(arg1, arg2) + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.deleteCollectionReturns + return fakeReturns.result1 +} + +func (fake *FakeGitHubSourceInterface) DeleteCollectionCallCount() int { + fake.deleteCollectionMutex.RLock() + defer fake.deleteCollectionMutex.RUnlock() + return len(fake.deleteCollectionArgsForCall) +} + +func (fake *FakeGitHubSourceInterface) DeleteCollectionCalls(stub func(*v1.DeleteOptions, v1.ListOptions) error) { + fake.deleteCollectionMutex.Lock() + defer fake.deleteCollectionMutex.Unlock() + fake.DeleteCollectionStub = stub +} + +func (fake *FakeGitHubSourceInterface) DeleteCollectionArgsForCall(i int) (*v1.DeleteOptions, v1.ListOptions) { + fake.deleteCollectionMutex.RLock() + defer fake.deleteCollectionMutex.RUnlock() + argsForCall := fake.deleteCollectionArgsForCall[i] + return argsForCall.arg1, argsForCall.arg2 +} + +func (fake *FakeGitHubSourceInterface) DeleteCollectionReturns(result1 error) { + fake.deleteCollectionMutex.Lock() + defer fake.deleteCollectionMutex.Unlock() + fake.DeleteCollectionStub = nil + fake.deleteCollectionReturns = struct { + result1 error + }{result1} +} + +func (fake *FakeGitHubSourceInterface) DeleteCollectionReturnsOnCall(i int, result1 error) { + fake.deleteCollectionMutex.Lock() + defer fake.deleteCollectionMutex.Unlock() + fake.DeleteCollectionStub = nil + if fake.deleteCollectionReturnsOnCall == nil { + fake.deleteCollectionReturnsOnCall = make(map[int]struct { + result1 error + }) + } + fake.deleteCollectionReturnsOnCall[i] = struct { + result1 error + }{result1} +} + +func (fake *FakeGitHubSourceInterface) Get(arg1 string, arg2 v1.GetOptions) (*v1alpha1a.GitHubSource, error) { + fake.getMutex.Lock() + ret, specificReturn := fake.getReturnsOnCall[len(fake.getArgsForCall)] + fake.getArgsForCall = append(fake.getArgsForCall, struct { + arg1 string + arg2 v1.GetOptions + }{arg1, arg2}) + fake.recordInvocation("Get", []interface{}{arg1, arg2}) + fake.getMutex.Unlock() + if fake.GetStub != nil { + return fake.GetStub(arg1, arg2) + } + if specificReturn { + return ret.result1, ret.result2 + } + fakeReturns := fake.getReturns + return fakeReturns.result1, fakeReturns.result2 +} + +func (fake *FakeGitHubSourceInterface) GetCallCount() int { + fake.getMutex.RLock() + defer fake.getMutex.RUnlock() + return len(fake.getArgsForCall) +} + +func (fake *FakeGitHubSourceInterface) GetCalls(stub func(string, v1.GetOptions) (*v1alpha1a.GitHubSource, error)) { + fake.getMutex.Lock() + defer fake.getMutex.Unlock() + fake.GetStub = stub +} + +func (fake *FakeGitHubSourceInterface) GetArgsForCall(i int) (string, v1.GetOptions) { + fake.getMutex.RLock() + defer fake.getMutex.RUnlock() + argsForCall := fake.getArgsForCall[i] + return argsForCall.arg1, argsForCall.arg2 +} + +func (fake *FakeGitHubSourceInterface) GetReturns(result1 *v1alpha1a.GitHubSource, result2 error) { + fake.getMutex.Lock() + defer fake.getMutex.Unlock() + fake.GetStub = nil + fake.getReturns = struct { + result1 *v1alpha1a.GitHubSource + result2 error + }{result1, result2} +} + +func (fake *FakeGitHubSourceInterface) GetReturnsOnCall(i int, result1 *v1alpha1a.GitHubSource, result2 error) { + fake.getMutex.Lock() + defer fake.getMutex.Unlock() + fake.GetStub = nil + if fake.getReturnsOnCall == nil { + fake.getReturnsOnCall = make(map[int]struct { + result1 *v1alpha1a.GitHubSource + result2 error + }) + } + fake.getReturnsOnCall[i] = struct { + result1 *v1alpha1a.GitHubSource + result2 error + }{result1, result2} +} + +func (fake *FakeGitHubSourceInterface) List(arg1 v1.ListOptions) (*v1alpha1a.GitHubSourceList, error) { + fake.listMutex.Lock() + ret, specificReturn := fake.listReturnsOnCall[len(fake.listArgsForCall)] + fake.listArgsForCall = append(fake.listArgsForCall, struct { + arg1 v1.ListOptions + }{arg1}) + fake.recordInvocation("List", []interface{}{arg1}) + fake.listMutex.Unlock() + if fake.ListStub != nil { + return fake.ListStub(arg1) + } + if specificReturn { + return ret.result1, ret.result2 + } + fakeReturns := fake.listReturns + return fakeReturns.result1, fakeReturns.result2 +} + +func (fake *FakeGitHubSourceInterface) ListCallCount() int { + fake.listMutex.RLock() + defer fake.listMutex.RUnlock() + return len(fake.listArgsForCall) +} + +func (fake *FakeGitHubSourceInterface) ListCalls(stub func(v1.ListOptions) (*v1alpha1a.GitHubSourceList, error)) { + fake.listMutex.Lock() + defer fake.listMutex.Unlock() + fake.ListStub = stub +} + +func (fake *FakeGitHubSourceInterface) ListArgsForCall(i int) v1.ListOptions { + fake.listMutex.RLock() + defer fake.listMutex.RUnlock() + argsForCall := fake.listArgsForCall[i] + return argsForCall.arg1 +} + +func (fake *FakeGitHubSourceInterface) ListReturns(result1 *v1alpha1a.GitHubSourceList, result2 error) { + fake.listMutex.Lock() + defer fake.listMutex.Unlock() + fake.ListStub = nil + fake.listReturns = struct { + result1 *v1alpha1a.GitHubSourceList + result2 error + }{result1, result2} +} + +func (fake *FakeGitHubSourceInterface) ListReturnsOnCall(i int, result1 *v1alpha1a.GitHubSourceList, result2 error) { + fake.listMutex.Lock() + defer fake.listMutex.Unlock() + fake.ListStub = nil + if fake.listReturnsOnCall == nil { + fake.listReturnsOnCall = make(map[int]struct { + result1 *v1alpha1a.GitHubSourceList + result2 error + }) + } + fake.listReturnsOnCall[i] = struct { + result1 *v1alpha1a.GitHubSourceList + result2 error + }{result1, result2} +} + +func (fake *FakeGitHubSourceInterface) Patch(arg1 string, arg2 types.PatchType, arg3 []byte, arg4 ...string) (*v1alpha1a.GitHubSource, error) { + var arg3Copy []byte + if arg3 != nil { + arg3Copy = make([]byte, len(arg3)) + copy(arg3Copy, arg3) + } + fake.patchMutex.Lock() + ret, specificReturn := fake.patchReturnsOnCall[len(fake.patchArgsForCall)] + fake.patchArgsForCall = append(fake.patchArgsForCall, struct { + arg1 string + arg2 types.PatchType + arg3 []byte + arg4 []string + }{arg1, arg2, arg3Copy, arg4}) + fake.recordInvocation("Patch", []interface{}{arg1, arg2, arg3Copy, arg4}) + fake.patchMutex.Unlock() + if fake.PatchStub != nil { + return fake.PatchStub(arg1, arg2, arg3, arg4...) + } + if specificReturn { + return ret.result1, ret.result2 + } + fakeReturns := fake.patchReturns + return fakeReturns.result1, fakeReturns.result2 +} + +func (fake *FakeGitHubSourceInterface) PatchCallCount() int { + fake.patchMutex.RLock() + defer fake.patchMutex.RUnlock() + return len(fake.patchArgsForCall) +} + +func (fake *FakeGitHubSourceInterface) PatchCalls(stub func(string, types.PatchType, []byte, ...string) (*v1alpha1a.GitHubSource, error)) { + fake.patchMutex.Lock() + defer fake.patchMutex.Unlock() + fake.PatchStub = stub +} + +func (fake *FakeGitHubSourceInterface) PatchArgsForCall(i int) (string, types.PatchType, []byte, []string) { + fake.patchMutex.RLock() + defer fake.patchMutex.RUnlock() + argsForCall := fake.patchArgsForCall[i] + return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3, argsForCall.arg4 +} + +func (fake *FakeGitHubSourceInterface) PatchReturns(result1 *v1alpha1a.GitHubSource, result2 error) { + fake.patchMutex.Lock() + defer fake.patchMutex.Unlock() + fake.PatchStub = nil + fake.patchReturns = struct { + result1 *v1alpha1a.GitHubSource + result2 error + }{result1, result2} +} + +func (fake *FakeGitHubSourceInterface) PatchReturnsOnCall(i int, result1 *v1alpha1a.GitHubSource, result2 error) { + fake.patchMutex.Lock() + defer fake.patchMutex.Unlock() + fake.PatchStub = nil + if fake.patchReturnsOnCall == nil { + fake.patchReturnsOnCall = make(map[int]struct { + result1 *v1alpha1a.GitHubSource + result2 error + }) + } + fake.patchReturnsOnCall[i] = struct { + result1 *v1alpha1a.GitHubSource + result2 error + }{result1, result2} +} + +func (fake *FakeGitHubSourceInterface) Update(arg1 *v1alpha1a.GitHubSource) (*v1alpha1a.GitHubSource, error) { + fake.updateMutex.Lock() + ret, specificReturn := fake.updateReturnsOnCall[len(fake.updateArgsForCall)] + fake.updateArgsForCall = append(fake.updateArgsForCall, struct { + arg1 *v1alpha1a.GitHubSource + }{arg1}) + fake.recordInvocation("Update", []interface{}{arg1}) + fake.updateMutex.Unlock() + if fake.UpdateStub != nil { + return fake.UpdateStub(arg1) + } + if specificReturn { + return ret.result1, ret.result2 + } + fakeReturns := fake.updateReturns + return fakeReturns.result1, fakeReturns.result2 +} + +func (fake *FakeGitHubSourceInterface) UpdateCallCount() int { + fake.updateMutex.RLock() + defer fake.updateMutex.RUnlock() + return len(fake.updateArgsForCall) +} + +func (fake *FakeGitHubSourceInterface) UpdateCalls(stub func(*v1alpha1a.GitHubSource) (*v1alpha1a.GitHubSource, error)) { + fake.updateMutex.Lock() + defer fake.updateMutex.Unlock() + fake.UpdateStub = stub +} + +func (fake *FakeGitHubSourceInterface) UpdateArgsForCall(i int) *v1alpha1a.GitHubSource { + fake.updateMutex.RLock() + defer fake.updateMutex.RUnlock() + argsForCall := fake.updateArgsForCall[i] + return argsForCall.arg1 +} + +func (fake *FakeGitHubSourceInterface) UpdateReturns(result1 *v1alpha1a.GitHubSource, result2 error) { + fake.updateMutex.Lock() + defer fake.updateMutex.Unlock() + fake.UpdateStub = nil + fake.updateReturns = struct { + result1 *v1alpha1a.GitHubSource + result2 error + }{result1, result2} +} + +func (fake *FakeGitHubSourceInterface) UpdateReturnsOnCall(i int, result1 *v1alpha1a.GitHubSource, result2 error) { + fake.updateMutex.Lock() + defer fake.updateMutex.Unlock() + fake.UpdateStub = nil + if fake.updateReturnsOnCall == nil { + fake.updateReturnsOnCall = make(map[int]struct { + result1 *v1alpha1a.GitHubSource + result2 error + }) + } + fake.updateReturnsOnCall[i] = struct { + result1 *v1alpha1a.GitHubSource + result2 error + }{result1, result2} +} + +func (fake *FakeGitHubSourceInterface) UpdateStatus(arg1 *v1alpha1a.GitHubSource) (*v1alpha1a.GitHubSource, error) { + fake.updateStatusMutex.Lock() + ret, specificReturn := fake.updateStatusReturnsOnCall[len(fake.updateStatusArgsForCall)] + fake.updateStatusArgsForCall = append(fake.updateStatusArgsForCall, struct { + arg1 *v1alpha1a.GitHubSource + }{arg1}) + fake.recordInvocation("UpdateStatus", []interface{}{arg1}) + fake.updateStatusMutex.Unlock() + if fake.UpdateStatusStub != nil { + return fake.UpdateStatusStub(arg1) + } + if specificReturn { + return ret.result1, ret.result2 + } + fakeReturns := fake.updateStatusReturns + return fakeReturns.result1, fakeReturns.result2 +} + +func (fake *FakeGitHubSourceInterface) UpdateStatusCallCount() int { + fake.updateStatusMutex.RLock() + defer fake.updateStatusMutex.RUnlock() + return len(fake.updateStatusArgsForCall) +} + +func (fake *FakeGitHubSourceInterface) UpdateStatusCalls(stub func(*v1alpha1a.GitHubSource) (*v1alpha1a.GitHubSource, error)) { + fake.updateStatusMutex.Lock() + defer fake.updateStatusMutex.Unlock() + fake.UpdateStatusStub = stub +} + +func (fake *FakeGitHubSourceInterface) UpdateStatusArgsForCall(i int) *v1alpha1a.GitHubSource { + fake.updateStatusMutex.RLock() + defer fake.updateStatusMutex.RUnlock() + argsForCall := fake.updateStatusArgsForCall[i] + return argsForCall.arg1 +} + +func (fake *FakeGitHubSourceInterface) UpdateStatusReturns(result1 *v1alpha1a.GitHubSource, result2 error) { + fake.updateStatusMutex.Lock() + defer fake.updateStatusMutex.Unlock() + fake.UpdateStatusStub = nil + fake.updateStatusReturns = struct { + result1 *v1alpha1a.GitHubSource + result2 error + }{result1, result2} +} + +func (fake *FakeGitHubSourceInterface) UpdateStatusReturnsOnCall(i int, result1 *v1alpha1a.GitHubSource, result2 error) { + fake.updateStatusMutex.Lock() + defer fake.updateStatusMutex.Unlock() + fake.UpdateStatusStub = nil + if fake.updateStatusReturnsOnCall == nil { + fake.updateStatusReturnsOnCall = make(map[int]struct { + result1 *v1alpha1a.GitHubSource + result2 error + }) + } + fake.updateStatusReturnsOnCall[i] = struct { + result1 *v1alpha1a.GitHubSource + result2 error + }{result1, result2} +} + +func (fake *FakeGitHubSourceInterface) Watch(arg1 v1.ListOptions) (watch.Interface, error) { + fake.watchMutex.Lock() + ret, specificReturn := fake.watchReturnsOnCall[len(fake.watchArgsForCall)] + fake.watchArgsForCall = append(fake.watchArgsForCall, struct { + arg1 v1.ListOptions + }{arg1}) + fake.recordInvocation("Watch", []interface{}{arg1}) + fake.watchMutex.Unlock() + if fake.WatchStub != nil { + return fake.WatchStub(arg1) + } + if specificReturn { + return ret.result1, ret.result2 + } + fakeReturns := fake.watchReturns + return fakeReturns.result1, fakeReturns.result2 +} + +func (fake *FakeGitHubSourceInterface) WatchCallCount() int { + fake.watchMutex.RLock() + defer fake.watchMutex.RUnlock() + return len(fake.watchArgsForCall) +} + +func (fake *FakeGitHubSourceInterface) WatchCalls(stub func(v1.ListOptions) (watch.Interface, error)) { + fake.watchMutex.Lock() + defer fake.watchMutex.Unlock() + fake.WatchStub = stub +} + +func (fake *FakeGitHubSourceInterface) WatchArgsForCall(i int) v1.ListOptions { + fake.watchMutex.RLock() + defer fake.watchMutex.RUnlock() + argsForCall := fake.watchArgsForCall[i] + return argsForCall.arg1 +} + +func (fake *FakeGitHubSourceInterface) WatchReturns(result1 watch.Interface, result2 error) { + fake.watchMutex.Lock() + defer fake.watchMutex.Unlock() + fake.WatchStub = nil + fake.watchReturns = struct { + result1 watch.Interface + result2 error + }{result1, result2} +} + +func (fake *FakeGitHubSourceInterface) WatchReturnsOnCall(i int, result1 watch.Interface, result2 error) { + fake.watchMutex.Lock() + defer fake.watchMutex.Unlock() + fake.WatchStub = nil + if fake.watchReturnsOnCall == nil { + fake.watchReturnsOnCall = make(map[int]struct { + result1 watch.Interface + result2 error + }) + } + fake.watchReturnsOnCall[i] = struct { + result1 watch.Interface + result2 error + }{result1, result2} +} + +func (fake *FakeGitHubSourceInterface) Invocations() map[string][][]interface{} { + fake.invocationsMutex.RLock() + defer fake.invocationsMutex.RUnlock() + fake.createMutex.RLock() + defer fake.createMutex.RUnlock() + fake.deleteMutex.RLock() + defer fake.deleteMutex.RUnlock() + fake.deleteCollectionMutex.RLock() + defer fake.deleteCollectionMutex.RUnlock() + fake.getMutex.RLock() + defer fake.getMutex.RUnlock() + fake.listMutex.RLock() + defer fake.listMutex.RUnlock() + fake.patchMutex.RLock() + defer fake.patchMutex.RUnlock() + fake.updateMutex.RLock() + defer fake.updateMutex.RUnlock() + fake.updateStatusMutex.RLock() + defer fake.updateStatusMutex.RUnlock() + fake.watchMutex.RLock() + defer fake.watchMutex.RUnlock() + copiedInvocations := map[string][][]interface{}{} + for key, value := range fake.invocations { + copiedInvocations[key] = value + } + return copiedInvocations +} + +func (fake *FakeGitHubSourceInterface) recordInvocation(key string, args []interface{}) { + fake.invocationsMutex.Lock() + defer fake.invocationsMutex.Unlock() + if fake.invocations == nil { + fake.invocations = map[string][][]interface{}{} + } + if fake.invocations[key] == nil { + fake.invocations[key] = [][]interface{}{} + } + fake.invocations[key] = append(fake.invocations[key], args) +} + +var _ v1alpha1.GitHubSourceInterface = new(FakeGitHubSourceInterface) diff --git a/plugins/source-github/pkg/fakes/fake_sources_githubsourcesgetter.go b/plugins/source-github/pkg/fakes/fake_sources_githubsourcesgetter.go new file mode 100644 index 00000000..adb664fc --- /dev/null +++ b/plugins/source-github/pkg/fakes/fake_sources_githubsourcesgetter.go @@ -0,0 +1,110 @@ +// Code generated by counterfeiter. DO NOT EDIT. +package fakes + +import ( + "sync" + + "knative.dev/eventing-contrib/github/pkg/client/clientset/versioned/typed/sources/v1alpha1" +) + +type FakeGitHubSourcesGetter struct { + GitHubSourcesStub func(string) v1alpha1.GitHubSourceInterface + gitHubSourcesMutex sync.RWMutex + gitHubSourcesArgsForCall []struct { + arg1 string + } + gitHubSourcesReturns struct { + result1 v1alpha1.GitHubSourceInterface + } + gitHubSourcesReturnsOnCall map[int]struct { + result1 v1alpha1.GitHubSourceInterface + } + invocations map[string][][]interface{} + invocationsMutex sync.RWMutex +} + +func (fake *FakeGitHubSourcesGetter) GitHubSources(arg1 string) v1alpha1.GitHubSourceInterface { + fake.gitHubSourcesMutex.Lock() + ret, specificReturn := fake.gitHubSourcesReturnsOnCall[len(fake.gitHubSourcesArgsForCall)] + fake.gitHubSourcesArgsForCall = append(fake.gitHubSourcesArgsForCall, struct { + arg1 string + }{arg1}) + fake.recordInvocation("GitHubSources", []interface{}{arg1}) + fake.gitHubSourcesMutex.Unlock() + if fake.GitHubSourcesStub != nil { + return fake.GitHubSourcesStub(arg1) + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.gitHubSourcesReturns + return fakeReturns.result1 +} + +func (fake *FakeGitHubSourcesGetter) GitHubSourcesCallCount() int { + fake.gitHubSourcesMutex.RLock() + defer fake.gitHubSourcesMutex.RUnlock() + return len(fake.gitHubSourcesArgsForCall) +} + +func (fake *FakeGitHubSourcesGetter) GitHubSourcesCalls(stub func(string) v1alpha1.GitHubSourceInterface) { + fake.gitHubSourcesMutex.Lock() + defer fake.gitHubSourcesMutex.Unlock() + fake.GitHubSourcesStub = stub +} + +func (fake *FakeGitHubSourcesGetter) GitHubSourcesArgsForCall(i int) string { + fake.gitHubSourcesMutex.RLock() + defer fake.gitHubSourcesMutex.RUnlock() + argsForCall := fake.gitHubSourcesArgsForCall[i] + return argsForCall.arg1 +} + +func (fake *FakeGitHubSourcesGetter) GitHubSourcesReturns(result1 v1alpha1.GitHubSourceInterface) { + fake.gitHubSourcesMutex.Lock() + defer fake.gitHubSourcesMutex.Unlock() + fake.GitHubSourcesStub = nil + fake.gitHubSourcesReturns = struct { + result1 v1alpha1.GitHubSourceInterface + }{result1} +} + +func (fake *FakeGitHubSourcesGetter) GitHubSourcesReturnsOnCall(i int, result1 v1alpha1.GitHubSourceInterface) { + fake.gitHubSourcesMutex.Lock() + defer fake.gitHubSourcesMutex.Unlock() + fake.GitHubSourcesStub = nil + if fake.gitHubSourcesReturnsOnCall == nil { + fake.gitHubSourcesReturnsOnCall = make(map[int]struct { + result1 v1alpha1.GitHubSourceInterface + }) + } + fake.gitHubSourcesReturnsOnCall[i] = struct { + result1 v1alpha1.GitHubSourceInterface + }{result1} +} + +func (fake *FakeGitHubSourcesGetter) Invocations() map[string][][]interface{} { + fake.invocationsMutex.RLock() + defer fake.invocationsMutex.RUnlock() + fake.gitHubSourcesMutex.RLock() + defer fake.gitHubSourcesMutex.RUnlock() + copiedInvocations := map[string][][]interface{}{} + for key, value := range fake.invocations { + copiedInvocations[key] = value + } + return copiedInvocations +} + +func (fake *FakeGitHubSourcesGetter) recordInvocation(key string, args []interface{}) { + fake.invocationsMutex.Lock() + defer fake.invocationsMutex.Unlock() + if fake.invocations == nil { + fake.invocations = map[string][][]interface{}{} + } + if fake.invocations[key] == nil { + fake.invocations[key] = [][]interface{}{} + } + fake.invocations[key] = append(fake.invocations[key], args) +} + +var _ v1alpha1.GitHubSourcesGetter = new(FakeGitHubSourcesGetter) diff --git a/plugins/source-github/pkg/fakes/fake_sources_v1alpha1interface.go b/plugins/source-github/pkg/fakes/fake_sources_v1alpha1interface.go new file mode 100644 index 00000000..a53bc9b4 --- /dev/null +++ b/plugins/source-github/pkg/fakes/fake_sources_v1alpha1interface.go @@ -0,0 +1,175 @@ +// Code generated by counterfeiter. DO NOT EDIT. +package fakes + +import ( + "sync" + + "k8s.io/client-go/rest" + "knative.dev/eventing-contrib/github/pkg/client/clientset/versioned/typed/sources/v1alpha1" +) + +type FakeSourcesV1alpha1Interface struct { + GitHubSourcesStub func(string) v1alpha1.GitHubSourceInterface + gitHubSourcesMutex sync.RWMutex + gitHubSourcesArgsForCall []struct { + arg1 string + } + gitHubSourcesReturns struct { + result1 v1alpha1.GitHubSourceInterface + } + gitHubSourcesReturnsOnCall map[int]struct { + result1 v1alpha1.GitHubSourceInterface + } + RESTClientStub func() rest.Interface + rESTClientMutex sync.RWMutex + rESTClientArgsForCall []struct { + } + rESTClientReturns struct { + result1 rest.Interface + } + rESTClientReturnsOnCall map[int]struct { + result1 rest.Interface + } + invocations map[string][][]interface{} + invocationsMutex sync.RWMutex +} + +func (fake *FakeSourcesV1alpha1Interface) GitHubSources(arg1 string) v1alpha1.GitHubSourceInterface { + fake.gitHubSourcesMutex.Lock() + ret, specificReturn := fake.gitHubSourcesReturnsOnCall[len(fake.gitHubSourcesArgsForCall)] + fake.gitHubSourcesArgsForCall = append(fake.gitHubSourcesArgsForCall, struct { + arg1 string + }{arg1}) + fake.recordInvocation("GitHubSources", []interface{}{arg1}) + fake.gitHubSourcesMutex.Unlock() + if fake.GitHubSourcesStub != nil { + return fake.GitHubSourcesStub(arg1) + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.gitHubSourcesReturns + return fakeReturns.result1 +} + +func (fake *FakeSourcesV1alpha1Interface) GitHubSourcesCallCount() int { + fake.gitHubSourcesMutex.RLock() + defer fake.gitHubSourcesMutex.RUnlock() + return len(fake.gitHubSourcesArgsForCall) +} + +func (fake *FakeSourcesV1alpha1Interface) GitHubSourcesCalls(stub func(string) v1alpha1.GitHubSourceInterface) { + fake.gitHubSourcesMutex.Lock() + defer fake.gitHubSourcesMutex.Unlock() + fake.GitHubSourcesStub = stub +} + +func (fake *FakeSourcesV1alpha1Interface) GitHubSourcesArgsForCall(i int) string { + fake.gitHubSourcesMutex.RLock() + defer fake.gitHubSourcesMutex.RUnlock() + argsForCall := fake.gitHubSourcesArgsForCall[i] + return argsForCall.arg1 +} + +func (fake *FakeSourcesV1alpha1Interface) GitHubSourcesReturns(result1 v1alpha1.GitHubSourceInterface) { + fake.gitHubSourcesMutex.Lock() + defer fake.gitHubSourcesMutex.Unlock() + fake.GitHubSourcesStub = nil + fake.gitHubSourcesReturns = struct { + result1 v1alpha1.GitHubSourceInterface + }{result1} +} + +func (fake *FakeSourcesV1alpha1Interface) GitHubSourcesReturnsOnCall(i int, result1 v1alpha1.GitHubSourceInterface) { + fake.gitHubSourcesMutex.Lock() + defer fake.gitHubSourcesMutex.Unlock() + fake.GitHubSourcesStub = nil + if fake.gitHubSourcesReturnsOnCall == nil { + fake.gitHubSourcesReturnsOnCall = make(map[int]struct { + result1 v1alpha1.GitHubSourceInterface + }) + } + fake.gitHubSourcesReturnsOnCall[i] = struct { + result1 v1alpha1.GitHubSourceInterface + }{result1} +} + +func (fake *FakeSourcesV1alpha1Interface) RESTClient() rest.Interface { + fake.rESTClientMutex.Lock() + ret, specificReturn := fake.rESTClientReturnsOnCall[len(fake.rESTClientArgsForCall)] + fake.rESTClientArgsForCall = append(fake.rESTClientArgsForCall, struct { + }{}) + fake.recordInvocation("RESTClient", []interface{}{}) + fake.rESTClientMutex.Unlock() + if fake.RESTClientStub != nil { + return fake.RESTClientStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.rESTClientReturns + return fakeReturns.result1 +} + +func (fake *FakeSourcesV1alpha1Interface) RESTClientCallCount() int { + fake.rESTClientMutex.RLock() + defer fake.rESTClientMutex.RUnlock() + return len(fake.rESTClientArgsForCall) +} + +func (fake *FakeSourcesV1alpha1Interface) RESTClientCalls(stub func() rest.Interface) { + fake.rESTClientMutex.Lock() + defer fake.rESTClientMutex.Unlock() + fake.RESTClientStub = stub +} + +func (fake *FakeSourcesV1alpha1Interface) RESTClientReturns(result1 rest.Interface) { + fake.rESTClientMutex.Lock() + defer fake.rESTClientMutex.Unlock() + fake.RESTClientStub = nil + fake.rESTClientReturns = struct { + result1 rest.Interface + }{result1} +} + +func (fake *FakeSourcesV1alpha1Interface) RESTClientReturnsOnCall(i int, result1 rest.Interface) { + fake.rESTClientMutex.Lock() + defer fake.rESTClientMutex.Unlock() + fake.RESTClientStub = nil + if fake.rESTClientReturnsOnCall == nil { + fake.rESTClientReturnsOnCall = make(map[int]struct { + result1 rest.Interface + }) + } + fake.rESTClientReturnsOnCall[i] = struct { + result1 rest.Interface + }{result1} +} + +func (fake *FakeSourcesV1alpha1Interface) Invocations() map[string][][]interface{} { + fake.invocationsMutex.RLock() + defer fake.invocationsMutex.RUnlock() + fake.gitHubSourcesMutex.RLock() + defer fake.gitHubSourcesMutex.RUnlock() + fake.rESTClientMutex.RLock() + defer fake.rESTClientMutex.RUnlock() + copiedInvocations := map[string][][]interface{}{} + for key, value := range fake.invocations { + copiedInvocations[key] = value + } + return copiedInvocations +} + +func (fake *FakeSourcesV1alpha1Interface) recordInvocation(key string, args []interface{}) { + fake.invocationsMutex.Lock() + defer fake.invocationsMutex.Unlock() + if fake.invocations == nil { + fake.invocations = map[string][][]interface{}{} + } + if fake.invocations[key] == nil { + fake.invocations[key] = [][]interface{}{} + } + fake.invocations[key] = append(fake.invocations[key], args) +} + +var _ v1alpha1.SourcesV1alpha1Interface = new(FakeSourcesV1alpha1Interface) diff --git a/plugins/source-github/pkg/types/interfaces.go b/plugins/source-github/pkg/types/interfaces.go index 8926d7d8..532a71a0 100644 --- a/plugins/source-github/pkg/types/interfaces.go +++ b/plugins/source-github/pkg/types/interfaces.go @@ -11,6 +11,8 @@ // 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. +// +//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 -generate package types @@ -20,6 +22,8 @@ import ( v1alpha1 "knative.dev/eventing-contrib/github/pkg/apis/sources/v1alpha1" ) +// GHSourceClient the GitHub source client interface +//counterfeiter:generate . GHSourceClient type GHSourceClient interface { sourcetypes.KnSourceClient GHSourceParams() *GHSourceParams @@ -30,6 +34,8 @@ type GHSourceClient interface { DeleteGHSource(name string) error } +// GHSourceFactory the GitHub source factory interface +//counterfeiter:generate . GHSourceFactory type GHSourceFactory interface { sourcetypes.KnSourceFactory @@ -40,18 +46,24 @@ type GHSourceFactory interface { CreateGHSourceClient(namespace string) GHSourceClient } +// GHCommandFactory the GitHub source command factory interface +//counterfeiter:generate . GHCommandFactory type GHCommandFactory interface { sourcetypes.CommandFactory GHSourceFactory() GHSourceFactory } +// GHFlagsFactory the GitHub source flags factory interface +//counterfeiter:generate . GHFlagsFactory type GHFlagsFactory interface { sourcetypes.FlagsFactory GHSourceFactory() GHSourceFactory } +// GHRunEFactory the GitHub source RunE factory interface +//counterfeiter:generate . GHRunEFactory type GHRunEFactory interface { sourcetypes.RunEFactory diff --git a/plugins/source-github/pkg/types/typesfakes/fake_ghcommand_factory.go b/plugins/source-github/pkg/types/typesfakes/fake_ghcommand_factory.go new file mode 100644 index 00000000..a47acfcc --- /dev/null +++ b/plugins/source-github/pkg/types/typesfakes/fake_ghcommand_factory.go @@ -0,0 +1,487 @@ +// Code generated by counterfeiter. DO NOT EDIT. +package typesfakes + +import ( + "sync" + + "github.com/maximilien/kn-source-github/pkg/types" + typesa "github.com/maximilien/kn-source-pkg/pkg/types" + "github.com/spf13/cobra" +) + +type FakeGHCommandFactory struct { + CreateCommandStub func() *cobra.Command + createCommandMutex sync.RWMutex + createCommandArgsForCall []struct { + } + createCommandReturns struct { + result1 *cobra.Command + } + createCommandReturnsOnCall map[int]struct { + result1 *cobra.Command + } + DeleteCommandStub func() *cobra.Command + deleteCommandMutex sync.RWMutex + deleteCommandArgsForCall []struct { + } + deleteCommandReturns struct { + result1 *cobra.Command + } + deleteCommandReturnsOnCall map[int]struct { + result1 *cobra.Command + } + DescribeCommandStub func() *cobra.Command + describeCommandMutex sync.RWMutex + describeCommandArgsForCall []struct { + } + describeCommandReturns struct { + result1 *cobra.Command + } + describeCommandReturnsOnCall map[int]struct { + result1 *cobra.Command + } + GHSourceFactoryStub func() types.GHSourceFactory + gHSourceFactoryMutex sync.RWMutex + gHSourceFactoryArgsForCall []struct { + } + gHSourceFactoryReturns struct { + result1 types.GHSourceFactory + } + gHSourceFactoryReturnsOnCall map[int]struct { + result1 types.GHSourceFactory + } + KnSourceFactoryStub func() typesa.KnSourceFactory + knSourceFactoryMutex sync.RWMutex + knSourceFactoryArgsForCall []struct { + } + knSourceFactoryReturns struct { + result1 typesa.KnSourceFactory + } + knSourceFactoryReturnsOnCall map[int]struct { + result1 typesa.KnSourceFactory + } + SourceCommandStub func() *cobra.Command + sourceCommandMutex sync.RWMutex + sourceCommandArgsForCall []struct { + } + sourceCommandReturns struct { + result1 *cobra.Command + } + sourceCommandReturnsOnCall map[int]struct { + result1 *cobra.Command + } + UpdateCommandStub func() *cobra.Command + updateCommandMutex sync.RWMutex + updateCommandArgsForCall []struct { + } + updateCommandReturns struct { + result1 *cobra.Command + } + updateCommandReturnsOnCall map[int]struct { + result1 *cobra.Command + } + invocations map[string][][]interface{} + invocationsMutex sync.RWMutex +} + +func (fake *FakeGHCommandFactory) CreateCommand() *cobra.Command { + fake.createCommandMutex.Lock() + ret, specificReturn := fake.createCommandReturnsOnCall[len(fake.createCommandArgsForCall)] + fake.createCommandArgsForCall = append(fake.createCommandArgsForCall, struct { + }{}) + fake.recordInvocation("CreateCommand", []interface{}{}) + fake.createCommandMutex.Unlock() + if fake.CreateCommandStub != nil { + return fake.CreateCommandStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.createCommandReturns + return fakeReturns.result1 +} + +func (fake *FakeGHCommandFactory) CreateCommandCallCount() int { + fake.createCommandMutex.RLock() + defer fake.createCommandMutex.RUnlock() + return len(fake.createCommandArgsForCall) +} + +func (fake *FakeGHCommandFactory) CreateCommandCalls(stub func() *cobra.Command) { + fake.createCommandMutex.Lock() + defer fake.createCommandMutex.Unlock() + fake.CreateCommandStub = stub +} + +func (fake *FakeGHCommandFactory) CreateCommandReturns(result1 *cobra.Command) { + fake.createCommandMutex.Lock() + defer fake.createCommandMutex.Unlock() + fake.CreateCommandStub = nil + fake.createCommandReturns = struct { + result1 *cobra.Command + }{result1} +} + +func (fake *FakeGHCommandFactory) CreateCommandReturnsOnCall(i int, result1 *cobra.Command) { + fake.createCommandMutex.Lock() + defer fake.createCommandMutex.Unlock() + fake.CreateCommandStub = nil + if fake.createCommandReturnsOnCall == nil { + fake.createCommandReturnsOnCall = make(map[int]struct { + result1 *cobra.Command + }) + } + fake.createCommandReturnsOnCall[i] = struct { + result1 *cobra.Command + }{result1} +} + +func (fake *FakeGHCommandFactory) DeleteCommand() *cobra.Command { + fake.deleteCommandMutex.Lock() + ret, specificReturn := fake.deleteCommandReturnsOnCall[len(fake.deleteCommandArgsForCall)] + fake.deleteCommandArgsForCall = append(fake.deleteCommandArgsForCall, struct { + }{}) + fake.recordInvocation("DeleteCommand", []interface{}{}) + fake.deleteCommandMutex.Unlock() + if fake.DeleteCommandStub != nil { + return fake.DeleteCommandStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.deleteCommandReturns + return fakeReturns.result1 +} + +func (fake *FakeGHCommandFactory) DeleteCommandCallCount() int { + fake.deleteCommandMutex.RLock() + defer fake.deleteCommandMutex.RUnlock() + return len(fake.deleteCommandArgsForCall) +} + +func (fake *FakeGHCommandFactory) DeleteCommandCalls(stub func() *cobra.Command) { + fake.deleteCommandMutex.Lock() + defer fake.deleteCommandMutex.Unlock() + fake.DeleteCommandStub = stub +} + +func (fake *FakeGHCommandFactory) DeleteCommandReturns(result1 *cobra.Command) { + fake.deleteCommandMutex.Lock() + defer fake.deleteCommandMutex.Unlock() + fake.DeleteCommandStub = nil + fake.deleteCommandReturns = struct { + result1 *cobra.Command + }{result1} +} + +func (fake *FakeGHCommandFactory) DeleteCommandReturnsOnCall(i int, result1 *cobra.Command) { + fake.deleteCommandMutex.Lock() + defer fake.deleteCommandMutex.Unlock() + fake.DeleteCommandStub = nil + if fake.deleteCommandReturnsOnCall == nil { + fake.deleteCommandReturnsOnCall = make(map[int]struct { + result1 *cobra.Command + }) + } + fake.deleteCommandReturnsOnCall[i] = struct { + result1 *cobra.Command + }{result1} +} + +func (fake *FakeGHCommandFactory) DescribeCommand() *cobra.Command { + fake.describeCommandMutex.Lock() + ret, specificReturn := fake.describeCommandReturnsOnCall[len(fake.describeCommandArgsForCall)] + fake.describeCommandArgsForCall = append(fake.describeCommandArgsForCall, struct { + }{}) + fake.recordInvocation("DescribeCommand", []interface{}{}) + fake.describeCommandMutex.Unlock() + if fake.DescribeCommandStub != nil { + return fake.DescribeCommandStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.describeCommandReturns + return fakeReturns.result1 +} + +func (fake *FakeGHCommandFactory) DescribeCommandCallCount() int { + fake.describeCommandMutex.RLock() + defer fake.describeCommandMutex.RUnlock() + return len(fake.describeCommandArgsForCall) +} + +func (fake *FakeGHCommandFactory) DescribeCommandCalls(stub func() *cobra.Command) { + fake.describeCommandMutex.Lock() + defer fake.describeCommandMutex.Unlock() + fake.DescribeCommandStub = stub +} + +func (fake *FakeGHCommandFactory) DescribeCommandReturns(result1 *cobra.Command) { + fake.describeCommandMutex.Lock() + defer fake.describeCommandMutex.Unlock() + fake.DescribeCommandStub = nil + fake.describeCommandReturns = struct { + result1 *cobra.Command + }{result1} +} + +func (fake *FakeGHCommandFactory) DescribeCommandReturnsOnCall(i int, result1 *cobra.Command) { + fake.describeCommandMutex.Lock() + defer fake.describeCommandMutex.Unlock() + fake.DescribeCommandStub = nil + if fake.describeCommandReturnsOnCall == nil { + fake.describeCommandReturnsOnCall = make(map[int]struct { + result1 *cobra.Command + }) + } + fake.describeCommandReturnsOnCall[i] = struct { + result1 *cobra.Command + }{result1} +} + +func (fake *FakeGHCommandFactory) GHSourceFactory() types.GHSourceFactory { + fake.gHSourceFactoryMutex.Lock() + ret, specificReturn := fake.gHSourceFactoryReturnsOnCall[len(fake.gHSourceFactoryArgsForCall)] + fake.gHSourceFactoryArgsForCall = append(fake.gHSourceFactoryArgsForCall, struct { + }{}) + fake.recordInvocation("GHSourceFactory", []interface{}{}) + fake.gHSourceFactoryMutex.Unlock() + if fake.GHSourceFactoryStub != nil { + return fake.GHSourceFactoryStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.gHSourceFactoryReturns + return fakeReturns.result1 +} + +func (fake *FakeGHCommandFactory) GHSourceFactoryCallCount() int { + fake.gHSourceFactoryMutex.RLock() + defer fake.gHSourceFactoryMutex.RUnlock() + return len(fake.gHSourceFactoryArgsForCall) +} + +func (fake *FakeGHCommandFactory) GHSourceFactoryCalls(stub func() types.GHSourceFactory) { + fake.gHSourceFactoryMutex.Lock() + defer fake.gHSourceFactoryMutex.Unlock() + fake.GHSourceFactoryStub = stub +} + +func (fake *FakeGHCommandFactory) GHSourceFactoryReturns(result1 types.GHSourceFactory) { + fake.gHSourceFactoryMutex.Lock() + defer fake.gHSourceFactoryMutex.Unlock() + fake.GHSourceFactoryStub = nil + fake.gHSourceFactoryReturns = struct { + result1 types.GHSourceFactory + }{result1} +} + +func (fake *FakeGHCommandFactory) GHSourceFactoryReturnsOnCall(i int, result1 types.GHSourceFactory) { + fake.gHSourceFactoryMutex.Lock() + defer fake.gHSourceFactoryMutex.Unlock() + fake.GHSourceFactoryStub = nil + if fake.gHSourceFactoryReturnsOnCall == nil { + fake.gHSourceFactoryReturnsOnCall = make(map[int]struct { + result1 types.GHSourceFactory + }) + } + fake.gHSourceFactoryReturnsOnCall[i] = struct { + result1 types.GHSourceFactory + }{result1} +} + +func (fake *FakeGHCommandFactory) KnSourceFactory() typesa.KnSourceFactory { + fake.knSourceFactoryMutex.Lock() + ret, specificReturn := fake.knSourceFactoryReturnsOnCall[len(fake.knSourceFactoryArgsForCall)] + fake.knSourceFactoryArgsForCall = append(fake.knSourceFactoryArgsForCall, struct { + }{}) + fake.recordInvocation("KnSourceFactory", []interface{}{}) + fake.knSourceFactoryMutex.Unlock() + if fake.KnSourceFactoryStub != nil { + return fake.KnSourceFactoryStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.knSourceFactoryReturns + return fakeReturns.result1 +} + +func (fake *FakeGHCommandFactory) KnSourceFactoryCallCount() int { + fake.knSourceFactoryMutex.RLock() + defer fake.knSourceFactoryMutex.RUnlock() + return len(fake.knSourceFactoryArgsForCall) +} + +func (fake *FakeGHCommandFactory) KnSourceFactoryCalls(stub func() typesa.KnSourceFactory) { + fake.knSourceFactoryMutex.Lock() + defer fake.knSourceFactoryMutex.Unlock() + fake.KnSourceFactoryStub = stub +} + +func (fake *FakeGHCommandFactory) KnSourceFactoryReturns(result1 typesa.KnSourceFactory) { + fake.knSourceFactoryMutex.Lock() + defer fake.knSourceFactoryMutex.Unlock() + fake.KnSourceFactoryStub = nil + fake.knSourceFactoryReturns = struct { + result1 typesa.KnSourceFactory + }{result1} +} + +func (fake *FakeGHCommandFactory) KnSourceFactoryReturnsOnCall(i int, result1 typesa.KnSourceFactory) { + fake.knSourceFactoryMutex.Lock() + defer fake.knSourceFactoryMutex.Unlock() + fake.KnSourceFactoryStub = nil + if fake.knSourceFactoryReturnsOnCall == nil { + fake.knSourceFactoryReturnsOnCall = make(map[int]struct { + result1 typesa.KnSourceFactory + }) + } + fake.knSourceFactoryReturnsOnCall[i] = struct { + result1 typesa.KnSourceFactory + }{result1} +} + +func (fake *FakeGHCommandFactory) SourceCommand() *cobra.Command { + fake.sourceCommandMutex.Lock() + ret, specificReturn := fake.sourceCommandReturnsOnCall[len(fake.sourceCommandArgsForCall)] + fake.sourceCommandArgsForCall = append(fake.sourceCommandArgsForCall, struct { + }{}) + fake.recordInvocation("SourceCommand", []interface{}{}) + fake.sourceCommandMutex.Unlock() + if fake.SourceCommandStub != nil { + return fake.SourceCommandStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.sourceCommandReturns + return fakeReturns.result1 +} + +func (fake *FakeGHCommandFactory) SourceCommandCallCount() int { + fake.sourceCommandMutex.RLock() + defer fake.sourceCommandMutex.RUnlock() + return len(fake.sourceCommandArgsForCall) +} + +func (fake *FakeGHCommandFactory) SourceCommandCalls(stub func() *cobra.Command) { + fake.sourceCommandMutex.Lock() + defer fake.sourceCommandMutex.Unlock() + fake.SourceCommandStub = stub +} + +func (fake *FakeGHCommandFactory) SourceCommandReturns(result1 *cobra.Command) { + fake.sourceCommandMutex.Lock() + defer fake.sourceCommandMutex.Unlock() + fake.SourceCommandStub = nil + fake.sourceCommandReturns = struct { + result1 *cobra.Command + }{result1} +} + +func (fake *FakeGHCommandFactory) SourceCommandReturnsOnCall(i int, result1 *cobra.Command) { + fake.sourceCommandMutex.Lock() + defer fake.sourceCommandMutex.Unlock() + fake.SourceCommandStub = nil + if fake.sourceCommandReturnsOnCall == nil { + fake.sourceCommandReturnsOnCall = make(map[int]struct { + result1 *cobra.Command + }) + } + fake.sourceCommandReturnsOnCall[i] = struct { + result1 *cobra.Command + }{result1} +} + +func (fake *FakeGHCommandFactory) UpdateCommand() *cobra.Command { + fake.updateCommandMutex.Lock() + ret, specificReturn := fake.updateCommandReturnsOnCall[len(fake.updateCommandArgsForCall)] + fake.updateCommandArgsForCall = append(fake.updateCommandArgsForCall, struct { + }{}) + fake.recordInvocation("UpdateCommand", []interface{}{}) + fake.updateCommandMutex.Unlock() + if fake.UpdateCommandStub != nil { + return fake.UpdateCommandStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.updateCommandReturns + return fakeReturns.result1 +} + +func (fake *FakeGHCommandFactory) UpdateCommandCallCount() int { + fake.updateCommandMutex.RLock() + defer fake.updateCommandMutex.RUnlock() + return len(fake.updateCommandArgsForCall) +} + +func (fake *FakeGHCommandFactory) UpdateCommandCalls(stub func() *cobra.Command) { + fake.updateCommandMutex.Lock() + defer fake.updateCommandMutex.Unlock() + fake.UpdateCommandStub = stub +} + +func (fake *FakeGHCommandFactory) UpdateCommandReturns(result1 *cobra.Command) { + fake.updateCommandMutex.Lock() + defer fake.updateCommandMutex.Unlock() + fake.UpdateCommandStub = nil + fake.updateCommandReturns = struct { + result1 *cobra.Command + }{result1} +} + +func (fake *FakeGHCommandFactory) UpdateCommandReturnsOnCall(i int, result1 *cobra.Command) { + fake.updateCommandMutex.Lock() + defer fake.updateCommandMutex.Unlock() + fake.UpdateCommandStub = nil + if fake.updateCommandReturnsOnCall == nil { + fake.updateCommandReturnsOnCall = make(map[int]struct { + result1 *cobra.Command + }) + } + fake.updateCommandReturnsOnCall[i] = struct { + result1 *cobra.Command + }{result1} +} + +func (fake *FakeGHCommandFactory) Invocations() map[string][][]interface{} { + fake.invocationsMutex.RLock() + defer fake.invocationsMutex.RUnlock() + fake.createCommandMutex.RLock() + defer fake.createCommandMutex.RUnlock() + fake.deleteCommandMutex.RLock() + defer fake.deleteCommandMutex.RUnlock() + fake.describeCommandMutex.RLock() + defer fake.describeCommandMutex.RUnlock() + fake.gHSourceFactoryMutex.RLock() + defer fake.gHSourceFactoryMutex.RUnlock() + fake.knSourceFactoryMutex.RLock() + defer fake.knSourceFactoryMutex.RUnlock() + fake.sourceCommandMutex.RLock() + defer fake.sourceCommandMutex.RUnlock() + fake.updateCommandMutex.RLock() + defer fake.updateCommandMutex.RUnlock() + copiedInvocations := map[string][][]interface{}{} + for key, value := range fake.invocations { + copiedInvocations[key] = value + } + return copiedInvocations +} + +func (fake *FakeGHCommandFactory) recordInvocation(key string, args []interface{}) { + fake.invocationsMutex.Lock() + defer fake.invocationsMutex.Unlock() + if fake.invocations == nil { + fake.invocations = map[string][][]interface{}{} + } + if fake.invocations[key] == nil { + fake.invocations[key] = [][]interface{}{} + } + fake.invocations[key] = append(fake.invocations[key], args) +} + +var _ types.GHCommandFactory = new(FakeGHCommandFactory) diff --git a/plugins/source-github/pkg/types/typesfakes/fake_ghflags_factory.go b/plugins/source-github/pkg/types/typesfakes/fake_ghflags_factory.go new file mode 100644 index 00000000..f621e368 --- /dev/null +++ b/plugins/source-github/pkg/types/typesfakes/fake_ghflags_factory.go @@ -0,0 +1,423 @@ +// Code generated by counterfeiter. DO NOT EDIT. +package typesfakes + +import ( + "sync" + + "github.com/maximilien/kn-source-github/pkg/types" + typesa "github.com/maximilien/kn-source-pkg/pkg/types" + "github.com/spf13/pflag" +) + +type FakeGHFlagsFactory struct { + CreateFlagsStub func() *pflag.FlagSet + createFlagsMutex sync.RWMutex + createFlagsArgsForCall []struct { + } + createFlagsReturns struct { + result1 *pflag.FlagSet + } + createFlagsReturnsOnCall map[int]struct { + result1 *pflag.FlagSet + } + DeleteFlagsStub func() *pflag.FlagSet + deleteFlagsMutex sync.RWMutex + deleteFlagsArgsForCall []struct { + } + deleteFlagsReturns struct { + result1 *pflag.FlagSet + } + deleteFlagsReturnsOnCall map[int]struct { + result1 *pflag.FlagSet + } + DescribeFlagsStub func() *pflag.FlagSet + describeFlagsMutex sync.RWMutex + describeFlagsArgsForCall []struct { + } + describeFlagsReturns struct { + result1 *pflag.FlagSet + } + describeFlagsReturnsOnCall map[int]struct { + result1 *pflag.FlagSet + } + GHSourceFactoryStub func() types.GHSourceFactory + gHSourceFactoryMutex sync.RWMutex + gHSourceFactoryArgsForCall []struct { + } + gHSourceFactoryReturns struct { + result1 types.GHSourceFactory + } + gHSourceFactoryReturnsOnCall map[int]struct { + result1 types.GHSourceFactory + } + KnSourceFactoryStub func() typesa.KnSourceFactory + knSourceFactoryMutex sync.RWMutex + knSourceFactoryArgsForCall []struct { + } + knSourceFactoryReturns struct { + result1 typesa.KnSourceFactory + } + knSourceFactoryReturnsOnCall map[int]struct { + result1 typesa.KnSourceFactory + } + UpdateFlagsStub func() *pflag.FlagSet + updateFlagsMutex sync.RWMutex + updateFlagsArgsForCall []struct { + } + updateFlagsReturns struct { + result1 *pflag.FlagSet + } + updateFlagsReturnsOnCall map[int]struct { + result1 *pflag.FlagSet + } + invocations map[string][][]interface{} + invocationsMutex sync.RWMutex +} + +func (fake *FakeGHFlagsFactory) CreateFlags() *pflag.FlagSet { + fake.createFlagsMutex.Lock() + ret, specificReturn := fake.createFlagsReturnsOnCall[len(fake.createFlagsArgsForCall)] + fake.createFlagsArgsForCall = append(fake.createFlagsArgsForCall, struct { + }{}) + fake.recordInvocation("CreateFlags", []interface{}{}) + fake.createFlagsMutex.Unlock() + if fake.CreateFlagsStub != nil { + return fake.CreateFlagsStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.createFlagsReturns + return fakeReturns.result1 +} + +func (fake *FakeGHFlagsFactory) CreateFlagsCallCount() int { + fake.createFlagsMutex.RLock() + defer fake.createFlagsMutex.RUnlock() + return len(fake.createFlagsArgsForCall) +} + +func (fake *FakeGHFlagsFactory) CreateFlagsCalls(stub func() *pflag.FlagSet) { + fake.createFlagsMutex.Lock() + defer fake.createFlagsMutex.Unlock() + fake.CreateFlagsStub = stub +} + +func (fake *FakeGHFlagsFactory) CreateFlagsReturns(result1 *pflag.FlagSet) { + fake.createFlagsMutex.Lock() + defer fake.createFlagsMutex.Unlock() + fake.CreateFlagsStub = nil + fake.createFlagsReturns = struct { + result1 *pflag.FlagSet + }{result1} +} + +func (fake *FakeGHFlagsFactory) CreateFlagsReturnsOnCall(i int, result1 *pflag.FlagSet) { + fake.createFlagsMutex.Lock() + defer fake.createFlagsMutex.Unlock() + fake.CreateFlagsStub = nil + if fake.createFlagsReturnsOnCall == nil { + fake.createFlagsReturnsOnCall = make(map[int]struct { + result1 *pflag.FlagSet + }) + } + fake.createFlagsReturnsOnCall[i] = struct { + result1 *pflag.FlagSet + }{result1} +} + +func (fake *FakeGHFlagsFactory) DeleteFlags() *pflag.FlagSet { + fake.deleteFlagsMutex.Lock() + ret, specificReturn := fake.deleteFlagsReturnsOnCall[len(fake.deleteFlagsArgsForCall)] + fake.deleteFlagsArgsForCall = append(fake.deleteFlagsArgsForCall, struct { + }{}) + fake.recordInvocation("DeleteFlags", []interface{}{}) + fake.deleteFlagsMutex.Unlock() + if fake.DeleteFlagsStub != nil { + return fake.DeleteFlagsStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.deleteFlagsReturns + return fakeReturns.result1 +} + +func (fake *FakeGHFlagsFactory) DeleteFlagsCallCount() int { + fake.deleteFlagsMutex.RLock() + defer fake.deleteFlagsMutex.RUnlock() + return len(fake.deleteFlagsArgsForCall) +} + +func (fake *FakeGHFlagsFactory) DeleteFlagsCalls(stub func() *pflag.FlagSet) { + fake.deleteFlagsMutex.Lock() + defer fake.deleteFlagsMutex.Unlock() + fake.DeleteFlagsStub = stub +} + +func (fake *FakeGHFlagsFactory) DeleteFlagsReturns(result1 *pflag.FlagSet) { + fake.deleteFlagsMutex.Lock() + defer fake.deleteFlagsMutex.Unlock() + fake.DeleteFlagsStub = nil + fake.deleteFlagsReturns = struct { + result1 *pflag.FlagSet + }{result1} +} + +func (fake *FakeGHFlagsFactory) DeleteFlagsReturnsOnCall(i int, result1 *pflag.FlagSet) { + fake.deleteFlagsMutex.Lock() + defer fake.deleteFlagsMutex.Unlock() + fake.DeleteFlagsStub = nil + if fake.deleteFlagsReturnsOnCall == nil { + fake.deleteFlagsReturnsOnCall = make(map[int]struct { + result1 *pflag.FlagSet + }) + } + fake.deleteFlagsReturnsOnCall[i] = struct { + result1 *pflag.FlagSet + }{result1} +} + +func (fake *FakeGHFlagsFactory) DescribeFlags() *pflag.FlagSet { + fake.describeFlagsMutex.Lock() + ret, specificReturn := fake.describeFlagsReturnsOnCall[len(fake.describeFlagsArgsForCall)] + fake.describeFlagsArgsForCall = append(fake.describeFlagsArgsForCall, struct { + }{}) + fake.recordInvocation("DescribeFlags", []interface{}{}) + fake.describeFlagsMutex.Unlock() + if fake.DescribeFlagsStub != nil { + return fake.DescribeFlagsStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.describeFlagsReturns + return fakeReturns.result1 +} + +func (fake *FakeGHFlagsFactory) DescribeFlagsCallCount() int { + fake.describeFlagsMutex.RLock() + defer fake.describeFlagsMutex.RUnlock() + return len(fake.describeFlagsArgsForCall) +} + +func (fake *FakeGHFlagsFactory) DescribeFlagsCalls(stub func() *pflag.FlagSet) { + fake.describeFlagsMutex.Lock() + defer fake.describeFlagsMutex.Unlock() + fake.DescribeFlagsStub = stub +} + +func (fake *FakeGHFlagsFactory) DescribeFlagsReturns(result1 *pflag.FlagSet) { + fake.describeFlagsMutex.Lock() + defer fake.describeFlagsMutex.Unlock() + fake.DescribeFlagsStub = nil + fake.describeFlagsReturns = struct { + result1 *pflag.FlagSet + }{result1} +} + +func (fake *FakeGHFlagsFactory) DescribeFlagsReturnsOnCall(i int, result1 *pflag.FlagSet) { + fake.describeFlagsMutex.Lock() + defer fake.describeFlagsMutex.Unlock() + fake.DescribeFlagsStub = nil + if fake.describeFlagsReturnsOnCall == nil { + fake.describeFlagsReturnsOnCall = make(map[int]struct { + result1 *pflag.FlagSet + }) + } + fake.describeFlagsReturnsOnCall[i] = struct { + result1 *pflag.FlagSet + }{result1} +} + +func (fake *FakeGHFlagsFactory) GHSourceFactory() types.GHSourceFactory { + fake.gHSourceFactoryMutex.Lock() + ret, specificReturn := fake.gHSourceFactoryReturnsOnCall[len(fake.gHSourceFactoryArgsForCall)] + fake.gHSourceFactoryArgsForCall = append(fake.gHSourceFactoryArgsForCall, struct { + }{}) + fake.recordInvocation("GHSourceFactory", []interface{}{}) + fake.gHSourceFactoryMutex.Unlock() + if fake.GHSourceFactoryStub != nil { + return fake.GHSourceFactoryStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.gHSourceFactoryReturns + return fakeReturns.result1 +} + +func (fake *FakeGHFlagsFactory) GHSourceFactoryCallCount() int { + fake.gHSourceFactoryMutex.RLock() + defer fake.gHSourceFactoryMutex.RUnlock() + return len(fake.gHSourceFactoryArgsForCall) +} + +func (fake *FakeGHFlagsFactory) GHSourceFactoryCalls(stub func() types.GHSourceFactory) { + fake.gHSourceFactoryMutex.Lock() + defer fake.gHSourceFactoryMutex.Unlock() + fake.GHSourceFactoryStub = stub +} + +func (fake *FakeGHFlagsFactory) GHSourceFactoryReturns(result1 types.GHSourceFactory) { + fake.gHSourceFactoryMutex.Lock() + defer fake.gHSourceFactoryMutex.Unlock() + fake.GHSourceFactoryStub = nil + fake.gHSourceFactoryReturns = struct { + result1 types.GHSourceFactory + }{result1} +} + +func (fake *FakeGHFlagsFactory) GHSourceFactoryReturnsOnCall(i int, result1 types.GHSourceFactory) { + fake.gHSourceFactoryMutex.Lock() + defer fake.gHSourceFactoryMutex.Unlock() + fake.GHSourceFactoryStub = nil + if fake.gHSourceFactoryReturnsOnCall == nil { + fake.gHSourceFactoryReturnsOnCall = make(map[int]struct { + result1 types.GHSourceFactory + }) + } + fake.gHSourceFactoryReturnsOnCall[i] = struct { + result1 types.GHSourceFactory + }{result1} +} + +func (fake *FakeGHFlagsFactory) KnSourceFactory() typesa.KnSourceFactory { + fake.knSourceFactoryMutex.Lock() + ret, specificReturn := fake.knSourceFactoryReturnsOnCall[len(fake.knSourceFactoryArgsForCall)] + fake.knSourceFactoryArgsForCall = append(fake.knSourceFactoryArgsForCall, struct { + }{}) + fake.recordInvocation("KnSourceFactory", []interface{}{}) + fake.knSourceFactoryMutex.Unlock() + if fake.KnSourceFactoryStub != nil { + return fake.KnSourceFactoryStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.knSourceFactoryReturns + return fakeReturns.result1 +} + +func (fake *FakeGHFlagsFactory) KnSourceFactoryCallCount() int { + fake.knSourceFactoryMutex.RLock() + defer fake.knSourceFactoryMutex.RUnlock() + return len(fake.knSourceFactoryArgsForCall) +} + +func (fake *FakeGHFlagsFactory) KnSourceFactoryCalls(stub func() typesa.KnSourceFactory) { + fake.knSourceFactoryMutex.Lock() + defer fake.knSourceFactoryMutex.Unlock() + fake.KnSourceFactoryStub = stub +} + +func (fake *FakeGHFlagsFactory) KnSourceFactoryReturns(result1 typesa.KnSourceFactory) { + fake.knSourceFactoryMutex.Lock() + defer fake.knSourceFactoryMutex.Unlock() + fake.KnSourceFactoryStub = nil + fake.knSourceFactoryReturns = struct { + result1 typesa.KnSourceFactory + }{result1} +} + +func (fake *FakeGHFlagsFactory) KnSourceFactoryReturnsOnCall(i int, result1 typesa.KnSourceFactory) { + fake.knSourceFactoryMutex.Lock() + defer fake.knSourceFactoryMutex.Unlock() + fake.KnSourceFactoryStub = nil + if fake.knSourceFactoryReturnsOnCall == nil { + fake.knSourceFactoryReturnsOnCall = make(map[int]struct { + result1 typesa.KnSourceFactory + }) + } + fake.knSourceFactoryReturnsOnCall[i] = struct { + result1 typesa.KnSourceFactory + }{result1} +} + +func (fake *FakeGHFlagsFactory) UpdateFlags() *pflag.FlagSet { + fake.updateFlagsMutex.Lock() + ret, specificReturn := fake.updateFlagsReturnsOnCall[len(fake.updateFlagsArgsForCall)] + fake.updateFlagsArgsForCall = append(fake.updateFlagsArgsForCall, struct { + }{}) + fake.recordInvocation("UpdateFlags", []interface{}{}) + fake.updateFlagsMutex.Unlock() + if fake.UpdateFlagsStub != nil { + return fake.UpdateFlagsStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.updateFlagsReturns + return fakeReturns.result1 +} + +func (fake *FakeGHFlagsFactory) UpdateFlagsCallCount() int { + fake.updateFlagsMutex.RLock() + defer fake.updateFlagsMutex.RUnlock() + return len(fake.updateFlagsArgsForCall) +} + +func (fake *FakeGHFlagsFactory) UpdateFlagsCalls(stub func() *pflag.FlagSet) { + fake.updateFlagsMutex.Lock() + defer fake.updateFlagsMutex.Unlock() + fake.UpdateFlagsStub = stub +} + +func (fake *FakeGHFlagsFactory) UpdateFlagsReturns(result1 *pflag.FlagSet) { + fake.updateFlagsMutex.Lock() + defer fake.updateFlagsMutex.Unlock() + fake.UpdateFlagsStub = nil + fake.updateFlagsReturns = struct { + result1 *pflag.FlagSet + }{result1} +} + +func (fake *FakeGHFlagsFactory) UpdateFlagsReturnsOnCall(i int, result1 *pflag.FlagSet) { + fake.updateFlagsMutex.Lock() + defer fake.updateFlagsMutex.Unlock() + fake.UpdateFlagsStub = nil + if fake.updateFlagsReturnsOnCall == nil { + fake.updateFlagsReturnsOnCall = make(map[int]struct { + result1 *pflag.FlagSet + }) + } + fake.updateFlagsReturnsOnCall[i] = struct { + result1 *pflag.FlagSet + }{result1} +} + +func (fake *FakeGHFlagsFactory) Invocations() map[string][][]interface{} { + fake.invocationsMutex.RLock() + defer fake.invocationsMutex.RUnlock() + fake.createFlagsMutex.RLock() + defer fake.createFlagsMutex.RUnlock() + fake.deleteFlagsMutex.RLock() + defer fake.deleteFlagsMutex.RUnlock() + fake.describeFlagsMutex.RLock() + defer fake.describeFlagsMutex.RUnlock() + fake.gHSourceFactoryMutex.RLock() + defer fake.gHSourceFactoryMutex.RUnlock() + fake.knSourceFactoryMutex.RLock() + defer fake.knSourceFactoryMutex.RUnlock() + fake.updateFlagsMutex.RLock() + defer fake.updateFlagsMutex.RUnlock() + copiedInvocations := map[string][][]interface{}{} + for key, value := range fake.invocations { + copiedInvocations[key] = value + } + return copiedInvocations +} + +func (fake *FakeGHFlagsFactory) recordInvocation(key string, args []interface{}) { + fake.invocationsMutex.Lock() + defer fake.invocationsMutex.Unlock() + if fake.invocations == nil { + fake.invocations = map[string][][]interface{}{} + } + if fake.invocations[key] == nil { + fake.invocations[key] = [][]interface{}{} + } + fake.invocations[key] = append(fake.invocations[key], args) +} + +var _ types.GHFlagsFactory = new(FakeGHFlagsFactory) diff --git a/plugins/source-github/pkg/types/typesfakes/fake_ghrun_efactory.go b/plugins/source-github/pkg/types/typesfakes/fake_ghrun_efactory.go new file mode 100644 index 00000000..5bf7061c --- /dev/null +++ b/plugins/source-github/pkg/types/typesfakes/fake_ghrun_efactory.go @@ -0,0 +1,569 @@ +// Code generated by counterfeiter. DO NOT EDIT. +package typesfakes + +import ( + "sync" + + "github.com/maximilien/kn-source-github/pkg/types" + typesa "github.com/maximilien/kn-source-pkg/pkg/types" + "github.com/spf13/cobra" +) + +type FakeGHRunEFactory struct { + CreateRunEStub func() func(cmd *cobra.Command, args []string) error + createRunEMutex sync.RWMutex + createRunEArgsForCall []struct { + } + createRunEReturns struct { + result1 func(cmd *cobra.Command, args []string) error + } + createRunEReturnsOnCall map[int]struct { + result1 func(cmd *cobra.Command, args []string) error + } + DeleteRunEStub func() func(cmd *cobra.Command, args []string) error + deleteRunEMutex sync.RWMutex + deleteRunEArgsForCall []struct { + } + deleteRunEReturns struct { + result1 func(cmd *cobra.Command, args []string) error + } + deleteRunEReturnsOnCall map[int]struct { + result1 func(cmd *cobra.Command, args []string) error + } + DescribeRunEStub func() func(cmd *cobra.Command, args []string) error + describeRunEMutex sync.RWMutex + describeRunEArgsForCall []struct { + } + describeRunEReturns struct { + result1 func(cmd *cobra.Command, args []string) error + } + describeRunEReturnsOnCall map[int]struct { + result1 func(cmd *cobra.Command, args []string) error + } + GHSourceClientStub func(string) types.GHSourceClient + gHSourceClientMutex sync.RWMutex + gHSourceClientArgsForCall []struct { + arg1 string + } + gHSourceClientReturns struct { + result1 types.GHSourceClient + } + gHSourceClientReturnsOnCall map[int]struct { + result1 types.GHSourceClient + } + GHSourceFactoryStub func() types.GHSourceFactory + gHSourceFactoryMutex sync.RWMutex + gHSourceFactoryArgsForCall []struct { + } + gHSourceFactoryReturns struct { + result1 types.GHSourceFactory + } + gHSourceFactoryReturnsOnCall map[int]struct { + result1 types.GHSourceFactory + } + KnSourceClientStub func(string) typesa.KnSourceClient + knSourceClientMutex sync.RWMutex + knSourceClientArgsForCall []struct { + arg1 string + } + knSourceClientReturns struct { + result1 typesa.KnSourceClient + } + knSourceClientReturnsOnCall map[int]struct { + result1 typesa.KnSourceClient + } + KnSourceFactoryStub func() typesa.KnSourceFactory + knSourceFactoryMutex sync.RWMutex + knSourceFactoryArgsForCall []struct { + } + knSourceFactoryReturns struct { + result1 typesa.KnSourceFactory + } + knSourceFactoryReturnsOnCall map[int]struct { + result1 typesa.KnSourceFactory + } + UpdateRunEStub func() func(cmd *cobra.Command, args []string) error + updateRunEMutex sync.RWMutex + updateRunEArgsForCall []struct { + } + updateRunEReturns struct { + result1 func(cmd *cobra.Command, args []string) error + } + updateRunEReturnsOnCall map[int]struct { + result1 func(cmd *cobra.Command, args []string) error + } + invocations map[string][][]interface{} + invocationsMutex sync.RWMutex +} + +func (fake *FakeGHRunEFactory) CreateRunE() func(cmd *cobra.Command, args []string) error { + fake.createRunEMutex.Lock() + ret, specificReturn := fake.createRunEReturnsOnCall[len(fake.createRunEArgsForCall)] + fake.createRunEArgsForCall = append(fake.createRunEArgsForCall, struct { + }{}) + fake.recordInvocation("CreateRunE", []interface{}{}) + fake.createRunEMutex.Unlock() + if fake.CreateRunEStub != nil { + return fake.CreateRunEStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.createRunEReturns + return fakeReturns.result1 +} + +func (fake *FakeGHRunEFactory) CreateRunECallCount() int { + fake.createRunEMutex.RLock() + defer fake.createRunEMutex.RUnlock() + return len(fake.createRunEArgsForCall) +} + +func (fake *FakeGHRunEFactory) CreateRunECalls(stub func() func(cmd *cobra.Command, args []string) error) { + fake.createRunEMutex.Lock() + defer fake.createRunEMutex.Unlock() + fake.CreateRunEStub = stub +} + +func (fake *FakeGHRunEFactory) CreateRunEReturns(result1 func(cmd *cobra.Command, args []string) error) { + fake.createRunEMutex.Lock() + defer fake.createRunEMutex.Unlock() + fake.CreateRunEStub = nil + fake.createRunEReturns = struct { + result1 func(cmd *cobra.Command, args []string) error + }{result1} +} + +func (fake *FakeGHRunEFactory) CreateRunEReturnsOnCall(i int, result1 func(cmd *cobra.Command, args []string) error) { + fake.createRunEMutex.Lock() + defer fake.createRunEMutex.Unlock() + fake.CreateRunEStub = nil + if fake.createRunEReturnsOnCall == nil { + fake.createRunEReturnsOnCall = make(map[int]struct { + result1 func(cmd *cobra.Command, args []string) error + }) + } + fake.createRunEReturnsOnCall[i] = struct { + result1 func(cmd *cobra.Command, args []string) error + }{result1} +} + +func (fake *FakeGHRunEFactory) DeleteRunE() func(cmd *cobra.Command, args []string) error { + fake.deleteRunEMutex.Lock() + ret, specificReturn := fake.deleteRunEReturnsOnCall[len(fake.deleteRunEArgsForCall)] + fake.deleteRunEArgsForCall = append(fake.deleteRunEArgsForCall, struct { + }{}) + fake.recordInvocation("DeleteRunE", []interface{}{}) + fake.deleteRunEMutex.Unlock() + if fake.DeleteRunEStub != nil { + return fake.DeleteRunEStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.deleteRunEReturns + return fakeReturns.result1 +} + +func (fake *FakeGHRunEFactory) DeleteRunECallCount() int { + fake.deleteRunEMutex.RLock() + defer fake.deleteRunEMutex.RUnlock() + return len(fake.deleteRunEArgsForCall) +} + +func (fake *FakeGHRunEFactory) DeleteRunECalls(stub func() func(cmd *cobra.Command, args []string) error) { + fake.deleteRunEMutex.Lock() + defer fake.deleteRunEMutex.Unlock() + fake.DeleteRunEStub = stub +} + +func (fake *FakeGHRunEFactory) DeleteRunEReturns(result1 func(cmd *cobra.Command, args []string) error) { + fake.deleteRunEMutex.Lock() + defer fake.deleteRunEMutex.Unlock() + fake.DeleteRunEStub = nil + fake.deleteRunEReturns = struct { + result1 func(cmd *cobra.Command, args []string) error + }{result1} +} + +func (fake *FakeGHRunEFactory) DeleteRunEReturnsOnCall(i int, result1 func(cmd *cobra.Command, args []string) error) { + fake.deleteRunEMutex.Lock() + defer fake.deleteRunEMutex.Unlock() + fake.DeleteRunEStub = nil + if fake.deleteRunEReturnsOnCall == nil { + fake.deleteRunEReturnsOnCall = make(map[int]struct { + result1 func(cmd *cobra.Command, args []string) error + }) + } + fake.deleteRunEReturnsOnCall[i] = struct { + result1 func(cmd *cobra.Command, args []string) error + }{result1} +} + +func (fake *FakeGHRunEFactory) DescribeRunE() func(cmd *cobra.Command, args []string) error { + fake.describeRunEMutex.Lock() + ret, specificReturn := fake.describeRunEReturnsOnCall[len(fake.describeRunEArgsForCall)] + fake.describeRunEArgsForCall = append(fake.describeRunEArgsForCall, struct { + }{}) + fake.recordInvocation("DescribeRunE", []interface{}{}) + fake.describeRunEMutex.Unlock() + if fake.DescribeRunEStub != nil { + return fake.DescribeRunEStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.describeRunEReturns + return fakeReturns.result1 +} + +func (fake *FakeGHRunEFactory) DescribeRunECallCount() int { + fake.describeRunEMutex.RLock() + defer fake.describeRunEMutex.RUnlock() + return len(fake.describeRunEArgsForCall) +} + +func (fake *FakeGHRunEFactory) DescribeRunECalls(stub func() func(cmd *cobra.Command, args []string) error) { + fake.describeRunEMutex.Lock() + defer fake.describeRunEMutex.Unlock() + fake.DescribeRunEStub = stub +} + +func (fake *FakeGHRunEFactory) DescribeRunEReturns(result1 func(cmd *cobra.Command, args []string) error) { + fake.describeRunEMutex.Lock() + defer fake.describeRunEMutex.Unlock() + fake.DescribeRunEStub = nil + fake.describeRunEReturns = struct { + result1 func(cmd *cobra.Command, args []string) error + }{result1} +} + +func (fake *FakeGHRunEFactory) DescribeRunEReturnsOnCall(i int, result1 func(cmd *cobra.Command, args []string) error) { + fake.describeRunEMutex.Lock() + defer fake.describeRunEMutex.Unlock() + fake.DescribeRunEStub = nil + if fake.describeRunEReturnsOnCall == nil { + fake.describeRunEReturnsOnCall = make(map[int]struct { + result1 func(cmd *cobra.Command, args []string) error + }) + } + fake.describeRunEReturnsOnCall[i] = struct { + result1 func(cmd *cobra.Command, args []string) error + }{result1} +} + +func (fake *FakeGHRunEFactory) GHSourceClient(arg1 string) types.GHSourceClient { + fake.gHSourceClientMutex.Lock() + ret, specificReturn := fake.gHSourceClientReturnsOnCall[len(fake.gHSourceClientArgsForCall)] + fake.gHSourceClientArgsForCall = append(fake.gHSourceClientArgsForCall, struct { + arg1 string + }{arg1}) + fake.recordInvocation("GHSourceClient", []interface{}{arg1}) + fake.gHSourceClientMutex.Unlock() + if fake.GHSourceClientStub != nil { + return fake.GHSourceClientStub(arg1) + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.gHSourceClientReturns + return fakeReturns.result1 +} + +func (fake *FakeGHRunEFactory) GHSourceClientCallCount() int { + fake.gHSourceClientMutex.RLock() + defer fake.gHSourceClientMutex.RUnlock() + return len(fake.gHSourceClientArgsForCall) +} + +func (fake *FakeGHRunEFactory) GHSourceClientCalls(stub func(string) types.GHSourceClient) { + fake.gHSourceClientMutex.Lock() + defer fake.gHSourceClientMutex.Unlock() + fake.GHSourceClientStub = stub +} + +func (fake *FakeGHRunEFactory) GHSourceClientArgsForCall(i int) string { + fake.gHSourceClientMutex.RLock() + defer fake.gHSourceClientMutex.RUnlock() + argsForCall := fake.gHSourceClientArgsForCall[i] + return argsForCall.arg1 +} + +func (fake *FakeGHRunEFactory) GHSourceClientReturns(result1 types.GHSourceClient) { + fake.gHSourceClientMutex.Lock() + defer fake.gHSourceClientMutex.Unlock() + fake.GHSourceClientStub = nil + fake.gHSourceClientReturns = struct { + result1 types.GHSourceClient + }{result1} +} + +func (fake *FakeGHRunEFactory) GHSourceClientReturnsOnCall(i int, result1 types.GHSourceClient) { + fake.gHSourceClientMutex.Lock() + defer fake.gHSourceClientMutex.Unlock() + fake.GHSourceClientStub = nil + if fake.gHSourceClientReturnsOnCall == nil { + fake.gHSourceClientReturnsOnCall = make(map[int]struct { + result1 types.GHSourceClient + }) + } + fake.gHSourceClientReturnsOnCall[i] = struct { + result1 types.GHSourceClient + }{result1} +} + +func (fake *FakeGHRunEFactory) GHSourceFactory() types.GHSourceFactory { + fake.gHSourceFactoryMutex.Lock() + ret, specificReturn := fake.gHSourceFactoryReturnsOnCall[len(fake.gHSourceFactoryArgsForCall)] + fake.gHSourceFactoryArgsForCall = append(fake.gHSourceFactoryArgsForCall, struct { + }{}) + fake.recordInvocation("GHSourceFactory", []interface{}{}) + fake.gHSourceFactoryMutex.Unlock() + if fake.GHSourceFactoryStub != nil { + return fake.GHSourceFactoryStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.gHSourceFactoryReturns + return fakeReturns.result1 +} + +func (fake *FakeGHRunEFactory) GHSourceFactoryCallCount() int { + fake.gHSourceFactoryMutex.RLock() + defer fake.gHSourceFactoryMutex.RUnlock() + return len(fake.gHSourceFactoryArgsForCall) +} + +func (fake *FakeGHRunEFactory) GHSourceFactoryCalls(stub func() types.GHSourceFactory) { + fake.gHSourceFactoryMutex.Lock() + defer fake.gHSourceFactoryMutex.Unlock() + fake.GHSourceFactoryStub = stub +} + +func (fake *FakeGHRunEFactory) GHSourceFactoryReturns(result1 types.GHSourceFactory) { + fake.gHSourceFactoryMutex.Lock() + defer fake.gHSourceFactoryMutex.Unlock() + fake.GHSourceFactoryStub = nil + fake.gHSourceFactoryReturns = struct { + result1 types.GHSourceFactory + }{result1} +} + +func (fake *FakeGHRunEFactory) GHSourceFactoryReturnsOnCall(i int, result1 types.GHSourceFactory) { + fake.gHSourceFactoryMutex.Lock() + defer fake.gHSourceFactoryMutex.Unlock() + fake.GHSourceFactoryStub = nil + if fake.gHSourceFactoryReturnsOnCall == nil { + fake.gHSourceFactoryReturnsOnCall = make(map[int]struct { + result1 types.GHSourceFactory + }) + } + fake.gHSourceFactoryReturnsOnCall[i] = struct { + result1 types.GHSourceFactory + }{result1} +} + +func (fake *FakeGHRunEFactory) KnSourceClient(arg1 string) typesa.KnSourceClient { + fake.knSourceClientMutex.Lock() + ret, specificReturn := fake.knSourceClientReturnsOnCall[len(fake.knSourceClientArgsForCall)] + fake.knSourceClientArgsForCall = append(fake.knSourceClientArgsForCall, struct { + arg1 string + }{arg1}) + fake.recordInvocation("KnSourceClient", []interface{}{arg1}) + fake.knSourceClientMutex.Unlock() + if fake.KnSourceClientStub != nil { + return fake.KnSourceClientStub(arg1) + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.knSourceClientReturns + return fakeReturns.result1 +} + +func (fake *FakeGHRunEFactory) KnSourceClientCallCount() int { + fake.knSourceClientMutex.RLock() + defer fake.knSourceClientMutex.RUnlock() + return len(fake.knSourceClientArgsForCall) +} + +func (fake *FakeGHRunEFactory) KnSourceClientCalls(stub func(string) typesa.KnSourceClient) { + fake.knSourceClientMutex.Lock() + defer fake.knSourceClientMutex.Unlock() + fake.KnSourceClientStub = stub +} + +func (fake *FakeGHRunEFactory) KnSourceClientArgsForCall(i int) string { + fake.knSourceClientMutex.RLock() + defer fake.knSourceClientMutex.RUnlock() + argsForCall := fake.knSourceClientArgsForCall[i] + return argsForCall.arg1 +} + +func (fake *FakeGHRunEFactory) KnSourceClientReturns(result1 typesa.KnSourceClient) { + fake.knSourceClientMutex.Lock() + defer fake.knSourceClientMutex.Unlock() + fake.KnSourceClientStub = nil + fake.knSourceClientReturns = struct { + result1 typesa.KnSourceClient + }{result1} +} + +func (fake *FakeGHRunEFactory) KnSourceClientReturnsOnCall(i int, result1 typesa.KnSourceClient) { + fake.knSourceClientMutex.Lock() + defer fake.knSourceClientMutex.Unlock() + fake.KnSourceClientStub = nil + if fake.knSourceClientReturnsOnCall == nil { + fake.knSourceClientReturnsOnCall = make(map[int]struct { + result1 typesa.KnSourceClient + }) + } + fake.knSourceClientReturnsOnCall[i] = struct { + result1 typesa.KnSourceClient + }{result1} +} + +func (fake *FakeGHRunEFactory) KnSourceFactory() typesa.KnSourceFactory { + fake.knSourceFactoryMutex.Lock() + ret, specificReturn := fake.knSourceFactoryReturnsOnCall[len(fake.knSourceFactoryArgsForCall)] + fake.knSourceFactoryArgsForCall = append(fake.knSourceFactoryArgsForCall, struct { + }{}) + fake.recordInvocation("KnSourceFactory", []interface{}{}) + fake.knSourceFactoryMutex.Unlock() + if fake.KnSourceFactoryStub != nil { + return fake.KnSourceFactoryStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.knSourceFactoryReturns + return fakeReturns.result1 +} + +func (fake *FakeGHRunEFactory) KnSourceFactoryCallCount() int { + fake.knSourceFactoryMutex.RLock() + defer fake.knSourceFactoryMutex.RUnlock() + return len(fake.knSourceFactoryArgsForCall) +} + +func (fake *FakeGHRunEFactory) KnSourceFactoryCalls(stub func() typesa.KnSourceFactory) { + fake.knSourceFactoryMutex.Lock() + defer fake.knSourceFactoryMutex.Unlock() + fake.KnSourceFactoryStub = stub +} + +func (fake *FakeGHRunEFactory) KnSourceFactoryReturns(result1 typesa.KnSourceFactory) { + fake.knSourceFactoryMutex.Lock() + defer fake.knSourceFactoryMutex.Unlock() + fake.KnSourceFactoryStub = nil + fake.knSourceFactoryReturns = struct { + result1 typesa.KnSourceFactory + }{result1} +} + +func (fake *FakeGHRunEFactory) KnSourceFactoryReturnsOnCall(i int, result1 typesa.KnSourceFactory) { + fake.knSourceFactoryMutex.Lock() + defer fake.knSourceFactoryMutex.Unlock() + fake.KnSourceFactoryStub = nil + if fake.knSourceFactoryReturnsOnCall == nil { + fake.knSourceFactoryReturnsOnCall = make(map[int]struct { + result1 typesa.KnSourceFactory + }) + } + fake.knSourceFactoryReturnsOnCall[i] = struct { + result1 typesa.KnSourceFactory + }{result1} +} + +func (fake *FakeGHRunEFactory) UpdateRunE() func(cmd *cobra.Command, args []string) error { + fake.updateRunEMutex.Lock() + ret, specificReturn := fake.updateRunEReturnsOnCall[len(fake.updateRunEArgsForCall)] + fake.updateRunEArgsForCall = append(fake.updateRunEArgsForCall, struct { + }{}) + fake.recordInvocation("UpdateRunE", []interface{}{}) + fake.updateRunEMutex.Unlock() + if fake.UpdateRunEStub != nil { + return fake.UpdateRunEStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.updateRunEReturns + return fakeReturns.result1 +} + +func (fake *FakeGHRunEFactory) UpdateRunECallCount() int { + fake.updateRunEMutex.RLock() + defer fake.updateRunEMutex.RUnlock() + return len(fake.updateRunEArgsForCall) +} + +func (fake *FakeGHRunEFactory) UpdateRunECalls(stub func() func(cmd *cobra.Command, args []string) error) { + fake.updateRunEMutex.Lock() + defer fake.updateRunEMutex.Unlock() + fake.UpdateRunEStub = stub +} + +func (fake *FakeGHRunEFactory) UpdateRunEReturns(result1 func(cmd *cobra.Command, args []string) error) { + fake.updateRunEMutex.Lock() + defer fake.updateRunEMutex.Unlock() + fake.UpdateRunEStub = nil + fake.updateRunEReturns = struct { + result1 func(cmd *cobra.Command, args []string) error + }{result1} +} + +func (fake *FakeGHRunEFactory) UpdateRunEReturnsOnCall(i int, result1 func(cmd *cobra.Command, args []string) error) { + fake.updateRunEMutex.Lock() + defer fake.updateRunEMutex.Unlock() + fake.UpdateRunEStub = nil + if fake.updateRunEReturnsOnCall == nil { + fake.updateRunEReturnsOnCall = make(map[int]struct { + result1 func(cmd *cobra.Command, args []string) error + }) + } + fake.updateRunEReturnsOnCall[i] = struct { + result1 func(cmd *cobra.Command, args []string) error + }{result1} +} + +func (fake *FakeGHRunEFactory) Invocations() map[string][][]interface{} { + fake.invocationsMutex.RLock() + defer fake.invocationsMutex.RUnlock() + fake.createRunEMutex.RLock() + defer fake.createRunEMutex.RUnlock() + fake.deleteRunEMutex.RLock() + defer fake.deleteRunEMutex.RUnlock() + fake.describeRunEMutex.RLock() + defer fake.describeRunEMutex.RUnlock() + fake.gHSourceClientMutex.RLock() + defer fake.gHSourceClientMutex.RUnlock() + fake.gHSourceFactoryMutex.RLock() + defer fake.gHSourceFactoryMutex.RUnlock() + fake.knSourceClientMutex.RLock() + defer fake.knSourceClientMutex.RUnlock() + fake.knSourceFactoryMutex.RLock() + defer fake.knSourceFactoryMutex.RUnlock() + fake.updateRunEMutex.RLock() + defer fake.updateRunEMutex.RUnlock() + copiedInvocations := map[string][][]interface{}{} + for key, value := range fake.invocations { + copiedInvocations[key] = value + } + return copiedInvocations +} + +func (fake *FakeGHRunEFactory) recordInvocation(key string, args []interface{}) { + fake.invocationsMutex.Lock() + defer fake.invocationsMutex.Unlock() + if fake.invocations == nil { + fake.invocations = map[string][][]interface{}{} + } + if fake.invocations[key] == nil { + fake.invocations[key] = [][]interface{}{} + } + fake.invocations[key] = append(fake.invocations[key], args) +} + +var _ types.GHRunEFactory = new(FakeGHRunEFactory) diff --git a/plugins/source-github/pkg/types/typesfakes/fake_ghsource_client.go b/plugins/source-github/pkg/types/typesfakes/fake_ghsource_client.go new file mode 100644 index 00000000..78f1b181 --- /dev/null +++ b/plugins/source-github/pkg/types/typesfakes/fake_ghsource_client.go @@ -0,0 +1,603 @@ +// Code generated by counterfeiter. DO NOT EDIT. +package typesfakes + +import ( + "sync" + + "github.com/maximilien/kn-source-github/pkg/types" + typesa "github.com/maximilien/kn-source-pkg/pkg/types" + "k8s.io/client-go/rest" + "knative.dev/eventing-contrib/github/pkg/apis/sources/v1alpha1" +) + +type FakeGHSourceClient struct { + CreateGHSourceStub func(*v1alpha1.GitHubSource) (*v1alpha1.GitHubSource, error) + createGHSourceMutex sync.RWMutex + createGHSourceArgsForCall []struct { + arg1 *v1alpha1.GitHubSource + } + createGHSourceReturns struct { + result1 *v1alpha1.GitHubSource + result2 error + } + createGHSourceReturnsOnCall map[int]struct { + result1 *v1alpha1.GitHubSource + result2 error + } + DeleteGHSourceStub func(string) error + deleteGHSourceMutex sync.RWMutex + deleteGHSourceArgsForCall []struct { + arg1 string + } + deleteGHSourceReturns struct { + result1 error + } + deleteGHSourceReturnsOnCall map[int]struct { + result1 error + } + GHSourceParamsStub func() *types.GHSourceParams + gHSourceParamsMutex sync.RWMutex + gHSourceParamsArgsForCall []struct { + } + gHSourceParamsReturns struct { + result1 *types.GHSourceParams + } + gHSourceParamsReturnsOnCall map[int]struct { + result1 *types.GHSourceParams + } + GetGHSourceStub func(string) (*v1alpha1.GitHubSource, error) + getGHSourceMutex sync.RWMutex + getGHSourceArgsForCall []struct { + arg1 string + } + getGHSourceReturns struct { + result1 *v1alpha1.GitHubSource + result2 error + } + getGHSourceReturnsOnCall map[int]struct { + result1 *v1alpha1.GitHubSource + result2 error + } + KnSourceParamsStub func() *typesa.KnSourceParams + knSourceParamsMutex sync.RWMutex + knSourceParamsArgsForCall []struct { + } + knSourceParamsReturns struct { + result1 *typesa.KnSourceParams + } + knSourceParamsReturnsOnCall map[int]struct { + result1 *typesa.KnSourceParams + } + NamespaceStub func() string + namespaceMutex sync.RWMutex + namespaceArgsForCall []struct { + } + namespaceReturns struct { + result1 string + } + namespaceReturnsOnCall map[int]struct { + result1 string + } + RestConfigStub func() *rest.Config + restConfigMutex sync.RWMutex + restConfigArgsForCall []struct { + } + restConfigReturns struct { + result1 *rest.Config + } + restConfigReturnsOnCall map[int]struct { + result1 *rest.Config + } + UpdateGHSourceStub func(*v1alpha1.GitHubSource) (*v1alpha1.GitHubSource, error) + updateGHSourceMutex sync.RWMutex + updateGHSourceArgsForCall []struct { + arg1 *v1alpha1.GitHubSource + } + updateGHSourceReturns struct { + result1 *v1alpha1.GitHubSource + result2 error + } + updateGHSourceReturnsOnCall map[int]struct { + result1 *v1alpha1.GitHubSource + result2 error + } + invocations map[string][][]interface{} + invocationsMutex sync.RWMutex +} + +func (fake *FakeGHSourceClient) CreateGHSource(arg1 *v1alpha1.GitHubSource) (*v1alpha1.GitHubSource, error) { + fake.createGHSourceMutex.Lock() + ret, specificReturn := fake.createGHSourceReturnsOnCall[len(fake.createGHSourceArgsForCall)] + fake.createGHSourceArgsForCall = append(fake.createGHSourceArgsForCall, struct { + arg1 *v1alpha1.GitHubSource + }{arg1}) + fake.recordInvocation("CreateGHSource", []interface{}{arg1}) + fake.createGHSourceMutex.Unlock() + if fake.CreateGHSourceStub != nil { + return fake.CreateGHSourceStub(arg1) + } + if specificReturn { + return ret.result1, ret.result2 + } + fakeReturns := fake.createGHSourceReturns + return fakeReturns.result1, fakeReturns.result2 +} + +func (fake *FakeGHSourceClient) CreateGHSourceCallCount() int { + fake.createGHSourceMutex.RLock() + defer fake.createGHSourceMutex.RUnlock() + return len(fake.createGHSourceArgsForCall) +} + +func (fake *FakeGHSourceClient) CreateGHSourceCalls(stub func(*v1alpha1.GitHubSource) (*v1alpha1.GitHubSource, error)) { + fake.createGHSourceMutex.Lock() + defer fake.createGHSourceMutex.Unlock() + fake.CreateGHSourceStub = stub +} + +func (fake *FakeGHSourceClient) CreateGHSourceArgsForCall(i int) *v1alpha1.GitHubSource { + fake.createGHSourceMutex.RLock() + defer fake.createGHSourceMutex.RUnlock() + argsForCall := fake.createGHSourceArgsForCall[i] + return argsForCall.arg1 +} + +func (fake *FakeGHSourceClient) CreateGHSourceReturns(result1 *v1alpha1.GitHubSource, result2 error) { + fake.createGHSourceMutex.Lock() + defer fake.createGHSourceMutex.Unlock() + fake.CreateGHSourceStub = nil + fake.createGHSourceReturns = struct { + result1 *v1alpha1.GitHubSource + result2 error + }{result1, result2} +} + +func (fake *FakeGHSourceClient) CreateGHSourceReturnsOnCall(i int, result1 *v1alpha1.GitHubSource, result2 error) { + fake.createGHSourceMutex.Lock() + defer fake.createGHSourceMutex.Unlock() + fake.CreateGHSourceStub = nil + if fake.createGHSourceReturnsOnCall == nil { + fake.createGHSourceReturnsOnCall = make(map[int]struct { + result1 *v1alpha1.GitHubSource + result2 error + }) + } + fake.createGHSourceReturnsOnCall[i] = struct { + result1 *v1alpha1.GitHubSource + result2 error + }{result1, result2} +} + +func (fake *FakeGHSourceClient) DeleteGHSource(arg1 string) error { + fake.deleteGHSourceMutex.Lock() + ret, specificReturn := fake.deleteGHSourceReturnsOnCall[len(fake.deleteGHSourceArgsForCall)] + fake.deleteGHSourceArgsForCall = append(fake.deleteGHSourceArgsForCall, struct { + arg1 string + }{arg1}) + fake.recordInvocation("DeleteGHSource", []interface{}{arg1}) + fake.deleteGHSourceMutex.Unlock() + if fake.DeleteGHSourceStub != nil { + return fake.DeleteGHSourceStub(arg1) + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.deleteGHSourceReturns + return fakeReturns.result1 +} + +func (fake *FakeGHSourceClient) DeleteGHSourceCallCount() int { + fake.deleteGHSourceMutex.RLock() + defer fake.deleteGHSourceMutex.RUnlock() + return len(fake.deleteGHSourceArgsForCall) +} + +func (fake *FakeGHSourceClient) DeleteGHSourceCalls(stub func(string) error) { + fake.deleteGHSourceMutex.Lock() + defer fake.deleteGHSourceMutex.Unlock() + fake.DeleteGHSourceStub = stub +} + +func (fake *FakeGHSourceClient) DeleteGHSourceArgsForCall(i int) string { + fake.deleteGHSourceMutex.RLock() + defer fake.deleteGHSourceMutex.RUnlock() + argsForCall := fake.deleteGHSourceArgsForCall[i] + return argsForCall.arg1 +} + +func (fake *FakeGHSourceClient) DeleteGHSourceReturns(result1 error) { + fake.deleteGHSourceMutex.Lock() + defer fake.deleteGHSourceMutex.Unlock() + fake.DeleteGHSourceStub = nil + fake.deleteGHSourceReturns = struct { + result1 error + }{result1} +} + +func (fake *FakeGHSourceClient) DeleteGHSourceReturnsOnCall(i int, result1 error) { + fake.deleteGHSourceMutex.Lock() + defer fake.deleteGHSourceMutex.Unlock() + fake.DeleteGHSourceStub = nil + if fake.deleteGHSourceReturnsOnCall == nil { + fake.deleteGHSourceReturnsOnCall = make(map[int]struct { + result1 error + }) + } + fake.deleteGHSourceReturnsOnCall[i] = struct { + result1 error + }{result1} +} + +func (fake *FakeGHSourceClient) GHSourceParams() *types.GHSourceParams { + fake.gHSourceParamsMutex.Lock() + ret, specificReturn := fake.gHSourceParamsReturnsOnCall[len(fake.gHSourceParamsArgsForCall)] + fake.gHSourceParamsArgsForCall = append(fake.gHSourceParamsArgsForCall, struct { + }{}) + fake.recordInvocation("GHSourceParams", []interface{}{}) + fake.gHSourceParamsMutex.Unlock() + if fake.GHSourceParamsStub != nil { + return fake.GHSourceParamsStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.gHSourceParamsReturns + return fakeReturns.result1 +} + +func (fake *FakeGHSourceClient) GHSourceParamsCallCount() int { + fake.gHSourceParamsMutex.RLock() + defer fake.gHSourceParamsMutex.RUnlock() + return len(fake.gHSourceParamsArgsForCall) +} + +func (fake *FakeGHSourceClient) GHSourceParamsCalls(stub func() *types.GHSourceParams) { + fake.gHSourceParamsMutex.Lock() + defer fake.gHSourceParamsMutex.Unlock() + fake.GHSourceParamsStub = stub +} + +func (fake *FakeGHSourceClient) GHSourceParamsReturns(result1 *types.GHSourceParams) { + fake.gHSourceParamsMutex.Lock() + defer fake.gHSourceParamsMutex.Unlock() + fake.GHSourceParamsStub = nil + fake.gHSourceParamsReturns = struct { + result1 *types.GHSourceParams + }{result1} +} + +func (fake *FakeGHSourceClient) GHSourceParamsReturnsOnCall(i int, result1 *types.GHSourceParams) { + fake.gHSourceParamsMutex.Lock() + defer fake.gHSourceParamsMutex.Unlock() + fake.GHSourceParamsStub = nil + if fake.gHSourceParamsReturnsOnCall == nil { + fake.gHSourceParamsReturnsOnCall = make(map[int]struct { + result1 *types.GHSourceParams + }) + } + fake.gHSourceParamsReturnsOnCall[i] = struct { + result1 *types.GHSourceParams + }{result1} +} + +func (fake *FakeGHSourceClient) GetGHSource(arg1 string) (*v1alpha1.GitHubSource, error) { + fake.getGHSourceMutex.Lock() + ret, specificReturn := fake.getGHSourceReturnsOnCall[len(fake.getGHSourceArgsForCall)] + fake.getGHSourceArgsForCall = append(fake.getGHSourceArgsForCall, struct { + arg1 string + }{arg1}) + fake.recordInvocation("GetGHSource", []interface{}{arg1}) + fake.getGHSourceMutex.Unlock() + if fake.GetGHSourceStub != nil { + return fake.GetGHSourceStub(arg1) + } + if specificReturn { + return ret.result1, ret.result2 + } + fakeReturns := fake.getGHSourceReturns + return fakeReturns.result1, fakeReturns.result2 +} + +func (fake *FakeGHSourceClient) GetGHSourceCallCount() int { + fake.getGHSourceMutex.RLock() + defer fake.getGHSourceMutex.RUnlock() + return len(fake.getGHSourceArgsForCall) +} + +func (fake *FakeGHSourceClient) GetGHSourceCalls(stub func(string) (*v1alpha1.GitHubSource, error)) { + fake.getGHSourceMutex.Lock() + defer fake.getGHSourceMutex.Unlock() + fake.GetGHSourceStub = stub +} + +func (fake *FakeGHSourceClient) GetGHSourceArgsForCall(i int) string { + fake.getGHSourceMutex.RLock() + defer fake.getGHSourceMutex.RUnlock() + argsForCall := fake.getGHSourceArgsForCall[i] + return argsForCall.arg1 +} + +func (fake *FakeGHSourceClient) GetGHSourceReturns(result1 *v1alpha1.GitHubSource, result2 error) { + fake.getGHSourceMutex.Lock() + defer fake.getGHSourceMutex.Unlock() + fake.GetGHSourceStub = nil + fake.getGHSourceReturns = struct { + result1 *v1alpha1.GitHubSource + result2 error + }{result1, result2} +} + +func (fake *FakeGHSourceClient) GetGHSourceReturnsOnCall(i int, result1 *v1alpha1.GitHubSource, result2 error) { + fake.getGHSourceMutex.Lock() + defer fake.getGHSourceMutex.Unlock() + fake.GetGHSourceStub = nil + if fake.getGHSourceReturnsOnCall == nil { + fake.getGHSourceReturnsOnCall = make(map[int]struct { + result1 *v1alpha1.GitHubSource + result2 error + }) + } + fake.getGHSourceReturnsOnCall[i] = struct { + result1 *v1alpha1.GitHubSource + result2 error + }{result1, result2} +} + +func (fake *FakeGHSourceClient) KnSourceParams() *typesa.KnSourceParams { + fake.knSourceParamsMutex.Lock() + ret, specificReturn := fake.knSourceParamsReturnsOnCall[len(fake.knSourceParamsArgsForCall)] + fake.knSourceParamsArgsForCall = append(fake.knSourceParamsArgsForCall, struct { + }{}) + fake.recordInvocation("KnSourceParams", []interface{}{}) + fake.knSourceParamsMutex.Unlock() + if fake.KnSourceParamsStub != nil { + return fake.KnSourceParamsStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.knSourceParamsReturns + return fakeReturns.result1 +} + +func (fake *FakeGHSourceClient) KnSourceParamsCallCount() int { + fake.knSourceParamsMutex.RLock() + defer fake.knSourceParamsMutex.RUnlock() + return len(fake.knSourceParamsArgsForCall) +} + +func (fake *FakeGHSourceClient) KnSourceParamsCalls(stub func() *typesa.KnSourceParams) { + fake.knSourceParamsMutex.Lock() + defer fake.knSourceParamsMutex.Unlock() + fake.KnSourceParamsStub = stub +} + +func (fake *FakeGHSourceClient) KnSourceParamsReturns(result1 *typesa.KnSourceParams) { + fake.knSourceParamsMutex.Lock() + defer fake.knSourceParamsMutex.Unlock() + fake.KnSourceParamsStub = nil + fake.knSourceParamsReturns = struct { + result1 *typesa.KnSourceParams + }{result1} +} + +func (fake *FakeGHSourceClient) KnSourceParamsReturnsOnCall(i int, result1 *typesa.KnSourceParams) { + fake.knSourceParamsMutex.Lock() + defer fake.knSourceParamsMutex.Unlock() + fake.KnSourceParamsStub = nil + if fake.knSourceParamsReturnsOnCall == nil { + fake.knSourceParamsReturnsOnCall = make(map[int]struct { + result1 *typesa.KnSourceParams + }) + } + fake.knSourceParamsReturnsOnCall[i] = struct { + result1 *typesa.KnSourceParams + }{result1} +} + +func (fake *FakeGHSourceClient) Namespace() string { + fake.namespaceMutex.Lock() + ret, specificReturn := fake.namespaceReturnsOnCall[len(fake.namespaceArgsForCall)] + fake.namespaceArgsForCall = append(fake.namespaceArgsForCall, struct { + }{}) + fake.recordInvocation("Namespace", []interface{}{}) + fake.namespaceMutex.Unlock() + if fake.NamespaceStub != nil { + return fake.NamespaceStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.namespaceReturns + return fakeReturns.result1 +} + +func (fake *FakeGHSourceClient) NamespaceCallCount() int { + fake.namespaceMutex.RLock() + defer fake.namespaceMutex.RUnlock() + return len(fake.namespaceArgsForCall) +} + +func (fake *FakeGHSourceClient) NamespaceCalls(stub func() string) { + fake.namespaceMutex.Lock() + defer fake.namespaceMutex.Unlock() + fake.NamespaceStub = stub +} + +func (fake *FakeGHSourceClient) NamespaceReturns(result1 string) { + fake.namespaceMutex.Lock() + defer fake.namespaceMutex.Unlock() + fake.NamespaceStub = nil + fake.namespaceReturns = struct { + result1 string + }{result1} +} + +func (fake *FakeGHSourceClient) NamespaceReturnsOnCall(i int, result1 string) { + fake.namespaceMutex.Lock() + defer fake.namespaceMutex.Unlock() + fake.NamespaceStub = nil + if fake.namespaceReturnsOnCall == nil { + fake.namespaceReturnsOnCall = make(map[int]struct { + result1 string + }) + } + fake.namespaceReturnsOnCall[i] = struct { + result1 string + }{result1} +} + +func (fake *FakeGHSourceClient) RestConfig() *rest.Config { + fake.restConfigMutex.Lock() + ret, specificReturn := fake.restConfigReturnsOnCall[len(fake.restConfigArgsForCall)] + fake.restConfigArgsForCall = append(fake.restConfigArgsForCall, struct { + }{}) + fake.recordInvocation("RestConfig", []interface{}{}) + fake.restConfigMutex.Unlock() + if fake.RestConfigStub != nil { + return fake.RestConfigStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.restConfigReturns + return fakeReturns.result1 +} + +func (fake *FakeGHSourceClient) RestConfigCallCount() int { + fake.restConfigMutex.RLock() + defer fake.restConfigMutex.RUnlock() + return len(fake.restConfigArgsForCall) +} + +func (fake *FakeGHSourceClient) RestConfigCalls(stub func() *rest.Config) { + fake.restConfigMutex.Lock() + defer fake.restConfigMutex.Unlock() + fake.RestConfigStub = stub +} + +func (fake *FakeGHSourceClient) RestConfigReturns(result1 *rest.Config) { + fake.restConfigMutex.Lock() + defer fake.restConfigMutex.Unlock() + fake.RestConfigStub = nil + fake.restConfigReturns = struct { + result1 *rest.Config + }{result1} +} + +func (fake *FakeGHSourceClient) RestConfigReturnsOnCall(i int, result1 *rest.Config) { + fake.restConfigMutex.Lock() + defer fake.restConfigMutex.Unlock() + fake.RestConfigStub = nil + if fake.restConfigReturnsOnCall == nil { + fake.restConfigReturnsOnCall = make(map[int]struct { + result1 *rest.Config + }) + } + fake.restConfigReturnsOnCall[i] = struct { + result1 *rest.Config + }{result1} +} + +func (fake *FakeGHSourceClient) UpdateGHSource(arg1 *v1alpha1.GitHubSource) (*v1alpha1.GitHubSource, error) { + fake.updateGHSourceMutex.Lock() + ret, specificReturn := fake.updateGHSourceReturnsOnCall[len(fake.updateGHSourceArgsForCall)] + fake.updateGHSourceArgsForCall = append(fake.updateGHSourceArgsForCall, struct { + arg1 *v1alpha1.GitHubSource + }{arg1}) + fake.recordInvocation("UpdateGHSource", []interface{}{arg1}) + fake.updateGHSourceMutex.Unlock() + if fake.UpdateGHSourceStub != nil { + return fake.UpdateGHSourceStub(arg1) + } + if specificReturn { + return ret.result1, ret.result2 + } + fakeReturns := fake.updateGHSourceReturns + return fakeReturns.result1, fakeReturns.result2 +} + +func (fake *FakeGHSourceClient) UpdateGHSourceCallCount() int { + fake.updateGHSourceMutex.RLock() + defer fake.updateGHSourceMutex.RUnlock() + return len(fake.updateGHSourceArgsForCall) +} + +func (fake *FakeGHSourceClient) UpdateGHSourceCalls(stub func(*v1alpha1.GitHubSource) (*v1alpha1.GitHubSource, error)) { + fake.updateGHSourceMutex.Lock() + defer fake.updateGHSourceMutex.Unlock() + fake.UpdateGHSourceStub = stub +} + +func (fake *FakeGHSourceClient) UpdateGHSourceArgsForCall(i int) *v1alpha1.GitHubSource { + fake.updateGHSourceMutex.RLock() + defer fake.updateGHSourceMutex.RUnlock() + argsForCall := fake.updateGHSourceArgsForCall[i] + return argsForCall.arg1 +} + +func (fake *FakeGHSourceClient) UpdateGHSourceReturns(result1 *v1alpha1.GitHubSource, result2 error) { + fake.updateGHSourceMutex.Lock() + defer fake.updateGHSourceMutex.Unlock() + fake.UpdateGHSourceStub = nil + fake.updateGHSourceReturns = struct { + result1 *v1alpha1.GitHubSource + result2 error + }{result1, result2} +} + +func (fake *FakeGHSourceClient) UpdateGHSourceReturnsOnCall(i int, result1 *v1alpha1.GitHubSource, result2 error) { + fake.updateGHSourceMutex.Lock() + defer fake.updateGHSourceMutex.Unlock() + fake.UpdateGHSourceStub = nil + if fake.updateGHSourceReturnsOnCall == nil { + fake.updateGHSourceReturnsOnCall = make(map[int]struct { + result1 *v1alpha1.GitHubSource + result2 error + }) + } + fake.updateGHSourceReturnsOnCall[i] = struct { + result1 *v1alpha1.GitHubSource + result2 error + }{result1, result2} +} + +func (fake *FakeGHSourceClient) Invocations() map[string][][]interface{} { + fake.invocationsMutex.RLock() + defer fake.invocationsMutex.RUnlock() + fake.createGHSourceMutex.RLock() + defer fake.createGHSourceMutex.RUnlock() + fake.deleteGHSourceMutex.RLock() + defer fake.deleteGHSourceMutex.RUnlock() + fake.gHSourceParamsMutex.RLock() + defer fake.gHSourceParamsMutex.RUnlock() + fake.getGHSourceMutex.RLock() + defer fake.getGHSourceMutex.RUnlock() + fake.knSourceParamsMutex.RLock() + defer fake.knSourceParamsMutex.RUnlock() + fake.namespaceMutex.RLock() + defer fake.namespaceMutex.RUnlock() + fake.restConfigMutex.RLock() + defer fake.restConfigMutex.RUnlock() + fake.updateGHSourceMutex.RLock() + defer fake.updateGHSourceMutex.RUnlock() + copiedInvocations := map[string][][]interface{}{} + for key, value := range fake.invocations { + copiedInvocations[key] = value + } + return copiedInvocations +} + +func (fake *FakeGHSourceClient) recordInvocation(key string, args []interface{}) { + fake.invocationsMutex.Lock() + defer fake.invocationsMutex.Unlock() + if fake.invocations == nil { + fake.invocations = map[string][][]interface{}{} + } + if fake.invocations[key] == nil { + fake.invocations[key] = [][]interface{}{} + } + fake.invocations[key] = append(fake.invocations[key], args) +} + +var _ types.GHSourceClient = new(FakeGHSourceClient) diff --git a/plugins/source-github/pkg/types/typesfakes/fake_ghsource_factory.go b/plugins/source-github/pkg/types/typesfakes/fake_ghsource_factory.go new file mode 100644 index 00000000..3958363a --- /dev/null +++ b/plugins/source-github/pkg/types/typesfakes/fake_ghsource_factory.go @@ -0,0 +1,504 @@ +// Code generated by counterfeiter. DO NOT EDIT. +package typesfakes + +import ( + "sync" + + "github.com/maximilien/kn-source-github/pkg/types" + typesa "github.com/maximilien/kn-source-pkg/pkg/types" +) + +type FakeGHSourceFactory struct { + CreateGHSourceClientStub func(string) types.GHSourceClient + createGHSourceClientMutex sync.RWMutex + createGHSourceClientArgsForCall []struct { + arg1 string + } + createGHSourceClientReturns struct { + result1 types.GHSourceClient + } + createGHSourceClientReturnsOnCall map[int]struct { + result1 types.GHSourceClient + } + CreateGHSourceParamsStub func() *types.GHSourceParams + createGHSourceParamsMutex sync.RWMutex + createGHSourceParamsArgsForCall []struct { + } + createGHSourceParamsReturns struct { + result1 *types.GHSourceParams + } + createGHSourceParamsReturnsOnCall map[int]struct { + result1 *types.GHSourceParams + } + CreateKnSourceClientStub func(string) typesa.KnSourceClient + createKnSourceClientMutex sync.RWMutex + createKnSourceClientArgsForCall []struct { + arg1 string + } + createKnSourceClientReturns struct { + result1 typesa.KnSourceClient + } + createKnSourceClientReturnsOnCall map[int]struct { + result1 typesa.KnSourceClient + } + CreateKnSourceParamsStub func() *typesa.KnSourceParams + createKnSourceParamsMutex sync.RWMutex + createKnSourceParamsArgsForCall []struct { + } + createKnSourceParamsReturns struct { + result1 *typesa.KnSourceParams + } + createKnSourceParamsReturnsOnCall map[int]struct { + result1 *typesa.KnSourceParams + } + GHSourceClientStub func() types.GHSourceClient + gHSourceClientMutex sync.RWMutex + gHSourceClientArgsForCall []struct { + } + gHSourceClientReturns struct { + result1 types.GHSourceClient + } + gHSourceClientReturnsOnCall map[int]struct { + result1 types.GHSourceClient + } + GHSourceParamsStub func() *types.GHSourceParams + gHSourceParamsMutex sync.RWMutex + gHSourceParamsArgsForCall []struct { + } + gHSourceParamsReturns struct { + result1 *types.GHSourceParams + } + gHSourceParamsReturnsOnCall map[int]struct { + result1 *types.GHSourceParams + } + KnSourceParamsStub func() *typesa.KnSourceParams + knSourceParamsMutex sync.RWMutex + knSourceParamsArgsForCall []struct { + } + knSourceParamsReturns struct { + result1 *typesa.KnSourceParams + } + knSourceParamsReturnsOnCall map[int]struct { + result1 *typesa.KnSourceParams + } + invocations map[string][][]interface{} + invocationsMutex sync.RWMutex +} + +func (fake *FakeGHSourceFactory) CreateGHSourceClient(arg1 string) types.GHSourceClient { + fake.createGHSourceClientMutex.Lock() + ret, specificReturn := fake.createGHSourceClientReturnsOnCall[len(fake.createGHSourceClientArgsForCall)] + fake.createGHSourceClientArgsForCall = append(fake.createGHSourceClientArgsForCall, struct { + arg1 string + }{arg1}) + fake.recordInvocation("CreateGHSourceClient", []interface{}{arg1}) + fake.createGHSourceClientMutex.Unlock() + if fake.CreateGHSourceClientStub != nil { + return fake.CreateGHSourceClientStub(arg1) + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.createGHSourceClientReturns + return fakeReturns.result1 +} + +func (fake *FakeGHSourceFactory) CreateGHSourceClientCallCount() int { + fake.createGHSourceClientMutex.RLock() + defer fake.createGHSourceClientMutex.RUnlock() + return len(fake.createGHSourceClientArgsForCall) +} + +func (fake *FakeGHSourceFactory) CreateGHSourceClientCalls(stub func(string) types.GHSourceClient) { + fake.createGHSourceClientMutex.Lock() + defer fake.createGHSourceClientMutex.Unlock() + fake.CreateGHSourceClientStub = stub +} + +func (fake *FakeGHSourceFactory) CreateGHSourceClientArgsForCall(i int) string { + fake.createGHSourceClientMutex.RLock() + defer fake.createGHSourceClientMutex.RUnlock() + argsForCall := fake.createGHSourceClientArgsForCall[i] + return argsForCall.arg1 +} + +func (fake *FakeGHSourceFactory) CreateGHSourceClientReturns(result1 types.GHSourceClient) { + fake.createGHSourceClientMutex.Lock() + defer fake.createGHSourceClientMutex.Unlock() + fake.CreateGHSourceClientStub = nil + fake.createGHSourceClientReturns = struct { + result1 types.GHSourceClient + }{result1} +} + +func (fake *FakeGHSourceFactory) CreateGHSourceClientReturnsOnCall(i int, result1 types.GHSourceClient) { + fake.createGHSourceClientMutex.Lock() + defer fake.createGHSourceClientMutex.Unlock() + fake.CreateGHSourceClientStub = nil + if fake.createGHSourceClientReturnsOnCall == nil { + fake.createGHSourceClientReturnsOnCall = make(map[int]struct { + result1 types.GHSourceClient + }) + } + fake.createGHSourceClientReturnsOnCall[i] = struct { + result1 types.GHSourceClient + }{result1} +} + +func (fake *FakeGHSourceFactory) CreateGHSourceParams() *types.GHSourceParams { + fake.createGHSourceParamsMutex.Lock() + ret, specificReturn := fake.createGHSourceParamsReturnsOnCall[len(fake.createGHSourceParamsArgsForCall)] + fake.createGHSourceParamsArgsForCall = append(fake.createGHSourceParamsArgsForCall, struct { + }{}) + fake.recordInvocation("CreateGHSourceParams", []interface{}{}) + fake.createGHSourceParamsMutex.Unlock() + if fake.CreateGHSourceParamsStub != nil { + return fake.CreateGHSourceParamsStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.createGHSourceParamsReturns + return fakeReturns.result1 +} + +func (fake *FakeGHSourceFactory) CreateGHSourceParamsCallCount() int { + fake.createGHSourceParamsMutex.RLock() + defer fake.createGHSourceParamsMutex.RUnlock() + return len(fake.createGHSourceParamsArgsForCall) +} + +func (fake *FakeGHSourceFactory) CreateGHSourceParamsCalls(stub func() *types.GHSourceParams) { + fake.createGHSourceParamsMutex.Lock() + defer fake.createGHSourceParamsMutex.Unlock() + fake.CreateGHSourceParamsStub = stub +} + +func (fake *FakeGHSourceFactory) CreateGHSourceParamsReturns(result1 *types.GHSourceParams) { + fake.createGHSourceParamsMutex.Lock() + defer fake.createGHSourceParamsMutex.Unlock() + fake.CreateGHSourceParamsStub = nil + fake.createGHSourceParamsReturns = struct { + result1 *types.GHSourceParams + }{result1} +} + +func (fake *FakeGHSourceFactory) CreateGHSourceParamsReturnsOnCall(i int, result1 *types.GHSourceParams) { + fake.createGHSourceParamsMutex.Lock() + defer fake.createGHSourceParamsMutex.Unlock() + fake.CreateGHSourceParamsStub = nil + if fake.createGHSourceParamsReturnsOnCall == nil { + fake.createGHSourceParamsReturnsOnCall = make(map[int]struct { + result1 *types.GHSourceParams + }) + } + fake.createGHSourceParamsReturnsOnCall[i] = struct { + result1 *types.GHSourceParams + }{result1} +} + +func (fake *FakeGHSourceFactory) CreateKnSourceClient(arg1 string) typesa.KnSourceClient { + fake.createKnSourceClientMutex.Lock() + ret, specificReturn := fake.createKnSourceClientReturnsOnCall[len(fake.createKnSourceClientArgsForCall)] + fake.createKnSourceClientArgsForCall = append(fake.createKnSourceClientArgsForCall, struct { + arg1 string + }{arg1}) + fake.recordInvocation("CreateKnSourceClient", []interface{}{arg1}) + fake.createKnSourceClientMutex.Unlock() + if fake.CreateKnSourceClientStub != nil { + return fake.CreateKnSourceClientStub(arg1) + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.createKnSourceClientReturns + return fakeReturns.result1 +} + +func (fake *FakeGHSourceFactory) CreateKnSourceClientCallCount() int { + fake.createKnSourceClientMutex.RLock() + defer fake.createKnSourceClientMutex.RUnlock() + return len(fake.createKnSourceClientArgsForCall) +} + +func (fake *FakeGHSourceFactory) CreateKnSourceClientCalls(stub func(string) typesa.KnSourceClient) { + fake.createKnSourceClientMutex.Lock() + defer fake.createKnSourceClientMutex.Unlock() + fake.CreateKnSourceClientStub = stub +} + +func (fake *FakeGHSourceFactory) CreateKnSourceClientArgsForCall(i int) string { + fake.createKnSourceClientMutex.RLock() + defer fake.createKnSourceClientMutex.RUnlock() + argsForCall := fake.createKnSourceClientArgsForCall[i] + return argsForCall.arg1 +} + +func (fake *FakeGHSourceFactory) CreateKnSourceClientReturns(result1 typesa.KnSourceClient) { + fake.createKnSourceClientMutex.Lock() + defer fake.createKnSourceClientMutex.Unlock() + fake.CreateKnSourceClientStub = nil + fake.createKnSourceClientReturns = struct { + result1 typesa.KnSourceClient + }{result1} +} + +func (fake *FakeGHSourceFactory) CreateKnSourceClientReturnsOnCall(i int, result1 typesa.KnSourceClient) { + fake.createKnSourceClientMutex.Lock() + defer fake.createKnSourceClientMutex.Unlock() + fake.CreateKnSourceClientStub = nil + if fake.createKnSourceClientReturnsOnCall == nil { + fake.createKnSourceClientReturnsOnCall = make(map[int]struct { + result1 typesa.KnSourceClient + }) + } + fake.createKnSourceClientReturnsOnCall[i] = struct { + result1 typesa.KnSourceClient + }{result1} +} + +func (fake *FakeGHSourceFactory) CreateKnSourceParams() *typesa.KnSourceParams { + fake.createKnSourceParamsMutex.Lock() + ret, specificReturn := fake.createKnSourceParamsReturnsOnCall[len(fake.createKnSourceParamsArgsForCall)] + fake.createKnSourceParamsArgsForCall = append(fake.createKnSourceParamsArgsForCall, struct { + }{}) + fake.recordInvocation("CreateKnSourceParams", []interface{}{}) + fake.createKnSourceParamsMutex.Unlock() + if fake.CreateKnSourceParamsStub != nil { + return fake.CreateKnSourceParamsStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.createKnSourceParamsReturns + return fakeReturns.result1 +} + +func (fake *FakeGHSourceFactory) CreateKnSourceParamsCallCount() int { + fake.createKnSourceParamsMutex.RLock() + defer fake.createKnSourceParamsMutex.RUnlock() + return len(fake.createKnSourceParamsArgsForCall) +} + +func (fake *FakeGHSourceFactory) CreateKnSourceParamsCalls(stub func() *typesa.KnSourceParams) { + fake.createKnSourceParamsMutex.Lock() + defer fake.createKnSourceParamsMutex.Unlock() + fake.CreateKnSourceParamsStub = stub +} + +func (fake *FakeGHSourceFactory) CreateKnSourceParamsReturns(result1 *typesa.KnSourceParams) { + fake.createKnSourceParamsMutex.Lock() + defer fake.createKnSourceParamsMutex.Unlock() + fake.CreateKnSourceParamsStub = nil + fake.createKnSourceParamsReturns = struct { + result1 *typesa.KnSourceParams + }{result1} +} + +func (fake *FakeGHSourceFactory) CreateKnSourceParamsReturnsOnCall(i int, result1 *typesa.KnSourceParams) { + fake.createKnSourceParamsMutex.Lock() + defer fake.createKnSourceParamsMutex.Unlock() + fake.CreateKnSourceParamsStub = nil + if fake.createKnSourceParamsReturnsOnCall == nil { + fake.createKnSourceParamsReturnsOnCall = make(map[int]struct { + result1 *typesa.KnSourceParams + }) + } + fake.createKnSourceParamsReturnsOnCall[i] = struct { + result1 *typesa.KnSourceParams + }{result1} +} + +func (fake *FakeGHSourceFactory) GHSourceClient() types.GHSourceClient { + fake.gHSourceClientMutex.Lock() + ret, specificReturn := fake.gHSourceClientReturnsOnCall[len(fake.gHSourceClientArgsForCall)] + fake.gHSourceClientArgsForCall = append(fake.gHSourceClientArgsForCall, struct { + }{}) + fake.recordInvocation("GHSourceClient", []interface{}{}) + fake.gHSourceClientMutex.Unlock() + if fake.GHSourceClientStub != nil { + return fake.GHSourceClientStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.gHSourceClientReturns + return fakeReturns.result1 +} + +func (fake *FakeGHSourceFactory) GHSourceClientCallCount() int { + fake.gHSourceClientMutex.RLock() + defer fake.gHSourceClientMutex.RUnlock() + return len(fake.gHSourceClientArgsForCall) +} + +func (fake *FakeGHSourceFactory) GHSourceClientCalls(stub func() types.GHSourceClient) { + fake.gHSourceClientMutex.Lock() + defer fake.gHSourceClientMutex.Unlock() + fake.GHSourceClientStub = stub +} + +func (fake *FakeGHSourceFactory) GHSourceClientReturns(result1 types.GHSourceClient) { + fake.gHSourceClientMutex.Lock() + defer fake.gHSourceClientMutex.Unlock() + fake.GHSourceClientStub = nil + fake.gHSourceClientReturns = struct { + result1 types.GHSourceClient + }{result1} +} + +func (fake *FakeGHSourceFactory) GHSourceClientReturnsOnCall(i int, result1 types.GHSourceClient) { + fake.gHSourceClientMutex.Lock() + defer fake.gHSourceClientMutex.Unlock() + fake.GHSourceClientStub = nil + if fake.gHSourceClientReturnsOnCall == nil { + fake.gHSourceClientReturnsOnCall = make(map[int]struct { + result1 types.GHSourceClient + }) + } + fake.gHSourceClientReturnsOnCall[i] = struct { + result1 types.GHSourceClient + }{result1} +} + +func (fake *FakeGHSourceFactory) GHSourceParams() *types.GHSourceParams { + fake.gHSourceParamsMutex.Lock() + ret, specificReturn := fake.gHSourceParamsReturnsOnCall[len(fake.gHSourceParamsArgsForCall)] + fake.gHSourceParamsArgsForCall = append(fake.gHSourceParamsArgsForCall, struct { + }{}) + fake.recordInvocation("GHSourceParams", []interface{}{}) + fake.gHSourceParamsMutex.Unlock() + if fake.GHSourceParamsStub != nil { + return fake.GHSourceParamsStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.gHSourceParamsReturns + return fakeReturns.result1 +} + +func (fake *FakeGHSourceFactory) GHSourceParamsCallCount() int { + fake.gHSourceParamsMutex.RLock() + defer fake.gHSourceParamsMutex.RUnlock() + return len(fake.gHSourceParamsArgsForCall) +} + +func (fake *FakeGHSourceFactory) GHSourceParamsCalls(stub func() *types.GHSourceParams) { + fake.gHSourceParamsMutex.Lock() + defer fake.gHSourceParamsMutex.Unlock() + fake.GHSourceParamsStub = stub +} + +func (fake *FakeGHSourceFactory) GHSourceParamsReturns(result1 *types.GHSourceParams) { + fake.gHSourceParamsMutex.Lock() + defer fake.gHSourceParamsMutex.Unlock() + fake.GHSourceParamsStub = nil + fake.gHSourceParamsReturns = struct { + result1 *types.GHSourceParams + }{result1} +} + +func (fake *FakeGHSourceFactory) GHSourceParamsReturnsOnCall(i int, result1 *types.GHSourceParams) { + fake.gHSourceParamsMutex.Lock() + defer fake.gHSourceParamsMutex.Unlock() + fake.GHSourceParamsStub = nil + if fake.gHSourceParamsReturnsOnCall == nil { + fake.gHSourceParamsReturnsOnCall = make(map[int]struct { + result1 *types.GHSourceParams + }) + } + fake.gHSourceParamsReturnsOnCall[i] = struct { + result1 *types.GHSourceParams + }{result1} +} + +func (fake *FakeGHSourceFactory) KnSourceParams() *typesa.KnSourceParams { + fake.knSourceParamsMutex.Lock() + ret, specificReturn := fake.knSourceParamsReturnsOnCall[len(fake.knSourceParamsArgsForCall)] + fake.knSourceParamsArgsForCall = append(fake.knSourceParamsArgsForCall, struct { + }{}) + fake.recordInvocation("KnSourceParams", []interface{}{}) + fake.knSourceParamsMutex.Unlock() + if fake.KnSourceParamsStub != nil { + return fake.KnSourceParamsStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.knSourceParamsReturns + return fakeReturns.result1 +} + +func (fake *FakeGHSourceFactory) KnSourceParamsCallCount() int { + fake.knSourceParamsMutex.RLock() + defer fake.knSourceParamsMutex.RUnlock() + return len(fake.knSourceParamsArgsForCall) +} + +func (fake *FakeGHSourceFactory) KnSourceParamsCalls(stub func() *typesa.KnSourceParams) { + fake.knSourceParamsMutex.Lock() + defer fake.knSourceParamsMutex.Unlock() + fake.KnSourceParamsStub = stub +} + +func (fake *FakeGHSourceFactory) KnSourceParamsReturns(result1 *typesa.KnSourceParams) { + fake.knSourceParamsMutex.Lock() + defer fake.knSourceParamsMutex.Unlock() + fake.KnSourceParamsStub = nil + fake.knSourceParamsReturns = struct { + result1 *typesa.KnSourceParams + }{result1} +} + +func (fake *FakeGHSourceFactory) KnSourceParamsReturnsOnCall(i int, result1 *typesa.KnSourceParams) { + fake.knSourceParamsMutex.Lock() + defer fake.knSourceParamsMutex.Unlock() + fake.KnSourceParamsStub = nil + if fake.knSourceParamsReturnsOnCall == nil { + fake.knSourceParamsReturnsOnCall = make(map[int]struct { + result1 *typesa.KnSourceParams + }) + } + fake.knSourceParamsReturnsOnCall[i] = struct { + result1 *typesa.KnSourceParams + }{result1} +} + +func (fake *FakeGHSourceFactory) Invocations() map[string][][]interface{} { + fake.invocationsMutex.RLock() + defer fake.invocationsMutex.RUnlock() + fake.createGHSourceClientMutex.RLock() + defer fake.createGHSourceClientMutex.RUnlock() + fake.createGHSourceParamsMutex.RLock() + defer fake.createGHSourceParamsMutex.RUnlock() + fake.createKnSourceClientMutex.RLock() + defer fake.createKnSourceClientMutex.RUnlock() + fake.createKnSourceParamsMutex.RLock() + defer fake.createKnSourceParamsMutex.RUnlock() + fake.gHSourceClientMutex.RLock() + defer fake.gHSourceClientMutex.RUnlock() + fake.gHSourceParamsMutex.RLock() + defer fake.gHSourceParamsMutex.RUnlock() + fake.knSourceParamsMutex.RLock() + defer fake.knSourceParamsMutex.RUnlock() + copiedInvocations := map[string][][]interface{}{} + for key, value := range fake.invocations { + copiedInvocations[key] = value + } + return copiedInvocations +} + +func (fake *FakeGHSourceFactory) recordInvocation(key string, args []interface{}) { + fake.invocationsMutex.Lock() + defer fake.invocationsMutex.Unlock() + if fake.invocations == nil { + fake.invocations = map[string][][]interface{}{} + } + if fake.invocations[key] == nil { + fake.invocations[key] = [][]interface{}{} + } + fake.invocations[key] = append(fake.invocations[key], args) +} + +var _ types.GHSourceFactory = new(FakeGHSourceFactory) diff --git a/plugins/source-github/test/e2e/basic_workflow_test.go b/plugins/source-github/test/e2e/basic_workflow_test.go new file mode 100644 index 00000000..2b9b978f --- /dev/null +++ b/plugins/source-github/test/e2e/basic_workflow_test.go @@ -0,0 +1,106 @@ +// Copyright 2019 The Knative 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. + +// +build e2e +// +build !eventing + +package e2e + +import ( + "os" + "path/filepath" + "testing" + + "gotest.tools/assert" + + "knative.dev/client/lib/test" + "knative.dev/client/pkg/util" + + commone2e "github.com/maximilien/kn-source-pkg/test/e2e" +) + +type e2eTest struct { + it *commone2e.E2ETest +} + +func newE2ETest(t *testing.T) *e2eTest { + currentDir, err := os.Getwd() + assert.NilError(t, err) + + it, err := commone2e.NewE2ETest("kn-source_github", filepath.Join(currentDir, "../.."), false) + assert.NilError(t, err) + defer func() { + assert.NilError(t, it.KnTest().Teardown()) + }() + + e2eTest := &e2eTest{ + it: it, + } + + return e2eTest +} + +func TestBasicWorkflow(t *testing.T) { + t.Parallel() + + e2eTest := newE2ETest(t) + assert.Assert(t, e2eTest != nil) + + r := test.NewKnRunResultCollector(t, e2eTest.it.KnTest()) + defer r.DumpIfFailed() + + err := e2eTest.it.KnPlugin().Install() + assert.NilError(t, err) + + t.Log("kn-source_github create 'source-name' with 'sink-name'") + e2eTest.ghSourceCreate(t, r, "source-name", "sink-name") + + t.Log("kn-source_github describe 'source-name'") + e2eTest.ghSourceDescribe(t, r, "source-name") + + t.Log("kn-source_github update 'source-name' with 'new-sink-name'") + e2eTest.ghSourceUpdate(t, r, "source-name", "new-sink-name") + + t.Log("kn-source_github delete 'source-name'") + e2eTest.ghSourceDelete(t, r, "source-name", "sink-name") + + err = e2eTest.it.KnPlugin().Uninstall() + assert.NilError(t, err) +} + +// Private + +func (et *e2eTest) ghSourceCreate(t *testing.T, r *test.KnRunResultCollector, sourceName, sinkName string) { + out := et.it.KnPlugin().Run("create", sourceName, "--sink", sinkName) + r.AssertNoError(out) + assert.Check(t, util.ContainsAllIgnoreCase(out.Stdout, "create", sourceName, "namespace", et.it.KnTest().Namespace(), "sink", sinkName)) +} + +func (et *e2eTest) ghSourceDescribe(t *testing.T, r *test.KnRunResultCollector, sourceName string) { + out := et.it.KnPlugin().Run("describe", sourceName) + r.AssertNoError(out) + assert.Check(t, util.ContainsAllIgnoreCase(out.Stdout, "describe", sourceName, "namespace", et.it.KnTest().Namespace())) +} + +func (et *e2eTest) ghSourceUpdate(t *testing.T, r *test.KnRunResultCollector, sourceName, sinkName string) { + out := et.it.KnPlugin().Run("update", sourceName, "--sink", sinkName) + r.AssertNoError(out) + assert.Check(t, util.ContainsAllIgnoreCase(out.Stdout, "update", sourceName, "namespace", et.it.KnTest().Namespace(), "sink", sinkName)) +} + +func (et *e2eTest) ghSourceDelete(t *testing.T, r *test.KnRunResultCollector, sourceName, sinkName string) { + out := et.it.KnPlugin().Run("delete", sourceName) + r.AssertNoError(out) + assert.Check(t, util.ContainsAllIgnoreCase(out.Stdout, "delete", sourceName, "namespace", et.it.KnTest().Namespace())) +} diff --git a/plugins/source-github/test/local-e2e-tests.sh b/plugins/source-github/test/local-e2e-tests.sh index 70541f0e..b9cd3710 100755 --- a/plugins/source-github/test/local-e2e-tests.sh +++ b/plugins/source-github/test/local-e2e-tests.sh @@ -45,12 +45,16 @@ echo "" # Start testing echo "🧪 Testing" -go test ${base}/test/e2e/ -test.v -tags "e2e ${E2E_TAGS}" "$@" +echo ${base}/test/e2e/ +go test ${base}/test/e2e/ -test.v -tags "e2e" ./... +err=$? # Output echo "" -if [ $? -eq 0 ]; then +if [ $err -eq 0 ]; then echo "✅ Success" else echo "❗️Failure" fi + +exit $err diff --git a/plugins/source-github/vendor/github.com/cpuguy83/go-md2man/v2/LICENSE.md b/plugins/source-github/vendor/github.com/cpuguy83/go-md2man/v2/LICENSE.md new file mode 100644 index 00000000..1cade6ce --- /dev/null +++ b/plugins/source-github/vendor/github.com/cpuguy83/go-md2man/v2/LICENSE.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Brian Goff + +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. diff --git a/plugins/source-github/vendor/github.com/cpuguy83/go-md2man/v2/md2man/md2man.go b/plugins/source-github/vendor/github.com/cpuguy83/go-md2man/v2/md2man/md2man.go new file mode 100644 index 00000000..b4800567 --- /dev/null +++ b/plugins/source-github/vendor/github.com/cpuguy83/go-md2man/v2/md2man/md2man.go @@ -0,0 +1,14 @@ +package md2man + +import ( + "github.com/russross/blackfriday/v2" +) + +// Render converts a markdown document into a roff formatted document. +func Render(doc []byte) []byte { + renderer := NewRoffRenderer() + + return blackfriday.Run(doc, + []blackfriday.Option{blackfriday.WithRenderer(renderer), + blackfriday.WithExtensions(renderer.GetExtensions())}...) +} diff --git a/plugins/source-github/vendor/github.com/cpuguy83/go-md2man/v2/md2man/roff.go b/plugins/source-github/vendor/github.com/cpuguy83/go-md2man/v2/md2man/roff.go new file mode 100644 index 00000000..0668a66c --- /dev/null +++ b/plugins/source-github/vendor/github.com/cpuguy83/go-md2man/v2/md2man/roff.go @@ -0,0 +1,345 @@ +package md2man + +import ( + "fmt" + "io" + "os" + "strings" + + "github.com/russross/blackfriday/v2" +) + +// roffRenderer implements the blackfriday.Renderer interface for creating +// roff format (manpages) from markdown text +type roffRenderer struct { + extensions blackfriday.Extensions + listCounters []int + firstHeader bool + defineTerm bool + listDepth int +} + +const ( + titleHeader = ".TH " + topLevelHeader = "\n\n.SH " + secondLevelHdr = "\n.SH " + otherHeader = "\n.SS " + crTag = "\n" + emphTag = "\\fI" + emphCloseTag = "\\fP" + strongTag = "\\fB" + strongCloseTag = "\\fP" + breakTag = "\n.br\n" + paraTag = "\n.PP\n" + hruleTag = "\n.ti 0\n\\l'\\n(.lu'\n" + linkTag = "\n\\[la]" + linkCloseTag = "\\[ra]" + codespanTag = "\\fB\\fC" + codespanCloseTag = "\\fR" + codeTag = "\n.PP\n.RS\n\n.nf\n" + codeCloseTag = "\n.fi\n.RE\n" + quoteTag = "\n.PP\n.RS\n" + quoteCloseTag = "\n.RE\n" + listTag = "\n.RS\n" + listCloseTag = "\n.RE\n" + arglistTag = "\n.TP\n" + tableStart = "\n.TS\nallbox;\n" + tableEnd = ".TE\n" + tableCellStart = "T{\n" + tableCellEnd = "\nT}\n" +) + +// NewRoffRenderer creates a new blackfriday Renderer for generating roff documents +// from markdown +func NewRoffRenderer() *roffRenderer { // nolint: golint + var extensions blackfriday.Extensions + + extensions |= blackfriday.NoIntraEmphasis + extensions |= blackfriday.Tables + extensions |= blackfriday.FencedCode + extensions |= blackfriday.SpaceHeadings + extensions |= blackfriday.Footnotes + extensions |= blackfriday.Titleblock + extensions |= blackfriday.DefinitionLists + return &roffRenderer{ + extensions: extensions, + } +} + +// GetExtensions returns the list of extensions used by this renderer implementation +func (r *roffRenderer) GetExtensions() blackfriday.Extensions { + return r.extensions +} + +// RenderHeader handles outputting the header at document start +func (r *roffRenderer) RenderHeader(w io.Writer, ast *blackfriday.Node) { + // disable hyphenation + out(w, ".nh\n") +} + +// RenderFooter handles outputting the footer at the document end; the roff +// renderer has no footer information +func (r *roffRenderer) RenderFooter(w io.Writer, ast *blackfriday.Node) { +} + +// RenderNode is called for each node in a markdown document; based on the node +// type the equivalent roff output is sent to the writer +func (r *roffRenderer) RenderNode(w io.Writer, node *blackfriday.Node, entering bool) blackfriday.WalkStatus { + + var walkAction = blackfriday.GoToNext + + switch node.Type { + case blackfriday.Text: + r.handleText(w, node, entering) + case blackfriday.Softbreak: + out(w, crTag) + case blackfriday.Hardbreak: + out(w, breakTag) + case blackfriday.Emph: + if entering { + out(w, emphTag) + } else { + out(w, emphCloseTag) + } + case blackfriday.Strong: + if entering { + out(w, strongTag) + } else { + out(w, strongCloseTag) + } + case blackfriday.Link: + if !entering { + out(w, linkTag+string(node.LinkData.Destination)+linkCloseTag) + } + case blackfriday.Image: + // ignore images + walkAction = blackfriday.SkipChildren + case blackfriday.Code: + out(w, codespanTag) + escapeSpecialChars(w, node.Literal) + out(w, codespanCloseTag) + case blackfriday.Document: + break + case blackfriday.Paragraph: + // roff .PP markers break lists + if r.listDepth > 0 { + return blackfriday.GoToNext + } + if entering { + out(w, paraTag) + } else { + out(w, crTag) + } + case blackfriday.BlockQuote: + if entering { + out(w, quoteTag) + } else { + out(w, quoteCloseTag) + } + case blackfriday.Heading: + r.handleHeading(w, node, entering) + case blackfriday.HorizontalRule: + out(w, hruleTag) + case blackfriday.List: + r.handleList(w, node, entering) + case blackfriday.Item: + r.handleItem(w, node, entering) + case blackfriday.CodeBlock: + out(w, codeTag) + escapeSpecialChars(w, node.Literal) + out(w, codeCloseTag) + case blackfriday.Table: + r.handleTable(w, node, entering) + case blackfriday.TableCell: + r.handleTableCell(w, node, entering) + case blackfriday.TableHead: + case blackfriday.TableBody: + case blackfriday.TableRow: + // no action as cell entries do all the nroff formatting + return blackfriday.GoToNext + default: + fmt.Fprintln(os.Stderr, "WARNING: go-md2man does not handle node type "+node.Type.String()) + } + return walkAction +} + +func (r *roffRenderer) handleText(w io.Writer, node *blackfriday.Node, entering bool) { + var ( + start, end string + ) + // handle special roff table cell text encapsulation + if node.Parent.Type == blackfriday.TableCell { + if len(node.Literal) > 30 { + start = tableCellStart + end = tableCellEnd + } else { + // end rows that aren't terminated by "tableCellEnd" with a cr if end of row + if node.Parent.Next == nil && !node.Parent.IsHeader { + end = crTag + } + } + } + out(w, start) + escapeSpecialChars(w, node.Literal) + out(w, end) +} + +func (r *roffRenderer) handleHeading(w io.Writer, node *blackfriday.Node, entering bool) { + if entering { + switch node.Level { + case 1: + if !r.firstHeader { + out(w, titleHeader) + r.firstHeader = true + break + } + out(w, topLevelHeader) + case 2: + out(w, secondLevelHdr) + default: + out(w, otherHeader) + } + } +} + +func (r *roffRenderer) handleList(w io.Writer, node *blackfriday.Node, entering bool) { + openTag := listTag + closeTag := listCloseTag + if node.ListFlags&blackfriday.ListTypeDefinition != 0 { + // tags for definition lists handled within Item node + openTag = "" + closeTag = "" + } + if entering { + r.listDepth++ + if node.ListFlags&blackfriday.ListTypeOrdered != 0 { + r.listCounters = append(r.listCounters, 1) + } + out(w, openTag) + } else { + if node.ListFlags&blackfriday.ListTypeOrdered != 0 { + r.listCounters = r.listCounters[:len(r.listCounters)-1] + } + out(w, closeTag) + r.listDepth-- + } +} + +func (r *roffRenderer) handleItem(w io.Writer, node *blackfriday.Node, entering bool) { + if entering { + if node.ListFlags&blackfriday.ListTypeOrdered != 0 { + out(w, fmt.Sprintf(".IP \"%3d.\" 5\n", r.listCounters[len(r.listCounters)-1])) + r.listCounters[len(r.listCounters)-1]++ + } else if node.ListFlags&blackfriday.ListTypeDefinition != 0 { + // state machine for handling terms and following definitions + // since blackfriday does not distinguish them properly, nor + // does it seperate them into separate lists as it should + if !r.defineTerm { + out(w, arglistTag) + r.defineTerm = true + } else { + r.defineTerm = false + } + } else { + out(w, ".IP \\(bu 2\n") + } + } else { + out(w, "\n") + } +} + +func (r *roffRenderer) handleTable(w io.Writer, node *blackfriday.Node, entering bool) { + if entering { + out(w, tableStart) + //call walker to count cells (and rows?) so format section can be produced + columns := countColumns(node) + out(w, strings.Repeat("l ", columns)+"\n") + out(w, strings.Repeat("l ", columns)+".\n") + } else { + out(w, tableEnd) + } +} + +func (r *roffRenderer) handleTableCell(w io.Writer, node *blackfriday.Node, entering bool) { + var ( + start, end string + ) + if node.IsHeader { + start = codespanTag + end = codespanCloseTag + } + if entering { + if node.Prev != nil && node.Prev.Type == blackfriday.TableCell { + out(w, "\t"+start) + } else { + out(w, start) + } + } else { + // need to carriage return if we are at the end of the header row + if node.IsHeader && node.Next == nil { + end = end + crTag + } + out(w, end) + } +} + +// because roff format requires knowing the column count before outputting any table +// data we need to walk a table tree and count the columns +func countColumns(node *blackfriday.Node) int { + var columns int + + node.Walk(func(node *blackfriday.Node, entering bool) blackfriday.WalkStatus { + switch node.Type { + case blackfriday.TableRow: + if !entering { + return blackfriday.Terminate + } + case blackfriday.TableCell: + if entering { + columns++ + } + default: + } + return blackfriday.GoToNext + }) + return columns +} + +func out(w io.Writer, output string) { + io.WriteString(w, output) // nolint: errcheck +} + +func needsBackslash(c byte) bool { + for _, r := range []byte("-_&\\~") { + if c == r { + return true + } + } + return false +} + +func escapeSpecialChars(w io.Writer, text []byte) { + for i := 0; i < len(text); i++ { + // escape initial apostrophe or period + if len(text) >= 1 && (text[0] == '\'' || text[0] == '.') { + out(w, "\\&") + } + + // directly copy normal characters + org := i + + for i < len(text) && !needsBackslash(text[i]) { + i++ + } + if i > org { + w.Write(text[org:i]) // nolint: errcheck + } + + // escape a character + if i >= len(text) { + break + } + + w.Write([]byte{'\\', text[i]}) // nolint: errcheck + } +} diff --git a/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/client/client.go b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/client/client.go new file mode 100644 index 00000000..ba96251f --- /dev/null +++ b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/client/client.go @@ -0,0 +1,58 @@ +// Copyright © 2020 The Knative 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 client + +import ( + "fmt" + + "github.com/maximilien/kn-source-pkg/pkg/types" + + "k8s.io/client-go/rest" +) + +type knSourceClient struct { + knSourceParams *types.KnSourceParams + namespace string + restConfig *rest.Config +} + +// NewKnSourceClient creates a new KnSourceClient with parameters and namespace +func NewKnSourceClient(knSourceParams *types.KnSourceParams, namespace string) types.KnSourceClient { + restConfig, err := knSourceParams.RestConfig() + if err != nil { + panic(fmt.Sprintf("Could not create GitHub sources client, error: %s", err.Error())) + } + + return &knSourceClient{ + knSourceParams: knSourceParams, + namespace: namespace, + restConfig: restConfig, + } +} + +// KnSourceParams returns the client's KnSourceParams +func (client *knSourceClient) KnSourceParams() *types.KnSourceParams { + return client.knSourceParams +} + +// Namespace returns the client's namespace +func (client *knSourceClient) Namespace() string { + return client.namespace +} + +// RestConfig a Config object to do REST invocations +func (client *knSourceClient) RestConfig() *rest.Config { + return client.restConfig +} diff --git a/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/commands/source/create.go b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/commands/source/create.go new file mode 100644 index 00000000..4fc5c023 --- /dev/null +++ b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/commands/source/create.go @@ -0,0 +1,30 @@ +// Copyright © 2020 The Knative 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 source + +import ( + "github.com/maximilien/kn-source-pkg/pkg/types" + "github.com/spf13/cobra" +) + +// NewCreateCommand for creating event sources +func NewCreateCommand(params *types.KnSourceParams) *cobra.Command { + createCmd := &cobra.Command{ + Use: "create NAME [flags]", + Short: "create {{.Name}} source", + Example: "{{.CreateExample}}", + } + return createCmd +} diff --git a/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/commands/source/delete.go b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/commands/source/delete.go new file mode 100644 index 00000000..10946030 --- /dev/null +++ b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/commands/source/delete.go @@ -0,0 +1,30 @@ +// Copyright © 2020 The Knative 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 source + +import ( + "github.com/maximilien/kn-source-pkg/pkg/types" + "github.com/spf13/cobra" +) + +// NewDeleteCommand for creating event sources +func NewDeleteCommand(params *types.KnSourceParams) *cobra.Command { + deleteCmd := &cobra.Command{ + Use: "delete NAME [flags]", + Short: "delete {{.Name}} source", + Example: "{{.DeleteExample}}", + } + return deleteCmd +} diff --git a/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/commands/source/describe.go b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/commands/source/describe.go new file mode 100644 index 00000000..9b3c0579 --- /dev/null +++ b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/commands/source/describe.go @@ -0,0 +1,30 @@ +// Copyright © 2020 The Knative 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 source + +import ( + "github.com/maximilien/kn-source-pkg/pkg/types" + "github.com/spf13/cobra" +) + +// NewDescribeCommand for creating event sources +func NewDescribeCommand(params *types.KnSourceParams) *cobra.Command { + describeCmd := &cobra.Command{ + Use: "describe NAME [flags]", + Short: "describe {{.Name}} source", + Example: "{{.DescribeExample}}", + } + return describeCmd +} diff --git a/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/commands/source/source.go b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/commands/source/source.go new file mode 100644 index 00000000..36d64dd4 --- /dev/null +++ b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/commands/source/source.go @@ -0,0 +1,30 @@ +// Copyright © 2020 The Knative 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 source + +import ( + "github.com/maximilien/kn-source-pkg/pkg/types" + "github.com/spf13/cobra" +) + +// NewSourceCommand as the root group command +func NewSourceCommand(knSourceParams *types.KnSourceParams) *cobra.Command { + createCmd := &cobra.Command{ + Use: "source", + Short: "Knative eventing {{.Name}} source plugin", + Long: "Manage your Knative {{.Name}} eventing sources", + } + return createCmd +} diff --git a/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/commands/source/update.go b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/commands/source/update.go new file mode 100644 index 00000000..a51ea2b0 --- /dev/null +++ b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/commands/source/update.go @@ -0,0 +1,30 @@ +// Copyright © 2020 The Knative 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 source + +import ( + "github.com/maximilien/kn-source-pkg/pkg/types" + "github.com/spf13/cobra" +) + +// NewUpdateCommand for creating event sources +func NewUpdateCommand(params *types.KnSourceParams) *cobra.Command { + updateCmd := &cobra.Command{ + Use: "update NAME [flags]", + Short: "update {{.Name}} source", + Example: "{{.UpdateExample}}", + } + return updateCmd +} diff --git a/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/core/root.go b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/core/root.go new file mode 100644 index 00000000..2fde2792 --- /dev/null +++ b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/core/root.go @@ -0,0 +1,83 @@ +// Copyright © 2020 The Knative 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 core + +import ( + "github.com/maximilien/kn-source-pkg/pkg/types" + + "github.com/spf13/cobra" +) + +func NewKnSourceCommand(knSourceFactory types.KnSourceFactory, + commandFactory types.CommandFactory, + flagsFactory types.FlagsFactory, + runEFactory types.RunEFactory) *cobra.Command { + knSourceParams := knSourceFactory.KnSourceParams() + rootCmd := commandFactory.SourceCommand() + + // Disable docs header + rootCmd.DisableAutoGenTag = true + + // Affects children as well + rootCmd.SilenceUsage = true + + // Prevents Cobra from dealing with errors as we deal with them in main.go + rootCmd.SilenceErrors = true + + if knSourceParams.Output != nil { + rootCmd.SetOutput(knSourceParams.Output) + } + + createCmd := commandFactory.CreateCommand() + addCommonFlags(knSourceParams, createCmd) + addCreateUpdateFlags(knSourceParams, createCmd) + createCmd.Flags().AddFlagSet(flagsFactory.CreateFlags()) + createCmd.RunE = runEFactory.CreateRunE() + rootCmd.AddCommand(createCmd) + + deleteCmd := commandFactory.DeleteCommand() + addCommonFlags(knSourceParams, deleteCmd) + deleteCmd.Flags().AddFlagSet(flagsFactory.DeleteFlags()) + deleteCmd.RunE = runEFactory.DeleteRunE() + rootCmd.AddCommand(deleteCmd) + + updateCmd := commandFactory.UpdateCommand() + addCommonFlags(knSourceParams, updateCmd) + addCreateUpdateFlags(knSourceParams, updateCmd) + updateCmd.Flags().AddFlagSet(flagsFactory.UpdateFlags()) + updateCmd.RunE = runEFactory.UpdateRunE() + rootCmd.AddCommand(updateCmd) + + describeCmd := commandFactory.DescribeCommand() + addCommonFlags(knSourceParams, describeCmd) + describeCmd.Flags().AddFlagSet(flagsFactory.DescribeFlags()) + describeCmd.RunE = runEFactory.DescribeRunE() + rootCmd.AddCommand(describeCmd) + + // Initialize default `help` cmd early to prevent unknown command errors + rootCmd.InitDefaultHelpCmd() + + return rootCmd +} + +// Private + +func addCommonFlags(knSourceParams *types.KnSourceParams, cmd *cobra.Command) { + knSourceParams.AddCommonFlags(cmd) +} + +func addCreateUpdateFlags(knSourceParams *types.KnSourceParams, cmd *cobra.Command) { + knSourceParams.AddCreateUpdateFlags(cmd) +} diff --git a/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/factories/boilerplate.go b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/factories/boilerplate.go new file mode 100644 index 00000000..9b7af201 --- /dev/null +++ b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/factories/boilerplate.go @@ -0,0 +1,49 @@ +// Copyright © 2020 The Knative 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 factories + +import "github.com/maximilien/kn-source-pkg/pkg/types" + +// KnSourceFactory + +func (f *DefautKnSourceFactory) KnSourceParams() *types.KnSourceParams { + if f.knSourceParams == nil { + f.knSourceParams = f.CreateKnSourceParams() + } + + return f.knSourceParams +} + +// CommandFactory + +func (f *DefautCommandFactory) KnSourceFactory() types.KnSourceFactory { + return f.knSourceFactory +} + +// FlagsFactory + +func (f *DefautFlagsFactory) KnSourceFactory() types.KnSourceFactory { + return f.knSourceFactory +} + +// RunEFactory + +func (f *DefautRunEFactory) KnSourceFactory() types.KnSourceFactory { + return f.knSourceFactory +} + +func (f *DefautRunEFactory) KnSourceClient(namespace string) types.KnSourceClient { + return f.knSourceFactory.CreateKnSourceClient(namespace) +} diff --git a/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/factories/command_factory.go b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/factories/command_factory.go new file mode 100644 index 00000000..40b8b62b --- /dev/null +++ b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/factories/command_factory.go @@ -0,0 +1,52 @@ +// Copyright © 2020 The Knative 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 factories + +import ( + "github.com/maximilien/kn-source-pkg/pkg/commands/source" + "github.com/maximilien/kn-source-pkg/pkg/types" + + "github.com/spf13/cobra" +) + +type DefautCommandFactory struct { + knSourceFactory types.KnSourceFactory +} + +func NewDefaultCommandFactory(knSourceFactory types.KnSourceFactory) types.CommandFactory { + return &DefautCommandFactory{ + knSourceFactory: knSourceFactory, + } +} + +func (f *DefautCommandFactory) SourceCommand() *cobra.Command { + return source.NewSourceCommand(f.knSourceFactory.KnSourceParams()) +} + +func (f *DefautCommandFactory) CreateCommand() *cobra.Command { + return source.NewCreateCommand(f.knSourceFactory.KnSourceParams()) +} + +func (f *DefautCommandFactory) DeleteCommand() *cobra.Command { + return source.NewDeleteCommand(f.knSourceFactory.KnSourceParams()) +} + +func (f *DefautCommandFactory) UpdateCommand() *cobra.Command { + return source.NewUpdateCommand(f.knSourceFactory.KnSourceParams()) +} + +func (f *DefautCommandFactory) DescribeCommand() *cobra.Command { + return source.NewDescribeCommand(f.knSourceFactory.KnSourceParams()) +} diff --git a/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/factories/flags_factory.go b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/factories/flags_factory.go new file mode 100644 index 00000000..8b0b8bb0 --- /dev/null +++ b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/factories/flags_factory.go @@ -0,0 +1,62 @@ +// Copyright © 2020 The Knative 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 factories + +import ( + "github.com/maximilien/kn-source-pkg/pkg/types" + "knative.dev/client/pkg/kn/commands" + + "github.com/spf13/pflag" +) + +type DefautFlagsFactory struct { + knSourceFactory types.KnSourceFactory +} + +func NewDefaultFlagsFactory(knSourceFactory types.KnSourceFactory) types.FlagsFactory { + return &DefautFlagsFactory{ + knSourceFactory: knSourceFactory, + } +} + +func (f *DefautFlagsFactory) CreateFlags() *pflag.FlagSet { + flagSet := pflag.NewFlagSet("create", pflag.ExitOnError) + f.addNamespaceFlag(flagSet) + return flagSet +} + +func (f *DefautFlagsFactory) DeleteFlags() *pflag.FlagSet { + flagSet := pflag.NewFlagSet("delete", pflag.ExitOnError) + f.addNamespaceFlag(flagSet) + return flagSet +} + +func (f *DefautFlagsFactory) UpdateFlags() *pflag.FlagSet { + flagSet := pflag.NewFlagSet("update", pflag.ExitOnError) + f.addNamespaceFlag(flagSet) + return flagSet +} + +func (f *DefautFlagsFactory) DescribeFlags() *pflag.FlagSet { + flagSet := pflag.NewFlagSet("describe", pflag.ExitOnError) + f.addNamespaceFlag(flagSet) + return flagSet +} + +// Private + +func (f *DefautFlagsFactory) addNamespaceFlag(flagSet *pflag.FlagSet) { + commands.AddNamespaceFlags(flagSet, false) +} diff --git a/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/factories/kn_source_factory.go b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/factories/kn_source_factory.go new file mode 100644 index 00000000..f8ff89f1 --- /dev/null +++ b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/factories/kn_source_factory.go @@ -0,0 +1,48 @@ +// Copyright © 2020 The Knative 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 factories + +import ( + "github.com/maximilien/kn-source-pkg/pkg/client" + "github.com/maximilien/kn-source-pkg/pkg/types" + + "knative.dev/client/pkg/kn/commands/flags" +) + +type DefautKnSourceFactory struct { + knSourceParams *types.KnSourceParams + + knSourceClientFunc KnSourceClientFunc +} + +type KnSourceClientFunc = func(knSourceParams *types.KnSourceParams, namespace string) types.KnSourceClient + +func NewDefaultKnSourceFactory() types.KnSourceFactory { + return &DefautKnSourceFactory{ + knSourceClientFunc: client.NewKnSourceClient, + } +} + +func (f *DefautKnSourceFactory) CreateKnSourceParams() *types.KnSourceParams { + f.knSourceParams = &types.KnSourceParams{ + SinkFlag: flags.SinkFlags{}, + } + f.knSourceParams.Initialize() + return f.knSourceParams +} + +func (f *DefautKnSourceFactory) CreateKnSourceClient(namespace string) types.KnSourceClient { + return f.knSourceClientFunc(f.knSourceParams, namespace) +} diff --git a/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/factories/rune_factory.go b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/factories/rune_factory.go new file mode 100644 index 00000000..d68feb21 --- /dev/null +++ b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/factories/rune_factory.go @@ -0,0 +1,101 @@ +// Copyright © 2020 The Knative 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 factories + +import ( + "fmt" + + "github.com/maximilien/kn-source-pkg/pkg/types" + + "github.com/spf13/cobra" +) + +type DefautRunEFactory struct { + knSourceFactory types.KnSourceFactory +} + +func NewDefaultRunEFactory(knSourceFactory types.KnSourceFactory) types.RunEFactory { + return &DefautRunEFactory{ + knSourceFactory: knSourceFactory, + } +} + +func (f *DefautRunEFactory) CreateRunE() types.RunE { + return func(cmd *cobra.Command, args []string) error { + namespace, err := f.KnSourceFactory().KnSourceParams().GetNamespace(cmd) + if err != nil { + return err + } + knSourceClient := f.KnSourceClient(namespace) + if err != nil { + return fmt.Errorf("could not access KnSourceClient for command %s", cmd.Name()) + } + + fmt.Printf("%s RunE called: args: %#v, client: %#v, sink: %s\n", cmd.Name(), args, knSourceClient, knSourceClient.KnSourceParams().SinkFlag) + + return nil + } +} + +func (f *DefautRunEFactory) DeleteRunE() types.RunE { + return func(cmd *cobra.Command, args []string) error { + namespace, err := f.KnSourceFactory().KnSourceParams().GetNamespace(cmd) + if err != nil { + return err + } + knSourceClient := f.KnSourceClient(namespace) + if err != nil { + return fmt.Errorf("could not access KnSourceClient for command %s", cmd.Name()) + } + + fmt.Printf("%s RunE called: args: %#v, client: %#v, sink: %s\n", cmd.Name(), args, knSourceClient, knSourceClient.KnSourceParams().SinkFlag) + + return nil + } +} + +func (f *DefautRunEFactory) UpdateRunE() types.RunE { + return func(cmd *cobra.Command, args []string) error { + namespace, err := f.KnSourceFactory().KnSourceParams().GetNamespace(cmd) + if err != nil { + return err + } + knSourceClient := f.KnSourceClient(namespace) + if err != nil { + return fmt.Errorf("could not access KnSourceClient for command %s", cmd.Name()) + } + + fmt.Printf("%s RunE called: args: %#v, client: %#v, sink: %s\n", cmd.Name(), args, knSourceClient, knSourceClient.KnSourceParams().SinkFlag) + + return nil + } +} + +func (f *DefautRunEFactory) DescribeRunE() types.RunE { + return func(cmd *cobra.Command, args []string) error { + namespace, err := f.KnSourceFactory().KnSourceParams().GetNamespace(cmd) + if err != nil { + return err + } + knSourceClient := f.KnSourceClient(namespace) + if err != nil { + return fmt.Errorf("could not access KnSourceClient for command %s", cmd.Name()) + } + + fmt.Printf("%s RunE called: args: %#v, client: %#v, sink: %s\n", cmd.Name(), args, knSourceClient, knSourceClient.KnSourceParams().SinkFlag) + + return nil + } +} diff --git a/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/types/interfaces.go b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/types/interfaces.go index ad63d176..cb03cedb 100644 --- a/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/types/interfaces.go +++ b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/types/interfaces.go @@ -11,21 +11,31 @@ // 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. +// +//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 -generate package types import ( "github.com/spf13/cobra" "github.com/spf13/pflag" + + "k8s.io/client-go/rest" ) +// RunE abstracts the Cobra RunE interface into a usable type type RunE = func(cmd *cobra.Command, args []string) error +// KnSourceClient is the base interface for all kn-source-extension +//counterfeiter:generate . KnSourceClient type KnSourceClient interface { KnSourceParams() *KnSourceParams Namespace() string + RestConfig() *rest.Config } +// KnSourceFactory is the base factory interface for all kn-source-extension factories +//counterfeiter:generate . KnSourceFactory type KnSourceFactory interface { KnSourceParams() *KnSourceParams @@ -33,6 +43,8 @@ type KnSourceFactory interface { CreateKnSourceClient(namespace string) KnSourceClient } +// CommandFactory is the factory for cobra.Command objects +//counterfeiter:generate . CommandFactory type CommandFactory interface { SourceCommand() *cobra.Command @@ -44,6 +56,8 @@ type CommandFactory interface { KnSourceFactory() KnSourceFactory } +// FlagsFactory is the factory for pflag.FlagSet objects +//counterfeiter:generate . FlagsFactory type FlagsFactory interface { CreateFlags() *pflag.FlagSet DeleteFlags() *pflag.FlagSet @@ -53,6 +67,8 @@ type FlagsFactory interface { KnSourceFactory() KnSourceFactory } +// RunEFactory is the factory for RunE objects +//counterfeiter:generate . RunEFactory type RunEFactory interface { CreateRunE() RunE DeleteRunE() RunE diff --git a/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/types/structs.go b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/types/structs.go index 6224b2cf..0aabf10d 100644 --- a/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/types/structs.go +++ b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/types/structs.go @@ -11,6 +11,8 @@ // 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. +// +// go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 -generate package types diff --git a/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/types/typesfakes/fake_command_factory.go b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/types/typesfakes/fake_command_factory.go new file mode 100644 index 00000000..b34cd255 --- /dev/null +++ b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/types/typesfakes/fake_command_factory.go @@ -0,0 +1,422 @@ +// Code generated by counterfeiter. DO NOT EDIT. +package typesfakes + +import ( + "sync" + + "github.com/maximilien/kn-source-pkg/pkg/types" + "github.com/spf13/cobra" +) + +type FakeCommandFactory struct { + CreateCommandStub func() *cobra.Command + createCommandMutex sync.RWMutex + createCommandArgsForCall []struct { + } + createCommandReturns struct { + result1 *cobra.Command + } + createCommandReturnsOnCall map[int]struct { + result1 *cobra.Command + } + DeleteCommandStub func() *cobra.Command + deleteCommandMutex sync.RWMutex + deleteCommandArgsForCall []struct { + } + deleteCommandReturns struct { + result1 *cobra.Command + } + deleteCommandReturnsOnCall map[int]struct { + result1 *cobra.Command + } + DescribeCommandStub func() *cobra.Command + describeCommandMutex sync.RWMutex + describeCommandArgsForCall []struct { + } + describeCommandReturns struct { + result1 *cobra.Command + } + describeCommandReturnsOnCall map[int]struct { + result1 *cobra.Command + } + KnSourceFactoryStub func() types.KnSourceFactory + knSourceFactoryMutex sync.RWMutex + knSourceFactoryArgsForCall []struct { + } + knSourceFactoryReturns struct { + result1 types.KnSourceFactory + } + knSourceFactoryReturnsOnCall map[int]struct { + result1 types.KnSourceFactory + } + SourceCommandStub func() *cobra.Command + sourceCommandMutex sync.RWMutex + sourceCommandArgsForCall []struct { + } + sourceCommandReturns struct { + result1 *cobra.Command + } + sourceCommandReturnsOnCall map[int]struct { + result1 *cobra.Command + } + UpdateCommandStub func() *cobra.Command + updateCommandMutex sync.RWMutex + updateCommandArgsForCall []struct { + } + updateCommandReturns struct { + result1 *cobra.Command + } + updateCommandReturnsOnCall map[int]struct { + result1 *cobra.Command + } + invocations map[string][][]interface{} + invocationsMutex sync.RWMutex +} + +func (fake *FakeCommandFactory) CreateCommand() *cobra.Command { + fake.createCommandMutex.Lock() + ret, specificReturn := fake.createCommandReturnsOnCall[len(fake.createCommandArgsForCall)] + fake.createCommandArgsForCall = append(fake.createCommandArgsForCall, struct { + }{}) + fake.recordInvocation("CreateCommand", []interface{}{}) + fake.createCommandMutex.Unlock() + if fake.CreateCommandStub != nil { + return fake.CreateCommandStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.createCommandReturns + return fakeReturns.result1 +} + +func (fake *FakeCommandFactory) CreateCommandCallCount() int { + fake.createCommandMutex.RLock() + defer fake.createCommandMutex.RUnlock() + return len(fake.createCommandArgsForCall) +} + +func (fake *FakeCommandFactory) CreateCommandCalls(stub func() *cobra.Command) { + fake.createCommandMutex.Lock() + defer fake.createCommandMutex.Unlock() + fake.CreateCommandStub = stub +} + +func (fake *FakeCommandFactory) CreateCommandReturns(result1 *cobra.Command) { + fake.createCommandMutex.Lock() + defer fake.createCommandMutex.Unlock() + fake.CreateCommandStub = nil + fake.createCommandReturns = struct { + result1 *cobra.Command + }{result1} +} + +func (fake *FakeCommandFactory) CreateCommandReturnsOnCall(i int, result1 *cobra.Command) { + fake.createCommandMutex.Lock() + defer fake.createCommandMutex.Unlock() + fake.CreateCommandStub = nil + if fake.createCommandReturnsOnCall == nil { + fake.createCommandReturnsOnCall = make(map[int]struct { + result1 *cobra.Command + }) + } + fake.createCommandReturnsOnCall[i] = struct { + result1 *cobra.Command + }{result1} +} + +func (fake *FakeCommandFactory) DeleteCommand() *cobra.Command { + fake.deleteCommandMutex.Lock() + ret, specificReturn := fake.deleteCommandReturnsOnCall[len(fake.deleteCommandArgsForCall)] + fake.deleteCommandArgsForCall = append(fake.deleteCommandArgsForCall, struct { + }{}) + fake.recordInvocation("DeleteCommand", []interface{}{}) + fake.deleteCommandMutex.Unlock() + if fake.DeleteCommandStub != nil { + return fake.DeleteCommandStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.deleteCommandReturns + return fakeReturns.result1 +} + +func (fake *FakeCommandFactory) DeleteCommandCallCount() int { + fake.deleteCommandMutex.RLock() + defer fake.deleteCommandMutex.RUnlock() + return len(fake.deleteCommandArgsForCall) +} + +func (fake *FakeCommandFactory) DeleteCommandCalls(stub func() *cobra.Command) { + fake.deleteCommandMutex.Lock() + defer fake.deleteCommandMutex.Unlock() + fake.DeleteCommandStub = stub +} + +func (fake *FakeCommandFactory) DeleteCommandReturns(result1 *cobra.Command) { + fake.deleteCommandMutex.Lock() + defer fake.deleteCommandMutex.Unlock() + fake.DeleteCommandStub = nil + fake.deleteCommandReturns = struct { + result1 *cobra.Command + }{result1} +} + +func (fake *FakeCommandFactory) DeleteCommandReturnsOnCall(i int, result1 *cobra.Command) { + fake.deleteCommandMutex.Lock() + defer fake.deleteCommandMutex.Unlock() + fake.DeleteCommandStub = nil + if fake.deleteCommandReturnsOnCall == nil { + fake.deleteCommandReturnsOnCall = make(map[int]struct { + result1 *cobra.Command + }) + } + fake.deleteCommandReturnsOnCall[i] = struct { + result1 *cobra.Command + }{result1} +} + +func (fake *FakeCommandFactory) DescribeCommand() *cobra.Command { + fake.describeCommandMutex.Lock() + ret, specificReturn := fake.describeCommandReturnsOnCall[len(fake.describeCommandArgsForCall)] + fake.describeCommandArgsForCall = append(fake.describeCommandArgsForCall, struct { + }{}) + fake.recordInvocation("DescribeCommand", []interface{}{}) + fake.describeCommandMutex.Unlock() + if fake.DescribeCommandStub != nil { + return fake.DescribeCommandStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.describeCommandReturns + return fakeReturns.result1 +} + +func (fake *FakeCommandFactory) DescribeCommandCallCount() int { + fake.describeCommandMutex.RLock() + defer fake.describeCommandMutex.RUnlock() + return len(fake.describeCommandArgsForCall) +} + +func (fake *FakeCommandFactory) DescribeCommandCalls(stub func() *cobra.Command) { + fake.describeCommandMutex.Lock() + defer fake.describeCommandMutex.Unlock() + fake.DescribeCommandStub = stub +} + +func (fake *FakeCommandFactory) DescribeCommandReturns(result1 *cobra.Command) { + fake.describeCommandMutex.Lock() + defer fake.describeCommandMutex.Unlock() + fake.DescribeCommandStub = nil + fake.describeCommandReturns = struct { + result1 *cobra.Command + }{result1} +} + +func (fake *FakeCommandFactory) DescribeCommandReturnsOnCall(i int, result1 *cobra.Command) { + fake.describeCommandMutex.Lock() + defer fake.describeCommandMutex.Unlock() + fake.DescribeCommandStub = nil + if fake.describeCommandReturnsOnCall == nil { + fake.describeCommandReturnsOnCall = make(map[int]struct { + result1 *cobra.Command + }) + } + fake.describeCommandReturnsOnCall[i] = struct { + result1 *cobra.Command + }{result1} +} + +func (fake *FakeCommandFactory) KnSourceFactory() types.KnSourceFactory { + fake.knSourceFactoryMutex.Lock() + ret, specificReturn := fake.knSourceFactoryReturnsOnCall[len(fake.knSourceFactoryArgsForCall)] + fake.knSourceFactoryArgsForCall = append(fake.knSourceFactoryArgsForCall, struct { + }{}) + fake.recordInvocation("KnSourceFactory", []interface{}{}) + fake.knSourceFactoryMutex.Unlock() + if fake.KnSourceFactoryStub != nil { + return fake.KnSourceFactoryStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.knSourceFactoryReturns + return fakeReturns.result1 +} + +func (fake *FakeCommandFactory) KnSourceFactoryCallCount() int { + fake.knSourceFactoryMutex.RLock() + defer fake.knSourceFactoryMutex.RUnlock() + return len(fake.knSourceFactoryArgsForCall) +} + +func (fake *FakeCommandFactory) KnSourceFactoryCalls(stub func() types.KnSourceFactory) { + fake.knSourceFactoryMutex.Lock() + defer fake.knSourceFactoryMutex.Unlock() + fake.KnSourceFactoryStub = stub +} + +func (fake *FakeCommandFactory) KnSourceFactoryReturns(result1 types.KnSourceFactory) { + fake.knSourceFactoryMutex.Lock() + defer fake.knSourceFactoryMutex.Unlock() + fake.KnSourceFactoryStub = nil + fake.knSourceFactoryReturns = struct { + result1 types.KnSourceFactory + }{result1} +} + +func (fake *FakeCommandFactory) KnSourceFactoryReturnsOnCall(i int, result1 types.KnSourceFactory) { + fake.knSourceFactoryMutex.Lock() + defer fake.knSourceFactoryMutex.Unlock() + fake.KnSourceFactoryStub = nil + if fake.knSourceFactoryReturnsOnCall == nil { + fake.knSourceFactoryReturnsOnCall = make(map[int]struct { + result1 types.KnSourceFactory + }) + } + fake.knSourceFactoryReturnsOnCall[i] = struct { + result1 types.KnSourceFactory + }{result1} +} + +func (fake *FakeCommandFactory) SourceCommand() *cobra.Command { + fake.sourceCommandMutex.Lock() + ret, specificReturn := fake.sourceCommandReturnsOnCall[len(fake.sourceCommandArgsForCall)] + fake.sourceCommandArgsForCall = append(fake.sourceCommandArgsForCall, struct { + }{}) + fake.recordInvocation("SourceCommand", []interface{}{}) + fake.sourceCommandMutex.Unlock() + if fake.SourceCommandStub != nil { + return fake.SourceCommandStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.sourceCommandReturns + return fakeReturns.result1 +} + +func (fake *FakeCommandFactory) SourceCommandCallCount() int { + fake.sourceCommandMutex.RLock() + defer fake.sourceCommandMutex.RUnlock() + return len(fake.sourceCommandArgsForCall) +} + +func (fake *FakeCommandFactory) SourceCommandCalls(stub func() *cobra.Command) { + fake.sourceCommandMutex.Lock() + defer fake.sourceCommandMutex.Unlock() + fake.SourceCommandStub = stub +} + +func (fake *FakeCommandFactory) SourceCommandReturns(result1 *cobra.Command) { + fake.sourceCommandMutex.Lock() + defer fake.sourceCommandMutex.Unlock() + fake.SourceCommandStub = nil + fake.sourceCommandReturns = struct { + result1 *cobra.Command + }{result1} +} + +func (fake *FakeCommandFactory) SourceCommandReturnsOnCall(i int, result1 *cobra.Command) { + fake.sourceCommandMutex.Lock() + defer fake.sourceCommandMutex.Unlock() + fake.SourceCommandStub = nil + if fake.sourceCommandReturnsOnCall == nil { + fake.sourceCommandReturnsOnCall = make(map[int]struct { + result1 *cobra.Command + }) + } + fake.sourceCommandReturnsOnCall[i] = struct { + result1 *cobra.Command + }{result1} +} + +func (fake *FakeCommandFactory) UpdateCommand() *cobra.Command { + fake.updateCommandMutex.Lock() + ret, specificReturn := fake.updateCommandReturnsOnCall[len(fake.updateCommandArgsForCall)] + fake.updateCommandArgsForCall = append(fake.updateCommandArgsForCall, struct { + }{}) + fake.recordInvocation("UpdateCommand", []interface{}{}) + fake.updateCommandMutex.Unlock() + if fake.UpdateCommandStub != nil { + return fake.UpdateCommandStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.updateCommandReturns + return fakeReturns.result1 +} + +func (fake *FakeCommandFactory) UpdateCommandCallCount() int { + fake.updateCommandMutex.RLock() + defer fake.updateCommandMutex.RUnlock() + return len(fake.updateCommandArgsForCall) +} + +func (fake *FakeCommandFactory) UpdateCommandCalls(stub func() *cobra.Command) { + fake.updateCommandMutex.Lock() + defer fake.updateCommandMutex.Unlock() + fake.UpdateCommandStub = stub +} + +func (fake *FakeCommandFactory) UpdateCommandReturns(result1 *cobra.Command) { + fake.updateCommandMutex.Lock() + defer fake.updateCommandMutex.Unlock() + fake.UpdateCommandStub = nil + fake.updateCommandReturns = struct { + result1 *cobra.Command + }{result1} +} + +func (fake *FakeCommandFactory) UpdateCommandReturnsOnCall(i int, result1 *cobra.Command) { + fake.updateCommandMutex.Lock() + defer fake.updateCommandMutex.Unlock() + fake.UpdateCommandStub = nil + if fake.updateCommandReturnsOnCall == nil { + fake.updateCommandReturnsOnCall = make(map[int]struct { + result1 *cobra.Command + }) + } + fake.updateCommandReturnsOnCall[i] = struct { + result1 *cobra.Command + }{result1} +} + +func (fake *FakeCommandFactory) Invocations() map[string][][]interface{} { + fake.invocationsMutex.RLock() + defer fake.invocationsMutex.RUnlock() + fake.createCommandMutex.RLock() + defer fake.createCommandMutex.RUnlock() + fake.deleteCommandMutex.RLock() + defer fake.deleteCommandMutex.RUnlock() + fake.describeCommandMutex.RLock() + defer fake.describeCommandMutex.RUnlock() + fake.knSourceFactoryMutex.RLock() + defer fake.knSourceFactoryMutex.RUnlock() + fake.sourceCommandMutex.RLock() + defer fake.sourceCommandMutex.RUnlock() + fake.updateCommandMutex.RLock() + defer fake.updateCommandMutex.RUnlock() + copiedInvocations := map[string][][]interface{}{} + for key, value := range fake.invocations { + copiedInvocations[key] = value + } + return copiedInvocations +} + +func (fake *FakeCommandFactory) recordInvocation(key string, args []interface{}) { + fake.invocationsMutex.Lock() + defer fake.invocationsMutex.Unlock() + if fake.invocations == nil { + fake.invocations = map[string][][]interface{}{} + } + if fake.invocations[key] == nil { + fake.invocations[key] = [][]interface{}{} + } + fake.invocations[key] = append(fake.invocations[key], args) +} + +var _ types.CommandFactory = new(FakeCommandFactory) diff --git a/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/types/typesfakes/fake_flags_factory.go b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/types/typesfakes/fake_flags_factory.go new file mode 100644 index 00000000..97195154 --- /dev/null +++ b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/types/typesfakes/fake_flags_factory.go @@ -0,0 +1,358 @@ +// Code generated by counterfeiter. DO NOT EDIT. +package typesfakes + +import ( + "sync" + + "github.com/maximilien/kn-source-pkg/pkg/types" + "github.com/spf13/pflag" +) + +type FakeFlagsFactory struct { + CreateFlagsStub func() *pflag.FlagSet + createFlagsMutex sync.RWMutex + createFlagsArgsForCall []struct { + } + createFlagsReturns struct { + result1 *pflag.FlagSet + } + createFlagsReturnsOnCall map[int]struct { + result1 *pflag.FlagSet + } + DeleteFlagsStub func() *pflag.FlagSet + deleteFlagsMutex sync.RWMutex + deleteFlagsArgsForCall []struct { + } + deleteFlagsReturns struct { + result1 *pflag.FlagSet + } + deleteFlagsReturnsOnCall map[int]struct { + result1 *pflag.FlagSet + } + DescribeFlagsStub func() *pflag.FlagSet + describeFlagsMutex sync.RWMutex + describeFlagsArgsForCall []struct { + } + describeFlagsReturns struct { + result1 *pflag.FlagSet + } + describeFlagsReturnsOnCall map[int]struct { + result1 *pflag.FlagSet + } + KnSourceFactoryStub func() types.KnSourceFactory + knSourceFactoryMutex sync.RWMutex + knSourceFactoryArgsForCall []struct { + } + knSourceFactoryReturns struct { + result1 types.KnSourceFactory + } + knSourceFactoryReturnsOnCall map[int]struct { + result1 types.KnSourceFactory + } + UpdateFlagsStub func() *pflag.FlagSet + updateFlagsMutex sync.RWMutex + updateFlagsArgsForCall []struct { + } + updateFlagsReturns struct { + result1 *pflag.FlagSet + } + updateFlagsReturnsOnCall map[int]struct { + result1 *pflag.FlagSet + } + invocations map[string][][]interface{} + invocationsMutex sync.RWMutex +} + +func (fake *FakeFlagsFactory) CreateFlags() *pflag.FlagSet { + fake.createFlagsMutex.Lock() + ret, specificReturn := fake.createFlagsReturnsOnCall[len(fake.createFlagsArgsForCall)] + fake.createFlagsArgsForCall = append(fake.createFlagsArgsForCall, struct { + }{}) + fake.recordInvocation("CreateFlags", []interface{}{}) + fake.createFlagsMutex.Unlock() + if fake.CreateFlagsStub != nil { + return fake.CreateFlagsStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.createFlagsReturns + return fakeReturns.result1 +} + +func (fake *FakeFlagsFactory) CreateFlagsCallCount() int { + fake.createFlagsMutex.RLock() + defer fake.createFlagsMutex.RUnlock() + return len(fake.createFlagsArgsForCall) +} + +func (fake *FakeFlagsFactory) CreateFlagsCalls(stub func() *pflag.FlagSet) { + fake.createFlagsMutex.Lock() + defer fake.createFlagsMutex.Unlock() + fake.CreateFlagsStub = stub +} + +func (fake *FakeFlagsFactory) CreateFlagsReturns(result1 *pflag.FlagSet) { + fake.createFlagsMutex.Lock() + defer fake.createFlagsMutex.Unlock() + fake.CreateFlagsStub = nil + fake.createFlagsReturns = struct { + result1 *pflag.FlagSet + }{result1} +} + +func (fake *FakeFlagsFactory) CreateFlagsReturnsOnCall(i int, result1 *pflag.FlagSet) { + fake.createFlagsMutex.Lock() + defer fake.createFlagsMutex.Unlock() + fake.CreateFlagsStub = nil + if fake.createFlagsReturnsOnCall == nil { + fake.createFlagsReturnsOnCall = make(map[int]struct { + result1 *pflag.FlagSet + }) + } + fake.createFlagsReturnsOnCall[i] = struct { + result1 *pflag.FlagSet + }{result1} +} + +func (fake *FakeFlagsFactory) DeleteFlags() *pflag.FlagSet { + fake.deleteFlagsMutex.Lock() + ret, specificReturn := fake.deleteFlagsReturnsOnCall[len(fake.deleteFlagsArgsForCall)] + fake.deleteFlagsArgsForCall = append(fake.deleteFlagsArgsForCall, struct { + }{}) + fake.recordInvocation("DeleteFlags", []interface{}{}) + fake.deleteFlagsMutex.Unlock() + if fake.DeleteFlagsStub != nil { + return fake.DeleteFlagsStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.deleteFlagsReturns + return fakeReturns.result1 +} + +func (fake *FakeFlagsFactory) DeleteFlagsCallCount() int { + fake.deleteFlagsMutex.RLock() + defer fake.deleteFlagsMutex.RUnlock() + return len(fake.deleteFlagsArgsForCall) +} + +func (fake *FakeFlagsFactory) DeleteFlagsCalls(stub func() *pflag.FlagSet) { + fake.deleteFlagsMutex.Lock() + defer fake.deleteFlagsMutex.Unlock() + fake.DeleteFlagsStub = stub +} + +func (fake *FakeFlagsFactory) DeleteFlagsReturns(result1 *pflag.FlagSet) { + fake.deleteFlagsMutex.Lock() + defer fake.deleteFlagsMutex.Unlock() + fake.DeleteFlagsStub = nil + fake.deleteFlagsReturns = struct { + result1 *pflag.FlagSet + }{result1} +} + +func (fake *FakeFlagsFactory) DeleteFlagsReturnsOnCall(i int, result1 *pflag.FlagSet) { + fake.deleteFlagsMutex.Lock() + defer fake.deleteFlagsMutex.Unlock() + fake.DeleteFlagsStub = nil + if fake.deleteFlagsReturnsOnCall == nil { + fake.deleteFlagsReturnsOnCall = make(map[int]struct { + result1 *pflag.FlagSet + }) + } + fake.deleteFlagsReturnsOnCall[i] = struct { + result1 *pflag.FlagSet + }{result1} +} + +func (fake *FakeFlagsFactory) DescribeFlags() *pflag.FlagSet { + fake.describeFlagsMutex.Lock() + ret, specificReturn := fake.describeFlagsReturnsOnCall[len(fake.describeFlagsArgsForCall)] + fake.describeFlagsArgsForCall = append(fake.describeFlagsArgsForCall, struct { + }{}) + fake.recordInvocation("DescribeFlags", []interface{}{}) + fake.describeFlagsMutex.Unlock() + if fake.DescribeFlagsStub != nil { + return fake.DescribeFlagsStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.describeFlagsReturns + return fakeReturns.result1 +} + +func (fake *FakeFlagsFactory) DescribeFlagsCallCount() int { + fake.describeFlagsMutex.RLock() + defer fake.describeFlagsMutex.RUnlock() + return len(fake.describeFlagsArgsForCall) +} + +func (fake *FakeFlagsFactory) DescribeFlagsCalls(stub func() *pflag.FlagSet) { + fake.describeFlagsMutex.Lock() + defer fake.describeFlagsMutex.Unlock() + fake.DescribeFlagsStub = stub +} + +func (fake *FakeFlagsFactory) DescribeFlagsReturns(result1 *pflag.FlagSet) { + fake.describeFlagsMutex.Lock() + defer fake.describeFlagsMutex.Unlock() + fake.DescribeFlagsStub = nil + fake.describeFlagsReturns = struct { + result1 *pflag.FlagSet + }{result1} +} + +func (fake *FakeFlagsFactory) DescribeFlagsReturnsOnCall(i int, result1 *pflag.FlagSet) { + fake.describeFlagsMutex.Lock() + defer fake.describeFlagsMutex.Unlock() + fake.DescribeFlagsStub = nil + if fake.describeFlagsReturnsOnCall == nil { + fake.describeFlagsReturnsOnCall = make(map[int]struct { + result1 *pflag.FlagSet + }) + } + fake.describeFlagsReturnsOnCall[i] = struct { + result1 *pflag.FlagSet + }{result1} +} + +func (fake *FakeFlagsFactory) KnSourceFactory() types.KnSourceFactory { + fake.knSourceFactoryMutex.Lock() + ret, specificReturn := fake.knSourceFactoryReturnsOnCall[len(fake.knSourceFactoryArgsForCall)] + fake.knSourceFactoryArgsForCall = append(fake.knSourceFactoryArgsForCall, struct { + }{}) + fake.recordInvocation("KnSourceFactory", []interface{}{}) + fake.knSourceFactoryMutex.Unlock() + if fake.KnSourceFactoryStub != nil { + return fake.KnSourceFactoryStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.knSourceFactoryReturns + return fakeReturns.result1 +} + +func (fake *FakeFlagsFactory) KnSourceFactoryCallCount() int { + fake.knSourceFactoryMutex.RLock() + defer fake.knSourceFactoryMutex.RUnlock() + return len(fake.knSourceFactoryArgsForCall) +} + +func (fake *FakeFlagsFactory) KnSourceFactoryCalls(stub func() types.KnSourceFactory) { + fake.knSourceFactoryMutex.Lock() + defer fake.knSourceFactoryMutex.Unlock() + fake.KnSourceFactoryStub = stub +} + +func (fake *FakeFlagsFactory) KnSourceFactoryReturns(result1 types.KnSourceFactory) { + fake.knSourceFactoryMutex.Lock() + defer fake.knSourceFactoryMutex.Unlock() + fake.KnSourceFactoryStub = nil + fake.knSourceFactoryReturns = struct { + result1 types.KnSourceFactory + }{result1} +} + +func (fake *FakeFlagsFactory) KnSourceFactoryReturnsOnCall(i int, result1 types.KnSourceFactory) { + fake.knSourceFactoryMutex.Lock() + defer fake.knSourceFactoryMutex.Unlock() + fake.KnSourceFactoryStub = nil + if fake.knSourceFactoryReturnsOnCall == nil { + fake.knSourceFactoryReturnsOnCall = make(map[int]struct { + result1 types.KnSourceFactory + }) + } + fake.knSourceFactoryReturnsOnCall[i] = struct { + result1 types.KnSourceFactory + }{result1} +} + +func (fake *FakeFlagsFactory) UpdateFlags() *pflag.FlagSet { + fake.updateFlagsMutex.Lock() + ret, specificReturn := fake.updateFlagsReturnsOnCall[len(fake.updateFlagsArgsForCall)] + fake.updateFlagsArgsForCall = append(fake.updateFlagsArgsForCall, struct { + }{}) + fake.recordInvocation("UpdateFlags", []interface{}{}) + fake.updateFlagsMutex.Unlock() + if fake.UpdateFlagsStub != nil { + return fake.UpdateFlagsStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.updateFlagsReturns + return fakeReturns.result1 +} + +func (fake *FakeFlagsFactory) UpdateFlagsCallCount() int { + fake.updateFlagsMutex.RLock() + defer fake.updateFlagsMutex.RUnlock() + return len(fake.updateFlagsArgsForCall) +} + +func (fake *FakeFlagsFactory) UpdateFlagsCalls(stub func() *pflag.FlagSet) { + fake.updateFlagsMutex.Lock() + defer fake.updateFlagsMutex.Unlock() + fake.UpdateFlagsStub = stub +} + +func (fake *FakeFlagsFactory) UpdateFlagsReturns(result1 *pflag.FlagSet) { + fake.updateFlagsMutex.Lock() + defer fake.updateFlagsMutex.Unlock() + fake.UpdateFlagsStub = nil + fake.updateFlagsReturns = struct { + result1 *pflag.FlagSet + }{result1} +} + +func (fake *FakeFlagsFactory) UpdateFlagsReturnsOnCall(i int, result1 *pflag.FlagSet) { + fake.updateFlagsMutex.Lock() + defer fake.updateFlagsMutex.Unlock() + fake.UpdateFlagsStub = nil + if fake.updateFlagsReturnsOnCall == nil { + fake.updateFlagsReturnsOnCall = make(map[int]struct { + result1 *pflag.FlagSet + }) + } + fake.updateFlagsReturnsOnCall[i] = struct { + result1 *pflag.FlagSet + }{result1} +} + +func (fake *FakeFlagsFactory) Invocations() map[string][][]interface{} { + fake.invocationsMutex.RLock() + defer fake.invocationsMutex.RUnlock() + fake.createFlagsMutex.RLock() + defer fake.createFlagsMutex.RUnlock() + fake.deleteFlagsMutex.RLock() + defer fake.deleteFlagsMutex.RUnlock() + fake.describeFlagsMutex.RLock() + defer fake.describeFlagsMutex.RUnlock() + fake.knSourceFactoryMutex.RLock() + defer fake.knSourceFactoryMutex.RUnlock() + fake.updateFlagsMutex.RLock() + defer fake.updateFlagsMutex.RUnlock() + copiedInvocations := map[string][][]interface{}{} + for key, value := range fake.invocations { + copiedInvocations[key] = value + } + return copiedInvocations +} + +func (fake *FakeFlagsFactory) recordInvocation(key string, args []interface{}) { + fake.invocationsMutex.Lock() + defer fake.invocationsMutex.Unlock() + if fake.invocations == nil { + fake.invocations = map[string][][]interface{}{} + } + if fake.invocations[key] == nil { + fake.invocations[key] = [][]interface{}{} + } + fake.invocations[key] = append(fake.invocations[key], args) +} + +var _ types.FlagsFactory = new(FakeFlagsFactory) diff --git a/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/types/typesfakes/fake_kn_source_client.go b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/types/typesfakes/fake_kn_source_client.go new file mode 100644 index 00000000..aa8d20ad --- /dev/null +++ b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/types/typesfakes/fake_kn_source_client.go @@ -0,0 +1,230 @@ +// Code generated by counterfeiter. DO NOT EDIT. +package typesfakes + +import ( + "sync" + + "github.com/maximilien/kn-source-pkg/pkg/types" + "k8s.io/client-go/rest" +) + +type FakeKnSourceClient struct { + KnSourceParamsStub func() *types.KnSourceParams + knSourceParamsMutex sync.RWMutex + knSourceParamsArgsForCall []struct { + } + knSourceParamsReturns struct { + result1 *types.KnSourceParams + } + knSourceParamsReturnsOnCall map[int]struct { + result1 *types.KnSourceParams + } + NamespaceStub func() string + namespaceMutex sync.RWMutex + namespaceArgsForCall []struct { + } + namespaceReturns struct { + result1 string + } + namespaceReturnsOnCall map[int]struct { + result1 string + } + RestConfigStub func() *rest.Config + restConfigMutex sync.RWMutex + restConfigArgsForCall []struct { + } + restConfigReturns struct { + result1 *rest.Config + } + restConfigReturnsOnCall map[int]struct { + result1 *rest.Config + } + invocations map[string][][]interface{} + invocationsMutex sync.RWMutex +} + +func (fake *FakeKnSourceClient) KnSourceParams() *types.KnSourceParams { + fake.knSourceParamsMutex.Lock() + ret, specificReturn := fake.knSourceParamsReturnsOnCall[len(fake.knSourceParamsArgsForCall)] + fake.knSourceParamsArgsForCall = append(fake.knSourceParamsArgsForCall, struct { + }{}) + fake.recordInvocation("KnSourceParams", []interface{}{}) + fake.knSourceParamsMutex.Unlock() + if fake.KnSourceParamsStub != nil { + return fake.KnSourceParamsStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.knSourceParamsReturns + return fakeReturns.result1 +} + +func (fake *FakeKnSourceClient) KnSourceParamsCallCount() int { + fake.knSourceParamsMutex.RLock() + defer fake.knSourceParamsMutex.RUnlock() + return len(fake.knSourceParamsArgsForCall) +} + +func (fake *FakeKnSourceClient) KnSourceParamsCalls(stub func() *types.KnSourceParams) { + fake.knSourceParamsMutex.Lock() + defer fake.knSourceParamsMutex.Unlock() + fake.KnSourceParamsStub = stub +} + +func (fake *FakeKnSourceClient) KnSourceParamsReturns(result1 *types.KnSourceParams) { + fake.knSourceParamsMutex.Lock() + defer fake.knSourceParamsMutex.Unlock() + fake.KnSourceParamsStub = nil + fake.knSourceParamsReturns = struct { + result1 *types.KnSourceParams + }{result1} +} + +func (fake *FakeKnSourceClient) KnSourceParamsReturnsOnCall(i int, result1 *types.KnSourceParams) { + fake.knSourceParamsMutex.Lock() + defer fake.knSourceParamsMutex.Unlock() + fake.KnSourceParamsStub = nil + if fake.knSourceParamsReturnsOnCall == nil { + fake.knSourceParamsReturnsOnCall = make(map[int]struct { + result1 *types.KnSourceParams + }) + } + fake.knSourceParamsReturnsOnCall[i] = struct { + result1 *types.KnSourceParams + }{result1} +} + +func (fake *FakeKnSourceClient) Namespace() string { + fake.namespaceMutex.Lock() + ret, specificReturn := fake.namespaceReturnsOnCall[len(fake.namespaceArgsForCall)] + fake.namespaceArgsForCall = append(fake.namespaceArgsForCall, struct { + }{}) + fake.recordInvocation("Namespace", []interface{}{}) + fake.namespaceMutex.Unlock() + if fake.NamespaceStub != nil { + return fake.NamespaceStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.namespaceReturns + return fakeReturns.result1 +} + +func (fake *FakeKnSourceClient) NamespaceCallCount() int { + fake.namespaceMutex.RLock() + defer fake.namespaceMutex.RUnlock() + return len(fake.namespaceArgsForCall) +} + +func (fake *FakeKnSourceClient) NamespaceCalls(stub func() string) { + fake.namespaceMutex.Lock() + defer fake.namespaceMutex.Unlock() + fake.NamespaceStub = stub +} + +func (fake *FakeKnSourceClient) NamespaceReturns(result1 string) { + fake.namespaceMutex.Lock() + defer fake.namespaceMutex.Unlock() + fake.NamespaceStub = nil + fake.namespaceReturns = struct { + result1 string + }{result1} +} + +func (fake *FakeKnSourceClient) NamespaceReturnsOnCall(i int, result1 string) { + fake.namespaceMutex.Lock() + defer fake.namespaceMutex.Unlock() + fake.NamespaceStub = nil + if fake.namespaceReturnsOnCall == nil { + fake.namespaceReturnsOnCall = make(map[int]struct { + result1 string + }) + } + fake.namespaceReturnsOnCall[i] = struct { + result1 string + }{result1} +} + +func (fake *FakeKnSourceClient) RestConfig() *rest.Config { + fake.restConfigMutex.Lock() + ret, specificReturn := fake.restConfigReturnsOnCall[len(fake.restConfigArgsForCall)] + fake.restConfigArgsForCall = append(fake.restConfigArgsForCall, struct { + }{}) + fake.recordInvocation("RestConfig", []interface{}{}) + fake.restConfigMutex.Unlock() + if fake.RestConfigStub != nil { + return fake.RestConfigStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.restConfigReturns + return fakeReturns.result1 +} + +func (fake *FakeKnSourceClient) RestConfigCallCount() int { + fake.restConfigMutex.RLock() + defer fake.restConfigMutex.RUnlock() + return len(fake.restConfigArgsForCall) +} + +func (fake *FakeKnSourceClient) RestConfigCalls(stub func() *rest.Config) { + fake.restConfigMutex.Lock() + defer fake.restConfigMutex.Unlock() + fake.RestConfigStub = stub +} + +func (fake *FakeKnSourceClient) RestConfigReturns(result1 *rest.Config) { + fake.restConfigMutex.Lock() + defer fake.restConfigMutex.Unlock() + fake.RestConfigStub = nil + fake.restConfigReturns = struct { + result1 *rest.Config + }{result1} +} + +func (fake *FakeKnSourceClient) RestConfigReturnsOnCall(i int, result1 *rest.Config) { + fake.restConfigMutex.Lock() + defer fake.restConfigMutex.Unlock() + fake.RestConfigStub = nil + if fake.restConfigReturnsOnCall == nil { + fake.restConfigReturnsOnCall = make(map[int]struct { + result1 *rest.Config + }) + } + fake.restConfigReturnsOnCall[i] = struct { + result1 *rest.Config + }{result1} +} + +func (fake *FakeKnSourceClient) Invocations() map[string][][]interface{} { + fake.invocationsMutex.RLock() + defer fake.invocationsMutex.RUnlock() + fake.knSourceParamsMutex.RLock() + defer fake.knSourceParamsMutex.RUnlock() + fake.namespaceMutex.RLock() + defer fake.namespaceMutex.RUnlock() + fake.restConfigMutex.RLock() + defer fake.restConfigMutex.RUnlock() + copiedInvocations := map[string][][]interface{}{} + for key, value := range fake.invocations { + copiedInvocations[key] = value + } + return copiedInvocations +} + +func (fake *FakeKnSourceClient) recordInvocation(key string, args []interface{}) { + fake.invocationsMutex.Lock() + defer fake.invocationsMutex.Unlock() + if fake.invocations == nil { + fake.invocations = map[string][][]interface{}{} + } + if fake.invocations[key] == nil { + fake.invocations[key] = [][]interface{}{} + } + fake.invocations[key] = append(fake.invocations[key], args) +} + +var _ types.KnSourceClient = new(FakeKnSourceClient) diff --git a/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/types/typesfakes/fake_kn_source_factory.go b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/types/typesfakes/fake_kn_source_factory.go new file mode 100644 index 00000000..7fd410ce --- /dev/null +++ b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/types/typesfakes/fake_kn_source_factory.go @@ -0,0 +1,238 @@ +// Code generated by counterfeiter. DO NOT EDIT. +package typesfakes + +import ( + "sync" + + "github.com/maximilien/kn-source-pkg/pkg/types" +) + +type FakeKnSourceFactory struct { + CreateKnSourceClientStub func(string) types.KnSourceClient + createKnSourceClientMutex sync.RWMutex + createKnSourceClientArgsForCall []struct { + arg1 string + } + createKnSourceClientReturns struct { + result1 types.KnSourceClient + } + createKnSourceClientReturnsOnCall map[int]struct { + result1 types.KnSourceClient + } + CreateKnSourceParamsStub func() *types.KnSourceParams + createKnSourceParamsMutex sync.RWMutex + createKnSourceParamsArgsForCall []struct { + } + createKnSourceParamsReturns struct { + result1 *types.KnSourceParams + } + createKnSourceParamsReturnsOnCall map[int]struct { + result1 *types.KnSourceParams + } + KnSourceParamsStub func() *types.KnSourceParams + knSourceParamsMutex sync.RWMutex + knSourceParamsArgsForCall []struct { + } + knSourceParamsReturns struct { + result1 *types.KnSourceParams + } + knSourceParamsReturnsOnCall map[int]struct { + result1 *types.KnSourceParams + } + invocations map[string][][]interface{} + invocationsMutex sync.RWMutex +} + +func (fake *FakeKnSourceFactory) CreateKnSourceClient(arg1 string) types.KnSourceClient { + fake.createKnSourceClientMutex.Lock() + ret, specificReturn := fake.createKnSourceClientReturnsOnCall[len(fake.createKnSourceClientArgsForCall)] + fake.createKnSourceClientArgsForCall = append(fake.createKnSourceClientArgsForCall, struct { + arg1 string + }{arg1}) + fake.recordInvocation("CreateKnSourceClient", []interface{}{arg1}) + fake.createKnSourceClientMutex.Unlock() + if fake.CreateKnSourceClientStub != nil { + return fake.CreateKnSourceClientStub(arg1) + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.createKnSourceClientReturns + return fakeReturns.result1 +} + +func (fake *FakeKnSourceFactory) CreateKnSourceClientCallCount() int { + fake.createKnSourceClientMutex.RLock() + defer fake.createKnSourceClientMutex.RUnlock() + return len(fake.createKnSourceClientArgsForCall) +} + +func (fake *FakeKnSourceFactory) CreateKnSourceClientCalls(stub func(string) types.KnSourceClient) { + fake.createKnSourceClientMutex.Lock() + defer fake.createKnSourceClientMutex.Unlock() + fake.CreateKnSourceClientStub = stub +} + +func (fake *FakeKnSourceFactory) CreateKnSourceClientArgsForCall(i int) string { + fake.createKnSourceClientMutex.RLock() + defer fake.createKnSourceClientMutex.RUnlock() + argsForCall := fake.createKnSourceClientArgsForCall[i] + return argsForCall.arg1 +} + +func (fake *FakeKnSourceFactory) CreateKnSourceClientReturns(result1 types.KnSourceClient) { + fake.createKnSourceClientMutex.Lock() + defer fake.createKnSourceClientMutex.Unlock() + fake.CreateKnSourceClientStub = nil + fake.createKnSourceClientReturns = struct { + result1 types.KnSourceClient + }{result1} +} + +func (fake *FakeKnSourceFactory) CreateKnSourceClientReturnsOnCall(i int, result1 types.KnSourceClient) { + fake.createKnSourceClientMutex.Lock() + defer fake.createKnSourceClientMutex.Unlock() + fake.CreateKnSourceClientStub = nil + if fake.createKnSourceClientReturnsOnCall == nil { + fake.createKnSourceClientReturnsOnCall = make(map[int]struct { + result1 types.KnSourceClient + }) + } + fake.createKnSourceClientReturnsOnCall[i] = struct { + result1 types.KnSourceClient + }{result1} +} + +func (fake *FakeKnSourceFactory) CreateKnSourceParams() *types.KnSourceParams { + fake.createKnSourceParamsMutex.Lock() + ret, specificReturn := fake.createKnSourceParamsReturnsOnCall[len(fake.createKnSourceParamsArgsForCall)] + fake.createKnSourceParamsArgsForCall = append(fake.createKnSourceParamsArgsForCall, struct { + }{}) + fake.recordInvocation("CreateKnSourceParams", []interface{}{}) + fake.createKnSourceParamsMutex.Unlock() + if fake.CreateKnSourceParamsStub != nil { + return fake.CreateKnSourceParamsStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.createKnSourceParamsReturns + return fakeReturns.result1 +} + +func (fake *FakeKnSourceFactory) CreateKnSourceParamsCallCount() int { + fake.createKnSourceParamsMutex.RLock() + defer fake.createKnSourceParamsMutex.RUnlock() + return len(fake.createKnSourceParamsArgsForCall) +} + +func (fake *FakeKnSourceFactory) CreateKnSourceParamsCalls(stub func() *types.KnSourceParams) { + fake.createKnSourceParamsMutex.Lock() + defer fake.createKnSourceParamsMutex.Unlock() + fake.CreateKnSourceParamsStub = stub +} + +func (fake *FakeKnSourceFactory) CreateKnSourceParamsReturns(result1 *types.KnSourceParams) { + fake.createKnSourceParamsMutex.Lock() + defer fake.createKnSourceParamsMutex.Unlock() + fake.CreateKnSourceParamsStub = nil + fake.createKnSourceParamsReturns = struct { + result1 *types.KnSourceParams + }{result1} +} + +func (fake *FakeKnSourceFactory) CreateKnSourceParamsReturnsOnCall(i int, result1 *types.KnSourceParams) { + fake.createKnSourceParamsMutex.Lock() + defer fake.createKnSourceParamsMutex.Unlock() + fake.CreateKnSourceParamsStub = nil + if fake.createKnSourceParamsReturnsOnCall == nil { + fake.createKnSourceParamsReturnsOnCall = make(map[int]struct { + result1 *types.KnSourceParams + }) + } + fake.createKnSourceParamsReturnsOnCall[i] = struct { + result1 *types.KnSourceParams + }{result1} +} + +func (fake *FakeKnSourceFactory) KnSourceParams() *types.KnSourceParams { + fake.knSourceParamsMutex.Lock() + ret, specificReturn := fake.knSourceParamsReturnsOnCall[len(fake.knSourceParamsArgsForCall)] + fake.knSourceParamsArgsForCall = append(fake.knSourceParamsArgsForCall, struct { + }{}) + fake.recordInvocation("KnSourceParams", []interface{}{}) + fake.knSourceParamsMutex.Unlock() + if fake.KnSourceParamsStub != nil { + return fake.KnSourceParamsStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.knSourceParamsReturns + return fakeReturns.result1 +} + +func (fake *FakeKnSourceFactory) KnSourceParamsCallCount() int { + fake.knSourceParamsMutex.RLock() + defer fake.knSourceParamsMutex.RUnlock() + return len(fake.knSourceParamsArgsForCall) +} + +func (fake *FakeKnSourceFactory) KnSourceParamsCalls(stub func() *types.KnSourceParams) { + fake.knSourceParamsMutex.Lock() + defer fake.knSourceParamsMutex.Unlock() + fake.KnSourceParamsStub = stub +} + +func (fake *FakeKnSourceFactory) KnSourceParamsReturns(result1 *types.KnSourceParams) { + fake.knSourceParamsMutex.Lock() + defer fake.knSourceParamsMutex.Unlock() + fake.KnSourceParamsStub = nil + fake.knSourceParamsReturns = struct { + result1 *types.KnSourceParams + }{result1} +} + +func (fake *FakeKnSourceFactory) KnSourceParamsReturnsOnCall(i int, result1 *types.KnSourceParams) { + fake.knSourceParamsMutex.Lock() + defer fake.knSourceParamsMutex.Unlock() + fake.KnSourceParamsStub = nil + if fake.knSourceParamsReturnsOnCall == nil { + fake.knSourceParamsReturnsOnCall = make(map[int]struct { + result1 *types.KnSourceParams + }) + } + fake.knSourceParamsReturnsOnCall[i] = struct { + result1 *types.KnSourceParams + }{result1} +} + +func (fake *FakeKnSourceFactory) Invocations() map[string][][]interface{} { + fake.invocationsMutex.RLock() + defer fake.invocationsMutex.RUnlock() + fake.createKnSourceClientMutex.RLock() + defer fake.createKnSourceClientMutex.RUnlock() + fake.createKnSourceParamsMutex.RLock() + defer fake.createKnSourceParamsMutex.RUnlock() + fake.knSourceParamsMutex.RLock() + defer fake.knSourceParamsMutex.RUnlock() + copiedInvocations := map[string][][]interface{}{} + for key, value := range fake.invocations { + copiedInvocations[key] = value + } + return copiedInvocations +} + +func (fake *FakeKnSourceFactory) recordInvocation(key string, args []interface{}) { + fake.invocationsMutex.Lock() + defer fake.invocationsMutex.Unlock() + if fake.invocations == nil { + fake.invocations = map[string][][]interface{}{} + } + if fake.invocations[key] == nil { + fake.invocations[key] = [][]interface{}{} + } + fake.invocations[key] = append(fake.invocations[key], args) +} + +var _ types.KnSourceFactory = new(FakeKnSourceFactory) diff --git a/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/types/typesfakes/fake_run_efactory.go b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/types/typesfakes/fake_run_efactory.go new file mode 100644 index 00000000..78fa7431 --- /dev/null +++ b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/types/typesfakes/fake_run_efactory.go @@ -0,0 +1,431 @@ +// Code generated by counterfeiter. DO NOT EDIT. +package typesfakes + +import ( + "sync" + + "github.com/maximilien/kn-source-pkg/pkg/types" + "github.com/spf13/cobra" +) + +type FakeRunEFactory struct { + CreateRunEStub func() func(cmd *cobra.Command, args []string) error + createRunEMutex sync.RWMutex + createRunEArgsForCall []struct { + } + createRunEReturns struct { + result1 func(cmd *cobra.Command, args []string) error + } + createRunEReturnsOnCall map[int]struct { + result1 func(cmd *cobra.Command, args []string) error + } + DeleteRunEStub func() func(cmd *cobra.Command, args []string) error + deleteRunEMutex sync.RWMutex + deleteRunEArgsForCall []struct { + } + deleteRunEReturns struct { + result1 func(cmd *cobra.Command, args []string) error + } + deleteRunEReturnsOnCall map[int]struct { + result1 func(cmd *cobra.Command, args []string) error + } + DescribeRunEStub func() func(cmd *cobra.Command, args []string) error + describeRunEMutex sync.RWMutex + describeRunEArgsForCall []struct { + } + describeRunEReturns struct { + result1 func(cmd *cobra.Command, args []string) error + } + describeRunEReturnsOnCall map[int]struct { + result1 func(cmd *cobra.Command, args []string) error + } + KnSourceClientStub func(string) types.KnSourceClient + knSourceClientMutex sync.RWMutex + knSourceClientArgsForCall []struct { + arg1 string + } + knSourceClientReturns struct { + result1 types.KnSourceClient + } + knSourceClientReturnsOnCall map[int]struct { + result1 types.KnSourceClient + } + KnSourceFactoryStub func() types.KnSourceFactory + knSourceFactoryMutex sync.RWMutex + knSourceFactoryArgsForCall []struct { + } + knSourceFactoryReturns struct { + result1 types.KnSourceFactory + } + knSourceFactoryReturnsOnCall map[int]struct { + result1 types.KnSourceFactory + } + UpdateRunEStub func() func(cmd *cobra.Command, args []string) error + updateRunEMutex sync.RWMutex + updateRunEArgsForCall []struct { + } + updateRunEReturns struct { + result1 func(cmd *cobra.Command, args []string) error + } + updateRunEReturnsOnCall map[int]struct { + result1 func(cmd *cobra.Command, args []string) error + } + invocations map[string][][]interface{} + invocationsMutex sync.RWMutex +} + +func (fake *FakeRunEFactory) CreateRunE() func(cmd *cobra.Command, args []string) error { + fake.createRunEMutex.Lock() + ret, specificReturn := fake.createRunEReturnsOnCall[len(fake.createRunEArgsForCall)] + fake.createRunEArgsForCall = append(fake.createRunEArgsForCall, struct { + }{}) + fake.recordInvocation("CreateRunE", []interface{}{}) + fake.createRunEMutex.Unlock() + if fake.CreateRunEStub != nil { + return fake.CreateRunEStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.createRunEReturns + return fakeReturns.result1 +} + +func (fake *FakeRunEFactory) CreateRunECallCount() int { + fake.createRunEMutex.RLock() + defer fake.createRunEMutex.RUnlock() + return len(fake.createRunEArgsForCall) +} + +func (fake *FakeRunEFactory) CreateRunECalls(stub func() func(cmd *cobra.Command, args []string) error) { + fake.createRunEMutex.Lock() + defer fake.createRunEMutex.Unlock() + fake.CreateRunEStub = stub +} + +func (fake *FakeRunEFactory) CreateRunEReturns(result1 func(cmd *cobra.Command, args []string) error) { + fake.createRunEMutex.Lock() + defer fake.createRunEMutex.Unlock() + fake.CreateRunEStub = nil + fake.createRunEReturns = struct { + result1 func(cmd *cobra.Command, args []string) error + }{result1} +} + +func (fake *FakeRunEFactory) CreateRunEReturnsOnCall(i int, result1 func(cmd *cobra.Command, args []string) error) { + fake.createRunEMutex.Lock() + defer fake.createRunEMutex.Unlock() + fake.CreateRunEStub = nil + if fake.createRunEReturnsOnCall == nil { + fake.createRunEReturnsOnCall = make(map[int]struct { + result1 func(cmd *cobra.Command, args []string) error + }) + } + fake.createRunEReturnsOnCall[i] = struct { + result1 func(cmd *cobra.Command, args []string) error + }{result1} +} + +func (fake *FakeRunEFactory) DeleteRunE() func(cmd *cobra.Command, args []string) error { + fake.deleteRunEMutex.Lock() + ret, specificReturn := fake.deleteRunEReturnsOnCall[len(fake.deleteRunEArgsForCall)] + fake.deleteRunEArgsForCall = append(fake.deleteRunEArgsForCall, struct { + }{}) + fake.recordInvocation("DeleteRunE", []interface{}{}) + fake.deleteRunEMutex.Unlock() + if fake.DeleteRunEStub != nil { + return fake.DeleteRunEStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.deleteRunEReturns + return fakeReturns.result1 +} + +func (fake *FakeRunEFactory) DeleteRunECallCount() int { + fake.deleteRunEMutex.RLock() + defer fake.deleteRunEMutex.RUnlock() + return len(fake.deleteRunEArgsForCall) +} + +func (fake *FakeRunEFactory) DeleteRunECalls(stub func() func(cmd *cobra.Command, args []string) error) { + fake.deleteRunEMutex.Lock() + defer fake.deleteRunEMutex.Unlock() + fake.DeleteRunEStub = stub +} + +func (fake *FakeRunEFactory) DeleteRunEReturns(result1 func(cmd *cobra.Command, args []string) error) { + fake.deleteRunEMutex.Lock() + defer fake.deleteRunEMutex.Unlock() + fake.DeleteRunEStub = nil + fake.deleteRunEReturns = struct { + result1 func(cmd *cobra.Command, args []string) error + }{result1} +} + +func (fake *FakeRunEFactory) DeleteRunEReturnsOnCall(i int, result1 func(cmd *cobra.Command, args []string) error) { + fake.deleteRunEMutex.Lock() + defer fake.deleteRunEMutex.Unlock() + fake.DeleteRunEStub = nil + if fake.deleteRunEReturnsOnCall == nil { + fake.deleteRunEReturnsOnCall = make(map[int]struct { + result1 func(cmd *cobra.Command, args []string) error + }) + } + fake.deleteRunEReturnsOnCall[i] = struct { + result1 func(cmd *cobra.Command, args []string) error + }{result1} +} + +func (fake *FakeRunEFactory) DescribeRunE() func(cmd *cobra.Command, args []string) error { + fake.describeRunEMutex.Lock() + ret, specificReturn := fake.describeRunEReturnsOnCall[len(fake.describeRunEArgsForCall)] + fake.describeRunEArgsForCall = append(fake.describeRunEArgsForCall, struct { + }{}) + fake.recordInvocation("DescribeRunE", []interface{}{}) + fake.describeRunEMutex.Unlock() + if fake.DescribeRunEStub != nil { + return fake.DescribeRunEStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.describeRunEReturns + return fakeReturns.result1 +} + +func (fake *FakeRunEFactory) DescribeRunECallCount() int { + fake.describeRunEMutex.RLock() + defer fake.describeRunEMutex.RUnlock() + return len(fake.describeRunEArgsForCall) +} + +func (fake *FakeRunEFactory) DescribeRunECalls(stub func() func(cmd *cobra.Command, args []string) error) { + fake.describeRunEMutex.Lock() + defer fake.describeRunEMutex.Unlock() + fake.DescribeRunEStub = stub +} + +func (fake *FakeRunEFactory) DescribeRunEReturns(result1 func(cmd *cobra.Command, args []string) error) { + fake.describeRunEMutex.Lock() + defer fake.describeRunEMutex.Unlock() + fake.DescribeRunEStub = nil + fake.describeRunEReturns = struct { + result1 func(cmd *cobra.Command, args []string) error + }{result1} +} + +func (fake *FakeRunEFactory) DescribeRunEReturnsOnCall(i int, result1 func(cmd *cobra.Command, args []string) error) { + fake.describeRunEMutex.Lock() + defer fake.describeRunEMutex.Unlock() + fake.DescribeRunEStub = nil + if fake.describeRunEReturnsOnCall == nil { + fake.describeRunEReturnsOnCall = make(map[int]struct { + result1 func(cmd *cobra.Command, args []string) error + }) + } + fake.describeRunEReturnsOnCall[i] = struct { + result1 func(cmd *cobra.Command, args []string) error + }{result1} +} + +func (fake *FakeRunEFactory) KnSourceClient(arg1 string) types.KnSourceClient { + fake.knSourceClientMutex.Lock() + ret, specificReturn := fake.knSourceClientReturnsOnCall[len(fake.knSourceClientArgsForCall)] + fake.knSourceClientArgsForCall = append(fake.knSourceClientArgsForCall, struct { + arg1 string + }{arg1}) + fake.recordInvocation("KnSourceClient", []interface{}{arg1}) + fake.knSourceClientMutex.Unlock() + if fake.KnSourceClientStub != nil { + return fake.KnSourceClientStub(arg1) + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.knSourceClientReturns + return fakeReturns.result1 +} + +func (fake *FakeRunEFactory) KnSourceClientCallCount() int { + fake.knSourceClientMutex.RLock() + defer fake.knSourceClientMutex.RUnlock() + return len(fake.knSourceClientArgsForCall) +} + +func (fake *FakeRunEFactory) KnSourceClientCalls(stub func(string) types.KnSourceClient) { + fake.knSourceClientMutex.Lock() + defer fake.knSourceClientMutex.Unlock() + fake.KnSourceClientStub = stub +} + +func (fake *FakeRunEFactory) KnSourceClientArgsForCall(i int) string { + fake.knSourceClientMutex.RLock() + defer fake.knSourceClientMutex.RUnlock() + argsForCall := fake.knSourceClientArgsForCall[i] + return argsForCall.arg1 +} + +func (fake *FakeRunEFactory) KnSourceClientReturns(result1 types.KnSourceClient) { + fake.knSourceClientMutex.Lock() + defer fake.knSourceClientMutex.Unlock() + fake.KnSourceClientStub = nil + fake.knSourceClientReturns = struct { + result1 types.KnSourceClient + }{result1} +} + +func (fake *FakeRunEFactory) KnSourceClientReturnsOnCall(i int, result1 types.KnSourceClient) { + fake.knSourceClientMutex.Lock() + defer fake.knSourceClientMutex.Unlock() + fake.KnSourceClientStub = nil + if fake.knSourceClientReturnsOnCall == nil { + fake.knSourceClientReturnsOnCall = make(map[int]struct { + result1 types.KnSourceClient + }) + } + fake.knSourceClientReturnsOnCall[i] = struct { + result1 types.KnSourceClient + }{result1} +} + +func (fake *FakeRunEFactory) KnSourceFactory() types.KnSourceFactory { + fake.knSourceFactoryMutex.Lock() + ret, specificReturn := fake.knSourceFactoryReturnsOnCall[len(fake.knSourceFactoryArgsForCall)] + fake.knSourceFactoryArgsForCall = append(fake.knSourceFactoryArgsForCall, struct { + }{}) + fake.recordInvocation("KnSourceFactory", []interface{}{}) + fake.knSourceFactoryMutex.Unlock() + if fake.KnSourceFactoryStub != nil { + return fake.KnSourceFactoryStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.knSourceFactoryReturns + return fakeReturns.result1 +} + +func (fake *FakeRunEFactory) KnSourceFactoryCallCount() int { + fake.knSourceFactoryMutex.RLock() + defer fake.knSourceFactoryMutex.RUnlock() + return len(fake.knSourceFactoryArgsForCall) +} + +func (fake *FakeRunEFactory) KnSourceFactoryCalls(stub func() types.KnSourceFactory) { + fake.knSourceFactoryMutex.Lock() + defer fake.knSourceFactoryMutex.Unlock() + fake.KnSourceFactoryStub = stub +} + +func (fake *FakeRunEFactory) KnSourceFactoryReturns(result1 types.KnSourceFactory) { + fake.knSourceFactoryMutex.Lock() + defer fake.knSourceFactoryMutex.Unlock() + fake.KnSourceFactoryStub = nil + fake.knSourceFactoryReturns = struct { + result1 types.KnSourceFactory + }{result1} +} + +func (fake *FakeRunEFactory) KnSourceFactoryReturnsOnCall(i int, result1 types.KnSourceFactory) { + fake.knSourceFactoryMutex.Lock() + defer fake.knSourceFactoryMutex.Unlock() + fake.KnSourceFactoryStub = nil + if fake.knSourceFactoryReturnsOnCall == nil { + fake.knSourceFactoryReturnsOnCall = make(map[int]struct { + result1 types.KnSourceFactory + }) + } + fake.knSourceFactoryReturnsOnCall[i] = struct { + result1 types.KnSourceFactory + }{result1} +} + +func (fake *FakeRunEFactory) UpdateRunE() func(cmd *cobra.Command, args []string) error { + fake.updateRunEMutex.Lock() + ret, specificReturn := fake.updateRunEReturnsOnCall[len(fake.updateRunEArgsForCall)] + fake.updateRunEArgsForCall = append(fake.updateRunEArgsForCall, struct { + }{}) + fake.recordInvocation("UpdateRunE", []interface{}{}) + fake.updateRunEMutex.Unlock() + if fake.UpdateRunEStub != nil { + return fake.UpdateRunEStub() + } + if specificReturn { + return ret.result1 + } + fakeReturns := fake.updateRunEReturns + return fakeReturns.result1 +} + +func (fake *FakeRunEFactory) UpdateRunECallCount() int { + fake.updateRunEMutex.RLock() + defer fake.updateRunEMutex.RUnlock() + return len(fake.updateRunEArgsForCall) +} + +func (fake *FakeRunEFactory) UpdateRunECalls(stub func() func(cmd *cobra.Command, args []string) error) { + fake.updateRunEMutex.Lock() + defer fake.updateRunEMutex.Unlock() + fake.UpdateRunEStub = stub +} + +func (fake *FakeRunEFactory) UpdateRunEReturns(result1 func(cmd *cobra.Command, args []string) error) { + fake.updateRunEMutex.Lock() + defer fake.updateRunEMutex.Unlock() + fake.UpdateRunEStub = nil + fake.updateRunEReturns = struct { + result1 func(cmd *cobra.Command, args []string) error + }{result1} +} + +func (fake *FakeRunEFactory) UpdateRunEReturnsOnCall(i int, result1 func(cmd *cobra.Command, args []string) error) { + fake.updateRunEMutex.Lock() + defer fake.updateRunEMutex.Unlock() + fake.UpdateRunEStub = nil + if fake.updateRunEReturnsOnCall == nil { + fake.updateRunEReturnsOnCall = make(map[int]struct { + result1 func(cmd *cobra.Command, args []string) error + }) + } + fake.updateRunEReturnsOnCall[i] = struct { + result1 func(cmd *cobra.Command, args []string) error + }{result1} +} + +func (fake *FakeRunEFactory) Invocations() map[string][][]interface{} { + fake.invocationsMutex.RLock() + defer fake.invocationsMutex.RUnlock() + fake.createRunEMutex.RLock() + defer fake.createRunEMutex.RUnlock() + fake.deleteRunEMutex.RLock() + defer fake.deleteRunEMutex.RUnlock() + fake.describeRunEMutex.RLock() + defer fake.describeRunEMutex.RUnlock() + fake.knSourceClientMutex.RLock() + defer fake.knSourceClientMutex.RUnlock() + fake.knSourceFactoryMutex.RLock() + defer fake.knSourceFactoryMutex.RUnlock() + fake.updateRunEMutex.RLock() + defer fake.updateRunEMutex.RUnlock() + copiedInvocations := map[string][][]interface{}{} + for key, value := range fake.invocations { + copiedInvocations[key] = value + } + return copiedInvocations +} + +func (fake *FakeRunEFactory) recordInvocation(key string, args []interface{}) { + fake.invocationsMutex.Lock() + defer fake.invocationsMutex.Unlock() + if fake.invocations == nil { + fake.invocations = map[string][][]interface{}{} + } + if fake.invocations[key] == nil { + fake.invocations[key] = [][]interface{}{} + } + fake.invocations[key] = append(fake.invocations[key], args) +} + +var _ types.RunEFactory = new(FakeRunEFactory) diff --git a/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/util/docs_generator.go b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/util/docs_generator.go new file mode 100644 index 00000000..78a88f8c --- /dev/null +++ b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/util/docs_generator.go @@ -0,0 +1,156 @@ +// Copyright © 2020 The Knative 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 util + +import ( + "bufio" + "bytes" + "fmt" + "io" + "io/ioutil" + "os" + "path/filepath" + "strings" + + "github.com/spf13/cobra" + "github.com/spf13/cobra/doc" +) + +const ( + readmePath = "." + readmeFilename = "README.md" + headerFilepath = "./docs/header.md" + footerFilepath = "./docs/footer.md" +) + +// ReadmeGenerator is to generate README.md for a plugin command, +// including header.md and footer.md under doc folder and command usages +func ReadmeGenerator(cmd *cobra.Command) error { + mdFilepath := filepath.Join(readmePath, readmeFilename) + return readmeGenerator(cmd, mdFilepath) +} + +//Private + +func readmeGenerator(cmd *cobra.Command, filepath string) error { + var ( + header string + footer string + err error + ) + writer := bytes.NewBufferString("") + err = docGenerator(cmd, writer) + if err != nil { + return err + } + + mdFile, err := os.OpenFile(filepath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644) + if err != nil { + return err + } + defer mdFile.Close() + + if header, err = getHeader(cmd); err != nil { + return err + } + if _, err := io.WriteString(mdFile, header+"\n"); err != nil { + return err + } + + if _, err = io.WriteString(mdFile, "## Usage\n\n"); err != nil { + return err + } + reader := bufio.NewReader(writer) + for { + line, err := reader.ReadString('\n') + if err == io.EOF { + break + } + if err != nil { + return err + } + if strings.Contains(line, "##") { + line = strings.Replace(line, "##", "###", 1) + } + _, err = io.WriteString(mdFile, line) + if err != nil { + return err + } + } + + if footer, err = getFooter(); err != nil { + return err + } + if _, err := io.WriteString(mdFile, footer+"\n"); err != nil { + return err + } + + return nil +} + +func docGenerator(cmd *cobra.Command, w io.Writer) error { + if err := doc.GenMarkdownCustom(cmd, w, linkConverter); err != nil { + return err + } + for _, c := range cmd.Commands() { + if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() { + continue + } + if err := docGenerator(c, w); err != nil { + return err + } + } + return nil +} + +func linkConverter(ins string) string { + outs := strings.TrimSuffix(ins, ".md") + outs = strings.Replace(outs, "_", "-", -1) + return "#" + outs +} + +func getHeader(cmd *cobra.Command) (string, error) { + if dirExists(headerFilepath) { + return readFileContent(headerFilepath) + } + name := cmd.CommandPath() + return fmt.Sprintf("# %s\n\nKnative Client plugin `%s`\n", name, name), nil +} + +func getFooter() (string, error) { + if dirExists(footerFilepath) { + return readFileContent(footerFilepath) + } + return `## More information + +* [Knative Client](https://github.com/knative/client) +* [How to contribute a plugin](https://github.com/knative/client-contrib#how-to-contribute-a-plugin) +`, nil +} + +func readFileContent(path string) (string, error) { + data, err := ioutil.ReadFile(path) + if err != nil { + return "", err + } + return string(data), nil +} + +func dirExists(path string) bool { + if _, err := os.Stat(path); !os.IsNotExist(err) { + return true + } + return false +} diff --git a/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/util/flags_helper.go b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/util/flags_helper.go new file mode 100644 index 00000000..30cb9468 --- /dev/null +++ b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/pkg/util/flags_helper.go @@ -0,0 +1,35 @@ +// Copyright © 2020 The Knative 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 util + +import ( + corev1 "k8s.io/api/core/v1" + duckv1 "knative.dev/pkg/apis/duck/v1" + duckv1beta1 "knative.dev/pkg/apis/duck/v1beta1" +) + +// SinkToDuckV1Beta1 converts a Destination from duckv1 to duckv1beta1 +func SinkToDuckV1Beta1(destination *duckv1.Destination) *duckv1beta1.Destination { + r := destination.Ref + return &duckv1beta1.Destination{ + Ref: &corev1.ObjectReference{ + Kind: r.Kind, + Namespace: r.Namespace, + Name: r.Name, + APIVersion: r.APIVersion, + }, + URI: destination.URI, + } +} diff --git a/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/test/e2e/common.go b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/test/e2e/common.go new file mode 100644 index 00000000..e78f105c --- /dev/null +++ b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/test/e2e/common.go @@ -0,0 +1,56 @@ +// Copyright 2020 The Knative 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 e2e + +import ( + "knative.dev/client/lib/test" +) + +type E2ETest struct { + knTest *test.KnTest + knPlugin *knPlugin +} + +// NewE2ETest for pluginName in pluginPath +func NewE2ETest(pluginName string, pluginPath string, install bool) (*E2ETest, error) { + knTest, err := test.NewKnTest() + if err != nil { + return nil, err + } + + knPlugin := &knPlugin{ + kn: knTest.Kn(), + pluginName: pluginName, + pluginPath: pluginPath, + install: install, + } + + e2eTest := &E2ETest{ + knTest: knTest, + knPlugin: knPlugin, + } + + return e2eTest, nil +} + +// KnTest object +func (e2eTest *E2ETest) KnTest() *test.KnTest { + return e2eTest.knTest +} + +// KnPlugin object +func (e2eTest *E2ETest) KnPlugin() *knPlugin { + return e2eTest.knPlugin +} diff --git a/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/test/e2e/kn_plugin.go b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/test/e2e/kn_plugin.go new file mode 100644 index 00000000..609705ca --- /dev/null +++ b/plugins/source-github/vendor/github.com/maximilien/kn-source-pkg/test/e2e/kn_plugin.go @@ -0,0 +1,162 @@ +// Copyright 2020 The Knative 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 e2e + +import ( + "fmt" + "io/ioutil" + "os" + "path/filepath" + "runtime" + "strings" + + homedir "github.com/mitchellh/go-homedir" + "knative.dev/client/lib/test" +) + +type knPlugin struct { + kn test.Kn + pluginName string + pluginPath string + install bool +} + +// Run the KnPlugin returning a KnRunResult +func (kp *knPlugin) Run(args ...string) test.KnRunResult { + if kp.install { + err := kp.Install() + if err != nil { + fmt.Printf("error installing kn plugin: %s\n", err.Error()) + return test.KnRunResult{} + } + defer kp.Uninstall() + } + return RunKnPlugin(kp.kn.Namespace(), kp.pluginName, args) +} + +// Kn object to run `kn` +func (kp *knPlugin) Kn() test.Kn { + return kp.kn +} + +// Install the KnPlugin +func (kp *knPlugin) Install() error { + configDir, err := defaultConfigDir() + if err != nil { + fmt.Printf("error determining config directory: %s\n", err.Error()) + return err + } + + pluginDir := filepath.Join(configDir, "plugins") + if !dirExists(pluginDir) { + err = os.MkdirAll(pluginDir, 0700) + if err != nil { + return err + } + } + + fmt.Printf("installing 'kn' plugin '%s' from path '%s' to config path: %s\n", kp.pluginName, kp.pluginPath, configDir) + + err = copyPluginFile(filepath.Join(kp.pluginPath, kp.pluginName), filepath.Join(pluginDir, kp.pluginName)) + if err != nil { + fmt.Printf("error copying plugin file to config directory: %s\n", err.Error()) + return err + } + + return nil +} + +// Uninstall the KnPlugin +func (kp *knPlugin) Uninstall() error { + configDir, err := defaultConfigDir() + if err != nil { + fmt.Printf("error determining config directory: %s\n", err.Error()) + return err + } + + fmt.Printf("uninstalling 'kn' plugin '%s' from config path '%s'\n", kp.pluginName, configDir) + + err = os.Remove(filepath.Join(configDir, "plugins", kp.pluginName)) + if err != nil { + fmt.Printf("error removing plugin from config directory: %s\n", err.Error()) + return err + } + + return nil +} + +// Utility functions + +func copyPluginFile(sourceFile string, destDir string) error { + input, err := ioutil.ReadFile(sourceFile) + if err != nil { + return err + } + + err = ioutil.WriteFile(destDir, input, 0700) + if err != nil { + return err + } + + return nil +} + +func defaultConfigDir() (string, error) { + home, err := homedir.Dir() + if err != nil { + fmt.Fprintf(os.Stderr, "%v\n", err) + os.Exit(1) + } + // Check the deprecated path first and fallback to it, add warning to error message + if configHome := filepath.Join(home, ".kn"); dirExists(configHome) { + migrationPath := filepath.Join(home, ".config", "kn") + if runtime.GOOS == "windows" { + migrationPath = filepath.Join(os.Getenv("APPDATA"), "kn") + } + return configHome, fmt.Errorf("WARNING: deprecated kn config directory detected. "+ + "Please move your configuration to: %s", migrationPath) + } + // Respect %APPDATA% on MS Windows + // C:\Documents and Settings\username\Application JsonData + if runtime.GOOS == "windows" { + return filepath.Join(os.Getenv("APPDATA"), "kn"), nil + } + // Respect XDG_CONFIG_HOME if set + if xdgHome := os.Getenv("XDG_CONFIG_HOME"); xdgHome != "" { + return filepath.Join(xdgHome, "kn"), nil + } + // Fallback to XDG default for both Linux and macOS + // ~/.config/kn + return filepath.Join(home, ".config", "kn"), nil +} + +func dirExists(path string) bool { + if _, err := os.Stat(path); !os.IsNotExist(err) { + return true + } + return false +} + +func pluginArgs(pluginName string) []string { + pluginParts := strings.Split(pluginName, "-") + return pluginParts[1:] +} + +func RunKnPlugin(namespace string, pluginName string, args []string) test.KnRunResult { + pluginArgs := pluginArgs(pluginName) + args = append(args, []string{"--namespace", namespace}...) + argsWithPlugin := append(pluginArgs, args...) + return test.RunKn(namespace, argsWithPlugin) +} diff --git a/plugins/source-github/vendor/github.com/mitchellh/go-homedir/LICENSE b/plugins/source-github/vendor/github.com/mitchellh/go-homedir/LICENSE new file mode 100644 index 00000000..f9c841a5 --- /dev/null +++ b/plugins/source-github/vendor/github.com/mitchellh/go-homedir/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2013 Mitchell Hashimoto + +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. diff --git a/plugins/source-github/vendor/github.com/mitchellh/go-homedir/README.md b/plugins/source-github/vendor/github.com/mitchellh/go-homedir/README.md new file mode 100644 index 00000000..d70706d5 --- /dev/null +++ b/plugins/source-github/vendor/github.com/mitchellh/go-homedir/README.md @@ -0,0 +1,14 @@ +# go-homedir + +This is a Go library for detecting the user's home directory without +the use of cgo, so the library can be used in cross-compilation environments. + +Usage is incredibly simple, just call `homedir.Dir()` to get the home directory +for a user, and `homedir.Expand()` to expand the `~` in a path to the home +directory. + +**Why not just use `os/user`?** The built-in `os/user` package requires +cgo on Darwin systems. This means that any Go code that uses that package +cannot cross compile. But 99% of the time the use for `os/user` is just to +retrieve the home directory, which we can do for the current user without +cgo. This library does that, enabling cross-compilation. diff --git a/plugins/source-github/vendor/github.com/mitchellh/go-homedir/go.mod b/plugins/source-github/vendor/github.com/mitchellh/go-homedir/go.mod new file mode 100644 index 00000000..7efa09a0 --- /dev/null +++ b/plugins/source-github/vendor/github.com/mitchellh/go-homedir/go.mod @@ -0,0 +1 @@ +module github.com/mitchellh/go-homedir diff --git a/plugins/source-github/vendor/github.com/mitchellh/go-homedir/homedir.go b/plugins/source-github/vendor/github.com/mitchellh/go-homedir/homedir.go new file mode 100644 index 00000000..25378537 --- /dev/null +++ b/plugins/source-github/vendor/github.com/mitchellh/go-homedir/homedir.go @@ -0,0 +1,167 @@ +package homedir + +import ( + "bytes" + "errors" + "os" + "os/exec" + "path/filepath" + "runtime" + "strconv" + "strings" + "sync" +) + +// DisableCache will disable caching of the home directory. Caching is enabled +// by default. +var DisableCache bool + +var homedirCache string +var cacheLock sync.RWMutex + +// Dir returns the home directory for the executing user. +// +// This uses an OS-specific method for discovering the home directory. +// An error is returned if a home directory cannot be detected. +func Dir() (string, error) { + if !DisableCache { + cacheLock.RLock() + cached := homedirCache + cacheLock.RUnlock() + if cached != "" { + return cached, nil + } + } + + cacheLock.Lock() + defer cacheLock.Unlock() + + var result string + var err error + if runtime.GOOS == "windows" { + result, err = dirWindows() + } else { + // Unix-like system, so just assume Unix + result, err = dirUnix() + } + + if err != nil { + return "", err + } + homedirCache = result + return result, nil +} + +// Expand expands the path to include the home directory if the path +// is prefixed with `~`. If it isn't prefixed with `~`, the path is +// returned as-is. +func Expand(path string) (string, error) { + if len(path) == 0 { + return path, nil + } + + if path[0] != '~' { + return path, nil + } + + if len(path) > 1 && path[1] != '/' && path[1] != '\\' { + return "", errors.New("cannot expand user-specific home dir") + } + + dir, err := Dir() + if err != nil { + return "", err + } + + return filepath.Join(dir, path[1:]), nil +} + +// Reset clears the cache, forcing the next call to Dir to re-detect +// the home directory. This generally never has to be called, but can be +// useful in tests if you're modifying the home directory via the HOME +// env var or something. +func Reset() { + cacheLock.Lock() + defer cacheLock.Unlock() + homedirCache = "" +} + +func dirUnix() (string, error) { + homeEnv := "HOME" + if runtime.GOOS == "plan9" { + // On plan9, env vars are lowercase. + homeEnv = "home" + } + + // First prefer the HOME environmental variable + if home := os.Getenv(homeEnv); home != "" { + return home, nil + } + + var stdout bytes.Buffer + + // If that fails, try OS specific commands + if runtime.GOOS == "darwin" { + cmd := exec.Command("sh", "-c", `dscl -q . -read /Users/"$(whoami)" NFSHomeDirectory | sed 's/^[^ ]*: //'`) + cmd.Stdout = &stdout + if err := cmd.Run(); err == nil { + result := strings.TrimSpace(stdout.String()) + if result != "" { + return result, nil + } + } + } else { + cmd := exec.Command("getent", "passwd", strconv.Itoa(os.Getuid())) + cmd.Stdout = &stdout + if err := cmd.Run(); err != nil { + // If the error is ErrNotFound, we ignore it. Otherwise, return it. + if err != exec.ErrNotFound { + return "", err + } + } else { + if passwd := strings.TrimSpace(stdout.String()); passwd != "" { + // username:password:uid:gid:gecos:home:shell + passwdParts := strings.SplitN(passwd, ":", 7) + if len(passwdParts) > 5 { + return passwdParts[5], nil + } + } + } + } + + // If all else fails, try the shell + stdout.Reset() + cmd := exec.Command("sh", "-c", "cd && pwd") + cmd.Stdout = &stdout + if err := cmd.Run(); err != nil { + return "", err + } + + result := strings.TrimSpace(stdout.String()) + if result == "" { + return "", errors.New("blank output when reading home directory") + } + + return result, nil +} + +func dirWindows() (string, error) { + // First prefer the HOME environmental variable + if home := os.Getenv("HOME"); home != "" { + return home, nil + } + + // Prefer standard environment variable USERPROFILE + if home := os.Getenv("USERPROFILE"); home != "" { + return home, nil + } + + drive := os.Getenv("HOMEDRIVE") + path := os.Getenv("HOMEPATH") + home := drive + path + if drive == "" || path == "" { + return "", errors.New("HOMEDRIVE, HOMEPATH, or USERPROFILE are blank") + } + + return home, nil +} diff --git a/plugins/source-github/vendor/github.com/russross/blackfriday/v2/.gitignore b/plugins/source-github/vendor/github.com/russross/blackfriday/v2/.gitignore new file mode 100644 index 00000000..75623dcc --- /dev/null +++ b/plugins/source-github/vendor/github.com/russross/blackfriday/v2/.gitignore @@ -0,0 +1,8 @@ +*.out +*.swp +*.8 +*.6 +_obj +_test* +markdown +tags diff --git a/plugins/source-github/vendor/github.com/russross/blackfriday/v2/.travis.yml b/plugins/source-github/vendor/github.com/russross/blackfriday/v2/.travis.yml new file mode 100644 index 00000000..b0b525a5 --- /dev/null +++ b/plugins/source-github/vendor/github.com/russross/blackfriday/v2/.travis.yml @@ -0,0 +1,17 @@ +sudo: false +language: go +go: + - "1.10.x" + - "1.11.x" + - tip +matrix: + fast_finish: true + allow_failures: + - go: tip +install: + - # Do nothing. This is needed to prevent default install action "go get -t -v ./..." from happening here (we want it to happen inside script step). +script: + - go get -t -v ./... + - diff -u <(echo -n) <(gofmt -d -s .) + - go tool vet . + - go test -v ./... diff --git a/plugins/source-github/vendor/github.com/russross/blackfriday/v2/LICENSE.txt b/plugins/source-github/vendor/github.com/russross/blackfriday/v2/LICENSE.txt new file mode 100644 index 00000000..2885af36 --- /dev/null +++ b/plugins/source-github/vendor/github.com/russross/blackfriday/v2/LICENSE.txt @@ -0,0 +1,29 @@ +Blackfriday is distributed under the Simplified BSD License: + +> Copyright © 2011 Russ Ross +> All rights reserved. +> +> Redistribution and use in source and binary forms, with or without +> modification, are permitted provided that the following conditions +> are met: +> +> 1. Redistributions of source code must retain the above copyright +> notice, this list of conditions and the following disclaimer. +> +> 2. Redistributions in binary form must reproduce the above +> copyright notice, this list of conditions and the following +> disclaimer in the documentation and/or other materials provided with +> the distribution. +> +> THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +> "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +> LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +> FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE +> COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, +> INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +> BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +> LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +> CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +> LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN +> ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +> POSSIBILITY OF SUCH DAMAGE. diff --git a/plugins/source-github/vendor/github.com/russross/blackfriday/v2/README.md b/plugins/source-github/vendor/github.com/russross/blackfriday/v2/README.md new file mode 100644 index 00000000..d5a8649b --- /dev/null +++ b/plugins/source-github/vendor/github.com/russross/blackfriday/v2/README.md @@ -0,0 +1,291 @@ +Blackfriday [![Build Status](https://travis-ci.org/russross/blackfriday.svg?branch=master)](https://travis-ci.org/russross/blackfriday) +=========== + +Blackfriday is a [Markdown][1] processor implemented in [Go][2]. It +is paranoid about its input (so you can safely feed it user-supplied +data), it is fast, it supports common extensions (tables, smart +punctuation substitutions, etc.), and it is safe for all utf-8 +(unicode) input. + +HTML output is currently supported, along with Smartypants +extensions. + +It started as a translation from C of [Sundown][3]. + + +Installation +------------ + +Blackfriday is compatible with any modern Go release. With Go 1.7 and git +installed: + + go get gopkg.in/russross/blackfriday.v2 + +will download, compile, and install the package into your `$GOPATH` +directory hierarchy. Alternatively, you can achieve the same if you +import it into a project: + + import "gopkg.in/russross/blackfriday.v2" + +and `go get` without parameters. + + +Versions +-------- + +Currently maintained and recommended version of Blackfriday is `v2`. It's being +developed on its own branch: https://github.com/russross/blackfriday/tree/v2 and the +documentation is available at +https://godoc.org/gopkg.in/russross/blackfriday.v2. + +It is `go get`-able via via [gopkg.in][6] at `gopkg.in/russross/blackfriday.v2`, +but we highly recommend using package management tool like [dep][7] or +[Glide][8] and make use of semantic versioning. With package management you +should import `github.com/russross/blackfriday` and specify that you're using +version 2.0.0. + +Version 2 offers a number of improvements over v1: + +* Cleaned up API +* A separate call to [`Parse`][4], which produces an abstract syntax tree for + the document +* Latest bug fixes +* Flexibility to easily add your own rendering extensions + +Potential drawbacks: + +* Our benchmarks show v2 to be slightly slower than v1. Currently in the + ballpark of around 15%. +* API breakage. If you can't afford modifying your code to adhere to the new API + and don't care too much about the new features, v2 is probably not for you. +* Several bug fixes are trailing behind and still need to be forward-ported to + v2. See issue [#348](https://github.com/russross/blackfriday/issues/348) for + tracking. + +Usage +----- + +For the most sensible markdown processing, it is as simple as getting your input +into a byte slice and calling: + +```go +output := blackfriday.Run(input) +``` + +Your input will be parsed and the output rendered with a set of most popular +extensions enabled. If you want the most basic feature set, corresponding with +the bare Markdown specification, use: + +```go +output := blackfriday.Run(input, blackfriday.WithNoExtensions()) +``` + +### Sanitize untrusted content + +Blackfriday itself does nothing to protect against malicious content. If you are +dealing with user-supplied markdown, we recommend running Blackfriday's output +through HTML sanitizer such as [Bluemonday][5]. + +Here's an example of simple usage of Blackfriday together with Bluemonday: + +```go +import ( + "github.com/microcosm-cc/bluemonday" + "github.com/russross/blackfriday" +) + +// ... +unsafe := blackfriday.Run(input) +html := bluemonday.UGCPolicy().SanitizeBytes(unsafe) +``` + +### Custom options + +If you want to customize the set of options, use `blackfriday.WithExtensions`, +`blackfriday.WithRenderer` and `blackfriday.WithRefOverride`. + +You can also check out `blackfriday-tool` for a more complete example +of how to use it. Download and install it using: + + go get github.com/russross/blackfriday-tool + +This is a simple command-line tool that allows you to process a +markdown file using a standalone program. You can also browse the +source directly on github if you are just looking for some example +code: + +* + +Note that if you have not already done so, installing +`blackfriday-tool` will be sufficient to download and install +blackfriday in addition to the tool itself. The tool binary will be +installed in `$GOPATH/bin`. This is a statically-linked binary that +can be copied to wherever you need it without worrying about +dependencies and library versions. + + +Features +-------- + +All features of Sundown are supported, including: + +* **Compatibility**. The Markdown v1.0.3 test suite passes with + the `--tidy` option. Without `--tidy`, the differences are + mostly in whitespace and entity escaping, where blackfriday is + more consistent and cleaner. + +* **Common extensions**, including table support, fenced code + blocks, autolinks, strikethroughs, non-strict emphasis, etc. + +* **Safety**. Blackfriday is paranoid when parsing, making it safe + to feed untrusted user input without fear of bad things + happening. The test suite stress tests this and there are no + known inputs that make it crash. If you find one, please let me + know and send me the input that does it. + + NOTE: "safety" in this context means *runtime safety only*. In order to + protect yourself against JavaScript injection in untrusted content, see + [this example](https://github.com/russross/blackfriday#sanitize-untrusted-content). + +* **Fast processing**. It is fast enough to render on-demand in + most web applications without having to cache the output. + +* **Thread safety**. You can run multiple parsers in different + goroutines without ill effect. There is no dependence on global + shared state. + +* **Minimal dependencies**. Blackfriday only depends on standard + library packages in Go. The source code is pretty + self-contained, so it is easy to add to any project, including + Google App Engine projects. + +* **Standards compliant**. Output successfully validates using the + W3C validation tool for HTML 4.01 and XHTML 1.0 Transitional. + + +Extensions +---------- + +In addition to the standard markdown syntax, this package +implements the following extensions: + +* **Intra-word emphasis supression**. The `_` character is + commonly used inside words when discussing code, so having + markdown interpret it as an emphasis command is usually the + wrong thing. Blackfriday lets you treat all emphasis markers as + normal characters when they occur inside a word. + +* **Tables**. Tables can be created by drawing them in the input + using a simple syntax: + + ``` + Name | Age + --------|------ + Bob | 27 + Alice | 23 + ``` + +* **Fenced code blocks**. In addition to the normal 4-space + indentation to mark code blocks, you can explicitly mark them + and supply a language (to make syntax highlighting simple). Just + mark it like this: + + ```go + func getTrue() bool { + return true + } + ``` + + You can use 3 or more backticks to mark the beginning of the + block, and the same number to mark the end of the block. + +* **Definition lists**. A simple definition list is made of a single-line + term followed by a colon and the definition for that term. + + Cat + : Fluffy animal everyone likes + + Internet + : Vector of transmission for pictures of cats + + Terms must be separated from the previous definition by a blank line. + +* **Footnotes**. A marker in the text that will become a superscript number; + a footnote definition that will be placed in a list of footnotes at the + end of the document. A footnote looks like this: + + This is a footnote.[^1] + + [^1]: the footnote text. + +* **Autolinking**. Blackfriday can find URLs that have not been + explicitly marked as links and turn them into links. + +* **Strikethrough**. Use two tildes (`~~`) to mark text that + should be crossed out. + +* **Hard line breaks**. With this extension enabled newlines in the input + translate into line breaks in the output. This extension is off by default. + +* **Smart quotes**. Smartypants-style punctuation substitution is + supported, turning normal double- and single-quote marks into + curly quotes, etc. + +* **LaTeX-style dash parsing** is an additional option, where `--` + is translated into `–`, and `---` is translated into + `—`. This differs from most smartypants processors, which + turn a single hyphen into an ndash and a double hyphen into an + mdash. + +* **Smart fractions**, where anything that looks like a fraction + is translated into suitable HTML (instead of just a few special + cases like most smartypant processors). For example, `4/5` + becomes `45`, which renders as + 45. + + +Other renderers +--------------- + +Blackfriday is structured to allow alternative rendering engines. Here +are a few of note: + +* [github_flavored_markdown](https://godoc.org/github.com/shurcooL/github_flavored_markdown): + provides a GitHub Flavored Markdown renderer with fenced code block + highlighting, clickable heading anchor links. + + It's not customizable, and its goal is to produce HTML output + equivalent to the [GitHub Markdown API endpoint](https://developer.github.com/v3/markdown/#render-a-markdown-document-in-raw-mode), + except the rendering is performed locally. + +* [markdownfmt](https://github.com/shurcooL/markdownfmt): like gofmt, + but for markdown. + +* [LaTeX output](https://github.com/Ambrevar/Blackfriday-LaTeX): + renders output as LaTeX. + +* [Blackfriday-Confluence](https://github.com/kentaro-m/blackfriday-confluence): provides a [Confluence Wiki Markup](https://confluence.atlassian.com/doc/confluence-wiki-markup-251003035.html) renderer. + + +Todo +---- + +* More unit testing +* Improve unicode support. It does not understand all unicode + rules (about what constitutes a letter, a punctuation symbol, + etc.), so it may fail to detect word boundaries correctly in + some instances. It is safe on all utf-8 input. + + +License +------- + +[Blackfriday is distributed under the Simplified BSD License](LICENSE.txt) + + + [1]: https://daringfireball.net/projects/markdown/ "Markdown" + [2]: https://golang.org/ "Go Language" + [3]: https://github.com/vmg/sundown "Sundown" + [4]: https://godoc.org/gopkg.in/russross/blackfriday.v2#Parse "Parse func" + [5]: https://github.com/microcosm-cc/bluemonday "Bluemonday" + [6]: https://labix.org/gopkg.in "gopkg.in" diff --git a/plugins/source-github/vendor/github.com/russross/blackfriday/v2/block.go b/plugins/source-github/vendor/github.com/russross/blackfriday/v2/block.go new file mode 100644 index 00000000..b8607474 --- /dev/null +++ b/plugins/source-github/vendor/github.com/russross/blackfriday/v2/block.go @@ -0,0 +1,1590 @@ +// +// Blackfriday Markdown Processor +// Available at http://github.com/russross/blackfriday +// +// Copyright © 2011 Russ Ross . +// Distributed under the Simplified BSD License. +// See README.md for details. +// + +// +// Functions to parse block-level elements. +// + +package blackfriday + +import ( + "bytes" + "html" + "regexp" + "strings" + + "github.com/shurcooL/sanitized_anchor_name" +) + +const ( + charEntity = "&(?:#x[a-f0-9]{1,8}|#[0-9]{1,8}|[a-z][a-z0-9]{1,31});" + escapable = "[!\"#$%&'()*+,./:;<=>?@[\\\\\\]^_`{|}~-]" +) + +var ( + reBackslashOrAmp = regexp.MustCompile("[\\&]") + reEntityOrEscapedChar = regexp.MustCompile("(?i)\\\\" + escapable + "|" + charEntity) +) + +// Parse block-level data. +// Note: this function and many that it calls assume that +// the input buffer ends with a newline. +func (p *Markdown) block(data []byte) { + // this is called recursively: enforce a maximum depth + if p.nesting >= p.maxNesting { + return + } + p.nesting++ + + // parse out one block-level construct at a time + for len(data) > 0 { + // prefixed heading: + // + // # Heading 1 + // ## Heading 2 + // ... + // ###### Heading 6 + if p.isPrefixHeading(data) { + data = data[p.prefixHeading(data):] + continue + } + + // block of preformatted HTML: + // + //
+ // ... + //
+ if data[0] == '<' { + if i := p.html(data, true); i > 0 { + data = data[i:] + continue + } + } + + // title block + // + // % stuff + // % more stuff + // % even more stuff + if p.extensions&Titleblock != 0 { + if data[0] == '%' { + if i := p.titleBlock(data, true); i > 0 { + data = data[i:] + continue + } + } + } + + // blank lines. note: returns the # of bytes to skip + if i := p.isEmpty(data); i > 0 { + data = data[i:] + continue + } + + // indented code block: + // + // func max(a, b int) int { + // if a > b { + // return a + // } + // return b + // } + if p.codePrefix(data) > 0 { + data = data[p.code(data):] + continue + } + + // fenced code block: + // + // ``` go + // func fact(n int) int { + // if n <= 1 { + // return n + // } + // return n * fact(n-1) + // } + // ``` + if p.extensions&FencedCode != 0 { + if i := p.fencedCodeBlock(data, true); i > 0 { + data = data[i:] + continue + } + } + + // horizontal rule: + // + // ------ + // or + // ****** + // or + // ______ + if p.isHRule(data) { + p.addBlock(HorizontalRule, nil) + var i int + for i = 0; i < len(data) && data[i] != '\n'; i++ { + } + data = data[i:] + continue + } + + // block quote: + // + // > A big quote I found somewhere + // > on the web + if p.quotePrefix(data) > 0 { + data = data[p.quote(data):] + continue + } + + // table: + // + // Name | Age | Phone + // ------|-----|--------- + // Bob | 31 | 555-1234 + // Alice | 27 | 555-4321 + if p.extensions&Tables != 0 { + if i := p.table(data); i > 0 { + data = data[i:] + continue + } + } + + // an itemized/unordered list: + // + // * Item 1 + // * Item 2 + // + // also works with + or - + if p.uliPrefix(data) > 0 { + data = data[p.list(data, 0):] + continue + } + + // a numbered/ordered list: + // + // 1. Item 1 + // 2. Item 2 + if p.oliPrefix(data) > 0 { + data = data[p.list(data, ListTypeOrdered):] + continue + } + + // definition lists: + // + // Term 1 + // : Definition a + // : Definition b + // + // Term 2 + // : Definition c + if p.extensions&DefinitionLists != 0 { + if p.dliPrefix(data) > 0 { + data = data[p.list(data, ListTypeDefinition):] + continue + } + } + + // anything else must look like a normal paragraph + // note: this finds underlined headings, too + data = data[p.paragraph(data):] + } + + p.nesting-- +} + +func (p *Markdown) addBlock(typ NodeType, content []byte) *Node { + p.closeUnmatchedBlocks() + container := p.addChild(typ, 0) + container.content = content + return container +} + +func (p *Markdown) isPrefixHeading(data []byte) bool { + if data[0] != '#' { + return false + } + + if p.extensions&SpaceHeadings != 0 { + level := 0 + for level < 6 && level < len(data) && data[level] == '#' { + level++ + } + if level == len(data) || data[level] != ' ' { + return false + } + } + return true +} + +func (p *Markdown) prefixHeading(data []byte) int { + level := 0 + for level < 6 && level < len(data) && data[level] == '#' { + level++ + } + i := skipChar(data, level, ' ') + end := skipUntilChar(data, i, '\n') + skip := end + id := "" + if p.extensions&HeadingIDs != 0 { + j, k := 0, 0 + // find start/end of heading id + for j = i; j < end-1 && (data[j] != '{' || data[j+1] != '#'); j++ { + } + for k = j + 1; k < end && data[k] != '}'; k++ { + } + // extract heading id iff found + if j < end && k < end { + id = string(data[j+2 : k]) + end = j + skip = k + 1 + for end > 0 && data[end-1] == ' ' { + end-- + } + } + } + for end > 0 && data[end-1] == '#' { + if isBackslashEscaped(data, end-1) { + break + } + end-- + } + for end > 0 && data[end-1] == ' ' { + end-- + } + if end > i { + if id == "" && p.extensions&AutoHeadingIDs != 0 { + id = sanitized_anchor_name.Create(string(data[i:end])) + } + block := p.addBlock(Heading, data[i:end]) + block.HeadingID = id + block.Level = level + } + return skip +} + +func (p *Markdown) isUnderlinedHeading(data []byte) int { + // test of level 1 heading + if data[0] == '=' { + i := skipChar(data, 1, '=') + i = skipChar(data, i, ' ') + if i < len(data) && data[i] == '\n' { + return 1 + } + return 0 + } + + // test of level 2 heading + if data[0] == '-' { + i := skipChar(data, 1, '-') + i = skipChar(data, i, ' ') + if i < len(data) && data[i] == '\n' { + return 2 + } + return 0 + } + + return 0 +} + +func (p *Markdown) titleBlock(data []byte, doRender bool) int { + if data[0] != '%' { + return 0 + } + splitData := bytes.Split(data, []byte("\n")) + var i int + for idx, b := range splitData { + if !bytes.HasPrefix(b, []byte("%")) { + i = idx // - 1 + break + } + } + + data = bytes.Join(splitData[0:i], []byte("\n")) + consumed := len(data) + data = bytes.TrimPrefix(data, []byte("% ")) + data = bytes.Replace(data, []byte("\n% "), []byte("\n"), -1) + block := p.addBlock(Heading, data) + block.Level = 1 + block.IsTitleblock = true + + return consumed +} + +func (p *Markdown) html(data []byte, doRender bool) int { + var i, j int + + // identify the opening tag + if data[0] != '<' { + return 0 + } + curtag, tagfound := p.htmlFindTag(data[1:]) + + // handle special cases + if !tagfound { + // check for an HTML comment + if size := p.htmlComment(data, doRender); size > 0 { + return size + } + + // check for an
tag + if size := p.htmlHr(data, doRender); size > 0 { + return size + } + + // no special case recognized + return 0 + } + + // look for an unindented matching closing tag + // followed by a blank line + found := false + /* + closetag := []byte("\n") + j = len(curtag) + 1 + for !found { + // scan for a closing tag at the beginning of a line + if skip := bytes.Index(data[j:], closetag); skip >= 0 { + j += skip + len(closetag) + } else { + break + } + + // see if it is the only thing on the line + if skip := p.isEmpty(data[j:]); skip > 0 { + // see if it is followed by a blank line/eof + j += skip + if j >= len(data) { + found = true + i = j + } else { + if skip := p.isEmpty(data[j:]); skip > 0 { + j += skip + found = true + i = j + } + } + } + } + */ + + // if not found, try a second pass looking for indented match + // but not if tag is "ins" or "del" (following original Markdown.pl) + if !found && curtag != "ins" && curtag != "del" { + i = 1 + for i < len(data) { + i++ + for i < len(data) && !(data[i-1] == '<' && data[i] == '/') { + i++ + } + + if i+2+len(curtag) >= len(data) { + break + } + + j = p.htmlFindEnd(curtag, data[i-1:]) + + if j > 0 { + i += j - 1 + found = true + break + } + } + } + + if !found { + return 0 + } + + // the end of the block has been found + if doRender { + // trim newlines + end := i + for end > 0 && data[end-1] == '\n' { + end-- + } + finalizeHTMLBlock(p.addBlock(HTMLBlock, data[:end])) + } + + return i +} + +func finalizeHTMLBlock(block *Node) { + block.Literal = block.content + block.content = nil +} + +// HTML comment, lax form +func (p *Markdown) htmlComment(data []byte, doRender bool) int { + i := p.inlineHTMLComment(data) + // needs to end with a blank line + if j := p.isEmpty(data[i:]); j > 0 { + size := i + j + if doRender { + // trim trailing newlines + end := size + for end > 0 && data[end-1] == '\n' { + end-- + } + block := p.addBlock(HTMLBlock, data[:end]) + finalizeHTMLBlock(block) + } + return size + } + return 0 +} + +// HR, which is the only self-closing block tag considered +func (p *Markdown) htmlHr(data []byte, doRender bool) int { + if len(data) < 4 { + return 0 + } + if data[0] != '<' || (data[1] != 'h' && data[1] != 'H') || (data[2] != 'r' && data[2] != 'R') { + return 0 + } + if data[3] != ' ' && data[3] != '/' && data[3] != '>' { + // not an
tag after all; at least not a valid one + return 0 + } + i := 3 + for i < len(data) && data[i] != '>' && data[i] != '\n' { + i++ + } + if i < len(data) && data[i] == '>' { + i++ + if j := p.isEmpty(data[i:]); j > 0 { + size := i + j + if doRender { + // trim newlines + end := size + for end > 0 && data[end-1] == '\n' { + end-- + } + finalizeHTMLBlock(p.addBlock(HTMLBlock, data[:end])) + } + return size + } + } + return 0 +} + +func (p *Markdown) htmlFindTag(data []byte) (string, bool) { + i := 0 + for i < len(data) && isalnum(data[i]) { + i++ + } + key := string(data[:i]) + if _, ok := blockTags[key]; ok { + return key, true + } + return "", false +} + +func (p *Markdown) htmlFindEnd(tag string, data []byte) int { + // assume data[0] == '<' && data[1] == '/' already tested + if tag == "hr" { + return 2 + } + // check if tag is a match + closetag := []byte("") + if !bytes.HasPrefix(data, closetag) { + return 0 + } + i := len(closetag) + + // check that the rest of the line is blank + skip := 0 + if skip = p.isEmpty(data[i:]); skip == 0 { + return 0 + } + i += skip + skip = 0 + + if i >= len(data) { + return i + } + + if p.extensions&LaxHTMLBlocks != 0 { + return i + } + if skip = p.isEmpty(data[i:]); skip == 0 { + // following line must be blank + return 0 + } + + return i + skip +} + +func (*Markdown) isEmpty(data []byte) int { + // it is okay to call isEmpty on an empty buffer + if len(data) == 0 { + return 0 + } + + var i int + for i = 0; i < len(data) && data[i] != '\n'; i++ { + if data[i] != ' ' && data[i] != '\t' { + return 0 + } + } + if i < len(data) && data[i] == '\n' { + i++ + } + return i +} + +func (*Markdown) isHRule(data []byte) bool { + i := 0 + + // skip up to three spaces + for i < 3 && data[i] == ' ' { + i++ + } + + // look at the hrule char + if data[i] != '*' && data[i] != '-' && data[i] != '_' { + return false + } + c := data[i] + + // the whole line must be the char or whitespace + n := 0 + for i < len(data) && data[i] != '\n' { + switch { + case data[i] == c: + n++ + case data[i] != ' ': + return false + } + i++ + } + + return n >= 3 +} + +// isFenceLine checks if there's a fence line (e.g., ``` or ``` go) at the beginning of data, +// and returns the end index if so, or 0 otherwise. It also returns the marker found. +// If info is not nil, it gets set to the syntax specified in the fence line. +func isFenceLine(data []byte, info *string, oldmarker string) (end int, marker string) { + i, size := 0, 0 + + // skip up to three spaces + for i < len(data) && i < 3 && data[i] == ' ' { + i++ + } + + // check for the marker characters: ~ or ` + if i >= len(data) { + return 0, "" + } + if data[i] != '~' && data[i] != '`' { + return 0, "" + } + + c := data[i] + + // the whole line must be the same char or whitespace + for i < len(data) && data[i] == c { + size++ + i++ + } + + // the marker char must occur at least 3 times + if size < 3 { + return 0, "" + } + marker = string(data[i-size : i]) + + // if this is the end marker, it must match the beginning marker + if oldmarker != "" && marker != oldmarker { + return 0, "" + } + + // TODO(shurcooL): It's probably a good idea to simplify the 2 code paths here + // into one, always get the info string, and discard it if the caller doesn't care. + if info != nil { + infoLength := 0 + i = skipChar(data, i, ' ') + + if i >= len(data) { + if i == len(data) { + return i, marker + } + return 0, "" + } + + infoStart := i + + if data[i] == '{' { + i++ + infoStart++ + + for i < len(data) && data[i] != '}' && data[i] != '\n' { + infoLength++ + i++ + } + + if i >= len(data) || data[i] != '}' { + return 0, "" + } + + // strip all whitespace at the beginning and the end + // of the {} block + for infoLength > 0 && isspace(data[infoStart]) { + infoStart++ + infoLength-- + } + + for infoLength > 0 && isspace(data[infoStart+infoLength-1]) { + infoLength-- + } + i++ + i = skipChar(data, i, ' ') + } else { + for i < len(data) && !isverticalspace(data[i]) { + infoLength++ + i++ + } + } + + *info = strings.TrimSpace(string(data[infoStart : infoStart+infoLength])) + } + + if i == len(data) { + return i, marker + } + if i > len(data) || data[i] != '\n' { + return 0, "" + } + return i + 1, marker // Take newline into account. +} + +// fencedCodeBlock returns the end index if data contains a fenced code block at the beginning, +// or 0 otherwise. It writes to out if doRender is true, otherwise it has no side effects. +// If doRender is true, a final newline is mandatory to recognize the fenced code block. +func (p *Markdown) fencedCodeBlock(data []byte, doRender bool) int { + var info string + beg, marker := isFenceLine(data, &info, "") + if beg == 0 || beg >= len(data) { + return 0 + } + + var work bytes.Buffer + work.Write([]byte(info)) + work.WriteByte('\n') + + for { + // safe to assume beg < len(data) + + // check for the end of the code block + fenceEnd, _ := isFenceLine(data[beg:], nil, marker) + if fenceEnd != 0 { + beg += fenceEnd + break + } + + // copy the current line + end := skipUntilChar(data, beg, '\n') + 1 + + // did we reach the end of the buffer without a closing marker? + if end >= len(data) { + return 0 + } + + // verbatim copy to the working buffer + if doRender { + work.Write(data[beg:end]) + } + beg = end + } + + if doRender { + block := p.addBlock(CodeBlock, work.Bytes()) // TODO: get rid of temp buffer + block.IsFenced = true + finalizeCodeBlock(block) + } + + return beg +} + +func unescapeChar(str []byte) []byte { + if str[0] == '\\' { + return []byte{str[1]} + } + return []byte(html.UnescapeString(string(str))) +} + +func unescapeString(str []byte) []byte { + if reBackslashOrAmp.Match(str) { + return reEntityOrEscapedChar.ReplaceAllFunc(str, unescapeChar) + } + return str +} + +func finalizeCodeBlock(block *Node) { + if block.IsFenced { + newlinePos := bytes.IndexByte(block.content, '\n') + firstLine := block.content[:newlinePos] + rest := block.content[newlinePos+1:] + block.Info = unescapeString(bytes.Trim(firstLine, "\n")) + block.Literal = rest + } else { + block.Literal = block.content + } + block.content = nil +} + +func (p *Markdown) table(data []byte) int { + table := p.addBlock(Table, nil) + i, columns := p.tableHeader(data) + if i == 0 { + p.tip = table.Parent + table.Unlink() + return 0 + } + + p.addBlock(TableBody, nil) + + for i < len(data) { + pipes, rowStart := 0, i + for ; i < len(data) && data[i] != '\n'; i++ { + if data[i] == '|' { + pipes++ + } + } + + if pipes == 0 { + i = rowStart + break + } + + // include the newline in data sent to tableRow + if i < len(data) && data[i] == '\n' { + i++ + } + p.tableRow(data[rowStart:i], columns, false) + } + + return i +} + +// check if the specified position is preceded by an odd number of backslashes +func isBackslashEscaped(data []byte, i int) bool { + backslashes := 0 + for i-backslashes-1 >= 0 && data[i-backslashes-1] == '\\' { + backslashes++ + } + return backslashes&1 == 1 +} + +func (p *Markdown) tableHeader(data []byte) (size int, columns []CellAlignFlags) { + i := 0 + colCount := 1 + for i = 0; i < len(data) && data[i] != '\n'; i++ { + if data[i] == '|' && !isBackslashEscaped(data, i) { + colCount++ + } + } + + // doesn't look like a table header + if colCount == 1 { + return + } + + // include the newline in the data sent to tableRow + j := i + if j < len(data) && data[j] == '\n' { + j++ + } + header := data[:j] + + // column count ignores pipes at beginning or end of line + if data[0] == '|' { + colCount-- + } + if i > 2 && data[i-1] == '|' && !isBackslashEscaped(data, i-1) { + colCount-- + } + + columns = make([]CellAlignFlags, colCount) + + // move on to the header underline + i++ + if i >= len(data) { + return + } + + if data[i] == '|' && !isBackslashEscaped(data, i) { + i++ + } + i = skipChar(data, i, ' ') + + // each column header is of form: / *:?-+:? *|/ with # dashes + # colons >= 3 + // and trailing | optional on last column + col := 0 + for i < len(data) && data[i] != '\n' { + dashes := 0 + + if data[i] == ':' { + i++ + columns[col] |= TableAlignmentLeft + dashes++ + } + for i < len(data) && data[i] == '-' { + i++ + dashes++ + } + if i < len(data) && data[i] == ':' { + i++ + columns[col] |= TableAlignmentRight + dashes++ + } + for i < len(data) && data[i] == ' ' { + i++ + } + if i == len(data) { + return + } + // end of column test is messy + switch { + case dashes < 3: + // not a valid column + return + + case data[i] == '|' && !isBackslashEscaped(data, i): + // marker found, now skip past trailing whitespace + col++ + i++ + for i < len(data) && data[i] == ' ' { + i++ + } + + // trailing junk found after last column + if col >= colCount && i < len(data) && data[i] != '\n' { + return + } + + case (data[i] != '|' || isBackslashEscaped(data, i)) && col+1 < colCount: + // something else found where marker was required + return + + case data[i] == '\n': + // marker is optional for the last column + col++ + + default: + // trailing junk found after last column + return + } + } + if col != colCount { + return + } + + p.addBlock(TableHead, nil) + p.tableRow(header, columns, true) + size = i + if size < len(data) && data[size] == '\n' { + size++ + } + return +} + +func (p *Markdown) tableRow(data []byte, columns []CellAlignFlags, header bool) { + p.addBlock(TableRow, nil) + i, col := 0, 0 + + if data[i] == '|' && !isBackslashEscaped(data, i) { + i++ + } + + for col = 0; col < len(columns) && i < len(data); col++ { + for i < len(data) && data[i] == ' ' { + i++ + } + + cellStart := i + + for i < len(data) && (data[i] != '|' || isBackslashEscaped(data, i)) && data[i] != '\n' { + i++ + } + + cellEnd := i + + // skip the end-of-cell marker, possibly taking us past end of buffer + i++ + + for cellEnd > cellStart && cellEnd-1 < len(data) && data[cellEnd-1] == ' ' { + cellEnd-- + } + + cell := p.addBlock(TableCell, data[cellStart:cellEnd]) + cell.IsHeader = header + cell.Align = columns[col] + } + + // pad it out with empty columns to get the right number + for ; col < len(columns); col++ { + cell := p.addBlock(TableCell, nil) + cell.IsHeader = header + cell.Align = columns[col] + } + + // silently ignore rows with too many cells +} + +// returns blockquote prefix length +func (p *Markdown) quotePrefix(data []byte) int { + i := 0 + for i < 3 && i < len(data) && data[i] == ' ' { + i++ + } + if i < len(data) && data[i] == '>' { + if i+1 < len(data) && data[i+1] == ' ' { + return i + 2 + } + return i + 1 + } + return 0 +} + +// blockquote ends with at least one blank line +// followed by something without a blockquote prefix +func (p *Markdown) terminateBlockquote(data []byte, beg, end int) bool { + if p.isEmpty(data[beg:]) <= 0 { + return false + } + if end >= len(data) { + return true + } + return p.quotePrefix(data[end:]) == 0 && p.isEmpty(data[end:]) == 0 +} + +// parse a blockquote fragment +func (p *Markdown) quote(data []byte) int { + block := p.addBlock(BlockQuote, nil) + var raw bytes.Buffer + beg, end := 0, 0 + for beg < len(data) { + end = beg + // Step over whole lines, collecting them. While doing that, check for + // fenced code and if one's found, incorporate it altogether, + // irregardless of any contents inside it + for end < len(data) && data[end] != '\n' { + if p.extensions&FencedCode != 0 { + if i := p.fencedCodeBlock(data[end:], false); i > 0 { + // -1 to compensate for the extra end++ after the loop: + end += i - 1 + break + } + } + end++ + } + if end < len(data) && data[end] == '\n' { + end++ + } + if pre := p.quotePrefix(data[beg:]); pre > 0 { + // skip the prefix + beg += pre + } else if p.terminateBlockquote(data, beg, end) { + break + } + // this line is part of the blockquote + raw.Write(data[beg:end]) + beg = end + } + p.block(raw.Bytes()) + p.finalize(block) + return end +} + +// returns prefix length for block code +func (p *Markdown) codePrefix(data []byte) int { + if len(data) >= 1 && data[0] == '\t' { + return 1 + } + if len(data) >= 4 && data[0] == ' ' && data[1] == ' ' && data[2] == ' ' && data[3] == ' ' { + return 4 + } + return 0 +} + +func (p *Markdown) code(data []byte) int { + var work bytes.Buffer + + i := 0 + for i < len(data) { + beg := i + for i < len(data) && data[i] != '\n' { + i++ + } + if i < len(data) && data[i] == '\n' { + i++ + } + + blankline := p.isEmpty(data[beg:i]) > 0 + if pre := p.codePrefix(data[beg:i]); pre > 0 { + beg += pre + } else if !blankline { + // non-empty, non-prefixed line breaks the pre + i = beg + break + } + + // verbatim copy to the working buffer + if blankline { + work.WriteByte('\n') + } else { + work.Write(data[beg:i]) + } + } + + // trim all the \n off the end of work + workbytes := work.Bytes() + eol := len(workbytes) + for eol > 0 && workbytes[eol-1] == '\n' { + eol-- + } + if eol != len(workbytes) { + work.Truncate(eol) + } + + work.WriteByte('\n') + + block := p.addBlock(CodeBlock, work.Bytes()) // TODO: get rid of temp buffer + block.IsFenced = false + finalizeCodeBlock(block) + + return i +} + +// returns unordered list item prefix +func (p *Markdown) uliPrefix(data []byte) int { + i := 0 + // start with up to 3 spaces + for i < len(data) && i < 3 && data[i] == ' ' { + i++ + } + if i >= len(data)-1 { + return 0 + } + // need one of {'*', '+', '-'} followed by a space or a tab + if (data[i] != '*' && data[i] != '+' && data[i] != '-') || + (data[i+1] != ' ' && data[i+1] != '\t') { + return 0 + } + return i + 2 +} + +// returns ordered list item prefix +func (p *Markdown) oliPrefix(data []byte) int { + i := 0 + + // start with up to 3 spaces + for i < 3 && i < len(data) && data[i] == ' ' { + i++ + } + + // count the digits + start := i + for i < len(data) && data[i] >= '0' && data[i] <= '9' { + i++ + } + if start == i || i >= len(data)-1 { + return 0 + } + + // we need >= 1 digits followed by a dot and a space or a tab + if data[i] != '.' || !(data[i+1] == ' ' || data[i+1] == '\t') { + return 0 + } + return i + 2 +} + +// returns definition list item prefix +func (p *Markdown) dliPrefix(data []byte) int { + if len(data) < 2 { + return 0 + } + i := 0 + // need a ':' followed by a space or a tab + if data[i] != ':' || !(data[i+1] == ' ' || data[i+1] == '\t') { + return 0 + } + for i < len(data) && data[i] == ' ' { + i++ + } + return i + 2 +} + +// parse ordered or unordered list block +func (p *Markdown) list(data []byte, flags ListType) int { + i := 0 + flags |= ListItemBeginningOfList + block := p.addBlock(List, nil) + block.ListFlags = flags + block.Tight = true + + for i < len(data) { + skip := p.listItem(data[i:], &flags) + if flags&ListItemContainsBlock != 0 { + block.ListData.Tight = false + } + i += skip + if skip == 0 || flags&ListItemEndOfList != 0 { + break + } + flags &= ^ListItemBeginningOfList + } + + above := block.Parent + finalizeList(block) + p.tip = above + return i +} + +// Returns true if the list item is not the same type as its parent list +func (p *Markdown) listTypeChanged(data []byte, flags *ListType) bool { + if p.dliPrefix(data) > 0 && *flags&ListTypeDefinition == 0 { + return true + } else if p.oliPrefix(data) > 0 && *flags&ListTypeOrdered == 0 { + return true + } else if p.uliPrefix(data) > 0 && (*flags&ListTypeOrdered != 0 || *flags&ListTypeDefinition != 0) { + return true + } + return false +} + +// Returns true if block ends with a blank line, descending if needed +// into lists and sublists. +func endsWithBlankLine(block *Node) bool { + // TODO: figure this out. Always false now. + for block != nil { + //if block.lastLineBlank { + //return true + //} + t := block.Type + if t == List || t == Item { + block = block.LastChild + } else { + break + } + } + return false +} + +func finalizeList(block *Node) { + block.open = false + item := block.FirstChild + for item != nil { + // check for non-final list item ending with blank line: + if endsWithBlankLine(item) && item.Next != nil { + block.ListData.Tight = false + break + } + // recurse into children of list item, to see if there are spaces + // between any of them: + subItem := item.FirstChild + for subItem != nil { + if endsWithBlankLine(subItem) && (item.Next != nil || subItem.Next != nil) { + block.ListData.Tight = false + break + } + subItem = subItem.Next + } + item = item.Next + } +} + +// Parse a single list item. +// Assumes initial prefix is already removed if this is a sublist. +func (p *Markdown) listItem(data []byte, flags *ListType) int { + // keep track of the indentation of the first line + itemIndent := 0 + if data[0] == '\t' { + itemIndent += 4 + } else { + for itemIndent < 3 && data[itemIndent] == ' ' { + itemIndent++ + } + } + + var bulletChar byte = '*' + i := p.uliPrefix(data) + if i == 0 { + i = p.oliPrefix(data) + } else { + bulletChar = data[i-2] + } + if i == 0 { + i = p.dliPrefix(data) + // reset definition term flag + if i > 0 { + *flags &= ^ListTypeTerm + } + } + if i == 0 { + // if in definition list, set term flag and continue + if *flags&ListTypeDefinition != 0 { + *flags |= ListTypeTerm + } else { + return 0 + } + } + + // skip leading whitespace on first line + for i < len(data) && data[i] == ' ' { + i++ + } + + // find the end of the line + line := i + for i > 0 && i < len(data) && data[i-1] != '\n' { + i++ + } + + // get working buffer + var raw bytes.Buffer + + // put the first line into the working buffer + raw.Write(data[line:i]) + line = i + + // process the following lines + containsBlankLine := false + sublist := 0 + codeBlockMarker := "" + +gatherlines: + for line < len(data) { + i++ + + // find the end of this line + for i < len(data) && data[i-1] != '\n' { + i++ + } + + // if it is an empty line, guess that it is part of this item + // and move on to the next line + if p.isEmpty(data[line:i]) > 0 { + containsBlankLine = true + line = i + continue + } + + // calculate the indentation + indent := 0 + indentIndex := 0 + if data[line] == '\t' { + indentIndex++ + indent += 4 + } else { + for indent < 4 && line+indent < i && data[line+indent] == ' ' { + indent++ + indentIndex++ + } + } + + chunk := data[line+indentIndex : i] + + if p.extensions&FencedCode != 0 { + // determine if in or out of codeblock + // if in codeblock, ignore normal list processing + _, marker := isFenceLine(chunk, nil, codeBlockMarker) + if marker != "" { + if codeBlockMarker == "" { + // start of codeblock + codeBlockMarker = marker + } else { + // end of codeblock. + codeBlockMarker = "" + } + } + // we are in a codeblock, write line, and continue + if codeBlockMarker != "" || marker != "" { + raw.Write(data[line+indentIndex : i]) + line = i + continue gatherlines + } + } + + // evaluate how this line fits in + switch { + // is this a nested list item? + case (p.uliPrefix(chunk) > 0 && !p.isHRule(chunk)) || + p.oliPrefix(chunk) > 0 || + p.dliPrefix(chunk) > 0: + + // to be a nested list, it must be indented more + // if not, it is either a different kind of list + // or the next item in the same list + if indent <= itemIndent { + if p.listTypeChanged(chunk, flags) { + *flags |= ListItemEndOfList + } else if containsBlankLine { + *flags |= ListItemContainsBlock + } + + break gatherlines + } + + if containsBlankLine { + *flags |= ListItemContainsBlock + } + + // is this the first item in the nested list? + if sublist == 0 { + sublist = raw.Len() + } + + // is this a nested prefix heading? + case p.isPrefixHeading(chunk): + // if the heading is not indented, it is not nested in the list + // and thus ends the list + if containsBlankLine && indent < 4 { + *flags |= ListItemEndOfList + break gatherlines + } + *flags |= ListItemContainsBlock + + // anything following an empty line is only part + // of this item if it is indented 4 spaces + // (regardless of the indentation of the beginning of the item) + case containsBlankLine && indent < 4: + if *flags&ListTypeDefinition != 0 && i < len(data)-1 { + // is the next item still a part of this list? + next := i + for next < len(data) && data[next] != '\n' { + next++ + } + for next < len(data)-1 && data[next] == '\n' { + next++ + } + if i < len(data)-1 && data[i] != ':' && data[next] != ':' { + *flags |= ListItemEndOfList + } + } else { + *flags |= ListItemEndOfList + } + break gatherlines + + // a blank line means this should be parsed as a block + case containsBlankLine: + raw.WriteByte('\n') + *flags |= ListItemContainsBlock + } + + // if this line was preceded by one or more blanks, + // re-introduce the blank into the buffer + if containsBlankLine { + containsBlankLine = false + raw.WriteByte('\n') + } + + // add the line into the working buffer without prefix + raw.Write(data[line+indentIndex : i]) + + line = i + } + + rawBytes := raw.Bytes() + + block := p.addBlock(Item, nil) + block.ListFlags = *flags + block.Tight = false + block.BulletChar = bulletChar + block.Delimiter = '.' // Only '.' is possible in Markdown, but ')' will also be possible in CommonMark + + // render the contents of the list item + if *flags&ListItemContainsBlock != 0 && *flags&ListTypeTerm == 0 { + // intermediate render of block item, except for definition term + if sublist > 0 { + p.block(rawBytes[:sublist]) + p.block(rawBytes[sublist:]) + } else { + p.block(rawBytes) + } + } else { + // intermediate render of inline item + if sublist > 0 { + child := p.addChild(Paragraph, 0) + child.content = rawBytes[:sublist] + p.block(rawBytes[sublist:]) + } else { + child := p.addChild(Paragraph, 0) + child.content = rawBytes + } + } + return line +} + +// render a single paragraph that has already been parsed out +func (p *Markdown) renderParagraph(data []byte) { + if len(data) == 0 { + return + } + + // trim leading spaces + beg := 0 + for data[beg] == ' ' { + beg++ + } + + end := len(data) + // trim trailing newline + if data[len(data)-1] == '\n' { + end-- + } + + // trim trailing spaces + for end > beg && data[end-1] == ' ' { + end-- + } + + p.addBlock(Paragraph, data[beg:end]) +} + +func (p *Markdown) paragraph(data []byte) int { + // prev: index of 1st char of previous line + // line: index of 1st char of current line + // i: index of cursor/end of current line + var prev, line, i int + tabSize := TabSizeDefault + if p.extensions&TabSizeEight != 0 { + tabSize = TabSizeDouble + } + // keep going until we find something to mark the end of the paragraph + for i < len(data) { + // mark the beginning of the current line + prev = line + current := data[i:] + line = i + + // did we find a reference or a footnote? If so, end a paragraph + // preceding it and report that we have consumed up to the end of that + // reference: + if refEnd := isReference(p, current, tabSize); refEnd > 0 { + p.renderParagraph(data[:i]) + return i + refEnd + } + + // did we find a blank line marking the end of the paragraph? + if n := p.isEmpty(current); n > 0 { + // did this blank line followed by a definition list item? + if p.extensions&DefinitionLists != 0 { + if i < len(data)-1 && data[i+1] == ':' { + return p.list(data[prev:], ListTypeDefinition) + } + } + + p.renderParagraph(data[:i]) + return i + n + } + + // an underline under some text marks a heading, so our paragraph ended on prev line + if i > 0 { + if level := p.isUnderlinedHeading(current); level > 0 { + // render the paragraph + p.renderParagraph(data[:prev]) + + // ignore leading and trailing whitespace + eol := i - 1 + for prev < eol && data[prev] == ' ' { + prev++ + } + for eol > prev && data[eol-1] == ' ' { + eol-- + } + + id := "" + if p.extensions&AutoHeadingIDs != 0 { + id = sanitized_anchor_name.Create(string(data[prev:eol])) + } + + block := p.addBlock(Heading, data[prev:eol]) + block.Level = level + block.HeadingID = id + + // find the end of the underline + for i < len(data) && data[i] != '\n' { + i++ + } + return i + } + } + + // if the next line starts a block of HTML, then the paragraph ends here + if p.extensions&LaxHTMLBlocks != 0 { + if data[i] == '<' && p.html(current, false) > 0 { + // rewind to before the HTML block + p.renderParagraph(data[:i]) + return i + } + } + + // if there's a prefixed heading or a horizontal rule after this, paragraph is over + if p.isPrefixHeading(current) || p.isHRule(current) { + p.renderParagraph(data[:i]) + return i + } + + // if there's a fenced code block, paragraph is over + if p.extensions&FencedCode != 0 { + if p.fencedCodeBlock(current, false) > 0 { + p.renderParagraph(data[:i]) + return i + } + } + + // if there's a definition list item, prev line is a definition term + if p.extensions&DefinitionLists != 0 { + if p.dliPrefix(current) != 0 { + ret := p.list(data[prev:], ListTypeDefinition) + return ret + } + } + + // if there's a list after this, paragraph is over + if p.extensions&NoEmptyLineBeforeBlock != 0 { + if p.uliPrefix(current) != 0 || + p.oliPrefix(current) != 0 || + p.quotePrefix(current) != 0 || + p.codePrefix(current) != 0 { + p.renderParagraph(data[:i]) + return i + } + } + + // otherwise, scan to the beginning of the next line + nl := bytes.IndexByte(data[i:], '\n') + if nl >= 0 { + i += nl + 1 + } else { + i += len(data[i:]) + } + } + + p.renderParagraph(data[:i]) + return i +} + +func skipChar(data []byte, start int, char byte) int { + i := start + for i < len(data) && data[i] == char { + i++ + } + return i +} + +func skipUntilChar(text []byte, start int, char byte) int { + i := start + for i < len(text) && text[i] != char { + i++ + } + return i +} diff --git a/plugins/source-github/vendor/github.com/russross/blackfriday/v2/doc.go b/plugins/source-github/vendor/github.com/russross/blackfriday/v2/doc.go new file mode 100644 index 00000000..5b3fa987 --- /dev/null +++ b/plugins/source-github/vendor/github.com/russross/blackfriday/v2/doc.go @@ -0,0 +1,18 @@ +// Package blackfriday is a markdown processor. +// +// It translates plain text with simple formatting rules into an AST, which can +// then be further processed to HTML (provided by Blackfriday itself) or other +// formats (provided by the community). +// +// The simplest way to invoke Blackfriday is to call the Run function. It will +// take a text input and produce a text output in HTML (or other format). +// +// A slightly more sophisticated way to use Blackfriday is to create a Markdown +// processor and to call Parse, which returns a syntax tree for the input +// document. You can leverage Blackfriday's parsing for content extraction from +// markdown documents. You can assign a custom renderer and set various options +// to the Markdown processor. +// +// If you're interested in calling Blackfriday from command line, see +// https://github.com/russross/blackfriday-tool. +package blackfriday diff --git a/plugins/source-github/vendor/github.com/russross/blackfriday/v2/esc.go b/plugins/source-github/vendor/github.com/russross/blackfriday/v2/esc.go new file mode 100644 index 00000000..6385f27c --- /dev/null +++ b/plugins/source-github/vendor/github.com/russross/blackfriday/v2/esc.go @@ -0,0 +1,34 @@ +package blackfriday + +import ( + "html" + "io" +) + +var htmlEscaper = [256][]byte{ + '&': []byte("&"), + '<': []byte("<"), + '>': []byte(">"), + '"': []byte("""), +} + +func escapeHTML(w io.Writer, s []byte) { + var start, end int + for end < len(s) { + escSeq := htmlEscaper[s[end]] + if escSeq != nil { + w.Write(s[start:end]) + w.Write(escSeq) + start = end + 1 + } + end++ + } + if start < len(s) && end <= len(s) { + w.Write(s[start:end]) + } +} + +func escLink(w io.Writer, text []byte) { + unesc := html.UnescapeString(string(text)) + escapeHTML(w, []byte(unesc)) +} diff --git a/plugins/source-github/vendor/github.com/russross/blackfriday/v2/go.mod b/plugins/source-github/vendor/github.com/russross/blackfriday/v2/go.mod new file mode 100644 index 00000000..620b74e0 --- /dev/null +++ b/plugins/source-github/vendor/github.com/russross/blackfriday/v2/go.mod @@ -0,0 +1 @@ +module github.com/russross/blackfriday/v2 diff --git a/plugins/source-github/vendor/github.com/russross/blackfriday/v2/html.go b/plugins/source-github/vendor/github.com/russross/blackfriday/v2/html.go new file mode 100644 index 00000000..284c8718 --- /dev/null +++ b/plugins/source-github/vendor/github.com/russross/blackfriday/v2/html.go @@ -0,0 +1,949 @@ +// +// Blackfriday Markdown Processor +// Available at http://github.com/russross/blackfriday +// +// Copyright © 2011 Russ Ross . +// Distributed under the Simplified BSD License. +// See README.md for details. +// + +// +// +// HTML rendering backend +// +// + +package blackfriday + +import ( + "bytes" + "fmt" + "io" + "regexp" + "strings" +) + +// HTMLFlags control optional behavior of HTML renderer. +type HTMLFlags int + +// HTML renderer configuration options. +const ( + HTMLFlagsNone HTMLFlags = 0 + SkipHTML HTMLFlags = 1 << iota // Skip preformatted HTML blocks + SkipImages // Skip embedded images + SkipLinks // Skip all links + Safelink // Only link to trusted protocols + NofollowLinks // Only link with rel="nofollow" + NoreferrerLinks // Only link with rel="noreferrer" + NoopenerLinks // Only link with rel="noopener" + HrefTargetBlank // Add a blank target + CompletePage // Generate a complete HTML page + UseXHTML // Generate XHTML output instead of HTML + FootnoteReturnLinks // Generate a link at the end of a footnote to return to the source + Smartypants // Enable smart punctuation substitutions + SmartypantsFractions // Enable smart fractions (with Smartypants) + SmartypantsDashes // Enable smart dashes (with Smartypants) + SmartypantsLatexDashes // Enable LaTeX-style dashes (with Smartypants) + SmartypantsAngledQuotes // Enable angled double quotes (with Smartypants) for double quotes rendering + SmartypantsQuotesNBSP // Enable « French guillemets » (with Smartypants) + TOC // Generate a table of contents +) + +var ( + htmlTagRe = regexp.MustCompile("(?i)^" + htmlTag) +) + +const ( + htmlTag = "(?:" + openTag + "|" + closeTag + "|" + htmlComment + "|" + + processingInstruction + "|" + declaration + "|" + cdata + ")" + closeTag = "]" + openTag = "<" + tagName + attribute + "*" + "\\s*/?>" + attribute = "(?:" + "\\s+" + attributeName + attributeValueSpec + "?)" + attributeValue = "(?:" + unquotedValue + "|" + singleQuotedValue + "|" + doubleQuotedValue + ")" + attributeValueSpec = "(?:" + "\\s*=" + "\\s*" + attributeValue + ")" + attributeName = "[a-zA-Z_:][a-zA-Z0-9:._-]*" + cdata = "" + declaration = "]*>" + doubleQuotedValue = "\"[^\"]*\"" + htmlComment = "|" + processingInstruction = "[<][?].*?[?][>]" + singleQuotedValue = "'[^']*'" + tagName = "[A-Za-z][A-Za-z0-9-]*" + unquotedValue = "[^\"'=<>`\\x00-\\x20]+" +) + +// HTMLRendererParameters is a collection of supplementary parameters tweaking +// the behavior of various parts of HTML renderer. +type HTMLRendererParameters struct { + // Prepend this text to each relative URL. + AbsolutePrefix string + // Add this text to each footnote anchor, to ensure uniqueness. + FootnoteAnchorPrefix string + // Show this text inside the tag for a footnote return link, if the + // HTML_FOOTNOTE_RETURN_LINKS flag is enabled. If blank, the string + // [return] is used. + FootnoteReturnLinkContents string + // If set, add this text to the front of each Heading ID, to ensure + // uniqueness. + HeadingIDPrefix string + // If set, add this text to the back of each Heading ID, to ensure uniqueness. + HeadingIDSuffix string + // Increase heading levels: if the offset is 1,

becomes

etc. + // Negative offset is also valid. + // Resulting levels are clipped between 1 and 6. + HeadingLevelOffset int + + Title string // Document title (used if CompletePage is set) + CSS string // Optional CSS file URL (used if CompletePage is set) + Icon string // Optional icon file URL (used if CompletePage is set) + + Flags HTMLFlags // Flags allow customizing this renderer's behavior +} + +// HTMLRenderer is a type that implements the Renderer interface for HTML output. +// +// Do not create this directly, instead use the NewHTMLRenderer function. +type HTMLRenderer struct { + HTMLRendererParameters + + closeTag string // how to end singleton tags: either " />" or ">" + + // Track heading IDs to prevent ID collision in a single generation. + headingIDs map[string]int + + lastOutputLen int + disableTags int + + sr *SPRenderer +} + +const ( + xhtmlClose = " />" + htmlClose = ">" +) + +// NewHTMLRenderer creates and configures an HTMLRenderer object, which +// satisfies the Renderer interface. +func NewHTMLRenderer(params HTMLRendererParameters) *HTMLRenderer { + // configure the rendering engine + closeTag := htmlClose + if params.Flags&UseXHTML != 0 { + closeTag = xhtmlClose + } + + if params.FootnoteReturnLinkContents == "" { + params.FootnoteReturnLinkContents = `[return]` + } + + return &HTMLRenderer{ + HTMLRendererParameters: params, + + closeTag: closeTag, + headingIDs: make(map[string]int), + + sr: NewSmartypantsRenderer(params.Flags), + } +} + +func isHTMLTag(tag []byte, tagname string) bool { + found, _ := findHTMLTagPos(tag, tagname) + return found +} + +// Look for a character, but ignore it when it's in any kind of quotes, it +// might be JavaScript +func skipUntilCharIgnoreQuotes(html []byte, start int, char byte) int { + inSingleQuote := false + inDoubleQuote := false + inGraveQuote := false + i := start + for i < len(html) { + switch { + case html[i] == char && !inSingleQuote && !inDoubleQuote && !inGraveQuote: + return i + case html[i] == '\'': + inSingleQuote = !inSingleQuote + case html[i] == '"': + inDoubleQuote = !inDoubleQuote + case html[i] == '`': + inGraveQuote = !inGraveQuote + } + i++ + } + return start +} + +func findHTMLTagPos(tag []byte, tagname string) (bool, int) { + i := 0 + if i < len(tag) && tag[0] != '<' { + return false, -1 + } + i++ + i = skipSpace(tag, i) + + if i < len(tag) && tag[i] == '/' { + i++ + } + + i = skipSpace(tag, i) + j := 0 + for ; i < len(tag); i, j = i+1, j+1 { + if j >= len(tagname) { + break + } + + if strings.ToLower(string(tag[i]))[0] != tagname[j] { + return false, -1 + } + } + + if i == len(tag) { + return false, -1 + } + + rightAngle := skipUntilCharIgnoreQuotes(tag, i, '>') + if rightAngle >= i { + return true, rightAngle + } + + return false, -1 +} + +func skipSpace(tag []byte, i int) int { + for i < len(tag) && isspace(tag[i]) { + i++ + } + return i +} + +func isRelativeLink(link []byte) (yes bool) { + // a tag begin with '#' + if link[0] == '#' { + return true + } + + // link begin with '/' but not '//', the second maybe a protocol relative link + if len(link) >= 2 && link[0] == '/' && link[1] != '/' { + return true + } + + // only the root '/' + if len(link) == 1 && link[0] == '/' { + return true + } + + // current directory : begin with "./" + if bytes.HasPrefix(link, []byte("./")) { + return true + } + + // parent directory : begin with "../" + if bytes.HasPrefix(link, []byte("../")) { + return true + } + + return false +} + +func (r *HTMLRenderer) ensureUniqueHeadingID(id string) string { + for count, found := r.headingIDs[id]; found; count, found = r.headingIDs[id] { + tmp := fmt.Sprintf("%s-%d", id, count+1) + + if _, tmpFound := r.headingIDs[tmp]; !tmpFound { + r.headingIDs[id] = count + 1 + id = tmp + } else { + id = id + "-1" + } + } + + if _, found := r.headingIDs[id]; !found { + r.headingIDs[id] = 0 + } + + return id +} + +func (r *HTMLRenderer) addAbsPrefix(link []byte) []byte { + if r.AbsolutePrefix != "" && isRelativeLink(link) && link[0] != '.' { + newDest := r.AbsolutePrefix + if link[0] != '/' { + newDest += "/" + } + newDest += string(link) + return []byte(newDest) + } + return link +} + +func appendLinkAttrs(attrs []string, flags HTMLFlags, link []byte) []string { + if isRelativeLink(link) { + return attrs + } + val := []string{} + if flags&NofollowLinks != 0 { + val = append(val, "nofollow") + } + if flags&NoreferrerLinks != 0 { + val = append(val, "noreferrer") + } + if flags&NoopenerLinks != 0 { + val = append(val, "noopener") + } + if flags&HrefTargetBlank != 0 { + attrs = append(attrs, "target=\"_blank\"") + } + if len(val) == 0 { + return attrs + } + attr := fmt.Sprintf("rel=%q", strings.Join(val, " ")) + return append(attrs, attr) +} + +func isMailto(link []byte) bool { + return bytes.HasPrefix(link, []byte("mailto:")) +} + +func needSkipLink(flags HTMLFlags, dest []byte) bool { + if flags&SkipLinks != 0 { + return true + } + return flags&Safelink != 0 && !isSafeLink(dest) && !isMailto(dest) +} + +func isSmartypantable(node *Node) bool { + pt := node.Parent.Type + return pt != Link && pt != CodeBlock && pt != Code +} + +func appendLanguageAttr(attrs []string, info []byte) []string { + if len(info) == 0 { + return attrs + } + endOfLang := bytes.IndexAny(info, "\t ") + if endOfLang < 0 { + endOfLang = len(info) + } + return append(attrs, fmt.Sprintf("class=\"language-%s\"", info[:endOfLang])) +} + +func (r *HTMLRenderer) tag(w io.Writer, name []byte, attrs []string) { + w.Write(name) + if len(attrs) > 0 { + w.Write(spaceBytes) + w.Write([]byte(strings.Join(attrs, " "))) + } + w.Write(gtBytes) + r.lastOutputLen = 1 +} + +func footnoteRef(prefix string, node *Node) []byte { + urlFrag := prefix + string(slugify(node.Destination)) + anchor := fmt.Sprintf(`%d`, urlFrag, node.NoteID) + return []byte(fmt.Sprintf(`%s`, urlFrag, anchor)) +} + +func footnoteItem(prefix string, slug []byte) []byte { + return []byte(fmt.Sprintf(`
  • `, prefix, slug)) +} + +func footnoteReturnLink(prefix, returnLink string, slug []byte) []byte { + const format = ` %s` + return []byte(fmt.Sprintf(format, prefix, slug, returnLink)) +} + +func itemOpenCR(node *Node) bool { + if node.Prev == nil { + return false + } + ld := node.Parent.ListData + return !ld.Tight && ld.ListFlags&ListTypeDefinition == 0 +} + +func skipParagraphTags(node *Node) bool { + grandparent := node.Parent.Parent + if grandparent == nil || grandparent.Type != List { + return false + } + tightOrTerm := grandparent.Tight || node.Parent.ListFlags&ListTypeTerm != 0 + return grandparent.Type == List && tightOrTerm +} + +func cellAlignment(align CellAlignFlags) string { + switch align { + case TableAlignmentLeft: + return "left" + case TableAlignmentRight: + return "right" + case TableAlignmentCenter: + return "center" + default: + return "" + } +} + +func (r *HTMLRenderer) out(w io.Writer, text []byte) { + if r.disableTags > 0 { + w.Write(htmlTagRe.ReplaceAll(text, []byte{})) + } else { + w.Write(text) + } + r.lastOutputLen = len(text) +} + +func (r *HTMLRenderer) cr(w io.Writer) { + if r.lastOutputLen > 0 { + r.out(w, nlBytes) + } +} + +var ( + nlBytes = []byte{'\n'} + gtBytes = []byte{'>'} + spaceBytes = []byte{' '} +) + +var ( + brTag = []byte("
    ") + brXHTMLTag = []byte("
    ") + emTag = []byte("") + emCloseTag = []byte("") + strongTag = []byte("") + strongCloseTag = []byte("") + delTag = []byte("") + delCloseTag = []byte("") + ttTag = []byte("") + ttCloseTag = []byte("") + aTag = []byte("") + preTag = []byte("
    ")
    +	preCloseTag        = []byte("
    ") + codeTag = []byte("") + codeCloseTag = []byte("") + pTag = []byte("

    ") + pCloseTag = []byte("

    ") + blockquoteTag = []byte("
    ") + blockquoteCloseTag = []byte("
    ") + hrTag = []byte("
    ") + hrXHTMLTag = []byte("
    ") + ulTag = []byte("
      ") + ulCloseTag = []byte("
    ") + olTag = []byte("
      ") + olCloseTag = []byte("
    ") + dlTag = []byte("
    ") + dlCloseTag = []byte("
    ") + liTag = []byte("
  • ") + liCloseTag = []byte("
  • ") + ddTag = []byte("
    ") + ddCloseTag = []byte("
    ") + dtTag = []byte("
    ") + dtCloseTag = []byte("
    ") + tableTag = []byte("") + tableCloseTag = []byte("
    ") + tdTag = []byte("") + thTag = []byte("") + theadTag = []byte("") + theadCloseTag = []byte("") + tbodyTag = []byte("") + tbodyCloseTag = []byte("") + trTag = []byte("") + trCloseTag = []byte("") + h1Tag = []byte("") + h2Tag = []byte("") + h3Tag = []byte("") + h4Tag = []byte("") + h5Tag = []byte("") + h6Tag = []byte("") + + footnotesDivBytes = []byte("\n
    \n\n") + footnotesCloseDivBytes = []byte("\n
    \n") +) + +func headingTagsFromLevel(level int) ([]byte, []byte) { + if level <= 1 { + return h1Tag, h1CloseTag + } + switch level { + case 2: + return h2Tag, h2CloseTag + case 3: + return h3Tag, h3CloseTag + case 4: + return h4Tag, h4CloseTag + case 5: + return h5Tag, h5CloseTag + } + return h6Tag, h6CloseTag +} + +func (r *HTMLRenderer) outHRTag(w io.Writer) { + if r.Flags&UseXHTML == 0 { + r.out(w, hrTag) + } else { + r.out(w, hrXHTMLTag) + } +} + +// RenderNode is a default renderer of a single node of a syntax tree. For +// block nodes it will be called twice: first time with entering=true, second +// time with entering=false, so that it could know when it's working on an open +// tag and when on close. It writes the result to w. +// +// The return value is a way to tell the calling walker to adjust its walk +// pattern: e.g. it can terminate the traversal by returning Terminate. Or it +// can ask the walker to skip a subtree of this node by returning SkipChildren. +// The typical behavior is to return GoToNext, which asks for the usual +// traversal to the next node. +func (r *HTMLRenderer) RenderNode(w io.Writer, node *Node, entering bool) WalkStatus { + attrs := []string{} + switch node.Type { + case Text: + if r.Flags&Smartypants != 0 { + var tmp bytes.Buffer + escapeHTML(&tmp, node.Literal) + r.sr.Process(w, tmp.Bytes()) + } else { + if node.Parent.Type == Link { + escLink(w, node.Literal) + } else { + escapeHTML(w, node.Literal) + } + } + case Softbreak: + r.cr(w) + // TODO: make it configurable via out(renderer.softbreak) + case Hardbreak: + if r.Flags&UseXHTML == 0 { + r.out(w, brTag) + } else { + r.out(w, brXHTMLTag) + } + r.cr(w) + case Emph: + if entering { + r.out(w, emTag) + } else { + r.out(w, emCloseTag) + } + case Strong: + if entering { + r.out(w, strongTag) + } else { + r.out(w, strongCloseTag) + } + case Del: + if entering { + r.out(w, delTag) + } else { + r.out(w, delCloseTag) + } + case HTMLSpan: + if r.Flags&SkipHTML != 0 { + break + } + r.out(w, node.Literal) + case Link: + // mark it but don't link it if it is not a safe link: no smartypants + dest := node.LinkData.Destination + if needSkipLink(r.Flags, dest) { + if entering { + r.out(w, ttTag) + } else { + r.out(w, ttCloseTag) + } + } else { + if entering { + dest = r.addAbsPrefix(dest) + var hrefBuf bytes.Buffer + hrefBuf.WriteString("href=\"") + escLink(&hrefBuf, dest) + hrefBuf.WriteByte('"') + attrs = append(attrs, hrefBuf.String()) + if node.NoteID != 0 { + r.out(w, footnoteRef(r.FootnoteAnchorPrefix, node)) + break + } + attrs = appendLinkAttrs(attrs, r.Flags, dest) + if len(node.LinkData.Title) > 0 { + var titleBuff bytes.Buffer + titleBuff.WriteString("title=\"") + escapeHTML(&titleBuff, node.LinkData.Title) + titleBuff.WriteByte('"') + attrs = append(attrs, titleBuff.String()) + } + r.tag(w, aTag, attrs) + } else { + if node.NoteID != 0 { + break + } + r.out(w, aCloseTag) + } + } + case Image: + if r.Flags&SkipImages != 0 { + return SkipChildren + } + if entering { + dest := node.LinkData.Destination + dest = r.addAbsPrefix(dest) + if r.disableTags == 0 { + //if options.safe && potentiallyUnsafe(dest) { + //out(w, ``)
+				//} else {
+				r.out(w, []byte(`<img src=`)) + } + } + case Code: + r.out(w, codeTag) + escapeHTML(w, node.Literal) + r.out(w, codeCloseTag) + case Document: + break + case Paragraph: + if skipParagraphTags(node) { + break + } + if entering { + // TODO: untangle this clusterfuck about when the newlines need + // to be added and when not. + if node.Prev != nil { + switch node.Prev.Type { + case HTMLBlock, List, Paragraph, Heading, CodeBlock, BlockQuote, HorizontalRule: + r.cr(w) + } + } + if node.Parent.Type == BlockQuote && node.Prev == nil { + r.cr(w) + } + r.out(w, pTag) + } else { + r.out(w, pCloseTag) + if !(node.Parent.Type == Item && node.Next == nil) { + r.cr(w) + } + } + case BlockQuote: + if entering { + r.cr(w) + r.out(w, blockquoteTag) + } else { + r.out(w, blockquoteCloseTag) + r.cr(w) + } + case HTMLBlock: + if r.Flags&SkipHTML != 0 { + break + } + r.cr(w) + r.out(w, node.Literal) + r.cr(w) + case Heading: + headingLevel := r.HTMLRendererParameters.HeadingLevelOffset + node.Level + openTag, closeTag := headingTagsFromLevel(headingLevel) + if entering { + if node.IsTitleblock { + attrs = append(attrs, `class="title"`) + } + if node.HeadingID != "" { + id := r.ensureUniqueHeadingID(node.HeadingID) + if r.HeadingIDPrefix != "" { + id = r.HeadingIDPrefix + id + } + if r.HeadingIDSuffix != "" { + id = id + r.HeadingIDSuffix + } + attrs = append(attrs, fmt.Sprintf(`id="%s"`, id)) + } + r.cr(w) + r.tag(w, openTag, attrs) + } else { + r.out(w, closeTag) + if !(node.Parent.Type == Item && node.Next == nil) { + r.cr(w) + } + } + case HorizontalRule: + r.cr(w) + r.outHRTag(w) + r.cr(w) + case List: + openTag := ulTag + closeTag := ulCloseTag + if node.ListFlags&ListTypeOrdered != 0 { + openTag = olTag + closeTag = olCloseTag + } + if node.ListFlags&ListTypeDefinition != 0 { + openTag = dlTag + closeTag = dlCloseTag + } + if entering { + if node.IsFootnotesList { + r.out(w, footnotesDivBytes) + r.outHRTag(w) + r.cr(w) + } + r.cr(w) + if node.Parent.Type == Item && node.Parent.Parent.Tight { + r.cr(w) + } + r.tag(w, openTag[:len(openTag)-1], attrs) + r.cr(w) + } else { + r.out(w, closeTag) + //cr(w) + //if node.parent.Type != Item { + // cr(w) + //} + if node.Parent.Type == Item && node.Next != nil { + r.cr(w) + } + if node.Parent.Type == Document || node.Parent.Type == BlockQuote { + r.cr(w) + } + if node.IsFootnotesList { + r.out(w, footnotesCloseDivBytes) + } + } + case Item: + openTag := liTag + closeTag := liCloseTag + if node.ListFlags&ListTypeDefinition != 0 { + openTag = ddTag + closeTag = ddCloseTag + } + if node.ListFlags&ListTypeTerm != 0 { + openTag = dtTag + closeTag = dtCloseTag + } + if entering { + if itemOpenCR(node) { + r.cr(w) + } + if node.ListData.RefLink != nil { + slug := slugify(node.ListData.RefLink) + r.out(w, footnoteItem(r.FootnoteAnchorPrefix, slug)) + break + } + r.out(w, openTag) + } else { + if node.ListData.RefLink != nil { + slug := slugify(node.ListData.RefLink) + if r.Flags&FootnoteReturnLinks != 0 { + r.out(w, footnoteReturnLink(r.FootnoteAnchorPrefix, r.FootnoteReturnLinkContents, slug)) + } + } + r.out(w, closeTag) + r.cr(w) + } + case CodeBlock: + attrs = appendLanguageAttr(attrs, node.Info) + r.cr(w) + r.out(w, preTag) + r.tag(w, codeTag[:len(codeTag)-1], attrs) + escapeHTML(w, node.Literal) + r.out(w, codeCloseTag) + r.out(w, preCloseTag) + if node.Parent.Type != Item { + r.cr(w) + } + case Table: + if entering { + r.cr(w) + r.out(w, tableTag) + } else { + r.out(w, tableCloseTag) + r.cr(w) + } + case TableCell: + openTag := tdTag + closeTag := tdCloseTag + if node.IsHeader { + openTag = thTag + closeTag = thCloseTag + } + if entering { + align := cellAlignment(node.Align) + if align != "" { + attrs = append(attrs, fmt.Sprintf(`align="%s"`, align)) + } + if node.Prev == nil { + r.cr(w) + } + r.tag(w, openTag, attrs) + } else { + r.out(w, closeTag) + r.cr(w) + } + case TableHead: + if entering { + r.cr(w) + r.out(w, theadTag) + } else { + r.out(w, theadCloseTag) + r.cr(w) + } + case TableBody: + if entering { + r.cr(w) + r.out(w, tbodyTag) + // XXX: this is to adhere to a rather silly test. Should fix test. + if node.FirstChild == nil { + r.cr(w) + } + } else { + r.out(w, tbodyCloseTag) + r.cr(w) + } + case TableRow: + if entering { + r.cr(w) + r.out(w, trTag) + } else { + r.out(w, trCloseTag) + r.cr(w) + } + default: + panic("Unknown node type " + node.Type.String()) + } + return GoToNext +} + +// RenderHeader writes HTML document preamble and TOC if requested. +func (r *HTMLRenderer) RenderHeader(w io.Writer, ast *Node) { + r.writeDocumentHeader(w) + if r.Flags&TOC != 0 { + r.writeTOC(w, ast) + } +} + +// RenderFooter writes HTML document footer. +func (r *HTMLRenderer) RenderFooter(w io.Writer, ast *Node) { + if r.Flags&CompletePage == 0 { + return + } + io.WriteString(w, "\n\n\n") +} + +func (r *HTMLRenderer) writeDocumentHeader(w io.Writer) { + if r.Flags&CompletePage == 0 { + return + } + ending := "" + if r.Flags&UseXHTML != 0 { + io.WriteString(w, "\n") + io.WriteString(w, "\n") + ending = " /" + } else { + io.WriteString(w, "\n") + io.WriteString(w, "\n") + } + io.WriteString(w, "\n") + io.WriteString(w, " ") + if r.Flags&Smartypants != 0 { + r.sr.Process(w, []byte(r.Title)) + } else { + escapeHTML(w, []byte(r.Title)) + } + io.WriteString(w, "\n") + io.WriteString(w, " \n") + io.WriteString(w, " \n") + if r.CSS != "" { + io.WriteString(w, " \n") + } + if r.Icon != "" { + io.WriteString(w, " \n") + } + io.WriteString(w, "\n") + io.WriteString(w, "\n\n") +} + +func (r *HTMLRenderer) writeTOC(w io.Writer, ast *Node) { + buf := bytes.Buffer{} + + inHeading := false + tocLevel := 0 + headingCount := 0 + + ast.Walk(func(node *Node, entering bool) WalkStatus { + if node.Type == Heading && !node.HeadingData.IsTitleblock { + inHeading = entering + if entering { + node.HeadingID = fmt.Sprintf("toc_%d", headingCount) + if node.Level == tocLevel { + buf.WriteString("\n\n
  • ") + } else if node.Level < tocLevel { + for node.Level < tocLevel { + tocLevel-- + buf.WriteString("
  • \n") + } + buf.WriteString("\n\n
  • ") + } else { + for node.Level > tocLevel { + tocLevel++ + buf.WriteString("\n") + } + + if buf.Len() > 0 { + io.WriteString(w, "\n") + } + r.lastOutputLen = buf.Len() +} diff --git a/plugins/source-github/vendor/github.com/russross/blackfriday/v2/inline.go b/plugins/source-github/vendor/github.com/russross/blackfriday/v2/inline.go new file mode 100644 index 00000000..4ed29079 --- /dev/null +++ b/plugins/source-github/vendor/github.com/russross/blackfriday/v2/inline.go @@ -0,0 +1,1228 @@ +// +// Blackfriday Markdown Processor +// Available at http://github.com/russross/blackfriday +// +// Copyright © 2011 Russ Ross . +// Distributed under the Simplified BSD License. +// See README.md for details. +// + +// +// Functions to parse inline elements. +// + +package blackfriday + +import ( + "bytes" + "regexp" + "strconv" +) + +var ( + urlRe = `((https?|ftp):\/\/|\/)[-A-Za-z0-9+&@#\/%?=~_|!:,.;\(\)]+` + anchorRe = regexp.MustCompile(`^(]+")?\s?>` + urlRe + `<\/a>)`) + + // https://www.w3.org/TR/html5/syntax.html#character-references + // highest unicode code point in 17 planes (2^20): 1,114,112d = + // 7 dec digits or 6 hex digits + // named entity references can be 2-31 characters with stuff like < + // at one end and ∳ at the other. There + // are also sometimes numbers at the end, although this isn't inherent + // in the specification; there are never numbers anywhere else in + // current character references, though; see ¾ and ▒, etc. + // https://www.w3.org/TR/html5/syntax.html#named-character-references + // + // entity := "&" (named group | number ref) ";" + // named group := [a-zA-Z]{2,31}[0-9]{0,2} + // number ref := "#" (dec ref | hex ref) + // dec ref := [0-9]{1,7} + // hex ref := ("x" | "X") [0-9a-fA-F]{1,6} + htmlEntityRe = regexp.MustCompile(`&([a-zA-Z]{2,31}[0-9]{0,2}|#([0-9]{1,7}|[xX][0-9a-fA-F]{1,6}));`) +) + +// Functions to parse text within a block +// Each function returns the number of chars taken care of +// data is the complete block being rendered +// offset is the number of valid chars before the current cursor + +func (p *Markdown) inline(currBlock *Node, data []byte) { + // handlers might call us recursively: enforce a maximum depth + if p.nesting >= p.maxNesting || len(data) == 0 { + return + } + p.nesting++ + beg, end := 0, 0 + for end < len(data) { + handler := p.inlineCallback[data[end]] + if handler != nil { + if consumed, node := handler(p, data, end); consumed == 0 { + // No action from the callback. + end++ + } else { + // Copy inactive chars into the output. + currBlock.AppendChild(text(data[beg:end])) + if node != nil { + currBlock.AppendChild(node) + } + // Skip past whatever the callback used. + beg = end + consumed + end = beg + } + } else { + end++ + } + } + if beg < len(data) { + if data[end-1] == '\n' { + end-- + } + currBlock.AppendChild(text(data[beg:end])) + } + p.nesting-- +} + +// single and double emphasis parsing +func emphasis(p *Markdown, data []byte, offset int) (int, *Node) { + data = data[offset:] + c := data[0] + + if len(data) > 2 && data[1] != c { + // whitespace cannot follow an opening emphasis; + // strikethrough only takes two characters '~~' + if c == '~' || isspace(data[1]) { + return 0, nil + } + ret, node := helperEmphasis(p, data[1:], c) + if ret == 0 { + return 0, nil + } + + return ret + 1, node + } + + if len(data) > 3 && data[1] == c && data[2] != c { + if isspace(data[2]) { + return 0, nil + } + ret, node := helperDoubleEmphasis(p, data[2:], c) + if ret == 0 { + return 0, nil + } + + return ret + 2, node + } + + if len(data) > 4 && data[1] == c && data[2] == c && data[3] != c { + if c == '~' || isspace(data[3]) { + return 0, nil + } + ret, node := helperTripleEmphasis(p, data, 3, c) + if ret == 0 { + return 0, nil + } + + return ret + 3, node + } + + return 0, nil +} + +func codeSpan(p *Markdown, data []byte, offset int) (int, *Node) { + data = data[offset:] + + nb := 0 + + // count the number of backticks in the delimiter + for nb < len(data) && data[nb] == '`' { + nb++ + } + + // find the next delimiter + i, end := 0, 0 + for end = nb; end < len(data) && i < nb; end++ { + if data[end] == '`' { + i++ + } else { + i = 0 + } + } + + // no matching delimiter? + if i < nb && end >= len(data) { + return 0, nil + } + + // trim outside whitespace + fBegin := nb + for fBegin < end && data[fBegin] == ' ' { + fBegin++ + } + + fEnd := end - nb + for fEnd > fBegin && data[fEnd-1] == ' ' { + fEnd-- + } + + // render the code span + if fBegin != fEnd { + code := NewNode(Code) + code.Literal = data[fBegin:fEnd] + return end, code + } + + return end, nil +} + +// newline preceded by two spaces becomes
    +func maybeLineBreak(p *Markdown, data []byte, offset int) (int, *Node) { + origOffset := offset + for offset < len(data) && data[offset] == ' ' { + offset++ + } + + if offset < len(data) && data[offset] == '\n' { + if offset-origOffset >= 2 { + return offset - origOffset + 1, NewNode(Hardbreak) + } + return offset - origOffset, nil + } + return 0, nil +} + +// newline without two spaces works when HardLineBreak is enabled +func lineBreak(p *Markdown, data []byte, offset int) (int, *Node) { + if p.extensions&HardLineBreak != 0 { + return 1, NewNode(Hardbreak) + } + return 0, nil +} + +type linkType int + +const ( + linkNormal linkType = iota + linkImg + linkDeferredFootnote + linkInlineFootnote +) + +func isReferenceStyleLink(data []byte, pos int, t linkType) bool { + if t == linkDeferredFootnote { + return false + } + return pos < len(data)-1 && data[pos] == '[' && data[pos+1] != '^' +} + +func maybeImage(p *Markdown, data []byte, offset int) (int, *Node) { + if offset < len(data)-1 && data[offset+1] == '[' { + return link(p, data, offset) + } + return 0, nil +} + +func maybeInlineFootnote(p *Markdown, data []byte, offset int) (int, *Node) { + if offset < len(data)-1 && data[offset+1] == '[' { + return link(p, data, offset) + } + return 0, nil +} + +// '[': parse a link or an image or a footnote +func link(p *Markdown, data []byte, offset int) (int, *Node) { + // no links allowed inside regular links, footnote, and deferred footnotes + if p.insideLink && (offset > 0 && data[offset-1] == '[' || len(data)-1 > offset && data[offset+1] == '^') { + return 0, nil + } + + var t linkType + switch { + // special case: ![^text] == deferred footnote (that follows something with + // an exclamation point) + case p.extensions&Footnotes != 0 && len(data)-1 > offset && data[offset+1] == '^': + t = linkDeferredFootnote + // ![alt] == image + case offset >= 0 && data[offset] == '!': + t = linkImg + offset++ + // ^[text] == inline footnote + // [^refId] == deferred footnote + case p.extensions&Footnotes != 0: + if offset >= 0 && data[offset] == '^' { + t = linkInlineFootnote + offset++ + } else if len(data)-1 > offset && data[offset+1] == '^' { + t = linkDeferredFootnote + } + // [text] == regular link + default: + t = linkNormal + } + + data = data[offset:] + + var ( + i = 1 + noteID int + title, link, altContent []byte + textHasNl = false + ) + + if t == linkDeferredFootnote { + i++ + } + + // look for the matching closing bracket + for level := 1; level > 0 && i < len(data); i++ { + switch { + case data[i] == '\n': + textHasNl = true + + case data[i-1] == '\\': + continue + + case data[i] == '[': + level++ + + case data[i] == ']': + level-- + if level <= 0 { + i-- // compensate for extra i++ in for loop + } + } + } + + if i >= len(data) { + return 0, nil + } + + txtE := i + i++ + var footnoteNode *Node + + // skip any amount of whitespace or newline + // (this is much more lax than original markdown syntax) + for i < len(data) && isspace(data[i]) { + i++ + } + + // inline style link + switch { + case i < len(data) && data[i] == '(': + // skip initial whitespace + i++ + + for i < len(data) && isspace(data[i]) { + i++ + } + + linkB := i + + // look for link end: ' " ) + findlinkend: + for i < len(data) { + switch { + case data[i] == '\\': + i += 2 + + case data[i] == ')' || data[i] == '\'' || data[i] == '"': + break findlinkend + + default: + i++ + } + } + + if i >= len(data) { + return 0, nil + } + linkE := i + + // look for title end if present + titleB, titleE := 0, 0 + if data[i] == '\'' || data[i] == '"' { + i++ + titleB = i + + findtitleend: + for i < len(data) { + switch { + case data[i] == '\\': + i += 2 + + case data[i] == ')': + break findtitleend + + default: + i++ + } + } + + if i >= len(data) { + return 0, nil + } + + // skip whitespace after title + titleE = i - 1 + for titleE > titleB && isspace(data[titleE]) { + titleE-- + } + + // check for closing quote presence + if data[titleE] != '\'' && data[titleE] != '"' { + titleB, titleE = 0, 0 + linkE = i + } + } + + // remove whitespace at the end of the link + for linkE > linkB && isspace(data[linkE-1]) { + linkE-- + } + + // remove optional angle brackets around the link + if data[linkB] == '<' { + linkB++ + } + if data[linkE-1] == '>' { + linkE-- + } + + // build escaped link and title + if linkE > linkB { + link = data[linkB:linkE] + } + + if titleE > titleB { + title = data[titleB:titleE] + } + + i++ + + // reference style link + case isReferenceStyleLink(data, i, t): + var id []byte + altContentConsidered := false + + // look for the id + i++ + linkB := i + for i < len(data) && data[i] != ']' { + i++ + } + if i >= len(data) { + return 0, nil + } + linkE := i + + // find the reference + if linkB == linkE { + if textHasNl { + var b bytes.Buffer + + for j := 1; j < txtE; j++ { + switch { + case data[j] != '\n': + b.WriteByte(data[j]) + case data[j-1] != ' ': + b.WriteByte(' ') + } + } + + id = b.Bytes() + } else { + id = data[1:txtE] + altContentConsidered = true + } + } else { + id = data[linkB:linkE] + } + + // find the reference with matching id + lr, ok := p.getRef(string(id)) + if !ok { + return 0, nil + } + + // keep link and title from reference + link = lr.link + title = lr.title + if altContentConsidered { + altContent = lr.text + } + i++ + + // shortcut reference style link or reference or inline footnote + default: + var id []byte + + // craft the id + if textHasNl { + var b bytes.Buffer + + for j := 1; j < txtE; j++ { + switch { + case data[j] != '\n': + b.WriteByte(data[j]) + case data[j-1] != ' ': + b.WriteByte(' ') + } + } + + id = b.Bytes() + } else { + if t == linkDeferredFootnote { + id = data[2:txtE] // get rid of the ^ + } else { + id = data[1:txtE] + } + } + + footnoteNode = NewNode(Item) + if t == linkInlineFootnote { + // create a new reference + noteID = len(p.notes) + 1 + + var fragment []byte + if len(id) > 0 { + if len(id) < 16 { + fragment = make([]byte, len(id)) + } else { + fragment = make([]byte, 16) + } + copy(fragment, slugify(id)) + } else { + fragment = append([]byte("footnote-"), []byte(strconv.Itoa(noteID))...) + } + + ref := &reference{ + noteID: noteID, + hasBlock: false, + link: fragment, + title: id, + footnote: footnoteNode, + } + + p.notes = append(p.notes, ref) + + link = ref.link + title = ref.title + } else { + // find the reference with matching id + lr, ok := p.getRef(string(id)) + if !ok { + return 0, nil + } + + if t == linkDeferredFootnote { + lr.noteID = len(p.notes) + 1 + lr.footnote = footnoteNode + p.notes = append(p.notes, lr) + } + + // keep link and title from reference + link = lr.link + // if inline footnote, title == footnote contents + title = lr.title + noteID = lr.noteID + } + + // rewind the whitespace + i = txtE + 1 + } + + var uLink []byte + if t == linkNormal || t == linkImg { + if len(link) > 0 { + var uLinkBuf bytes.Buffer + unescapeText(&uLinkBuf, link) + uLink = uLinkBuf.Bytes() + } + + // links need something to click on and somewhere to go + if len(uLink) == 0 || (t == linkNormal && txtE <= 1) { + return 0, nil + } + } + + // call the relevant rendering function + var linkNode *Node + switch t { + case linkNormal: + linkNode = NewNode(Link) + linkNode.Destination = normalizeURI(uLink) + linkNode.Title = title + if len(altContent) > 0 { + linkNode.AppendChild(text(altContent)) + } else { + // links cannot contain other links, so turn off link parsing + // temporarily and recurse + insideLink := p.insideLink + p.insideLink = true + p.inline(linkNode, data[1:txtE]) + p.insideLink = insideLink + } + + case linkImg: + linkNode = NewNode(Image) + linkNode.Destination = uLink + linkNode.Title = title + linkNode.AppendChild(text(data[1:txtE])) + i++ + + case linkInlineFootnote, linkDeferredFootnote: + linkNode = NewNode(Link) + linkNode.Destination = link + linkNode.Title = title + linkNode.NoteID = noteID + linkNode.Footnote = footnoteNode + if t == linkInlineFootnote { + i++ + } + + default: + return 0, nil + } + + return i, linkNode +} + +func (p *Markdown) inlineHTMLComment(data []byte) int { + if len(data) < 5 { + return 0 + } + if data[0] != '<' || data[1] != '!' || data[2] != '-' || data[3] != '-' { + return 0 + } + i := 5 + // scan for an end-of-comment marker, across lines if necessary + for i < len(data) && !(data[i-2] == '-' && data[i-1] == '-' && data[i] == '>') { + i++ + } + // no end-of-comment marker + if i >= len(data) { + return 0 + } + return i + 1 +} + +func stripMailto(link []byte) []byte { + if bytes.HasPrefix(link, []byte("mailto://")) { + return link[9:] + } else if bytes.HasPrefix(link, []byte("mailto:")) { + return link[7:] + } else { + return link + } +} + +// autolinkType specifies a kind of autolink that gets detected. +type autolinkType int + +// These are the possible flag values for the autolink renderer. +const ( + notAutolink autolinkType = iota + normalAutolink + emailAutolink +) + +// '<' when tags or autolinks are allowed +func leftAngle(p *Markdown, data []byte, offset int) (int, *Node) { + data = data[offset:] + altype, end := tagLength(data) + if size := p.inlineHTMLComment(data); size > 0 { + end = size + } + if end > 2 { + if altype != notAutolink { + var uLink bytes.Buffer + unescapeText(&uLink, data[1:end+1-2]) + if uLink.Len() > 0 { + link := uLink.Bytes() + node := NewNode(Link) + node.Destination = link + if altype == emailAutolink { + node.Destination = append([]byte("mailto:"), link...) + } + node.AppendChild(text(stripMailto(link))) + return end, node + } + } else { + htmlTag := NewNode(HTMLSpan) + htmlTag.Literal = data[:end] + return end, htmlTag + } + } + + return end, nil +} + +// '\\' backslash escape +var escapeChars = []byte("\\`*_{}[]()#+-.!:|&<>~") + +func escape(p *Markdown, data []byte, offset int) (int, *Node) { + data = data[offset:] + + if len(data) > 1 { + if p.extensions&BackslashLineBreak != 0 && data[1] == '\n' { + return 2, NewNode(Hardbreak) + } + if bytes.IndexByte(escapeChars, data[1]) < 0 { + return 0, nil + } + + return 2, text(data[1:2]) + } + + return 2, nil +} + +func unescapeText(ob *bytes.Buffer, src []byte) { + i := 0 + for i < len(src) { + org := i + for i < len(src) && src[i] != '\\' { + i++ + } + + if i > org { + ob.Write(src[org:i]) + } + + if i+1 >= len(src) { + break + } + + ob.WriteByte(src[i+1]) + i += 2 + } +} + +// '&' escaped when it doesn't belong to an entity +// valid entities are assumed to be anything matching &#?[A-Za-z0-9]+; +func entity(p *Markdown, data []byte, offset int) (int, *Node) { + data = data[offset:] + + end := 1 + + if end < len(data) && data[end] == '#' { + end++ + } + + for end < len(data) && isalnum(data[end]) { + end++ + } + + if end < len(data) && data[end] == ';' { + end++ // real entity + } else { + return 0, nil // lone '&' + } + + ent := data[:end] + // undo & escaping or it will be converted to &amp; by another + // escaper in the renderer + if bytes.Equal(ent, []byte("&")) { + ent = []byte{'&'} + } + + return end, text(ent) +} + +func linkEndsWithEntity(data []byte, linkEnd int) bool { + entityRanges := htmlEntityRe.FindAllIndex(data[:linkEnd], -1) + return entityRanges != nil && entityRanges[len(entityRanges)-1][1] == linkEnd +} + +// hasPrefixCaseInsensitive is a custom implementation of +// strings.HasPrefix(strings.ToLower(s), prefix) +// we rolled our own because ToLower pulls in a huge machinery of lowercasing +// anything from Unicode and that's very slow. Since this func will only be +// used on ASCII protocol prefixes, we can take shortcuts. +func hasPrefixCaseInsensitive(s, prefix []byte) bool { + if len(s) < len(prefix) { + return false + } + delta := byte('a' - 'A') + for i, b := range prefix { + if b != s[i] && b != s[i]+delta { + return false + } + } + return true +} + +var protocolPrefixes = [][]byte{ + []byte("http://"), + []byte("https://"), + []byte("ftp://"), + []byte("file://"), + []byte("mailto:"), +} + +const shortestPrefix = 6 // len("ftp://"), the shortest of the above + +func maybeAutoLink(p *Markdown, data []byte, offset int) (int, *Node) { + // quick check to rule out most false hits + if p.insideLink || len(data) < offset+shortestPrefix { + return 0, nil + } + for _, prefix := range protocolPrefixes { + endOfHead := offset + 8 // 8 is the len() of the longest prefix + if endOfHead > len(data) { + endOfHead = len(data) + } + if hasPrefixCaseInsensitive(data[offset:endOfHead], prefix) { + return autoLink(p, data, offset) + } + } + return 0, nil +} + +func autoLink(p *Markdown, data []byte, offset int) (int, *Node) { + // Now a more expensive check to see if we're not inside an anchor element + anchorStart := offset + offsetFromAnchor := 0 + for anchorStart > 0 && data[anchorStart] != '<' { + anchorStart-- + offsetFromAnchor++ + } + + anchorStr := anchorRe.Find(data[anchorStart:]) + if anchorStr != nil { + anchorClose := NewNode(HTMLSpan) + anchorClose.Literal = anchorStr[offsetFromAnchor:] + return len(anchorStr) - offsetFromAnchor, anchorClose + } + + // scan backward for a word boundary + rewind := 0 + for offset-rewind > 0 && rewind <= 7 && isletter(data[offset-rewind-1]) { + rewind++ + } + if rewind > 6 { // longest supported protocol is "mailto" which has 6 letters + return 0, nil + } + + origData := data + data = data[offset-rewind:] + + if !isSafeLink(data) { + return 0, nil + } + + linkEnd := 0 + for linkEnd < len(data) && !isEndOfLink(data[linkEnd]) { + linkEnd++ + } + + // Skip punctuation at the end of the link + if (data[linkEnd-1] == '.' || data[linkEnd-1] == ',') && data[linkEnd-2] != '\\' { + linkEnd-- + } + + // But don't skip semicolon if it's a part of escaped entity: + if data[linkEnd-1] == ';' && data[linkEnd-2] != '\\' && !linkEndsWithEntity(data, linkEnd) { + linkEnd-- + } + + // See if the link finishes with a punctuation sign that can be closed. + var copen byte + switch data[linkEnd-1] { + case '"': + copen = '"' + case '\'': + copen = '\'' + case ')': + copen = '(' + case ']': + copen = '[' + case '}': + copen = '{' + default: + copen = 0 + } + + if copen != 0 { + bufEnd := offset - rewind + linkEnd - 2 + + openDelim := 1 + + /* Try to close the final punctuation sign in this same line; + * if we managed to close it outside of the URL, that means that it's + * not part of the URL. If it closes inside the URL, that means it + * is part of the URL. + * + * Examples: + * + * foo http://www.pokemon.com/Pikachu_(Electric) bar + * => http://www.pokemon.com/Pikachu_(Electric) + * + * foo (http://www.pokemon.com/Pikachu_(Electric)) bar + * => http://www.pokemon.com/Pikachu_(Electric) + * + * foo http://www.pokemon.com/Pikachu_(Electric)) bar + * => http://www.pokemon.com/Pikachu_(Electric)) + * + * (foo http://www.pokemon.com/Pikachu_(Electric)) bar + * => foo http://www.pokemon.com/Pikachu_(Electric) + */ + + for bufEnd >= 0 && origData[bufEnd] != '\n' && openDelim != 0 { + if origData[bufEnd] == data[linkEnd-1] { + openDelim++ + } + + if origData[bufEnd] == copen { + openDelim-- + } + + bufEnd-- + } + + if openDelim == 0 { + linkEnd-- + } + } + + var uLink bytes.Buffer + unescapeText(&uLink, data[:linkEnd]) + + if uLink.Len() > 0 { + node := NewNode(Link) + node.Destination = uLink.Bytes() + node.AppendChild(text(uLink.Bytes())) + return linkEnd, node + } + + return linkEnd, nil +} + +func isEndOfLink(char byte) bool { + return isspace(char) || char == '<' +} + +var validUris = [][]byte{[]byte("http://"), []byte("https://"), []byte("ftp://"), []byte("mailto://")} +var validPaths = [][]byte{[]byte("/"), []byte("./"), []byte("../")} + +func isSafeLink(link []byte) bool { + for _, path := range validPaths { + if len(link) >= len(path) && bytes.Equal(link[:len(path)], path) { + if len(link) == len(path) { + return true + } else if isalnum(link[len(path)]) { + return true + } + } + } + + for _, prefix := range validUris { + // TODO: handle unicode here + // case-insensitive prefix test + if len(link) > len(prefix) && bytes.Equal(bytes.ToLower(link[:len(prefix)]), prefix) && isalnum(link[len(prefix)]) { + return true + } + } + + return false +} + +// return the length of the given tag, or 0 is it's not valid +func tagLength(data []byte) (autolink autolinkType, end int) { + var i, j int + + // a valid tag can't be shorter than 3 chars + if len(data) < 3 { + return notAutolink, 0 + } + + // begins with a '<' optionally followed by '/', followed by letter or number + if data[0] != '<' { + return notAutolink, 0 + } + if data[1] == '/' { + i = 2 + } else { + i = 1 + } + + if !isalnum(data[i]) { + return notAutolink, 0 + } + + // scheme test + autolink = notAutolink + + // try to find the beginning of an URI + for i < len(data) && (isalnum(data[i]) || data[i] == '.' || data[i] == '+' || data[i] == '-') { + i++ + } + + if i > 1 && i < len(data) && data[i] == '@' { + if j = isMailtoAutoLink(data[i:]); j != 0 { + return emailAutolink, i + j + } + } + + if i > 2 && i < len(data) && data[i] == ':' { + autolink = normalAutolink + i++ + } + + // complete autolink test: no whitespace or ' or " + switch { + case i >= len(data): + autolink = notAutolink + case autolink != notAutolink: + j = i + + for i < len(data) { + if data[i] == '\\' { + i += 2 + } else if data[i] == '>' || data[i] == '\'' || data[i] == '"' || isspace(data[i]) { + break + } else { + i++ + } + + } + + if i >= len(data) { + return autolink, 0 + } + if i > j && data[i] == '>' { + return autolink, i + 1 + } + + // one of the forbidden chars has been found + autolink = notAutolink + } + i += bytes.IndexByte(data[i:], '>') + if i < 0 { + return autolink, 0 + } + return autolink, i + 1 +} + +// look for the address part of a mail autolink and '>' +// this is less strict than the original markdown e-mail address matching +func isMailtoAutoLink(data []byte) int { + nb := 0 + + // address is assumed to be: [-@._a-zA-Z0-9]+ with exactly one '@' + for i := 0; i < len(data); i++ { + if isalnum(data[i]) { + continue + } + + switch data[i] { + case '@': + nb++ + + case '-', '.', '_': + break + + case '>': + if nb == 1 { + return i + 1 + } + return 0 + default: + return 0 + } + } + + return 0 +} + +// look for the next emph char, skipping other constructs +func helperFindEmphChar(data []byte, c byte) int { + i := 0 + + for i < len(data) { + for i < len(data) && data[i] != c && data[i] != '`' && data[i] != '[' { + i++ + } + if i >= len(data) { + return 0 + } + // do not count escaped chars + if i != 0 && data[i-1] == '\\' { + i++ + continue + } + if data[i] == c { + return i + } + + if data[i] == '`' { + // skip a code span + tmpI := 0 + i++ + for i < len(data) && data[i] != '`' { + if tmpI == 0 && data[i] == c { + tmpI = i + } + i++ + } + if i >= len(data) { + return tmpI + } + i++ + } else if data[i] == '[' { + // skip a link + tmpI := 0 + i++ + for i < len(data) && data[i] != ']' { + if tmpI == 0 && data[i] == c { + tmpI = i + } + i++ + } + i++ + for i < len(data) && (data[i] == ' ' || data[i] == '\n') { + i++ + } + if i >= len(data) { + return tmpI + } + if data[i] != '[' && data[i] != '(' { // not a link + if tmpI > 0 { + return tmpI + } + continue + } + cc := data[i] + i++ + for i < len(data) && data[i] != cc { + if tmpI == 0 && data[i] == c { + return i + } + i++ + } + if i >= len(data) { + return tmpI + } + i++ + } + } + return 0 +} + +func helperEmphasis(p *Markdown, data []byte, c byte) (int, *Node) { + i := 0 + + // skip one symbol if coming from emph3 + if len(data) > 1 && data[0] == c && data[1] == c { + i = 1 + } + + for i < len(data) { + length := helperFindEmphChar(data[i:], c) + if length == 0 { + return 0, nil + } + i += length + if i >= len(data) { + return 0, nil + } + + if i+1 < len(data) && data[i+1] == c { + i++ + continue + } + + if data[i] == c && !isspace(data[i-1]) { + + if p.extensions&NoIntraEmphasis != 0 { + if !(i+1 == len(data) || isspace(data[i+1]) || ispunct(data[i+1])) { + continue + } + } + + emph := NewNode(Emph) + p.inline(emph, data[:i]) + return i + 1, emph + } + } + + return 0, nil +} + +func helperDoubleEmphasis(p *Markdown, data []byte, c byte) (int, *Node) { + i := 0 + + for i < len(data) { + length := helperFindEmphChar(data[i:], c) + if length == 0 { + return 0, nil + } + i += length + + if i+1 < len(data) && data[i] == c && data[i+1] == c && i > 0 && !isspace(data[i-1]) { + nodeType := Strong + if c == '~' { + nodeType = Del + } + node := NewNode(nodeType) + p.inline(node, data[:i]) + return i + 2, node + } + i++ + } + return 0, nil +} + +func helperTripleEmphasis(p *Markdown, data []byte, offset int, c byte) (int, *Node) { + i := 0 + origData := data + data = data[offset:] + + for i < len(data) { + length := helperFindEmphChar(data[i:], c) + if length == 0 { + return 0, nil + } + i += length + + // skip whitespace preceded symbols + if data[i] != c || isspace(data[i-1]) { + continue + } + + switch { + case i+2 < len(data) && data[i+1] == c && data[i+2] == c: + // triple symbol found + strong := NewNode(Strong) + em := NewNode(Emph) + strong.AppendChild(em) + p.inline(em, data[:i]) + return i + 3, strong + case (i+1 < len(data) && data[i+1] == c): + // double symbol found, hand over to emph1 + length, node := helperEmphasis(p, origData[offset-2:], c) + if length == 0 { + return 0, nil + } + return length - 2, node + default: + // single symbol found, hand over to emph2 + length, node := helperDoubleEmphasis(p, origData[offset-1:], c) + if length == 0 { + return 0, nil + } + return length - 1, node + } + } + return 0, nil +} + +func text(s []byte) *Node { + node := NewNode(Text) + node.Literal = s + return node +} + +func normalizeURI(s []byte) []byte { + return s // TODO: implement +} diff --git a/plugins/source-github/vendor/github.com/russross/blackfriday/v2/markdown.go b/plugins/source-github/vendor/github.com/russross/blackfriday/v2/markdown.go new file mode 100644 index 00000000..58d2e453 --- /dev/null +++ b/plugins/source-github/vendor/github.com/russross/blackfriday/v2/markdown.go @@ -0,0 +1,950 @@ +// Blackfriday Markdown Processor +// Available at http://github.com/russross/blackfriday +// +// Copyright © 2011 Russ Ross . +// Distributed under the Simplified BSD License. +// See README.md for details. + +package blackfriday + +import ( + "bytes" + "fmt" + "io" + "strings" + "unicode/utf8" +) + +// +// Markdown parsing and processing +// + +// Version string of the package. Appears in the rendered document when +// CompletePage flag is on. +const Version = "2.0" + +// Extensions is a bitwise or'ed collection of enabled Blackfriday's +// extensions. +type Extensions int + +// These are the supported markdown parsing extensions. +// OR these values together to select multiple extensions. +const ( + NoExtensions Extensions = 0 + NoIntraEmphasis Extensions = 1 << iota // Ignore emphasis markers inside words + Tables // Render tables + FencedCode // Render fenced code blocks + Autolink // Detect embedded URLs that are not explicitly marked + Strikethrough // Strikethrough text using ~~test~~ + LaxHTMLBlocks // Loosen up HTML block parsing rules + SpaceHeadings // Be strict about prefix heading rules + HardLineBreak // Translate newlines into line breaks + TabSizeEight // Expand tabs to eight spaces instead of four + Footnotes // Pandoc-style footnotes + NoEmptyLineBeforeBlock // No need to insert an empty line to start a (code, quote, ordered list, unordered list) block + HeadingIDs // specify heading IDs with {#id} + Titleblock // Titleblock ala pandoc + AutoHeadingIDs // Create the heading ID from the text + BackslashLineBreak // Translate trailing backslashes into line breaks + DefinitionLists // Render definition lists + + CommonHTMLFlags HTMLFlags = UseXHTML | Smartypants | + SmartypantsFractions | SmartypantsDashes | SmartypantsLatexDashes + + CommonExtensions Extensions = NoIntraEmphasis | Tables | FencedCode | + Autolink | Strikethrough | SpaceHeadings | HeadingIDs | + BackslashLineBreak | DefinitionLists +) + +// ListType contains bitwise or'ed flags for list and list item objects. +type ListType int + +// These are the possible flag values for the ListItem renderer. +// Multiple flag values may be ORed together. +// These are mostly of interest if you are writing a new output format. +const ( + ListTypeOrdered ListType = 1 << iota + ListTypeDefinition + ListTypeTerm + + ListItemContainsBlock + ListItemBeginningOfList // TODO: figure out if this is of any use now + ListItemEndOfList +) + +// CellAlignFlags holds a type of alignment in a table cell. +type CellAlignFlags int + +// These are the possible flag values for the table cell renderer. +// Only a single one of these values will be used; they are not ORed together. +// These are mostly of interest if you are writing a new output format. +const ( + TableAlignmentLeft CellAlignFlags = 1 << iota + TableAlignmentRight + TableAlignmentCenter = (TableAlignmentLeft | TableAlignmentRight) +) + +// The size of a tab stop. +const ( + TabSizeDefault = 4 + TabSizeDouble = 8 +) + +// blockTags is a set of tags that are recognized as HTML block tags. +// Any of these can be included in markdown text without special escaping. +var blockTags = map[string]struct{}{ + "blockquote": {}, + "del": {}, + "div": {}, + "dl": {}, + "fieldset": {}, + "form": {}, + "h1": {}, + "h2": {}, + "h3": {}, + "h4": {}, + "h5": {}, + "h6": {}, + "iframe": {}, + "ins": {}, + "math": {}, + "noscript": {}, + "ol": {}, + "pre": {}, + "p": {}, + "script": {}, + "style": {}, + "table": {}, + "ul": {}, + + // HTML5 + "address": {}, + "article": {}, + "aside": {}, + "canvas": {}, + "figcaption": {}, + "figure": {}, + "footer": {}, + "header": {}, + "hgroup": {}, + "main": {}, + "nav": {}, + "output": {}, + "progress": {}, + "section": {}, + "video": {}, +} + +// Renderer is the rendering interface. This is mostly of interest if you are +// implementing a new rendering format. +// +// Only an HTML implementation is provided in this repository, see the README +// for external implementations. +type Renderer interface { + // RenderNode is the main rendering method. It will be called once for + // every leaf node and twice for every non-leaf node (first with + // entering=true, then with entering=false). The method should write its + // rendition of the node to the supplied writer w. + RenderNode(w io.Writer, node *Node, entering bool) WalkStatus + + // RenderHeader is a method that allows the renderer to produce some + // content preceding the main body of the output document. The header is + // understood in the broad sense here. For example, the default HTML + // renderer will write not only the HTML document preamble, but also the + // table of contents if it was requested. + // + // The method will be passed an entire document tree, in case a particular + // implementation needs to inspect it to produce output. + // + // The output should be written to the supplied writer w. If your + // implementation has no header to write, supply an empty implementation. + RenderHeader(w io.Writer, ast *Node) + + // RenderFooter is a symmetric counterpart of RenderHeader. + RenderFooter(w io.Writer, ast *Node) +} + +// Callback functions for inline parsing. One such function is defined +// for each character that triggers a response when parsing inline data. +type inlineParser func(p *Markdown, data []byte, offset int) (int, *Node) + +// Markdown is a type that holds extensions and the runtime state used by +// Parse, and the renderer. You can not use it directly, construct it with New. +type Markdown struct { + renderer Renderer + referenceOverride ReferenceOverrideFunc + refs map[string]*reference + inlineCallback [256]inlineParser + extensions Extensions + nesting int + maxNesting int + insideLink bool + + // Footnotes need to be ordered as well as available to quickly check for + // presence. If a ref is also a footnote, it's stored both in refs and here + // in notes. Slice is nil if footnotes not enabled. + notes []*reference + + doc *Node + tip *Node // = doc + oldTip *Node + lastMatchedContainer *Node // = doc + allClosed bool +} + +func (p *Markdown) getRef(refid string) (ref *reference, found bool) { + if p.referenceOverride != nil { + r, overridden := p.referenceOverride(refid) + if overridden { + if r == nil { + return nil, false + } + return &reference{ + link: []byte(r.Link), + title: []byte(r.Title), + noteID: 0, + hasBlock: false, + text: []byte(r.Text)}, true + } + } + // refs are case insensitive + ref, found = p.refs[strings.ToLower(refid)] + return ref, found +} + +func (p *Markdown) finalize(block *Node) { + above := block.Parent + block.open = false + p.tip = above +} + +func (p *Markdown) addChild(node NodeType, offset uint32) *Node { + return p.addExistingChild(NewNode(node), offset) +} + +func (p *Markdown) addExistingChild(node *Node, offset uint32) *Node { + for !p.tip.canContain(node.Type) { + p.finalize(p.tip) + } + p.tip.AppendChild(node) + p.tip = node + return node +} + +func (p *Markdown) closeUnmatchedBlocks() { + if !p.allClosed { + for p.oldTip != p.lastMatchedContainer { + parent := p.oldTip.Parent + p.finalize(p.oldTip) + p.oldTip = parent + } + p.allClosed = true + } +} + +// +// +// Public interface +// +// + +// Reference represents the details of a link. +// See the documentation in Options for more details on use-case. +type Reference struct { + // Link is usually the URL the reference points to. + Link string + // Title is the alternate text describing the link in more detail. + Title string + // Text is the optional text to override the ref with if the syntax used was + // [refid][] + Text string +} + +// ReferenceOverrideFunc is expected to be called with a reference string and +// return either a valid Reference type that the reference string maps to or +// nil. If overridden is false, the default reference logic will be executed. +// See the documentation in Options for more details on use-case. +type ReferenceOverrideFunc func(reference string) (ref *Reference, overridden bool) + +// New constructs a Markdown processor. You can use the same With* functions as +// for Run() to customize parser's behavior and the renderer. +func New(opts ...Option) *Markdown { + var p Markdown + for _, opt := range opts { + opt(&p) + } + p.refs = make(map[string]*reference) + p.maxNesting = 16 + p.insideLink = false + docNode := NewNode(Document) + p.doc = docNode + p.tip = docNode + p.oldTip = docNode + p.lastMatchedContainer = docNode + p.allClosed = true + // register inline parsers + p.inlineCallback[' '] = maybeLineBreak + p.inlineCallback['*'] = emphasis + p.inlineCallback['_'] = emphasis + if p.extensions&Strikethrough != 0 { + p.inlineCallback['~'] = emphasis + } + p.inlineCallback['`'] = codeSpan + p.inlineCallback['\n'] = lineBreak + p.inlineCallback['['] = link + p.inlineCallback['<'] = leftAngle + p.inlineCallback['\\'] = escape + p.inlineCallback['&'] = entity + p.inlineCallback['!'] = maybeImage + p.inlineCallback['^'] = maybeInlineFootnote + if p.extensions&Autolink != 0 { + p.inlineCallback['h'] = maybeAutoLink + p.inlineCallback['m'] = maybeAutoLink + p.inlineCallback['f'] = maybeAutoLink + p.inlineCallback['H'] = maybeAutoLink + p.inlineCallback['M'] = maybeAutoLink + p.inlineCallback['F'] = maybeAutoLink + } + if p.extensions&Footnotes != 0 { + p.notes = make([]*reference, 0) + } + return &p +} + +// Option customizes the Markdown processor's default behavior. +type Option func(*Markdown) + +// WithRenderer allows you to override the default renderer. +func WithRenderer(r Renderer) Option { + return func(p *Markdown) { + p.renderer = r + } +} + +// WithExtensions allows you to pick some of the many extensions provided by +// Blackfriday. You can bitwise OR them. +func WithExtensions(e Extensions) Option { + return func(p *Markdown) { + p.extensions = e + } +} + +// WithNoExtensions turns off all extensions and custom behavior. +func WithNoExtensions() Option { + return func(p *Markdown) { + p.extensions = NoExtensions + p.renderer = NewHTMLRenderer(HTMLRendererParameters{ + Flags: HTMLFlagsNone, + }) + } +} + +// WithRefOverride sets an optional function callback that is called every +// time a reference is resolved. +// +// In Markdown, the link reference syntax can be made to resolve a link to +// a reference instead of an inline URL, in one of the following ways: +// +// * [link text][refid] +// * [refid][] +// +// Usually, the refid is defined at the bottom of the Markdown document. If +// this override function is provided, the refid is passed to the override +// function first, before consulting the defined refids at the bottom. If +// the override function indicates an override did not occur, the refids at +// the bottom will be used to fill in the link details. +func WithRefOverride(o ReferenceOverrideFunc) Option { + return func(p *Markdown) { + p.referenceOverride = o + } +} + +// Run is the main entry point to Blackfriday. It parses and renders a +// block of markdown-encoded text. +// +// The simplest invocation of Run takes one argument, input: +// output := Run(input) +// This will parse the input with CommonExtensions enabled and render it with +// the default HTMLRenderer (with CommonHTMLFlags). +// +// Variadic arguments opts can customize the default behavior. Since Markdown +// type does not contain exported fields, you can not use it directly. Instead, +// use the With* functions. For example, this will call the most basic +// functionality, with no extensions: +// output := Run(input, WithNoExtensions()) +// +// You can use any number of With* arguments, even contradicting ones. They +// will be applied in order of appearance and the latter will override the +// former: +// output := Run(input, WithNoExtensions(), WithExtensions(exts), +// WithRenderer(yourRenderer)) +func Run(input []byte, opts ...Option) []byte { + r := NewHTMLRenderer(HTMLRendererParameters{ + Flags: CommonHTMLFlags, + }) + optList := []Option{WithRenderer(r), WithExtensions(CommonExtensions)} + optList = append(optList, opts...) + parser := New(optList...) + ast := parser.Parse(input) + var buf bytes.Buffer + parser.renderer.RenderHeader(&buf, ast) + ast.Walk(func(node *Node, entering bool) WalkStatus { + return parser.renderer.RenderNode(&buf, node, entering) + }) + parser.renderer.RenderFooter(&buf, ast) + return buf.Bytes() +} + +// Parse is an entry point to the parsing part of Blackfriday. It takes an +// input markdown document and produces a syntax tree for its contents. This +// tree can then be rendered with a default or custom renderer, or +// analyzed/transformed by the caller to whatever non-standard needs they have. +// The return value is the root node of the syntax tree. +func (p *Markdown) Parse(input []byte) *Node { + p.block(input) + // Walk the tree and finish up some of unfinished blocks + for p.tip != nil { + p.finalize(p.tip) + } + // Walk the tree again and process inline markdown in each block + p.doc.Walk(func(node *Node, entering bool) WalkStatus { + if node.Type == Paragraph || node.Type == Heading || node.Type == TableCell { + p.inline(node, node.content) + node.content = nil + } + return GoToNext + }) + p.parseRefsToAST() + return p.doc +} + +func (p *Markdown) parseRefsToAST() { + if p.extensions&Footnotes == 0 || len(p.notes) == 0 { + return + } + p.tip = p.doc + block := p.addBlock(List, nil) + block.IsFootnotesList = true + block.ListFlags = ListTypeOrdered + flags := ListItemBeginningOfList + // Note: this loop is intentionally explicit, not range-form. This is + // because the body of the loop will append nested footnotes to p.notes and + // we need to process those late additions. Range form would only walk over + // the fixed initial set. + for i := 0; i < len(p.notes); i++ { + ref := p.notes[i] + p.addExistingChild(ref.footnote, 0) + block := ref.footnote + block.ListFlags = flags | ListTypeOrdered + block.RefLink = ref.link + if ref.hasBlock { + flags |= ListItemContainsBlock + p.block(ref.title) + } else { + p.inline(block, ref.title) + } + flags &^= ListItemBeginningOfList | ListItemContainsBlock + } + above := block.Parent + finalizeList(block) + p.tip = above + block.Walk(func(node *Node, entering bool) WalkStatus { + if node.Type == Paragraph || node.Type == Heading { + p.inline(node, node.content) + node.content = nil + } + return GoToNext + }) +} + +// +// Link references +// +// This section implements support for references that (usually) appear +// as footnotes in a document, and can be referenced anywhere in the document. +// The basic format is: +// +// [1]: http://www.google.com/ "Google" +// [2]: http://www.github.com/ "Github" +// +// Anywhere in the document, the reference can be linked by referring to its +// label, i.e., 1 and 2 in this example, as in: +// +// This library is hosted on [Github][2], a git hosting site. +// +// Actual footnotes as specified in Pandoc and supported by some other Markdown +// libraries such as php-markdown are also taken care of. They look like this: +// +// This sentence needs a bit of further explanation.[^note] +// +// [^note]: This is the explanation. +// +// Footnotes should be placed at the end of the document in an ordered list. +// Finally, there are inline footnotes such as: +// +// Inline footnotes^[Also supported.] provide a quick inline explanation, +// but are rendered at the bottom of the document. +// + +// reference holds all information necessary for a reference-style links or +// footnotes. +// +// Consider this markdown with reference-style links: +// +// [link][ref] +// +// [ref]: /url/ "tooltip title" +// +// It will be ultimately converted to this HTML: +// +//

    link

    +// +// And a reference structure will be populated as follows: +// +// p.refs["ref"] = &reference{ +// link: "/url/", +// title: "tooltip title", +// } +// +// Alternatively, reference can contain information about a footnote. Consider +// this markdown: +// +// Text needing a footnote.[^a] +// +// [^a]: This is the note +// +// A reference structure will be populated as follows: +// +// p.refs["a"] = &reference{ +// link: "a", +// title: "This is the note", +// noteID: , +// } +// +// TODO: As you can see, it begs for splitting into two dedicated structures +// for refs and for footnotes. +type reference struct { + link []byte + title []byte + noteID int // 0 if not a footnote ref + hasBlock bool + footnote *Node // a link to the Item node within a list of footnotes + + text []byte // only gets populated by refOverride feature with Reference.Text +} + +func (r *reference) String() string { + return fmt.Sprintf("{link: %q, title: %q, text: %q, noteID: %d, hasBlock: %v}", + r.link, r.title, r.text, r.noteID, r.hasBlock) +} + +// Check whether or not data starts with a reference link. +// If so, it is parsed and stored in the list of references +// (in the render struct). +// Returns the number of bytes to skip to move past it, +// or zero if the first line is not a reference. +func isReference(p *Markdown, data []byte, tabSize int) int { + // up to 3 optional leading spaces + if len(data) < 4 { + return 0 + } + i := 0 + for i < 3 && data[i] == ' ' { + i++ + } + + noteID := 0 + + // id part: anything but a newline between brackets + if data[i] != '[' { + return 0 + } + i++ + if p.extensions&Footnotes != 0 { + if i < len(data) && data[i] == '^' { + // we can set it to anything here because the proper noteIds will + // be assigned later during the second pass. It just has to be != 0 + noteID = 1 + i++ + } + } + idOffset := i + for i < len(data) && data[i] != '\n' && data[i] != '\r' && data[i] != ']' { + i++ + } + if i >= len(data) || data[i] != ']' { + return 0 + } + idEnd := i + // footnotes can have empty ID, like this: [^], but a reference can not be + // empty like this: []. Break early if it's not a footnote and there's no ID + if noteID == 0 && idOffset == idEnd { + return 0 + } + // spacer: colon (space | tab)* newline? (space | tab)* + i++ + if i >= len(data) || data[i] != ':' { + return 0 + } + i++ + for i < len(data) && (data[i] == ' ' || data[i] == '\t') { + i++ + } + if i < len(data) && (data[i] == '\n' || data[i] == '\r') { + i++ + if i < len(data) && data[i] == '\n' && data[i-1] == '\r' { + i++ + } + } + for i < len(data) && (data[i] == ' ' || data[i] == '\t') { + i++ + } + if i >= len(data) { + return 0 + } + + var ( + linkOffset, linkEnd int + titleOffset, titleEnd int + lineEnd int + raw []byte + hasBlock bool + ) + + if p.extensions&Footnotes != 0 && noteID != 0 { + linkOffset, linkEnd, raw, hasBlock = scanFootnote(p, data, i, tabSize) + lineEnd = linkEnd + } else { + linkOffset, linkEnd, titleOffset, titleEnd, lineEnd = scanLinkRef(p, data, i) + } + if lineEnd == 0 { + return 0 + } + + // a valid ref has been found + + ref := &reference{ + noteID: noteID, + hasBlock: hasBlock, + } + + if noteID > 0 { + // reusing the link field for the id since footnotes don't have links + ref.link = data[idOffset:idEnd] + // if footnote, it's not really a title, it's the contained text + ref.title = raw + } else { + ref.link = data[linkOffset:linkEnd] + ref.title = data[titleOffset:titleEnd] + } + + // id matches are case-insensitive + id := string(bytes.ToLower(data[idOffset:idEnd])) + + p.refs[id] = ref + + return lineEnd +} + +func scanLinkRef(p *Markdown, data []byte, i int) (linkOffset, linkEnd, titleOffset, titleEnd, lineEnd int) { + // link: whitespace-free sequence, optionally between angle brackets + if data[i] == '<' { + i++ + } + linkOffset = i + for i < len(data) && data[i] != ' ' && data[i] != '\t' && data[i] != '\n' && data[i] != '\r' { + i++ + } + linkEnd = i + if data[linkOffset] == '<' && data[linkEnd-1] == '>' { + linkOffset++ + linkEnd-- + } + + // optional spacer: (space | tab)* (newline | '\'' | '"' | '(' ) + for i < len(data) && (data[i] == ' ' || data[i] == '\t') { + i++ + } + if i < len(data) && data[i] != '\n' && data[i] != '\r' && data[i] != '\'' && data[i] != '"' && data[i] != '(' { + return + } + + // compute end-of-line + if i >= len(data) || data[i] == '\r' || data[i] == '\n' { + lineEnd = i + } + if i+1 < len(data) && data[i] == '\r' && data[i+1] == '\n' { + lineEnd++ + } + + // optional (space|tab)* spacer after a newline + if lineEnd > 0 { + i = lineEnd + 1 + for i < len(data) && (data[i] == ' ' || data[i] == '\t') { + i++ + } + } + + // optional title: any non-newline sequence enclosed in '"() alone on its line + if i+1 < len(data) && (data[i] == '\'' || data[i] == '"' || data[i] == '(') { + i++ + titleOffset = i + + // look for EOL + for i < len(data) && data[i] != '\n' && data[i] != '\r' { + i++ + } + if i+1 < len(data) && data[i] == '\n' && data[i+1] == '\r' { + titleEnd = i + 1 + } else { + titleEnd = i + } + + // step back + i-- + for i > titleOffset && (data[i] == ' ' || data[i] == '\t') { + i-- + } + if i > titleOffset && (data[i] == '\'' || data[i] == '"' || data[i] == ')') { + lineEnd = titleEnd + titleEnd = i + } + } + + return +} + +// The first bit of this logic is the same as Parser.listItem, but the rest +// is much simpler. This function simply finds the entire block and shifts it +// over by one tab if it is indeed a block (just returns the line if it's not). +// blockEnd is the end of the section in the input buffer, and contents is the +// extracted text that was shifted over one tab. It will need to be rendered at +// the end of the document. +func scanFootnote(p *Markdown, data []byte, i, indentSize int) (blockStart, blockEnd int, contents []byte, hasBlock bool) { + if i == 0 || len(data) == 0 { + return + } + + // skip leading whitespace on first line + for i < len(data) && data[i] == ' ' { + i++ + } + + blockStart = i + + // find the end of the line + blockEnd = i + for i < len(data) && data[i-1] != '\n' { + i++ + } + + // get working buffer + var raw bytes.Buffer + + // put the first line into the working buffer + raw.Write(data[blockEnd:i]) + blockEnd = i + + // process the following lines + containsBlankLine := false + +gatherLines: + for blockEnd < len(data) { + i++ + + // find the end of this line + for i < len(data) && data[i-1] != '\n' { + i++ + } + + // if it is an empty line, guess that it is part of this item + // and move on to the next line + if p.isEmpty(data[blockEnd:i]) > 0 { + containsBlankLine = true + blockEnd = i + continue + } + + n := 0 + if n = isIndented(data[blockEnd:i], indentSize); n == 0 { + // this is the end of the block. + // we don't want to include this last line in the index. + break gatherLines + } + + // if there were blank lines before this one, insert a new one now + if containsBlankLine { + raw.WriteByte('\n') + containsBlankLine = false + } + + // get rid of that first tab, write to buffer + raw.Write(data[blockEnd+n : i]) + hasBlock = true + + blockEnd = i + } + + if data[blockEnd-1] != '\n' { + raw.WriteByte('\n') + } + + contents = raw.Bytes() + + return +} + +// +// +// Miscellaneous helper functions +// +// + +// Test if a character is a punctuation symbol. +// Taken from a private function in regexp in the stdlib. +func ispunct(c byte) bool { + for _, r := range []byte("!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~") { + if c == r { + return true + } + } + return false +} + +// Test if a character is a whitespace character. +func isspace(c byte) bool { + return ishorizontalspace(c) || isverticalspace(c) +} + +// Test if a character is a horizontal whitespace character. +func ishorizontalspace(c byte) bool { + return c == ' ' || c == '\t' +} + +// Test if a character is a vertical character. +func isverticalspace(c byte) bool { + return c == '\n' || c == '\r' || c == '\f' || c == '\v' +} + +// Test if a character is letter. +func isletter(c byte) bool { + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') +} + +// Test if a character is a letter or a digit. +// TODO: check when this is looking for ASCII alnum and when it should use unicode +func isalnum(c byte) bool { + return (c >= '0' && c <= '9') || isletter(c) +} + +// Replace tab characters with spaces, aligning to the next TAB_SIZE column. +// always ends output with a newline +func expandTabs(out *bytes.Buffer, line []byte, tabSize int) { + // first, check for common cases: no tabs, or only tabs at beginning of line + i, prefix := 0, 0 + slowcase := false + for i = 0; i < len(line); i++ { + if line[i] == '\t' { + if prefix == i { + prefix++ + } else { + slowcase = true + break + } + } + } + + // no need to decode runes if all tabs are at the beginning of the line + if !slowcase { + for i = 0; i < prefix*tabSize; i++ { + out.WriteByte(' ') + } + out.Write(line[prefix:]) + return + } + + // the slow case: we need to count runes to figure out how + // many spaces to insert for each tab + column := 0 + i = 0 + for i < len(line) { + start := i + for i < len(line) && line[i] != '\t' { + _, size := utf8.DecodeRune(line[i:]) + i += size + column++ + } + + if i > start { + out.Write(line[start:i]) + } + + if i >= len(line) { + break + } + + for { + out.WriteByte(' ') + column++ + if column%tabSize == 0 { + break + } + } + + i++ + } +} + +// Find if a line counts as indented or not. +// Returns number of characters the indent is (0 = not indented). +func isIndented(data []byte, indentSize int) int { + if len(data) == 0 { + return 0 + } + if data[0] == '\t' { + return 1 + } + if len(data) < indentSize { + return 0 + } + for i := 0; i < indentSize; i++ { + if data[i] != ' ' { + return 0 + } + } + return indentSize +} + +// Create a url-safe slug for fragments +func slugify(in []byte) []byte { + if len(in) == 0 { + return in + } + out := make([]byte, 0, len(in)) + sym := false + + for _, ch := range in { + if isalnum(ch) { + sym = false + out = append(out, ch) + } else if sym { + continue + } else { + out = append(out, '-') + sym = true + } + } + var a, b int + var ch byte + for a, ch = range out { + if ch != '-' { + break + } + } + for b = len(out) - 1; b > 0; b-- { + if out[b] != '-' { + break + } + } + return out[a : b+1] +} diff --git a/plugins/source-github/vendor/github.com/russross/blackfriday/v2/node.go b/plugins/source-github/vendor/github.com/russross/blackfriday/v2/node.go new file mode 100644 index 00000000..51b9e8c1 --- /dev/null +++ b/plugins/source-github/vendor/github.com/russross/blackfriday/v2/node.go @@ -0,0 +1,354 @@ +package blackfriday + +import ( + "bytes" + "fmt" +) + +// NodeType specifies a type of a single node of a syntax tree. Usually one +// node (and its type) corresponds to a single markdown feature, e.g. emphasis +// or code block. +type NodeType int + +// Constants for identifying different types of nodes. See NodeType. +const ( + Document NodeType = iota + BlockQuote + List + Item + Paragraph + Heading + HorizontalRule + Emph + Strong + Del + Link + Image + Text + HTMLBlock + CodeBlock + Softbreak + Hardbreak + Code + HTMLSpan + Table + TableCell + TableHead + TableBody + TableRow +) + +var nodeTypeNames = []string{ + Document: "Document", + BlockQuote: "BlockQuote", + List: "List", + Item: "Item", + Paragraph: "Paragraph", + Heading: "Heading", + HorizontalRule: "HorizontalRule", + Emph: "Emph", + Strong: "Strong", + Del: "Del", + Link: "Link", + Image: "Image", + Text: "Text", + HTMLBlock: "HTMLBlock", + CodeBlock: "CodeBlock", + Softbreak: "Softbreak", + Hardbreak: "Hardbreak", + Code: "Code", + HTMLSpan: "HTMLSpan", + Table: "Table", + TableCell: "TableCell", + TableHead: "TableHead", + TableBody: "TableBody", + TableRow: "TableRow", +} + +func (t NodeType) String() string { + return nodeTypeNames[t] +} + +// ListData contains fields relevant to a List and Item node type. +type ListData struct { + ListFlags ListType + Tight bool // Skip

    s around list item data if true + BulletChar byte // '*', '+' or '-' in bullet lists + Delimiter byte // '.' or ')' after the number in ordered lists + RefLink []byte // If not nil, turns this list item into a footnote item and triggers different rendering + IsFootnotesList bool // This is a list of footnotes +} + +// LinkData contains fields relevant to a Link node type. +type LinkData struct { + Destination []byte // Destination is what goes into a href + Title []byte // Title is the tooltip thing that goes in a title attribute + NoteID int // NoteID contains a serial number of a footnote, zero if it's not a footnote + Footnote *Node // If it's a footnote, this is a direct link to the footnote Node. Otherwise nil. +} + +// CodeBlockData contains fields relevant to a CodeBlock node type. +type CodeBlockData struct { + IsFenced bool // Specifies whether it's a fenced code block or an indented one + Info []byte // This holds the info string + FenceChar byte + FenceLength int + FenceOffset int +} + +// TableCellData contains fields relevant to a TableCell node type. +type TableCellData struct { + IsHeader bool // This tells if it's under the header row + Align CellAlignFlags // This holds the value for align attribute +} + +// HeadingData contains fields relevant to a Heading node type. +type HeadingData struct { + Level int // This holds the heading level number + HeadingID string // This might hold heading ID, if present + IsTitleblock bool // Specifies whether it's a title block +} + +// Node is a single element in the abstract syntax tree of the parsed document. +// It holds connections to the structurally neighboring nodes and, for certain +// types of nodes, additional information that might be needed when rendering. +type Node struct { + Type NodeType // Determines the type of the node + Parent *Node // Points to the parent + FirstChild *Node // Points to the first child, if any + LastChild *Node // Points to the last child, if any + Prev *Node // Previous sibling; nil if it's the first child + Next *Node // Next sibling; nil if it's the last child + + Literal []byte // Text contents of the leaf nodes + + HeadingData // Populated if Type is Heading + ListData // Populated if Type is List + CodeBlockData // Populated if Type is CodeBlock + LinkData // Populated if Type is Link + TableCellData // Populated if Type is TableCell + + content []byte // Markdown content of the block nodes + open bool // Specifies an open block node that has not been finished to process yet +} + +// NewNode allocates a node of a specified type. +func NewNode(typ NodeType) *Node { + return &Node{ + Type: typ, + open: true, + } +} + +func (n *Node) String() string { + ellipsis := "" + snippet := n.Literal + if len(snippet) > 16 { + snippet = snippet[:16] + ellipsis = "..." + } + return fmt.Sprintf("%s: '%s%s'", n.Type, snippet, ellipsis) +} + +// Unlink removes node 'n' from the tree. +// It panics if the node is nil. +func (n *Node) Unlink() { + if n.Prev != nil { + n.Prev.Next = n.Next + } else if n.Parent != nil { + n.Parent.FirstChild = n.Next + } + if n.Next != nil { + n.Next.Prev = n.Prev + } else if n.Parent != nil { + n.Parent.LastChild = n.Prev + } + n.Parent = nil + n.Next = nil + n.Prev = nil +} + +// AppendChild adds a node 'child' as a child of 'n'. +// It panics if either node is nil. +func (n *Node) AppendChild(child *Node) { + child.Unlink() + child.Parent = n + if n.LastChild != nil { + n.LastChild.Next = child + child.Prev = n.LastChild + n.LastChild = child + } else { + n.FirstChild = child + n.LastChild = child + } +} + +// InsertBefore inserts 'sibling' immediately before 'n'. +// It panics if either node is nil. +func (n *Node) InsertBefore(sibling *Node) { + sibling.Unlink() + sibling.Prev = n.Prev + if sibling.Prev != nil { + sibling.Prev.Next = sibling + } + sibling.Next = n + n.Prev = sibling + sibling.Parent = n.Parent + if sibling.Prev == nil { + sibling.Parent.FirstChild = sibling + } +} + +func (n *Node) isContainer() bool { + switch n.Type { + case Document: + fallthrough + case BlockQuote: + fallthrough + case List: + fallthrough + case Item: + fallthrough + case Paragraph: + fallthrough + case Heading: + fallthrough + case Emph: + fallthrough + case Strong: + fallthrough + case Del: + fallthrough + case Link: + fallthrough + case Image: + fallthrough + case Table: + fallthrough + case TableHead: + fallthrough + case TableBody: + fallthrough + case TableRow: + fallthrough + case TableCell: + return true + default: + return false + } +} + +func (n *Node) canContain(t NodeType) bool { + if n.Type == List { + return t == Item + } + if n.Type == Document || n.Type == BlockQuote || n.Type == Item { + return t != Item + } + if n.Type == Table { + return t == TableHead || t == TableBody + } + if n.Type == TableHead || n.Type == TableBody { + return t == TableRow + } + if n.Type == TableRow { + return t == TableCell + } + return false +} + +// WalkStatus allows NodeVisitor to have some control over the tree traversal. +// It is returned from NodeVisitor and different values allow Node.Walk to +// decide which node to go to next. +type WalkStatus int + +const ( + // GoToNext is the default traversal of every node. + GoToNext WalkStatus = iota + // SkipChildren tells walker to skip all children of current node. + SkipChildren + // Terminate tells walker to terminate the traversal. + Terminate +) + +// NodeVisitor is a callback to be called when traversing the syntax tree. +// Called twice for every node: once with entering=true when the branch is +// first visited, then with entering=false after all the children are done. +type NodeVisitor func(node *Node, entering bool) WalkStatus + +// Walk is a convenience method that instantiates a walker and starts a +// traversal of subtree rooted at n. +func (n *Node) Walk(visitor NodeVisitor) { + w := newNodeWalker(n) + for w.current != nil { + status := visitor(w.current, w.entering) + switch status { + case GoToNext: + w.next() + case SkipChildren: + w.entering = false + w.next() + case Terminate: + return + } + } +} + +type nodeWalker struct { + current *Node + root *Node + entering bool +} + +func newNodeWalker(root *Node) *nodeWalker { + return &nodeWalker{ + current: root, + root: root, + entering: true, + } +} + +func (nw *nodeWalker) next() { + if (!nw.current.isContainer() || !nw.entering) && nw.current == nw.root { + nw.current = nil + return + } + if nw.entering && nw.current.isContainer() { + if nw.current.FirstChild != nil { + nw.current = nw.current.FirstChild + nw.entering = true + } else { + nw.entering = false + } + } else if nw.current.Next == nil { + nw.current = nw.current.Parent + nw.entering = false + } else { + nw.current = nw.current.Next + nw.entering = true + } +} + +func dump(ast *Node) { + fmt.Println(dumpString(ast)) +} + +func dumpR(ast *Node, depth int) string { + if ast == nil { + return "" + } + indent := bytes.Repeat([]byte("\t"), depth) + content := ast.Literal + if content == nil { + content = ast.content + } + result := fmt.Sprintf("%s%s(%q)\n", indent, ast.Type, content) + for n := ast.FirstChild; n != nil; n = n.Next { + result += dumpR(n, depth+1) + } + return result +} + +func dumpString(ast *Node) string { + return dumpR(ast, 0) +} diff --git a/plugins/source-github/vendor/github.com/russross/blackfriday/v2/smartypants.go b/plugins/source-github/vendor/github.com/russross/blackfriday/v2/smartypants.go new file mode 100644 index 00000000..3a220e94 --- /dev/null +++ b/plugins/source-github/vendor/github.com/russross/blackfriday/v2/smartypants.go @@ -0,0 +1,457 @@ +// +// Blackfriday Markdown Processor +// Available at http://github.com/russross/blackfriday +// +// Copyright © 2011 Russ Ross . +// Distributed under the Simplified BSD License. +// See README.md for details. +// + +// +// +// SmartyPants rendering +// +// + +package blackfriday + +import ( + "bytes" + "io" +) + +// SPRenderer is a struct containing state of a Smartypants renderer. +type SPRenderer struct { + inSingleQuote bool + inDoubleQuote bool + callbacks [256]smartCallback +} + +func wordBoundary(c byte) bool { + return c == 0 || isspace(c) || ispunct(c) +} + +func tolower(c byte) byte { + if c >= 'A' && c <= 'Z' { + return c - 'A' + 'a' + } + return c +} + +func isdigit(c byte) bool { + return c >= '0' && c <= '9' +} + +func smartQuoteHelper(out *bytes.Buffer, previousChar byte, nextChar byte, quote byte, isOpen *bool, addNBSP bool) bool { + // edge of the buffer is likely to be a tag that we don't get to see, + // so we treat it like text sometimes + + // enumerate all sixteen possibilities for (previousChar, nextChar) + // each can be one of {0, space, punct, other} + switch { + case previousChar == 0 && nextChar == 0: + // context is not any help here, so toggle + *isOpen = !*isOpen + case isspace(previousChar) && nextChar == 0: + // [ "] might be [ "foo...] + *isOpen = true + case ispunct(previousChar) && nextChar == 0: + // [!"] hmm... could be [Run!"] or [("...] + *isOpen = false + case /* isnormal(previousChar) && */ nextChar == 0: + // [a"] is probably a close + *isOpen = false + case previousChar == 0 && isspace(nextChar): + // [" ] might be [...foo" ] + *isOpen = false + case isspace(previousChar) && isspace(nextChar): + // [ " ] context is not any help here, so toggle + *isOpen = !*isOpen + case ispunct(previousChar) && isspace(nextChar): + // [!" ] is probably a close + *isOpen = false + case /* isnormal(previousChar) && */ isspace(nextChar): + // [a" ] this is one of the easy cases + *isOpen = false + case previousChar == 0 && ispunct(nextChar): + // ["!] hmm... could be ["$1.95] or ["!...] + *isOpen = false + case isspace(previousChar) && ispunct(nextChar): + // [ "!] looks more like [ "$1.95] + *isOpen = true + case ispunct(previousChar) && ispunct(nextChar): + // [!"!] context is not any help here, so toggle + *isOpen = !*isOpen + case /* isnormal(previousChar) && */ ispunct(nextChar): + // [a"!] is probably a close + *isOpen = false + case previousChar == 0 /* && isnormal(nextChar) */ : + // ["a] is probably an open + *isOpen = true + case isspace(previousChar) /* && isnormal(nextChar) */ : + // [ "a] this is one of the easy cases + *isOpen = true + case ispunct(previousChar) /* && isnormal(nextChar) */ : + // [!"a] is probably an open + *isOpen = true + default: + // [a'b] maybe a contraction? + *isOpen = false + } + + // Note that with the limited lookahead, this non-breaking + // space will also be appended to single double quotes. + if addNBSP && !*isOpen { + out.WriteString(" ") + } + + out.WriteByte('&') + if *isOpen { + out.WriteByte('l') + } else { + out.WriteByte('r') + } + out.WriteByte(quote) + out.WriteString("quo;") + + if addNBSP && *isOpen { + out.WriteString(" ") + } + + return true +} + +func (r *SPRenderer) smartSingleQuote(out *bytes.Buffer, previousChar byte, text []byte) int { + if len(text) >= 2 { + t1 := tolower(text[1]) + + if t1 == '\'' { + nextChar := byte(0) + if len(text) >= 3 { + nextChar = text[2] + } + if smartQuoteHelper(out, previousChar, nextChar, 'd', &r.inDoubleQuote, false) { + return 1 + } + } + + if (t1 == 's' || t1 == 't' || t1 == 'm' || t1 == 'd') && (len(text) < 3 || wordBoundary(text[2])) { + out.WriteString("’") + return 0 + } + + if len(text) >= 3 { + t2 := tolower(text[2]) + + if ((t1 == 'r' && t2 == 'e') || (t1 == 'l' && t2 == 'l') || (t1 == 'v' && t2 == 'e')) && + (len(text) < 4 || wordBoundary(text[3])) { + out.WriteString("’") + return 0 + } + } + } + + nextChar := byte(0) + if len(text) > 1 { + nextChar = text[1] + } + if smartQuoteHelper(out, previousChar, nextChar, 's', &r.inSingleQuote, false) { + return 0 + } + + out.WriteByte(text[0]) + return 0 +} + +func (r *SPRenderer) smartParens(out *bytes.Buffer, previousChar byte, text []byte) int { + if len(text) >= 3 { + t1 := tolower(text[1]) + t2 := tolower(text[2]) + + if t1 == 'c' && t2 == ')' { + out.WriteString("©") + return 2 + } + + if t1 == 'r' && t2 == ')' { + out.WriteString("®") + return 2 + } + + if len(text) >= 4 && t1 == 't' && t2 == 'm' && text[3] == ')' { + out.WriteString("™") + return 3 + } + } + + out.WriteByte(text[0]) + return 0 +} + +func (r *SPRenderer) smartDash(out *bytes.Buffer, previousChar byte, text []byte) int { + if len(text) >= 2 { + if text[1] == '-' { + out.WriteString("—") + return 1 + } + + if wordBoundary(previousChar) && wordBoundary(text[1]) { + out.WriteString("–") + return 0 + } + } + + out.WriteByte(text[0]) + return 0 +} + +func (r *SPRenderer) smartDashLatex(out *bytes.Buffer, previousChar byte, text []byte) int { + if len(text) >= 3 && text[1] == '-' && text[2] == '-' { + out.WriteString("—") + return 2 + } + if len(text) >= 2 && text[1] == '-' { + out.WriteString("–") + return 1 + } + + out.WriteByte(text[0]) + return 0 +} + +func (r *SPRenderer) smartAmpVariant(out *bytes.Buffer, previousChar byte, text []byte, quote byte, addNBSP bool) int { + if bytes.HasPrefix(text, []byte(""")) { + nextChar := byte(0) + if len(text) >= 7 { + nextChar = text[6] + } + if smartQuoteHelper(out, previousChar, nextChar, quote, &r.inDoubleQuote, addNBSP) { + return 5 + } + } + + if bytes.HasPrefix(text, []byte("�")) { + return 3 + } + + out.WriteByte('&') + return 0 +} + +func (r *SPRenderer) smartAmp(angledQuotes, addNBSP bool) func(*bytes.Buffer, byte, []byte) int { + var quote byte = 'd' + if angledQuotes { + quote = 'a' + } + + return func(out *bytes.Buffer, previousChar byte, text []byte) int { + return r.smartAmpVariant(out, previousChar, text, quote, addNBSP) + } +} + +func (r *SPRenderer) smartPeriod(out *bytes.Buffer, previousChar byte, text []byte) int { + if len(text) >= 3 && text[1] == '.' && text[2] == '.' { + out.WriteString("…") + return 2 + } + + if len(text) >= 5 && text[1] == ' ' && text[2] == '.' && text[3] == ' ' && text[4] == '.' { + out.WriteString("…") + return 4 + } + + out.WriteByte(text[0]) + return 0 +} + +func (r *SPRenderer) smartBacktick(out *bytes.Buffer, previousChar byte, text []byte) int { + if len(text) >= 2 && text[1] == '`' { + nextChar := byte(0) + if len(text) >= 3 { + nextChar = text[2] + } + if smartQuoteHelper(out, previousChar, nextChar, 'd', &r.inDoubleQuote, false) { + return 1 + } + } + + out.WriteByte(text[0]) + return 0 +} + +func (r *SPRenderer) smartNumberGeneric(out *bytes.Buffer, previousChar byte, text []byte) int { + if wordBoundary(previousChar) && previousChar != '/' && len(text) >= 3 { + // is it of the form digits/digits(word boundary)?, i.e., \d+/\d+\b + // note: check for regular slash (/) or fraction slash (⁄, 0x2044, or 0xe2 81 84 in utf-8) + // and avoid changing dates like 1/23/2005 into fractions. + numEnd := 0 + for len(text) > numEnd && isdigit(text[numEnd]) { + numEnd++ + } + if numEnd == 0 { + out.WriteByte(text[0]) + return 0 + } + denStart := numEnd + 1 + if len(text) > numEnd+3 && text[numEnd] == 0xe2 && text[numEnd+1] == 0x81 && text[numEnd+2] == 0x84 { + denStart = numEnd + 3 + } else if len(text) < numEnd+2 || text[numEnd] != '/' { + out.WriteByte(text[0]) + return 0 + } + denEnd := denStart + for len(text) > denEnd && isdigit(text[denEnd]) { + denEnd++ + } + if denEnd == denStart { + out.WriteByte(text[0]) + return 0 + } + if len(text) == denEnd || wordBoundary(text[denEnd]) && text[denEnd] != '/' { + out.WriteString("") + out.Write(text[:numEnd]) + out.WriteString("") + out.Write(text[denStart:denEnd]) + out.WriteString("") + return denEnd - 1 + } + } + + out.WriteByte(text[0]) + return 0 +} + +func (r *SPRenderer) smartNumber(out *bytes.Buffer, previousChar byte, text []byte) int { + if wordBoundary(previousChar) && previousChar != '/' && len(text) >= 3 { + if text[0] == '1' && text[1] == '/' && text[2] == '2' { + if len(text) < 4 || wordBoundary(text[3]) && text[3] != '/' { + out.WriteString("½") + return 2 + } + } + + if text[0] == '1' && text[1] == '/' && text[2] == '4' { + if len(text) < 4 || wordBoundary(text[3]) && text[3] != '/' || (len(text) >= 5 && tolower(text[3]) == 't' && tolower(text[4]) == 'h') { + out.WriteString("¼") + return 2 + } + } + + if text[0] == '3' && text[1] == '/' && text[2] == '4' { + if len(text) < 4 || wordBoundary(text[3]) && text[3] != '/' || (len(text) >= 6 && tolower(text[3]) == 't' && tolower(text[4]) == 'h' && tolower(text[5]) == 's') { + out.WriteString("¾") + return 2 + } + } + } + + out.WriteByte(text[0]) + return 0 +} + +func (r *SPRenderer) smartDoubleQuoteVariant(out *bytes.Buffer, previousChar byte, text []byte, quote byte) int { + nextChar := byte(0) + if len(text) > 1 { + nextChar = text[1] + } + if !smartQuoteHelper(out, previousChar, nextChar, quote, &r.inDoubleQuote, false) { + out.WriteString(""") + } + + return 0 +} + +func (r *SPRenderer) smartDoubleQuote(out *bytes.Buffer, previousChar byte, text []byte) int { + return r.smartDoubleQuoteVariant(out, previousChar, text, 'd') +} + +func (r *SPRenderer) smartAngledDoubleQuote(out *bytes.Buffer, previousChar byte, text []byte) int { + return r.smartDoubleQuoteVariant(out, previousChar, text, 'a') +} + +func (r *SPRenderer) smartLeftAngle(out *bytes.Buffer, previousChar byte, text []byte) int { + i := 0 + + for i < len(text) && text[i] != '>' { + i++ + } + + out.Write(text[:i+1]) + return i +} + +type smartCallback func(out *bytes.Buffer, previousChar byte, text []byte) int + +// NewSmartypantsRenderer constructs a Smartypants renderer object. +func NewSmartypantsRenderer(flags HTMLFlags) *SPRenderer { + var ( + r SPRenderer + + smartAmpAngled = r.smartAmp(true, false) + smartAmpAngledNBSP = r.smartAmp(true, true) + smartAmpRegular = r.smartAmp(false, false) + smartAmpRegularNBSP = r.smartAmp(false, true) + + addNBSP = flags&SmartypantsQuotesNBSP != 0 + ) + + if flags&SmartypantsAngledQuotes == 0 { + r.callbacks['"'] = r.smartDoubleQuote + if !addNBSP { + r.callbacks['&'] = smartAmpRegular + } else { + r.callbacks['&'] = smartAmpRegularNBSP + } + } else { + r.callbacks['"'] = r.smartAngledDoubleQuote + if !addNBSP { + r.callbacks['&'] = smartAmpAngled + } else { + r.callbacks['&'] = smartAmpAngledNBSP + } + } + r.callbacks['\''] = r.smartSingleQuote + r.callbacks['('] = r.smartParens + if flags&SmartypantsDashes != 0 { + if flags&SmartypantsLatexDashes == 0 { + r.callbacks['-'] = r.smartDash + } else { + r.callbacks['-'] = r.smartDashLatex + } + } + r.callbacks['.'] = r.smartPeriod + if flags&SmartypantsFractions == 0 { + r.callbacks['1'] = r.smartNumber + r.callbacks['3'] = r.smartNumber + } else { + for ch := '1'; ch <= '9'; ch++ { + r.callbacks[ch] = r.smartNumberGeneric + } + } + r.callbacks['<'] = r.smartLeftAngle + r.callbacks['`'] = r.smartBacktick + return &r +} + +// Process is the entry point of the Smartypants renderer. +func (r *SPRenderer) Process(w io.Writer, text []byte) { + mark := 0 + for i := 0; i < len(text); i++ { + if action := r.callbacks[text[i]]; action != nil { + if i > mark { + w.Write(text[mark:i]) + } + previousChar := byte(0) + if i > 0 { + previousChar = text[i-1] + } + var tmp bytes.Buffer + i += action(&tmp, previousChar, text[i:]) + w.Write(tmp.Bytes()) + mark = i + 1 + } + } + if mark < len(text) { + w.Write(text[mark:]) + } +} diff --git a/plugins/source-github/vendor/github.com/shurcooL/sanitized_anchor_name/.travis.yml b/plugins/source-github/vendor/github.com/shurcooL/sanitized_anchor_name/.travis.yml new file mode 100644 index 00000000..93b1fcdb --- /dev/null +++ b/plugins/source-github/vendor/github.com/shurcooL/sanitized_anchor_name/.travis.yml @@ -0,0 +1,16 @@ +sudo: false +language: go +go: + - 1.x + - master +matrix: + allow_failures: + - go: master + fast_finish: true +install: + - # Do nothing. This is needed to prevent default install action "go get -t -v ./..." from happening here (we want it to happen inside script step). +script: + - go get -t -v ./... + - diff -u <(echo -n) <(gofmt -d -s .) + - go tool vet . + - go test -v -race ./... diff --git a/plugins/source-github/vendor/github.com/shurcooL/sanitized_anchor_name/LICENSE b/plugins/source-github/vendor/github.com/shurcooL/sanitized_anchor_name/LICENSE new file mode 100644 index 00000000..c35c17af --- /dev/null +++ b/plugins/source-github/vendor/github.com/shurcooL/sanitized_anchor_name/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2015 Dmitri Shuralyov + +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. diff --git a/plugins/source-github/vendor/github.com/shurcooL/sanitized_anchor_name/README.md b/plugins/source-github/vendor/github.com/shurcooL/sanitized_anchor_name/README.md new file mode 100644 index 00000000..670bf0fe --- /dev/null +++ b/plugins/source-github/vendor/github.com/shurcooL/sanitized_anchor_name/README.md @@ -0,0 +1,36 @@ +sanitized_anchor_name +===================== + +[![Build Status](https://travis-ci.org/shurcooL/sanitized_anchor_name.svg?branch=master)](https://travis-ci.org/shurcooL/sanitized_anchor_name) [![GoDoc](https://godoc.org/github.com/shurcooL/sanitized_anchor_name?status.svg)](https://godoc.org/github.com/shurcooL/sanitized_anchor_name) + +Package sanitized_anchor_name provides a func to create sanitized anchor names. + +Its logic can be reused by multiple packages to create interoperable anchor names +and links to those anchors. + +At this time, it does not try to ensure that generated anchor names +are unique, that responsibility falls on the caller. + +Installation +------------ + +```bash +go get -u github.com/shurcooL/sanitized_anchor_name +``` + +Example +------- + +```Go +anchorName := sanitized_anchor_name.Create("This is a header") + +fmt.Println(anchorName) + +// Output: +// this-is-a-header +``` + +License +------- + +- [MIT License](LICENSE) diff --git a/plugins/source-github/vendor/github.com/shurcooL/sanitized_anchor_name/go.mod b/plugins/source-github/vendor/github.com/shurcooL/sanitized_anchor_name/go.mod new file mode 100644 index 00000000..1e255347 --- /dev/null +++ b/plugins/source-github/vendor/github.com/shurcooL/sanitized_anchor_name/go.mod @@ -0,0 +1 @@ +module github.com/shurcooL/sanitized_anchor_name diff --git a/plugins/source-github/vendor/github.com/shurcooL/sanitized_anchor_name/main.go b/plugins/source-github/vendor/github.com/shurcooL/sanitized_anchor_name/main.go new file mode 100644 index 00000000..6a77d124 --- /dev/null +++ b/plugins/source-github/vendor/github.com/shurcooL/sanitized_anchor_name/main.go @@ -0,0 +1,29 @@ +// Package sanitized_anchor_name provides a func to create sanitized anchor names. +// +// Its logic can be reused by multiple packages to create interoperable anchor names +// and links to those anchors. +// +// At this time, it does not try to ensure that generated anchor names +// are unique, that responsibility falls on the caller. +package sanitized_anchor_name // import "github.com/shurcooL/sanitized_anchor_name" + +import "unicode" + +// Create returns a sanitized anchor name for the given text. +func Create(text string) string { + var anchorName []rune + var futureDash = false + for _, r := range text { + switch { + case unicode.IsLetter(r) || unicode.IsNumber(r): + if futureDash && len(anchorName) > 0 { + anchorName = append(anchorName, '-') + } + futureDash = false + anchorName = append(anchorName, unicode.ToLower(r)) + default: + futureDash = true + } + } + return string(anchorName) +} diff --git a/plugins/source-github/vendor/github.com/spf13/cobra/doc/man_docs.go b/plugins/source-github/vendor/github.com/spf13/cobra/doc/man_docs.go new file mode 100644 index 00000000..8c7fba44 --- /dev/null +++ b/plugins/source-github/vendor/github.com/spf13/cobra/doc/man_docs.go @@ -0,0 +1,247 @@ +// Copyright 2015 Red Hat Inc. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package doc + +import ( + "bytes" + "fmt" + "io" + "os" + "path/filepath" + "sort" + "strconv" + "strings" + "time" + + "github.com/cpuguy83/go-md2man/v2/md2man" + "github.com/spf13/cobra" + "github.com/spf13/pflag" +) + +// GenManTree will generate a man page for this command and all descendants +// in the directory given. The header may be nil. This function may not work +// correctly if your command names have `-` in them. If you have `cmd` with two +// subcmds, `sub` and `sub-third`, and `sub` has a subcommand called `third` +// it is undefined which help output will be in the file `cmd-sub-third.1`. +func GenManTree(cmd *cobra.Command, header *GenManHeader, dir string) error { + return GenManTreeFromOpts(cmd, GenManTreeOptions{ + Header: header, + Path: dir, + CommandSeparator: "-", + }) +} + +// GenManTreeFromOpts generates a man page for the command and all descendants. +// The pages are written to the opts.Path directory. +func GenManTreeFromOpts(cmd *cobra.Command, opts GenManTreeOptions) error { + header := opts.Header + if header == nil { + header = &GenManHeader{} + } + for _, c := range cmd.Commands() { + if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() { + continue + } + if err := GenManTreeFromOpts(c, opts); err != nil { + return err + } + } + section := "1" + if header.Section != "" { + section = header.Section + } + + separator := "_" + if opts.CommandSeparator != "" { + separator = opts.CommandSeparator + } + basename := strings.Replace(cmd.CommandPath(), " ", separator, -1) + filename := filepath.Join(opts.Path, basename+"."+section) + f, err := os.Create(filename) + if err != nil { + return err + } + defer f.Close() + + headerCopy := *header + return GenMan(cmd, &headerCopy, f) +} + +// GenManTreeOptions is the options for generating the man pages. +// Used only in GenManTreeFromOpts. +type GenManTreeOptions struct { + Header *GenManHeader + Path string + CommandSeparator string +} + +// GenManHeader is a lot like the .TH header at the start of man pages. These +// include the title, section, date, source, and manual. We will use the +// current time if Date is unset and will use "Auto generated by spf13/cobra" +// if the Source is unset. +type GenManHeader struct { + Title string + Section string + Date *time.Time + date string + Source string + Manual string +} + +// GenMan will generate a man page for the given command and write it to +// w. The header argument may be nil, however obviously w may not. +func GenMan(cmd *cobra.Command, header *GenManHeader, w io.Writer) error { + if header == nil { + header = &GenManHeader{} + } + if err := fillHeader(header, cmd.CommandPath()); err != nil { + return err + } + + b := genMan(cmd, header) + _, err := w.Write(md2man.Render(b)) + return err +} + +func fillHeader(header *GenManHeader, name string) error { + if header.Title == "" { + header.Title = strings.ToUpper(strings.Replace(name, " ", "\\-", -1)) + } + if header.Section == "" { + header.Section = "1" + } + if header.Date == nil { + now := time.Now() + if epoch := os.Getenv("SOURCE_DATE_EPOCH"); epoch != "" { + unixEpoch, err := strconv.ParseInt(epoch, 10, 64) + if err != nil { + return fmt.Errorf("invalid SOURCE_DATE_EPOCH: %v", err) + } + now = time.Unix(unixEpoch, 0) + } + header.Date = &now + } + header.date = (*header.Date).Format("Jan 2006") + if header.Source == "" { + header.Source = "Auto generated by spf13/cobra" + } + return nil +} + +func manPreamble(buf *bytes.Buffer, header *GenManHeader, cmd *cobra.Command, dashedName string) { + description := cmd.Long + if len(description) == 0 { + description = cmd.Short + } + + buf.WriteString(fmt.Sprintf(`%% %s(%s)%s +%% %s +%% %s +# NAME +`, header.Title, header.Section, header.date, header.Source, header.Manual)) + buf.WriteString(fmt.Sprintf("%s \\- %s\n\n", dashedName, cmd.Short)) + buf.WriteString("# SYNOPSIS\n") + buf.WriteString(fmt.Sprintf("**%s**\n\n", cmd.UseLine())) + buf.WriteString("# DESCRIPTION\n") + buf.WriteString(description + "\n\n") +} + +func manPrintFlags(buf *bytes.Buffer, flags *pflag.FlagSet) { + flags.VisitAll(func(flag *pflag.Flag) { + if len(flag.Deprecated) > 0 || flag.Hidden { + return + } + format := "" + if len(flag.Shorthand) > 0 && len(flag.ShorthandDeprecated) == 0 { + format = fmt.Sprintf("**-%s**, **--%s**", flag.Shorthand, flag.Name) + } else { + format = fmt.Sprintf("**--%s**", flag.Name) + } + if len(flag.NoOptDefVal) > 0 { + format += "[" + } + if flag.Value.Type() == "string" { + // put quotes on the value + format += "=%q" + } else { + format += "=%s" + } + if len(flag.NoOptDefVal) > 0 { + format += "]" + } + format += "\n\t%s\n\n" + buf.WriteString(fmt.Sprintf(format, flag.DefValue, flag.Usage)) + }) +} + +func manPrintOptions(buf *bytes.Buffer, command *cobra.Command) { + flags := command.NonInheritedFlags() + if flags.HasAvailableFlags() { + buf.WriteString("# OPTIONS\n") + manPrintFlags(buf, flags) + buf.WriteString("\n") + } + flags = command.InheritedFlags() + if flags.HasAvailableFlags() { + buf.WriteString("# OPTIONS INHERITED FROM PARENT COMMANDS\n") + manPrintFlags(buf, flags) + buf.WriteString("\n") + } +} + +func genMan(cmd *cobra.Command, header *GenManHeader) []byte { + cmd.InitDefaultHelpCmd() + cmd.InitDefaultHelpFlag() + + // something like `rootcmd-subcmd1-subcmd2` + dashCommandName := strings.Replace(cmd.CommandPath(), " ", "-", -1) + + buf := new(bytes.Buffer) + + manPreamble(buf, header, cmd, dashCommandName) + manPrintOptions(buf, cmd) + if len(cmd.Example) > 0 { + buf.WriteString("# EXAMPLE\n") + buf.WriteString(fmt.Sprintf("```\n%s\n```\n", cmd.Example)) + } + if hasSeeAlso(cmd) { + buf.WriteString("# SEE ALSO\n") + seealsos := make([]string, 0) + if cmd.HasParent() { + parentPath := cmd.Parent().CommandPath() + dashParentPath := strings.Replace(parentPath, " ", "-", -1) + seealso := fmt.Sprintf("**%s(%s)**", dashParentPath, header.Section) + seealsos = append(seealsos, seealso) + cmd.VisitParents(func(c *cobra.Command) { + if c.DisableAutoGenTag { + cmd.DisableAutoGenTag = c.DisableAutoGenTag + } + }) + } + children := cmd.Commands() + sort.Sort(byName(children)) + for _, c := range children { + if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() { + continue + } + seealso := fmt.Sprintf("**%s-%s(%s)**", dashCommandName, c.Name(), header.Section) + seealsos = append(seealsos, seealso) + } + buf.WriteString(strings.Join(seealsos, ", ") + "\n") + } + if !cmd.DisableAutoGenTag { + buf.WriteString(fmt.Sprintf("# HISTORY\n%s Auto generated by spf13/cobra\n", header.Date.Format("2-Jan-2006"))) + } + return buf.Bytes() +} diff --git a/plugins/source-github/vendor/github.com/spf13/cobra/doc/man_docs.md b/plugins/source-github/vendor/github.com/spf13/cobra/doc/man_docs.md new file mode 100644 index 00000000..3709160f --- /dev/null +++ b/plugins/source-github/vendor/github.com/spf13/cobra/doc/man_docs.md @@ -0,0 +1,31 @@ +# Generating Man Pages For Your Own cobra.Command + +Generating man pages from a cobra command is incredibly easy. An example is as follows: + +```go +package main + +import ( + "log" + + "github.com/spf13/cobra" + "github.com/spf13/cobra/doc" +) + +func main() { + cmd := &cobra.Command{ + Use: "test", + Short: "my test program", + } + header := &doc.GenManHeader{ + Title: "MINE", + Section: "3", + } + err := doc.GenManTree(cmd, header, "/tmp") + if err != nil { + log.Fatal(err) + } +} +``` + +That will get you a man page `/tmp/test.3` diff --git a/plugins/source-github/vendor/github.com/spf13/cobra/doc/md_docs.go b/plugins/source-github/vendor/github.com/spf13/cobra/doc/md_docs.go new file mode 100644 index 00000000..d76f6d5e --- /dev/null +++ b/plugins/source-github/vendor/github.com/spf13/cobra/doc/md_docs.go @@ -0,0 +1,159 @@ +//Copyright 2015 Red Hat Inc. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package doc + +import ( + "bytes" + "fmt" + "io" + "os" + "path/filepath" + "sort" + "strings" + "time" + + "github.com/spf13/cobra" +) + +func printOptions(buf *bytes.Buffer, cmd *cobra.Command, name string) error { + flags := cmd.NonInheritedFlags() + flags.SetOutput(buf) + if flags.HasAvailableFlags() { + buf.WriteString("### Options\n\n```\n") + flags.PrintDefaults() + buf.WriteString("```\n\n") + } + + parentFlags := cmd.InheritedFlags() + parentFlags.SetOutput(buf) + if parentFlags.HasAvailableFlags() { + buf.WriteString("### Options inherited from parent commands\n\n```\n") + parentFlags.PrintDefaults() + buf.WriteString("```\n\n") + } + return nil +} + +// GenMarkdown creates markdown output. +func GenMarkdown(cmd *cobra.Command, w io.Writer) error { + return GenMarkdownCustom(cmd, w, func(s string) string { return s }) +} + +// GenMarkdownCustom creates custom markdown output. +func GenMarkdownCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) string) error { + cmd.InitDefaultHelpCmd() + cmd.InitDefaultHelpFlag() + + buf := new(bytes.Buffer) + name := cmd.CommandPath() + + short := cmd.Short + long := cmd.Long + if len(long) == 0 { + long = short + } + + buf.WriteString("## " + name + "\n\n") + buf.WriteString(short + "\n\n") + buf.WriteString("### Synopsis\n\n") + buf.WriteString(long + "\n\n") + + if cmd.Runnable() { + buf.WriteString(fmt.Sprintf("```\n%s\n```\n\n", cmd.UseLine())) + } + + if len(cmd.Example) > 0 { + buf.WriteString("### Examples\n\n") + buf.WriteString(fmt.Sprintf("```\n%s\n```\n\n", cmd.Example)) + } + + if err := printOptions(buf, cmd, name); err != nil { + return err + } + if hasSeeAlso(cmd) { + buf.WriteString("### SEE ALSO\n\n") + if cmd.HasParent() { + parent := cmd.Parent() + pname := parent.CommandPath() + link := pname + ".md" + link = strings.Replace(link, " ", "_", -1) + buf.WriteString(fmt.Sprintf("* [%s](%s)\t - %s\n", pname, linkHandler(link), parent.Short)) + cmd.VisitParents(func(c *cobra.Command) { + if c.DisableAutoGenTag { + cmd.DisableAutoGenTag = c.DisableAutoGenTag + } + }) + } + + children := cmd.Commands() + sort.Sort(byName(children)) + + for _, child := range children { + if !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() { + continue + } + cname := name + " " + child.Name() + link := cname + ".md" + link = strings.Replace(link, " ", "_", -1) + buf.WriteString(fmt.Sprintf("* [%s](%s)\t - %s\n", cname, linkHandler(link), child.Short)) + } + buf.WriteString("\n") + } + if !cmd.DisableAutoGenTag { + buf.WriteString("###### Auto generated by spf13/cobra on " + time.Now().Format("2-Jan-2006") + "\n") + } + _, err := buf.WriteTo(w) + return err +} + +// GenMarkdownTree will generate a markdown page for this command and all +// descendants in the directory given. The header may be nil. +// This function may not work correctly if your command names have `-` in them. +// If you have `cmd` with two subcmds, `sub` and `sub-third`, +// and `sub` has a subcommand called `third`, it is undefined which +// help output will be in the file `cmd-sub-third.1`. +func GenMarkdownTree(cmd *cobra.Command, dir string) error { + identity := func(s string) string { return s } + emptyStr := func(s string) string { return "" } + return GenMarkdownTreeCustom(cmd, dir, emptyStr, identity) +} + +// GenMarkdownTreeCustom is the the same as GenMarkdownTree, but +// with custom filePrepender and linkHandler. +func GenMarkdownTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHandler func(string) string) error { + for _, c := range cmd.Commands() { + if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() { + continue + } + if err := GenMarkdownTreeCustom(c, dir, filePrepender, linkHandler); err != nil { + return err + } + } + + basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".md" + filename := filepath.Join(dir, basename) + f, err := os.Create(filename) + if err != nil { + return err + } + defer f.Close() + + if _, err := io.WriteString(f, filePrepender(filename)); err != nil { + return err + } + if err := GenMarkdownCustom(cmd, f, linkHandler); err != nil { + return err + } + return nil +} diff --git a/plugins/source-github/vendor/github.com/spf13/cobra/doc/md_docs.md b/plugins/source-github/vendor/github.com/spf13/cobra/doc/md_docs.md new file mode 100644 index 00000000..5c870625 --- /dev/null +++ b/plugins/source-github/vendor/github.com/spf13/cobra/doc/md_docs.md @@ -0,0 +1,115 @@ +# Generating Markdown Docs For Your Own cobra.Command + +Generating Markdown pages from a cobra command is incredibly easy. An example is as follows: + +```go +package main + +import ( + "log" + + "github.com/spf13/cobra" + "github.com/spf13/cobra/doc" +) + +func main() { + cmd := &cobra.Command{ + Use: "test", + Short: "my test program", + } + err := doc.GenMarkdownTree(cmd, "/tmp") + if err != nil { + log.Fatal(err) + } +} +``` + +That will get you a Markdown document `/tmp/test.md` + +## Generate markdown docs for the entire command tree + +This program can actually generate docs for the kubectl command in the kubernetes project + +```go +package main + +import ( + "log" + "io/ioutil" + "os" + + "k8s.io/kubernetes/pkg/kubectl/cmd" + cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" + + "github.com/spf13/cobra/doc" +) + +func main() { + kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard) + err := doc.GenMarkdownTree(kubectl, "./") + if err != nil { + log.Fatal(err) + } +} +``` + +This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./") + +## Generate markdown docs for a single command + +You may wish to have more control over the output, or only generate for a single command, instead of the entire command tree. If this is the case you may prefer to `GenMarkdown` instead of `GenMarkdownTree` + +```go + out := new(bytes.Buffer) + err := doc.GenMarkdown(cmd, out) + if err != nil { + log.Fatal(err) + } +``` + +This will write the markdown doc for ONLY "cmd" into the out, buffer. + +## Customize the output + +Both `GenMarkdown` and `GenMarkdownTree` have alternate versions with callbacks to get some control of the output: + +```go +func GenMarkdownTreeCustom(cmd *Command, dir string, filePrepender, linkHandler func(string) string) error { + //... +} +``` + +```go +func GenMarkdownCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) error { + //... +} +``` + +The `filePrepender` will prepend the return value given the full filepath to the rendered Markdown file. A common use case is to add front matter to use the generated documentation with [Hugo](http://gohugo.io/): + +```go +const fmTemplate = `--- +date: %s +title: "%s" +slug: %s +url: %s +--- +` + +filePrepender := func(filename string) string { + now := time.Now().Format(time.RFC3339) + name := filepath.Base(filename) + base := strings.TrimSuffix(name, path.Ext(name)) + url := "/commands/" + strings.ToLower(base) + "/" + return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url) +} +``` + +The `linkHandler` can be used to customize the rendered internal links to the commands, given a filename: + +```go +linkHandler := func(name string) string { + base := strings.TrimSuffix(name, path.Ext(name)) + return "/commands/" + strings.ToLower(base) + "/" +} +``` diff --git a/plugins/source-github/vendor/github.com/spf13/cobra/doc/rest_docs.go b/plugins/source-github/vendor/github.com/spf13/cobra/doc/rest_docs.go new file mode 100644 index 00000000..051d8dc8 --- /dev/null +++ b/plugins/source-github/vendor/github.com/spf13/cobra/doc/rest_docs.go @@ -0,0 +1,185 @@ +//Copyright 2015 Red Hat Inc. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package doc + +import ( + "bytes" + "fmt" + "io" + "os" + "path/filepath" + "sort" + "strings" + "time" + + "github.com/spf13/cobra" +) + +func printOptionsReST(buf *bytes.Buffer, cmd *cobra.Command, name string) error { + flags := cmd.NonInheritedFlags() + flags.SetOutput(buf) + if flags.HasAvailableFlags() { + buf.WriteString("Options\n") + buf.WriteString("~~~~~~~\n\n::\n\n") + flags.PrintDefaults() + buf.WriteString("\n") + } + + parentFlags := cmd.InheritedFlags() + parentFlags.SetOutput(buf) + if parentFlags.HasAvailableFlags() { + buf.WriteString("Options inherited from parent commands\n") + buf.WriteString("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n::\n\n") + parentFlags.PrintDefaults() + buf.WriteString("\n") + } + return nil +} + +// linkHandler for default ReST hyperlink markup +func defaultLinkHandler(name, ref string) string { + return fmt.Sprintf("`%s <%s.rst>`_", name, ref) +} + +// GenReST creates reStructured Text output. +func GenReST(cmd *cobra.Command, w io.Writer) error { + return GenReSTCustom(cmd, w, defaultLinkHandler) +} + +// GenReSTCustom creates custom reStructured Text output. +func GenReSTCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string, string) string) error { + cmd.InitDefaultHelpCmd() + cmd.InitDefaultHelpFlag() + + buf := new(bytes.Buffer) + name := cmd.CommandPath() + + short := cmd.Short + long := cmd.Long + if len(long) == 0 { + long = short + } + ref := strings.Replace(name, " ", "_", -1) + + buf.WriteString(".. _" + ref + ":\n\n") + buf.WriteString(name + "\n") + buf.WriteString(strings.Repeat("-", len(name)) + "\n\n") + buf.WriteString(short + "\n\n") + buf.WriteString("Synopsis\n") + buf.WriteString("~~~~~~~~\n\n") + buf.WriteString("\n" + long + "\n\n") + + if cmd.Runnable() { + buf.WriteString(fmt.Sprintf("::\n\n %s\n\n", cmd.UseLine())) + } + + if len(cmd.Example) > 0 { + buf.WriteString("Examples\n") + buf.WriteString("~~~~~~~~\n\n") + buf.WriteString(fmt.Sprintf("::\n\n%s\n\n", indentString(cmd.Example, " "))) + } + + if err := printOptionsReST(buf, cmd, name); err != nil { + return err + } + if hasSeeAlso(cmd) { + buf.WriteString("SEE ALSO\n") + buf.WriteString("~~~~~~~~\n\n") + if cmd.HasParent() { + parent := cmd.Parent() + pname := parent.CommandPath() + ref = strings.Replace(pname, " ", "_", -1) + buf.WriteString(fmt.Sprintf("* %s \t - %s\n", linkHandler(pname, ref), parent.Short)) + cmd.VisitParents(func(c *cobra.Command) { + if c.DisableAutoGenTag { + cmd.DisableAutoGenTag = c.DisableAutoGenTag + } + }) + } + + children := cmd.Commands() + sort.Sort(byName(children)) + + for _, child := range children { + if !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() { + continue + } + cname := name + " " + child.Name() + ref = strings.Replace(cname, " ", "_", -1) + buf.WriteString(fmt.Sprintf("* %s \t - %s\n", linkHandler(cname, ref), child.Short)) + } + buf.WriteString("\n") + } + if !cmd.DisableAutoGenTag { + buf.WriteString("*Auto generated by spf13/cobra on " + time.Now().Format("2-Jan-2006") + "*\n") + } + _, err := buf.WriteTo(w) + return err +} + +// GenReSTTree will generate a ReST page for this command and all +// descendants in the directory given. +// This function may not work correctly if your command names have `-` in them. +// If you have `cmd` with two subcmds, `sub` and `sub-third`, +// and `sub` has a subcommand called `third`, it is undefined which +// help output will be in the file `cmd-sub-third.1`. +func GenReSTTree(cmd *cobra.Command, dir string) error { + emptyStr := func(s string) string { return "" } + return GenReSTTreeCustom(cmd, dir, emptyStr, defaultLinkHandler) +} + +// GenReSTTreeCustom is the the same as GenReSTTree, but +// with custom filePrepender and linkHandler. +func GenReSTTreeCustom(cmd *cobra.Command, dir string, filePrepender func(string) string, linkHandler func(string, string) string) error { + for _, c := range cmd.Commands() { + if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() { + continue + } + if err := GenReSTTreeCustom(c, dir, filePrepender, linkHandler); err != nil { + return err + } + } + + basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".rst" + filename := filepath.Join(dir, basename) + f, err := os.Create(filename) + if err != nil { + return err + } + defer f.Close() + + if _, err := io.WriteString(f, filePrepender(filename)); err != nil { + return err + } + if err := GenReSTCustom(cmd, f, linkHandler); err != nil { + return err + } + return nil +} + +// adapted from: https://github.com/kr/text/blob/main/indent.go +func indentString(s, p string) string { + var res []byte + b := []byte(s) + prefix := []byte(p) + bol := true + for _, c := range b { + if bol && c != '\n' { + res = append(res, prefix...) + } + res = append(res, c) + bol = c == '\n' + } + return string(res) +} diff --git a/plugins/source-github/vendor/github.com/spf13/cobra/doc/rest_docs.md b/plugins/source-github/vendor/github.com/spf13/cobra/doc/rest_docs.md new file mode 100644 index 00000000..6098430e --- /dev/null +++ b/plugins/source-github/vendor/github.com/spf13/cobra/doc/rest_docs.md @@ -0,0 +1,114 @@ +# Generating ReStructured Text Docs For Your Own cobra.Command + +Generating ReST pages from a cobra command is incredibly easy. An example is as follows: + +```go +package main + +import ( + "log" + + "github.com/spf13/cobra" + "github.com/spf13/cobra/doc" +) + +func main() { + cmd := &cobra.Command{ + Use: "test", + Short: "my test program", + } + err := doc.GenReSTTree(cmd, "/tmp") + if err != nil { + log.Fatal(err) + } +} +``` + +That will get you a ReST document `/tmp/test.rst` + +## Generate ReST docs for the entire command tree + +This program can actually generate docs for the kubectl command in the kubernetes project + +```go +package main + +import ( + "log" + "io/ioutil" + "os" + + "k8s.io/kubernetes/pkg/kubectl/cmd" + cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" + + "github.com/spf13/cobra/doc" +) + +func main() { + kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard) + err := doc.GenReSTTree(kubectl, "./") + if err != nil { + log.Fatal(err) + } +} +``` + +This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./") + +## Generate ReST docs for a single command + +You may wish to have more control over the output, or only generate for a single command, instead of the entire command tree. If this is the case you may prefer to `GenReST` instead of `GenReSTTree` + +```go + out := new(bytes.Buffer) + err := doc.GenReST(cmd, out) + if err != nil { + log.Fatal(err) + } +``` + +This will write the ReST doc for ONLY "cmd" into the out, buffer. + +## Customize the output + +Both `GenReST` and `GenReSTTree` have alternate versions with callbacks to get some control of the output: + +```go +func GenReSTTreeCustom(cmd *Command, dir string, filePrepender func(string) string, linkHandler func(string, string) string) error { + //... +} +``` + +```go +func GenReSTCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string, string) string) error { + //... +} +``` + +The `filePrepender` will prepend the return value given the full filepath to the rendered ReST file. A common use case is to add front matter to use the generated documentation with [Hugo](http://gohugo.io/): + +```go +const fmTemplate = `--- +date: %s +title: "%s" +slug: %s +url: %s +--- +` +filePrepender := func(filename string) string { + now := time.Now().Format(time.RFC3339) + name := filepath.Base(filename) + base := strings.TrimSuffix(name, path.Ext(name)) + url := "/commands/" + strings.ToLower(base) + "/" + return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url) +} +``` + +The `linkHandler` can be used to customize the rendered links to the commands, given a command name and reference. This is useful while converting rst to html or while generating documentation with tools like Sphinx where `:ref:` is used: + +```go +// Sphinx cross-referencing format +linkHandler := func(name, ref string) string { + return fmt.Sprintf(":ref:`%s <%s>`", name, ref) +} +``` diff --git a/plugins/source-github/vendor/github.com/spf13/cobra/doc/util.go b/plugins/source-github/vendor/github.com/spf13/cobra/doc/util.go new file mode 100644 index 00000000..8d3dbece --- /dev/null +++ b/plugins/source-github/vendor/github.com/spf13/cobra/doc/util.go @@ -0,0 +1,51 @@ +// Copyright 2015 Red Hat Inc. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package doc + +import ( + "strings" + + "github.com/spf13/cobra" +) + +// Test to see if we have a reason to print See Also information in docs +// Basically this is a test for a parent commend or a subcommand which is +// both not deprecated and not the autogenerated help command. +func hasSeeAlso(cmd *cobra.Command) bool { + if cmd.HasParent() { + return true + } + for _, c := range cmd.Commands() { + if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() { + continue + } + return true + } + return false +} + +// Temporary workaround for yaml lib generating incorrect yaml with long strings +// that do not contain \n. +func forceMultiLine(s string) string { + if len(s) > 60 && !strings.Contains(s, "\n") { + s = s + "\n" + } + return s +} + +type byName []*cobra.Command + +func (s byName) Len() int { return len(s) } +func (s byName) Swap(i, j int) { s[i], s[j] = s[j], s[i] } +func (s byName) Less(i, j int) bool { return s[i].Name() < s[j].Name() } diff --git a/plugins/source-github/vendor/github.com/spf13/cobra/doc/yaml_docs.go b/plugins/source-github/vendor/github.com/spf13/cobra/doc/yaml_docs.go new file mode 100644 index 00000000..ea00af07 --- /dev/null +++ b/plugins/source-github/vendor/github.com/spf13/cobra/doc/yaml_docs.go @@ -0,0 +1,169 @@ +// Copyright 2016 French Ben. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package doc + +import ( + "fmt" + "io" + "os" + "path/filepath" + "sort" + "strings" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" + "gopkg.in/yaml.v2" +) + +type cmdOption struct { + Name string + Shorthand string `yaml:",omitempty"` + DefaultValue string `yaml:"default_value,omitempty"` + Usage string `yaml:",omitempty"` +} + +type cmdDoc struct { + Name string + Synopsis string `yaml:",omitempty"` + Description string `yaml:",omitempty"` + Options []cmdOption `yaml:",omitempty"` + InheritedOptions []cmdOption `yaml:"inherited_options,omitempty"` + Example string `yaml:",omitempty"` + SeeAlso []string `yaml:"see_also,omitempty"` +} + +// GenYamlTree creates yaml structured ref files for this command and all descendants +// in the directory given. This function may not work +// correctly if your command names have `-` in them. If you have `cmd` with two +// subcmds, `sub` and `sub-third`, and `sub` has a subcommand called `third` +// it is undefined which help output will be in the file `cmd-sub-third.1`. +func GenYamlTree(cmd *cobra.Command, dir string) error { + identity := func(s string) string { return s } + emptyStr := func(s string) string { return "" } + return GenYamlTreeCustom(cmd, dir, emptyStr, identity) +} + +// GenYamlTreeCustom creates yaml structured ref files. +func GenYamlTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHandler func(string) string) error { + for _, c := range cmd.Commands() { + if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() { + continue + } + if err := GenYamlTreeCustom(c, dir, filePrepender, linkHandler); err != nil { + return err + } + } + + basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".yaml" + filename := filepath.Join(dir, basename) + f, err := os.Create(filename) + if err != nil { + return err + } + defer f.Close() + + if _, err := io.WriteString(f, filePrepender(filename)); err != nil { + return err + } + if err := GenYamlCustom(cmd, f, linkHandler); err != nil { + return err + } + return nil +} + +// GenYaml creates yaml output. +func GenYaml(cmd *cobra.Command, w io.Writer) error { + return GenYamlCustom(cmd, w, func(s string) string { return s }) +} + +// GenYamlCustom creates custom yaml output. +func GenYamlCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) string) error { + cmd.InitDefaultHelpCmd() + cmd.InitDefaultHelpFlag() + + yamlDoc := cmdDoc{} + yamlDoc.Name = cmd.CommandPath() + + yamlDoc.Synopsis = forceMultiLine(cmd.Short) + yamlDoc.Description = forceMultiLine(cmd.Long) + + if len(cmd.Example) > 0 { + yamlDoc.Example = cmd.Example + } + + flags := cmd.NonInheritedFlags() + if flags.HasFlags() { + yamlDoc.Options = genFlagResult(flags) + } + flags = cmd.InheritedFlags() + if flags.HasFlags() { + yamlDoc.InheritedOptions = genFlagResult(flags) + } + + if hasSeeAlso(cmd) { + result := []string{} + if cmd.HasParent() { + parent := cmd.Parent() + result = append(result, parent.CommandPath()+" - "+parent.Short) + } + children := cmd.Commands() + sort.Sort(byName(children)) + for _, child := range children { + if !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() { + continue + } + result = append(result, child.Name()+" - "+child.Short) + } + yamlDoc.SeeAlso = result + } + + final, err := yaml.Marshal(&yamlDoc) + if err != nil { + fmt.Println(err) + os.Exit(1) + } + + if _, err := w.Write(final); err != nil { + return err + } + return nil +} + +func genFlagResult(flags *pflag.FlagSet) []cmdOption { + var result []cmdOption + + flags.VisitAll(func(flag *pflag.Flag) { + // Todo, when we mark a shorthand is deprecated, but specify an empty message. + // The flag.ShorthandDeprecated is empty as the shorthand is deprecated. + // Using len(flag.ShorthandDeprecated) > 0 can't handle this, others are ok. + if !(len(flag.ShorthandDeprecated) > 0) && len(flag.Shorthand) > 0 { + opt := cmdOption{ + flag.Name, + flag.Shorthand, + flag.DefValue, + forceMultiLine(flag.Usage), + } + result = append(result, opt) + } else { + opt := cmdOption{ + Name: flag.Name, + DefaultValue: forceMultiLine(flag.DefValue), + Usage: forceMultiLine(flag.Usage), + } + result = append(result, opt) + } + }) + + return result +} diff --git a/plugins/source-github/vendor/github.com/spf13/cobra/doc/yaml_docs.md b/plugins/source-github/vendor/github.com/spf13/cobra/doc/yaml_docs.md new file mode 100644 index 00000000..1a9b7c6a --- /dev/null +++ b/plugins/source-github/vendor/github.com/spf13/cobra/doc/yaml_docs.md @@ -0,0 +1,112 @@ +# Generating Yaml Docs For Your Own cobra.Command + +Generating yaml files from a cobra command is incredibly easy. An example is as follows: + +```go +package main + +import ( + "log" + + "github.com/spf13/cobra" + "github.com/spf13/cobra/doc" +) + +func main() { + cmd := &cobra.Command{ + Use: "test", + Short: "my test program", + } + err := doc.GenYamlTree(cmd, "/tmp") + if err != nil { + log.Fatal(err) + } +} +``` + +That will get you a Yaml document `/tmp/test.yaml` + +## Generate yaml docs for the entire command tree + +This program can actually generate docs for the kubectl command in the kubernetes project + +```go +package main + +import ( + "io/ioutil" + "log" + "os" + + "k8s.io/kubernetes/pkg/kubectl/cmd" + cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util" + + "github.com/spf13/cobra/doc" +) + +func main() { + kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard) + err := doc.GenYamlTree(kubectl, "./") + if err != nil { + log.Fatal(err) + } +} +``` + +This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./") + +## Generate yaml docs for a single command + +You may wish to have more control over the output, or only generate for a single command, instead of the entire command tree. If this is the case you may prefer to `GenYaml` instead of `GenYamlTree` + +```go + out := new(bytes.Buffer) + doc.GenYaml(cmd, out) +``` + +This will write the yaml doc for ONLY "cmd" into the out, buffer. + +## Customize the output + +Both `GenYaml` and `GenYamlTree` have alternate versions with callbacks to get some control of the output: + +```go +func GenYamlTreeCustom(cmd *Command, dir string, filePrepender, linkHandler func(string) string) error { + //... +} +``` + +```go +func GenYamlCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) error { + //... +} +``` + +The `filePrepender` will prepend the return value given the full filepath to the rendered Yaml file. A common use case is to add front matter to use the generated documentation with [Hugo](http://gohugo.io/): + +```go +const fmTemplate = `--- +date: %s +title: "%s" +slug: %s +url: %s +--- +` + +filePrepender := func(filename string) string { + now := time.Now().Format(time.RFC3339) + name := filepath.Base(filename) + base := strings.TrimSuffix(name, path.Ext(name)) + url := "/commands/" + strings.ToLower(base) + "/" + return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url) +} +``` + +The `linkHandler` can be used to customize the rendered internal links to the commands, given a filename: + +```go +linkHandler := func(name string) string { + base := strings.TrimSuffix(name, path.Ext(name)) + return "/commands/" + strings.ToLower(base) + "/" +} +``` diff --git a/plugins/source-github/vendor/golang.org/x/crypto/ssh/terminal/terminal.go b/plugins/source-github/vendor/golang.org/x/crypto/ssh/terminal/terminal.go index 2f04ee5b..d1b4fca3 100644 --- a/plugins/source-github/vendor/golang.org/x/crypto/ssh/terminal/terminal.go +++ b/plugins/source-github/vendor/golang.org/x/crypto/ssh/terminal/terminal.go @@ -7,6 +7,7 @@ package terminal import ( "bytes" "io" + "runtime" "strconv" "sync" "unicode/utf8" @@ -939,6 +940,8 @@ func (s *stRingBuffer) NthPreviousEntry(n int) (value string, ok bool) { // readPasswordLine reads from reader until it finds \n or io.EOF. // The slice returned does not include the \n. // readPasswordLine also ignores any \r it finds. +// Windows uses \r as end of line. So, on Windows, readPasswordLine +// reads until it finds \r and ignores any \n it finds during processing. func readPasswordLine(reader io.Reader) ([]byte, error) { var buf [1]byte var ret []byte @@ -947,10 +950,20 @@ func readPasswordLine(reader io.Reader) ([]byte, error) { n, err := reader.Read(buf[:]) if n > 0 { switch buf[0] { + case '\b': + if len(ret) > 0 { + ret = ret[:len(ret)-1] + } case '\n': - return ret, nil + if runtime.GOOS != "windows" { + return ret, nil + } + // otherwise ignore \n case '\r': - // remove \r from passwords on Windows + if runtime.GOOS == "windows" { + return ret, nil + } + // otherwise ignore \r default: ret = append(ret, buf[0]) } diff --git a/plugins/source-github/vendor/golang.org/x/crypto/ssh/terminal/util_windows.go b/plugins/source-github/vendor/golang.org/x/crypto/ssh/terminal/util_windows.go index 5cfdf8f3..f614e9cb 100644 --- a/plugins/source-github/vendor/golang.org/x/crypto/ssh/terminal/util_windows.go +++ b/plugins/source-github/vendor/golang.org/x/crypto/ssh/terminal/util_windows.go @@ -85,8 +85,8 @@ func ReadPassword(fd int) ([]byte, error) { } old := st - st &^= (windows.ENABLE_ECHO_INPUT) - st |= (windows.ENABLE_PROCESSED_INPUT | windows.ENABLE_LINE_INPUT | windows.ENABLE_PROCESSED_OUTPUT) + st &^= (windows.ENABLE_ECHO_INPUT | windows.ENABLE_LINE_INPUT) + st |= (windows.ENABLE_PROCESSED_OUTPUT | windows.ENABLE_PROCESSED_INPUT) if err := windows.SetConsoleMode(windows.Handle(fd), st); err != nil { return nil, err } diff --git a/plugins/source-github/vendor/gopkg.in/yaml.v2/.travis.yml b/plugins/source-github/vendor/gopkg.in/yaml.v2/.travis.yml index 9f556934..055480b9 100644 --- a/plugins/source-github/vendor/gopkg.in/yaml.v2/.travis.yml +++ b/plugins/source-github/vendor/gopkg.in/yaml.v2/.travis.yml @@ -1,12 +1,16 @@ language: go go: - - 1.4 - - 1.5 - - 1.6 - - 1.7 - - 1.8 - - 1.9 - - tip + - "1.4.x" + - "1.5.x" + - "1.6.x" + - "1.7.x" + - "1.8.x" + - "1.9.x" + - "1.10.x" + - "1.11.x" + - "1.12.x" + - "1.13.x" + - "tip" go_import_path: gopkg.in/yaml.v2 diff --git a/plugins/source-github/vendor/gopkg.in/yaml.v2/decode.go b/plugins/source-github/vendor/gopkg.in/yaml.v2/decode.go index 53108765..129bc2a9 100644 --- a/plugins/source-github/vendor/gopkg.in/yaml.v2/decode.go +++ b/plugins/source-github/vendor/gopkg.in/yaml.v2/decode.go @@ -319,10 +319,14 @@ func (d *decoder) prepare(n *node, out reflect.Value) (newout reflect.Value, unm } const ( - // 400,000 decode operations is ~500kb of dense object declarations, or ~5kb of dense object declarations with 10000% alias expansion + // 400,000 decode operations is ~500kb of dense object declarations, or + // ~5kb of dense object declarations with 10000% alias expansion alias_ratio_range_low = 400000 - // 4,000,000 decode operations is ~5MB of dense object declarations, or ~4.5MB of dense object declarations with 10% alias expansion + + // 4,000,000 decode operations is ~5MB of dense object declarations, or + // ~4.5MB of dense object declarations with 10% alias expansion alias_ratio_range_high = 4000000 + // alias_ratio_range is the range over which we scale allowed alias ratios alias_ratio_range = float64(alias_ratio_range_high - alias_ratio_range_low) ) @@ -784,8 +788,7 @@ func (d *decoder) merge(n *node, out reflect.Value) { case mappingNode: d.unmarshal(n, out) case aliasNode: - an, ok := d.doc.anchors[n.value] - if ok && an.kind != mappingNode { + if n.alias != nil && n.alias.kind != mappingNode { failWantMap() } d.unmarshal(n, out) @@ -794,8 +797,7 @@ func (d *decoder) merge(n *node, out reflect.Value) { for i := len(n.children) - 1; i >= 0; i-- { ni := n.children[i] if ni.kind == aliasNode { - an, ok := d.doc.anchors[ni.value] - if ok && an.kind != mappingNode { + if ni.alias != nil && ni.alias.kind != mappingNode { failWantMap() } } else if ni.kind != mappingNode { diff --git a/plugins/source-github/vendor/gopkg.in/yaml.v2/scannerc.go b/plugins/source-github/vendor/gopkg.in/yaml.v2/scannerc.go index 570b8ecd..0b9bb603 100644 --- a/plugins/source-github/vendor/gopkg.in/yaml.v2/scannerc.go +++ b/plugins/source-github/vendor/gopkg.in/yaml.v2/scannerc.go @@ -626,31 +626,18 @@ func trace(args ...interface{}) func() { func yaml_parser_fetch_more_tokens(parser *yaml_parser_t) bool { // While we need more tokens to fetch, do it. for { - // Check if we really need to fetch more tokens. - need_more_tokens := false - - if parser.tokens_head == len(parser.tokens) { - // Queue is empty. - need_more_tokens = true - } else { - // Check if any potential simple key may occupy the head position. - if !yaml_parser_stale_simple_keys(parser) { + if parser.tokens_head != len(parser.tokens) { + // If queue is non-empty, check if any potential simple key may + // occupy the head position. + head_tok_idx, ok := parser.simple_keys_by_tok[parser.tokens_parsed] + if !ok { + break + } else if valid, ok := yaml_simple_key_is_valid(parser, &parser.simple_keys[head_tok_idx]); !ok { return false - } - - for i := range parser.simple_keys { - simple_key := &parser.simple_keys[i] - if simple_key.possible && simple_key.token_number == parser.tokens_parsed { - need_more_tokens = true - break - } + } else if !valid { + break } } - - // We are finished. - if !need_more_tokens { - break - } // Fetch the next token. if !yaml_parser_fetch_next_token(parser) { return false @@ -678,11 +665,6 @@ func yaml_parser_fetch_next_token(parser *yaml_parser_t) bool { return false } - // Remove obsolete potential simple keys. - if !yaml_parser_stale_simple_keys(parser) { - return false - } - // Check the indentation level against the current column. if !yaml_parser_unroll_indent(parser, parser.mark.column) { return false @@ -837,29 +819,30 @@ func yaml_parser_fetch_next_token(parser *yaml_parser_t) bool { "found character that cannot start any token") } -// Check the list of potential simple keys and remove the positions that -// cannot contain simple keys anymore. -func yaml_parser_stale_simple_keys(parser *yaml_parser_t) bool { - // Check for a potential simple key for each flow level. - for i := range parser.simple_keys { - simple_key := &parser.simple_keys[i] - - // The specification requires that a simple key - // - // - is limited to a single line, - // - is shorter than 1024 characters. - if simple_key.possible && (simple_key.mark.line < parser.mark.line || simple_key.mark.index+1024 < parser.mark.index) { - - // Check if the potential simple key to be removed is required. - if simple_key.required { - return yaml_parser_set_scanner_error(parser, - "while scanning a simple key", simple_key.mark, - "could not find expected ':'") - } - simple_key.possible = false +func yaml_simple_key_is_valid(parser *yaml_parser_t, simple_key *yaml_simple_key_t) (valid, ok bool) { + if !simple_key.possible { + return false, true + } + + // The 1.2 specification says: + // + // "If the ? indicator is omitted, parsing needs to see past the + // implicit key to recognize it as such. To limit the amount of + // lookahead required, the “:” indicator must appear at most 1024 + // Unicode characters beyond the start of the key. In addition, the key + // is restricted to a single line." + // + if simple_key.mark.line < parser.mark.line || simple_key.mark.index+1024 < parser.mark.index { + // Check if the potential simple key to be removed is required. + if simple_key.required { + return false, yaml_parser_set_scanner_error(parser, + "while scanning a simple key", simple_key.mark, + "could not find expected ':'") } + simple_key.possible = false + return false, true } - return true + return true, true } // Check if a simple key may start at the current position and add it if @@ -879,13 +862,14 @@ func yaml_parser_save_simple_key(parser *yaml_parser_t) bool { possible: true, required: required, token_number: parser.tokens_parsed + (len(parser.tokens) - parser.tokens_head), + mark: parser.mark, } - simple_key.mark = parser.mark if !yaml_parser_remove_simple_key(parser) { return false } parser.simple_keys[len(parser.simple_keys)-1] = simple_key + parser.simple_keys_by_tok[simple_key.token_number] = len(parser.simple_keys) - 1 } return true } @@ -900,9 +884,10 @@ func yaml_parser_remove_simple_key(parser *yaml_parser_t) bool { "while scanning a simple key", parser.simple_keys[i].mark, "could not find expected ':'") } + // Remove the key from the stack. + parser.simple_keys[i].possible = false + delete(parser.simple_keys_by_tok, parser.simple_keys[i].token_number) } - // Remove the key from the stack. - parser.simple_keys[i].possible = false return true } @@ -912,7 +897,12 @@ const max_flow_level = 10000 // Increase the flow level and resize the simple key list if needed. func yaml_parser_increase_flow_level(parser *yaml_parser_t) bool { // Reset the simple key on the next level. - parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{}) + parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{ + possible: false, + required: false, + token_number: parser.tokens_parsed + (len(parser.tokens) - parser.tokens_head), + mark: parser.mark, + }) // Increase the flow level. parser.flow_level++ @@ -928,7 +918,9 @@ func yaml_parser_increase_flow_level(parser *yaml_parser_t) bool { func yaml_parser_decrease_flow_level(parser *yaml_parser_t) bool { if parser.flow_level > 0 { parser.flow_level-- - parser.simple_keys = parser.simple_keys[:len(parser.simple_keys)-1] + last := len(parser.simple_keys) - 1 + delete(parser.simple_keys_by_tok, parser.simple_keys[last].token_number) + parser.simple_keys = parser.simple_keys[:last] } return true } @@ -1005,6 +997,8 @@ func yaml_parser_fetch_stream_start(parser *yaml_parser_t) bool { // Initialize the simple key stack. parser.simple_keys = append(parser.simple_keys, yaml_simple_key_t{}) + parser.simple_keys_by_tok = make(map[int]int) + // A simple key is allowed at the beginning of the stream. parser.simple_key_allowed = true @@ -1286,7 +1280,11 @@ func yaml_parser_fetch_value(parser *yaml_parser_t) bool { simple_key := &parser.simple_keys[len(parser.simple_keys)-1] // Have we found a simple key? - if simple_key.possible { + if valid, ok := yaml_simple_key_is_valid(parser, simple_key); !ok { + return false + + } else if valid { + // Create the KEY token and insert it into the queue. token := yaml_token_t{ typ: yaml_KEY_TOKEN, @@ -1304,6 +1302,7 @@ func yaml_parser_fetch_value(parser *yaml_parser_t) bool { // Remove the simple key. simple_key.possible = false + delete(parser.simple_keys_by_tok, simple_key.token_number) // A simple key cannot follow another simple key. parser.simple_key_allowed = false diff --git a/plugins/source-github/vendor/gopkg.in/yaml.v2/yaml.go b/plugins/source-github/vendor/gopkg.in/yaml.v2/yaml.go index de85aa4c..89650e29 100644 --- a/plugins/source-github/vendor/gopkg.in/yaml.v2/yaml.go +++ b/plugins/source-github/vendor/gopkg.in/yaml.v2/yaml.go @@ -89,7 +89,7 @@ func UnmarshalStrict(in []byte, out interface{}) (err error) { return unmarshal(in, out, true) } -// A Decorder reads and decodes YAML values from an input stream. +// A Decoder reads and decodes YAML values from an input stream. type Decoder struct { strict bool parser *parser diff --git a/plugins/source-github/vendor/gopkg.in/yaml.v2/yamlh.go b/plugins/source-github/vendor/gopkg.in/yaml.v2/yamlh.go index e25cee56..f6a9c8e3 100644 --- a/plugins/source-github/vendor/gopkg.in/yaml.v2/yamlh.go +++ b/plugins/source-github/vendor/gopkg.in/yaml.v2/yamlh.go @@ -579,6 +579,7 @@ type yaml_parser_t struct { simple_key_allowed bool // May a simple key occur at the current position? simple_keys []yaml_simple_key_t // The stack of simple keys. + simple_keys_by_tok map[int]int // possible simple_key indexes indexed by token_number // Parser stuff diff --git a/plugins/source-github/vendor/k8s.io/client-go/discovery/discovery_client.go b/plugins/source-github/vendor/k8s.io/client-go/discovery/discovery_client.go index 61b9c448..5d89457c 100644 --- a/plugins/source-github/vendor/k8s.io/client-go/discovery/discovery_client.go +++ b/plugins/source-github/vendor/k8s.io/client-go/discovery/discovery_client.go @@ -463,6 +463,13 @@ func setDiscoveryDefaults(config *restclient.Config) error { if config.Timeout == 0 { config.Timeout = defaultTimeout } + if config.Burst == 0 && config.QPS < 100 { + // discovery is expected to be bursty, increase the default burst + // to accommodate looking up resource info for many API groups. + // matches burst set by ConfigFlags#ToDiscoveryClient(). + // see https://issue.k8s.io/86149 + config.Burst = 100 + } codec := runtime.NoopEncoder{Decoder: scheme.Codecs.UniversalDecoder()} config.NegotiatedSerializer = serializer.NegotiatedSerializerWrapper(runtime.SerializerInfo{Serializer: codec}) if len(config.UserAgent) == 0 { diff --git a/plugins/source-github/vendor/k8s.io/client-go/tools/cache/reflector.go b/plugins/source-github/vendor/k8s.io/client-go/tools/cache/reflector.go index 1165c523..62749ed7 100644 --- a/plugins/source-github/vendor/k8s.io/client-go/tools/cache/reflector.go +++ b/plugins/source-github/vendor/k8s.io/client-go/tools/cache/reflector.go @@ -74,9 +74,6 @@ type Reflector struct { // observed when doing a sync with the underlying store // it is thread safe, but not synchronized with the underlying store lastSyncResourceVersion string - // isLastSyncResourceVersionGone is true if the previous list or watch request with lastSyncResourceVersion - // failed with an HTTP 410 (Gone) status code. - isLastSyncResourceVersionGone bool // lastSyncResourceVersionMutex guards read/write access to lastSyncResourceVersion lastSyncResourceVersionMutex sync.RWMutex // WatchListPageSize is the requested chunk size of initial and resync watch lists. @@ -188,7 +185,10 @@ func (r *Reflector) ListAndWatch(stopCh <-chan struct{}) error { klog.V(3).Infof("Listing and watching %v from %s", r.expectedTypeName, r.name) var resourceVersion string - options := metav1.ListOptions{ResourceVersion: r.relistResourceVersion()} + // Explicitly set "0" as resource version - it's fine for the List() + // to be served from cache and potentially be delayed relative to + // etcd contents. Reflector framework will catch up via Watch() eventually. + options := metav1.ListOptions{ResourceVersion: "0"} if err := func() error { initTrace := trace.New("Reflector ListAndWatch", trace.Field{"name", r.name}) @@ -211,17 +211,8 @@ func (r *Reflector) ListAndWatch(stopCh <-chan struct{}) error { if r.WatchListPageSize != 0 { pager.PageSize = r.WatchListPageSize } - + // Pager falls back to full list if paginated list calls fail due to an "Expired" error. list, err = pager.List(context.Background(), options) - if isExpiredError(err) { - r.setIsLastSyncResourceVersionExpired(true) - // Retry immediately if the resource version used to list is expired. - // The pager already falls back to full list if paginated list calls fail due to an "Expired" error on - // continuation pages, but the pager might not be enabled, or the full list might fail because the - // resource version it is listing at is expired, so we need to fallback to resourceVersion="" in all - // to recover and ensure the reflector makes forward progress. - list, err = pager.List(context.Background(), metav1.ListOptions{ResourceVersion: r.relistResourceVersion()}) - } close(listCh) }() select { @@ -234,7 +225,6 @@ func (r *Reflector) ListAndWatch(stopCh <-chan struct{}) error { if err != nil { return fmt.Errorf("%s: Failed to list %v: %v", r.name, r.expectedTypeName, err) } - r.setIsLastSyncResourceVersionExpired(false) // list was successful initTrace.Step("Objects listed") listMetaInterface, err := meta.ListAccessor(list) if err != nil { @@ -308,13 +298,10 @@ func (r *Reflector) ListAndWatch(stopCh <-chan struct{}) error { w, err := r.listerWatcher.Watch(options) if err != nil { - switch { - case isExpiredError(err): - r.setIsLastSyncResourceVersionExpired(true) - klog.V(4).Infof("%s: watch of %v closed with: %v", r.name, r.expectedTypeName, err) - case err == io.EOF: + switch err { + case io.EOF: // watch closed normally - case err == io.ErrUnexpectedEOF: + case io.ErrUnexpectedEOF: klog.V(1).Infof("%s: Watch for %v closed with unexpected EOF: %v", r.name, r.expectedTypeName, err) default: utilruntime.HandleError(fmt.Errorf("%s: Failed to watch %v: %v", r.name, r.expectedTypeName, err)) @@ -333,8 +320,7 @@ func (r *Reflector) ListAndWatch(stopCh <-chan struct{}) error { if err := r.watchHandler(w, &resourceVersion, resyncerrc, stopCh); err != nil { if err != errorStopRequested { switch { - case isExpiredError(err): - r.setIsLastSyncResourceVersionExpired(true) + case apierrs.IsResourceExpired(err): klog.V(4).Infof("%s: watch of %v ended with: %v", r.name, r.expectedTypeName, err) default: klog.Warningf("%s: watch of %v ended with: %v", r.name, r.expectedTypeName, err) @@ -446,42 +432,3 @@ func (r *Reflector) setLastSyncResourceVersion(v string) { defer r.lastSyncResourceVersionMutex.Unlock() r.lastSyncResourceVersion = v } - -// relistResourceVersion determines the resource version the reflector should list or relist from. -// Returns either the lastSyncResourceVersion so that this reflector will relist with a resource -// versions no older than has already been observed in relist results or watch events, or, if the last relist resulted -// in an HTTP 410 (Gone) status code, returns "" so that the relist will use the latest resource version available in -// etcd via a quorum read. -func (r *Reflector) relistResourceVersion() string { - r.lastSyncResourceVersionMutex.RLock() - defer r.lastSyncResourceVersionMutex.RUnlock() - - if r.isLastSyncResourceVersionGone { - // Since this reflector makes paginated list requests, and all paginated list requests skip the watch cache - // if the lastSyncResourceVersion is expired, we set ResourceVersion="" and list again to re-establish reflector - // to the latest available ResourceVersion, using a consistent read from etcd. - return "" - } - if r.lastSyncResourceVersion == "" { - // For performance reasons, initial list performed by reflector uses "0" as resource version to allow it to - // be served from the watch cache if it is enabled. - return "0" - } - return r.lastSyncResourceVersion -} - -// setIsLastSyncResourceVersionExpired sets if the last list or watch request with lastSyncResourceVersion returned a -// expired error: HTTP 410 (Gone) Status Code. -func (r *Reflector) setIsLastSyncResourceVersionExpired(isExpired bool) { - r.lastSyncResourceVersionMutex.Lock() - defer r.lastSyncResourceVersionMutex.Unlock() - r.isLastSyncResourceVersionGone = isExpired -} - -func isExpiredError(err error) bool { - // In Kubernetes 1.17 and earlier, the api server returns both apierrs.StatusReasonExpired and - // apierrs.StatusReasonGone for HTTP 410 (Gone) status code responses. In 1.18 the kube server is more consistent - // and always returns apierrs.StatusReasonExpired. For backward compatibility we can only remove the apierrs.IsGone - // check when we fully drop support for Kubernetes 1.17 servers from reflectors. - return apierrs.IsResourceExpired(err) || apierrs.IsGone(err) -} diff --git a/plugins/source-github/vendor/k8s.io/client-go/tools/clientcmd/api/v1/conversion.go b/plugins/source-github/vendor/k8s.io/client-go/tools/clientcmd/api/v1/conversion.go index 0d27672e..c38ebc07 100644 --- a/plugins/source-github/vendor/k8s.io/client-go/tools/clientcmd/api/v1/conversion.go +++ b/plugins/source-github/vendor/k8s.io/client-go/tools/clientcmd/api/v1/conversion.go @@ -31,6 +31,9 @@ func Convert_Slice_v1_NamedCluster_To_Map_string_To_Pointer_api_Cluster(in *[]Na if err := Convert_v1_Cluster_To_api_Cluster(&curr.Cluster, newCluster, s); err != nil { return err } + if *out == nil { + *out = make(map[string]*api.Cluster) + } if (*out)[curr.Name] == nil { (*out)[curr.Name] = newCluster } else { @@ -65,6 +68,9 @@ func Convert_Slice_v1_NamedAuthInfo_To_Map_string_To_Pointer_api_AuthInfo(in *[] if err := Convert_v1_AuthInfo_To_api_AuthInfo(&curr.AuthInfo, newAuthInfo, s); err != nil { return err } + if *out == nil { + *out = make(map[string]*api.AuthInfo) + } if (*out)[curr.Name] == nil { (*out)[curr.Name] = newAuthInfo } else { @@ -99,6 +105,9 @@ func Convert_Slice_v1_NamedContext_To_Map_string_To_Pointer_api_Context(in *[]Na if err := Convert_v1_Context_To_api_Context(&curr.Context, newContext, s); err != nil { return err } + if *out == nil { + *out = make(map[string]*api.Context) + } if (*out)[curr.Name] == nil { (*out)[curr.Name] = newContext } else { @@ -133,6 +142,9 @@ func Convert_Slice_v1_NamedExtension_To_Map_string_To_runtime_Object(in *[]Named if err := runtime.Convert_runtime_RawExtension_To_runtime_Object(&curr.Extension, &newExtension, s); err != nil { return err } + if *out == nil { + *out = make(map[string]runtime.Object) + } if (*out)[curr.Name] == nil { (*out)[curr.Name] = newExtension } else { diff --git a/plugins/source-github/vendor/k8s.io/client-go/util/connrotation/connrotation.go b/plugins/source-github/vendor/k8s.io/client-go/util/connrotation/connrotation.go index 235a9e01..f98faee4 100644 --- a/plugins/source-github/vendor/k8s.io/client-go/util/connrotation/connrotation.go +++ b/plugins/source-github/vendor/k8s.io/client-go/util/connrotation/connrotation.go @@ -77,11 +77,6 @@ func (d *Dialer) DialContext(ctx context.Context, network, address string) (net. closable := &closableConn{Conn: conn} - // Start tracking the connection - d.mu.Lock() - d.conns[closable] = struct{}{} - d.mu.Unlock() - // When the connection is closed, remove it from the map. This will // be no-op if the connection isn't in the map, e.g. if CloseAll() // is called. @@ -91,6 +86,11 @@ func (d *Dialer) DialContext(ctx context.Context, network, address string) (net. d.mu.Unlock() } + // Start tracking the connection + d.mu.Lock() + d.conns[closable] = struct{}{} + d.mu.Unlock() + return closable, nil } diff --git a/plugins/source-github/vendor/knative.dev/client/lib/test/cli.go b/plugins/source-github/vendor/knative.dev/client/lib/test/cli.go new file mode 100644 index 00000000..93f37d55 --- /dev/null +++ b/plugins/source-github/vendor/knative.dev/client/lib/test/cli.go @@ -0,0 +1,238 @@ +// Copyright 2020 The Knative 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 test + +import ( + "bytes" + "fmt" + "os/exec" + "strings" + + "github.com/pkg/errors" +) + +const ( + seperatorHeavy = "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━" + seperatorLight = "╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍╍" +) + +// Kn type +type Kn struct { + namespace string +} + +// NewKn object +func NewKn() Kn { + return Kn{} +} + +// RunNoNamespace the 'kn' CLI with args but no namespace +func (k Kn) RunNoNamespace(args ...string) KnRunResult { + return RunKn("", args) +} + +// Run the 'kn' CLI with args +func (k Kn) Run(args ...string) KnRunResult { + return RunKn(k.namespace, args) +} + +// Namespace that this Kn instance uses +func (k Kn) Namespace() string { + return k.namespace +} + +// Kubectl type +type Kubectl struct { + namespace string +} + +// New Kubectl object +func NewKubectl(namespace string) Kubectl { + return Kubectl{ + namespace: namespace, + } +} + +// Run the 'kubectl' CLI with args +func (k Kubectl) Run(args ...string) (string, error) { + return RunKubectl(k.namespace, args...) +} + +// Namespace that this Kubectl instance uses +func (k Kubectl) Namespace() string { + return k.namespace +} + +// Public functions + +// RunKn runs "kn" in a given namespace +func RunKn(namespace string, args []string) KnRunResult { + if namespace != "" { + args = append(args, "--namespace", namespace) + } + stdout, stderr, err := runCli("kn", args) + result := KnRunResult{ + CmdLine: cmdCLIDesc("kn", args), + Stdout: stdout, + Stderr: stderr, + Error: err, + } + if err != nil { + command := args[0] + if command == "source" && len(args) > 1 { + command = "source " + args[1] + args = args[1:] + } + result.DumpInfo = extractDumpInfo(command, args, namespace) + } + return result +} + +// RunKubectl runs "kubectl" in a given namespace +func RunKubectl(namespace string, args ...string) (string, error) { + if namespace != "" { + args = append(args, "--namespace", namespace) + } + stdout, stderr, err := runCli("kubectl", args) + if err != nil { + return stdout, errors.Wrap(err, fmt.Sprintf("stderr: %s", stderr)) + } + return stdout, nil +} + +// Private + +func runCli(cli string, args []string) (string, string, error) { + var stderr bytes.Buffer + var stdout bytes.Buffer + + cmd := exec.Command(cli, args...) + cmd.Stderr = &stderr + cmd.Stdout = &stdout + cmd.Stdin = nil + + err := cmd.Run() + return stdout.String(), stderr.String(), err +} + +type dumpFunc func(namespace string, args []string) string + +// Dump handler for specific commands ("service", "revision") which should add extra infos +// Relies on that argv[1] is the command and argv[3] is the name of the object +var dumpHandlers = map[string]dumpFunc{ + "service": dumpService, + "revision": dumpRevision, + "route": dumpRoute, + "trigger": dumpTrigger, + "source apiserver": dumpApiServerSource, +} + +func extractDumpInfoWithName(command string, name string, namespace string) string { + return extractDumpInfo(command, []string{command, "", name}, namespace) +} + +func extractDumpInfo(command string, args []string, namespace string) string { + dumpHandler := dumpHandlers[command] + if dumpHandler != nil { + return dumpHandler(namespace, args) + } + return "" +} + +func dumpService(namespace string, args []string) string { + // For list like operation we don't have a name + if len(args) < 3 || args[2] == "" { + return "" + } + name := args[2] + var buffer bytes.Buffer + + // Service info + appendResourceInfo(&buffer, "ksvc", name, namespace) + fmt.Fprintf(&buffer, "%s\n", seperatorHeavy) + // Service's configuration + appendResourceInfo(&buffer, "configuration", name, namespace) + fmt.Fprintf(&buffer, "%s\n", seperatorHeavy) + // Get all revisions for this service + appendResourceInfoWithNameSelector(&buffer, "revision", name, namespace, "serving.knative.dev/service") + // Get all routes for this service + appendResourceInfoWithNameSelector(&buffer, "route", name, namespace, "serving.knative.dev/service") + return buffer.String() +} + +func dumpRevision(namespace string, args []string) string { + return simpleDump("revision", args, namespace) +} + +func dumpRoute(namespace string, args []string) string { + return simpleDump("route", args, namespace) +} + +func dumpApiServerSource(namespace string, args []string) string { + return simpleDump("apiserversource", args, namespace) +} + +func dumpTrigger(namespace string, args []string) string { + return simpleDump("trigger", args, namespace) +} + +func simpleDump(kind string, args []string, namespace string) string { + if len(args) < 3 || args[2] == "" { + return "" + } + + var buffer bytes.Buffer + appendResourceInfo(&buffer, kind, args[2], namespace) + return buffer.String() +} + +func appendResourceInfo(buffer *bytes.Buffer, kind string, name string, namespace string) { + appendResourceInfoWithNameSelector(buffer, kind, name, namespace, "") +} + +func appendResourceInfoWithNameSelector(buffer *bytes.Buffer, kind string, name string, namespace string, selector string) { + var extra string + argsDescribe := []string{"describe", kind} + argsGet := []string{"get", "-oyaml", kind} + + if selector != "" { + labelArg := fmt.Sprintf("%s=%s", selector, name) + argsDescribe = append(argsDescribe, "--selector", labelArg) + argsGet = append(argsGet, "--selector", labelArg) + extra = fmt.Sprintf(" --selector %s", labelArg) + } else { + argsDescribe = append(argsDescribe, name) + argsGet = append(argsGet, name) + extra = "" + } + + out, err := RunKubectl(namespace, argsDescribe...) + appendCLIOutput(buffer, fmt.Sprintf("kubectl describe %s %s --namespace %s%s", kind, name, namespace, extra), out, err) + fmt.Fprintf(buffer, "%s\n", seperatorLight) + out, err = RunKubectl(namespace, argsGet...) + appendCLIOutput(buffer, fmt.Sprintf("kubectl get %s %s --namespace %s -oyaml%s", kind, name, namespace, extra), out, err) +} + +func appendCLIOutput(buffer *bytes.Buffer, desc string, out string, err error) { + buffer.WriteString(fmt.Sprintf("==== %s\n", desc)) + if err != nil { + buffer.WriteString(fmt.Sprintf("%s: %v\n", "!!!! ERROR", err)) + } + buffer.WriteString(out) +} + +func cmdCLIDesc(cli string, args []string) string { + return fmt.Sprintf("%s %s", cli, strings.Join(args, " ")) +} diff --git a/plugins/source-github/vendor/knative.dev/client/lib/test/flags.go b/plugins/source-github/vendor/knative.dev/client/lib/test/flags.go new file mode 100644 index 00000000..71fe8998 --- /dev/null +++ b/plugins/source-github/vendor/knative.dev/client/lib/test/flags.go @@ -0,0 +1,42 @@ +/* +Copyright 2019 The Knative 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 + + https://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 test + +import ( + "flag" + "os" +) + +// Flags holds the command line flags or defaults for settings in the user's environment. +// See ClientFlags for the list of supported fields. +var Flags = InitializeFlags() + +// ClientFlags define the flags that are needed to run the e2e tests. +type ClientFlags struct { + DockerConfigJSON string +} + +// InitializeFlags initializes the client's flags +func InitializeFlags() *ClientFlags { + var f ClientFlags + + dockerConfigJSON := os.Getenv("DOCKER_CONFIG_JSON") + flag.StringVar(&f.DockerConfigJSON, "dockerconfigjson", dockerConfigJSON, + "Provide the path to Docker configuration file in json format. Defaults to $DOCKER_CONFIG_JSON") + + return &f +} diff --git a/plugins/source-github/vendor/knative.dev/client/lib/test/integration.go b/plugins/source-github/vendor/knative.dev/client/lib/test/integration.go new file mode 100644 index 00000000..0e8574cf --- /dev/null +++ b/plugins/source-github/vendor/knative.dev/client/lib/test/integration.go @@ -0,0 +1,223 @@ +// Copyright 2019 The Knative 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 test + +import ( + "fmt" + "os" + "regexp" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/pkg/errors" +) + +const ( + KnDefaultTestImage string = "gcr.io/knative-samples/helloworld-go" + MaxRetries int = 10 + RetrySleepDuration time.Duration = 5 * time.Second +) + +var nsMutex sync.Mutex +var serviceMutex sync.Mutex +var serviceCount int +var namespaceCount int + +// KnTest type +type KnTest struct { + namespace string + kn Kn +} + +// NewKnTest creates a new KnTest object +func NewKnTest() (*KnTest, error) { + ns := NextNamespace() + + err := CreateNamespace(ns) + if err != nil { + return nil, err + } + err = WaitForNamespaceCreated(ns) + if err != nil { + return nil, err + } + + return &KnTest{ + namespace: ns, + kn: Kn{ns}, + }, nil +} + +// Teardown clean up +func (test *KnTest) Teardown() error { + return DeleteNamespace(test.namespace) +} + +// Kn object used by this KnTest +func (test *KnTest) Kn() Kn { + return test.kn +} + +// Namespace used by the test +func (test *KnTest) Namespace() string { + return test.namespace +} + +// Public functions + +// NextNamespace return the next unique namespace +func NextNamespace() string { + ns := os.Getenv("KN_E2E_NAMESPACE") + if ns == "" { + ns = "kne2etests" + } + return fmt.Sprintf("%s%d", ns, GetNextNamespaceId()) +} + +// GetNextNamespaceId return the next unique ID for the next namespace +func GetNextNamespaceId() int { + nsMutex.Lock() + defer nsMutex.Unlock() + current := namespaceCount + namespaceCount++ + return current +} + +// GetNextServiceName return the name for the next namespace +func GetNextServiceName(base string) string { + serviceMutex.Lock() + defer serviceMutex.Unlock() + current := serviceCount + serviceCount++ + return base + strconv.Itoa(current) +} + +// CreateNamespace creates and tests a namesspace creation invoking kubectl +func CreateNamespace(namespace string) error { + expectedOutputRegexp := fmt.Sprintf("namespace?.+%s.+created", namespace) + out, err := createNamespaceWithRetry(namespace, MaxRetries) + if err != nil { + return errors.Wrap(err, "could not create namespace "+namespace) + } + + // check that last output indeed show created namespace + matched, err := matchRegexp(expectedOutputRegexp, out) + if err != nil { + return err + } + if !matched { + return fmt.Errorf("Expected output incorrect, expecting to include:\n%s\n Instead found:\n%s\n", expectedOutputRegexp, out) + } + return nil +} + +// DeleteNamespace deletes and tests a namesspace deletion invoking kubectl +func DeleteNamespace(namespace string) error { + kubectl := Kubectl{namespace} + out, err := kubectl.Run("delete", "namespace", namespace) + if err != nil { + return errors.Wrap(err, fmt.Sprintf("Cannot delete namespace %s", namespace)) + } + + expectedOutputRegexp := fmt.Sprintf("namespace?.+%s.+deleted", namespace) + matched, err := matchRegexp(expectedOutputRegexp, out) + if err != nil { + return err + } + if !matched { + return fmt.Errorf("Expected output incorrect, expecting to include:\n%s\n Instead found:\n%s\n", expectedOutputRegexp, out) + } + return nil +} + +// WaitForNamespaceDeleted wait until namespace is deleted +func WaitForNamespaceDeleted(namespace string) error { + deleted := checkNamespace(namespace, false, MaxRetries) + if !deleted { + return fmt.Errorf("error deleting namespace %s, timed out after %d retries", namespace, MaxRetries) + } + return nil +} + +// WaitForNamespaceCreated wait until namespace is created +func WaitForNamespaceCreated(namespace string) error { + created := checkNamespace(namespace, true, MaxRetries) + if !created { + return fmt.Errorf("error creating namespace %s, timed out after %d retries", namespace, MaxRetries) + } + return nil +} + +func CurrentDir(t *testing.T) string { + dir, err := os.Getwd() + if err != nil { + t.Fatal("Unable to read current dir:", err) + } + return dir +} + +// Private functions + +func checkNamespace(namespace string, created bool, maxRetries int) bool { + retries := 0 + for retries < MaxRetries { + output, _ := Kubectl{}.Run("get", "namespace") + + // check for namespace deleted + if !created && !strings.Contains(output, namespace) { + return true + } + + // check for namespace created + if created && strings.Contains(output, namespace) { + return true + } + + retries++ + time.Sleep(RetrySleepDuration) + } + + return true +} + +func createNamespaceWithRetry(namespace string, maxRetries int) (string, error) { + var ( + retries int + err error + out string + ) + + for retries < maxRetries { + out, err = Kubectl{}.Run("create", "namespace", namespace) + if err == nil { + return out, nil + } + retries++ + time.Sleep(RetrySleepDuration) + } + + return out, err +} + +func matchRegexp(matchingRegexp, actual string) (bool, error) { + matched, err := regexp.MatchString(matchingRegexp, actual) + if err != nil { + return false, errors.Wrap(err, fmt.Sprintf("failed to match regexp '%s'", matchingRegexp)) + } + return matched, nil +} diff --git a/plugins/source-github/vendor/knative.dev/client/lib/test/result_collector.go b/plugins/source-github/vendor/knative.dev/client/lib/test/result_collector.go new file mode 100644 index 00000000..02661226 --- /dev/null +++ b/plugins/source-github/vendor/knative.dev/client/lib/test/result_collector.go @@ -0,0 +1,151 @@ +// Copyright 2020 The Knative 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 test + +import ( + "bytes" + "fmt" + "io" + "strings" + "testing" +) + +// KnRunResult holds command and result artifacts of a "kn" call +type KnRunResult struct { + // Command line called + CmdLine string + // Standard output of command + Stdout string + // Standard error of command + Stderr string + // And extra dump informations in case of an unexpected error + DumpInfo string + // Error occurred during execution + Error error + // Was an error expected ? + ErrorExpected bool +} + +// KnRunResultCollector collects Kn run's results +type KnRunResultCollector struct { + results []KnRunResult + extraDumps []string + + t *testing.T + knTest *KnTest +} + +// NewKnRunResultCollector returns a new KnRunResultCollector +func NewKnRunResultCollector(t *testing.T, knTest *KnTest) *KnRunResultCollector { + return &KnRunResultCollector{ + results: []KnRunResult{}, + extraDumps: []string{}, + + t: t, + knTest: knTest, + } +} + +// T returns the *testing.T object +func (c *KnRunResultCollector) T() *testing.T { + return c.t +} + +// KnTest returns the KnTest object +func (c *KnRunResultCollector) KnTest() *KnTest { + return c.knTest +} + +// AssertNoError helper to assert no error on result +func (c *KnRunResultCollector) AssertNoError(result KnRunResult) { + c.results = append(c.results, result) + if result.Error != nil { + c.t.Logf("ERROR: %v", result.Stderr) + c.t.FailNow() + } +} + +// AssertError helper to assert error on result +func (c *KnRunResultCollector) AssertError(result KnRunResult) { + c.results = append(c.results, result) + if result.Error == nil { + c.t.Log("ERROR: Error expected but no error happened") + c.t.FailNow() + } +} + +// AddDump adds extra dump information to the collector which is printed +// out if an error occurs +func (c *KnRunResultCollector) AddDump(kind string, name string, namespace string) { + dumpInfo := extractDumpInfoWithName(kind, name, namespace) + if dumpInfo != "" { + c.extraDumps = append(c.extraDumps, dumpInfo) + } +} + +// DumpIfFailed logs if collector failed +func (c *KnRunResultCollector) DumpIfFailed() { + if c.t.Failed() { + c.t.Log(c.errorDetails()) + } +} + +// Private + +func (c *KnRunResultCollector) errorDetails() string { + var out = bytes.Buffer{} + fmt.Fprintln(&out, "=== FAIL: =======================[[ERROR]]========================") + c.printCommands(&out) + var dumpInfos []string + if len(c.results) > 0 { + dumpInfo := c.results[len(c.results)-1].DumpInfo + if dumpInfo != "" { + dumpInfos = append(dumpInfos, dumpInfo) + } + } + dumpInfos = append(dumpInfos, c.extraDumps...) + for _, d := range dumpInfos { + fmt.Fprintln(&out, "--------------------------[[DUMP]]-------------------------------") + fmt.Fprintf(&out, d) + } + + fmt.Fprintln(&out, "=================================================================") + return out.String() +} + +func (c *KnRunResultCollector) printCommands(out io.Writer) { + for i, result := range c.results { + c.printCommand(out, result) + if i < len(c.results)-1 { + fmt.Fprintf(out, "┣━%s\n", seperatorHeavy) + } + } +} + +func (c *KnRunResultCollector) printCommand(out io.Writer, result KnRunResult) { + fmt.Fprintf(out, "🦆 %s\n", result.CmdLine) + for _, l := range strings.Split(result.Stdout, "\n") { + fmt.Fprintf(out, "┃ %s\n", l) + } + if result.Stderr != "" { + errorPrefix := "🔥" + if result.ErrorExpected { + errorPrefix = "︙" + } + for _, l := range strings.Split(result.Stderr, "\n") { + fmt.Fprintf(out, "%s %s\n", errorPrefix, l) + } + } +} diff --git a/plugins/source-github/vendor/knative.dev/client/pkg/kn/commands/flags/listprint.go b/plugins/source-github/vendor/knative.dev/client/pkg/kn/commands/flags/listprint.go index a19cca49..da73381c 100644 --- a/plugins/source-github/vendor/knative.dev/client/pkg/kn/commands/flags/listprint.go +++ b/plugins/source-github/vendor/knative.dev/client/pkg/kn/commands/flags/listprint.go @@ -15,11 +15,15 @@ package flags import ( + "io" + "github.com/spf13/cobra" + "k8s.io/apimachinery/pkg/runtime" "k8s.io/cli-runtime/pkg/genericclioptions" "knative.dev/client/pkg/kn/commands" hprinters "knative.dev/client/pkg/printers" + "knative.dev/client/pkg/util" ) // ListFlags composes common printer flag structs @@ -56,6 +60,24 @@ func (f *ListPrintFlags) ToPrinter() (hprinters.ResourcePrinter, error) { return p, nil } +// Print is to print an Object to a Writer +func (f *ListPrintFlags) Print(obj runtime.Object, w io.Writer) error { + printer, err := f.ToPrinter() + if err != nil { + return err + } + + if f.GenericPrintFlags.OutputFlagSpecified() { + unstructuredList, err := util.ToUnstructuredList(obj) + if err != nil { + return err + } + return printer.PrintObj(unstructuredList, w) + } + + return printer.PrintObj(obj, w) +} + // AddFlags receives a *cobra.Command reference and binds // flags related to humanreadable and template printing. func (f *ListPrintFlags) AddFlags(cmd *cobra.Command) { diff --git a/plugins/source-github/vendor/knative.dev/client/pkg/kn/commands/wait_flags.go b/plugins/source-github/vendor/knative.dev/client/pkg/kn/commands/wait_flags.go index ca783685..32e0e07c 100644 --- a/plugins/source-github/vendor/knative.dev/client/pkg/kn/commands/wait_flags.go +++ b/plugins/source-github/vendor/knative.dev/client/pkg/kn/commands/wait_flags.go @@ -18,6 +18,8 @@ import ( "fmt" "github.com/spf13/cobra" + + knflags "knative.dev/client/pkg/kn/flags" ) // Default time out to use when waiting for reconciliation. It is deliberately very long as it is expected that @@ -29,9 +31,8 @@ const WaitDefaultTimeout = 600 type WaitFlags struct { // Timeout in seconds for how long to wait for a command to return TimeoutInSeconds int - - // If set then just apply resources and don't wait - NoWait bool + // If set then apply resources and wait for completion + Wait bool //TODO: deprecated variable should be removed with --async flag Async bool } @@ -40,11 +41,16 @@ type WaitFlags struct { // resources. Set `waitDefault` argument if the default behaviour is synchronous. // Use `what` for describing what is waited for. func (p *WaitFlags) AddConditionWaitFlags(command *cobra.Command, waitTimeoutDefault int, action, what, until string) { - waitUsage := fmt.Sprintf("%s %s and don't wait for it to be %s.", action, what, until) - //TODO: deprecated flag should be removed in next release - command.Flags().BoolVar(&p.Async, "async", false, "DEPRECATED: please use --no-wait instead. "+waitUsage) - command.Flags().BoolVar(&p.NoWait, "no-wait", false, waitUsage) + waitUsage := fmt.Sprintf("Wait for '%s %s' operation to be completed.", what, action) + waitDefault := true + // Special-case 'delete' command so it comes back to the user immediately + if action == "delete" { + waitDefault = false + } + //TODO: deprecated flag should be removed in next release + command.Flags().BoolVar(&p.Async, "async", !waitDefault, "DEPRECATED: please use --no-wait instead. "+knflags.InvertUsage(waitUsage)) + knflags.AddBothBoolFlagsUnhidden(command.Flags(), &p.Wait, "wait", "", waitDefault, waitUsage) timeoutUsage := fmt.Sprintf("Seconds to wait before giving up on waiting for %s to be %s.", what, until) command.Flags().IntVar(&p.TimeoutInSeconds, "wait-timeout", waitTimeoutDefault, timeoutUsage) } diff --git a/plugins/source-github/vendor/knative.dev/client/pkg/kn/flags/bool.go b/plugins/source-github/vendor/knative.dev/client/pkg/kn/flags/bool.go index 026638b8..111af22e 100644 --- a/plugins/source-github/vendor/knative.dev/client/pkg/kn/flags/bool.go +++ b/plugins/source-github/vendor/knative.dev/client/pkg/kn/flags/bool.go @@ -24,7 +24,10 @@ import ( "github.com/spf13/pflag" ) -var negPrefix = "no-" +var ( + negPrefix = "no-" + deprecatedPrefix = "DEPRECATED:" +) // AddBothBoolFlagsUnhidden is just like AddBothBoolFlags but shows both flags. func AddBothBoolFlagsUnhidden(f *pflag.FlagSet, p *bool, name, short string, value bool, usage string) { @@ -32,7 +35,7 @@ func AddBothBoolFlagsUnhidden(f *pflag.FlagSet, p *bool, name, short string, val negativeName := negPrefix + name f.BoolVarP(p, name, short, value, usage) - f.Bool(negativeName, !value, "Do not "+firstCharToLower(usage)) + f.Bool(negativeName, !value, InvertUsage(usage)) } // AddBothBoolFlags adds the given flag in both `--foo` and `--no-foo` variants. @@ -65,6 +68,20 @@ func ReconcileBoolFlags(f *pflag.FlagSet) error { if err != nil { return } + + // handle async flag + if flag.Name == "async" && flag.Changed { + if f.Lookup("wait").Changed || f.Lookup("no-wait").Changed { + err = fmt.Errorf("only one of (DEPRECATED) --async, --wait and --no-wait may be specified") + return + } + err = checkExplicitFalse(flag, "wait") + if err != nil { + return + } + f.Lookup("no-wait").Value.Set("true") + } + // Walk the "no-" versions of the flags. Make sure we didn't set // both, and set the positive value to the opposite of the "no-" // value if it exists. @@ -90,6 +107,7 @@ func ReconcileBoolFlags(f *pflag.FlagSet) error { err = checkExplicitFalse(positive, flag.Name) } } + }) return err } @@ -110,7 +128,13 @@ func checkExplicitFalse(f *pflag.Flag, betterFlag string) error { return nil } -func firstCharToLower(s string) string { +// FirstCharToLower converts first char in given string to lowercase +func FirstCharToLower(s string) string { r, n := utf8.DecodeRuneInString(s) return string(unicode.ToLower(r)) + s[n:] } + +// InvertUsage inverts the usage string with prefix "Do not" +func InvertUsage(usage string) string { + return "Do not " + FirstCharToLower(usage) +} diff --git a/plugins/source-github/vendor/knative.dev/client/pkg/printers/tableprinter.go b/plugins/source-github/vendor/knative.dev/client/pkg/printers/tableprinter.go index f51bc139..0f309b40 100644 --- a/plugins/source-github/vendor/knative.dev/client/pkg/printers/tableprinter.go +++ b/plugins/source-github/vendor/knative.dev/client/pkg/printers/tableprinter.go @@ -41,6 +41,10 @@ func NewTablePrinter(options PrintOptions) *HumanReadablePrinter { // PrintObj prints the obj in a human-friendly format according to the type of the obj. func (h *HumanReadablePrinter) PrintObj(obj runtime.Object, output io.Writer) error { + if obj == nil { + return nil + } + w, found := output.(*tabwriter.Writer) if !found { w = NewTabWriter(output) diff --git a/plugins/source-github/vendor/knative.dev/client/pkg/serving/config_changes.go b/plugins/source-github/vendor/knative.dev/client/pkg/serving/config_changes.go index b91e2612..e1235474 100644 --- a/plugins/source-github/vendor/knative.dev/client/pkg/serving/config_changes.go +++ b/plugins/source-github/vendor/knative.dev/client/pkg/serving/config_changes.go @@ -198,6 +198,11 @@ func UpdateConcurrencyTarget(template *servingv1.RevisionTemplateSpec, target in return UpdateRevisionTemplateAnnotation(template, autoscaling.TargetAnnotationKey, strconv.Itoa(target)) } +// UpdateConcurrencyUtilization updates container target utilization percentage annotation +func UpdateConcurrencyUtilization(template *servingv1.RevisionTemplateSpec, target int) error { + return UpdateRevisionTemplateAnnotation(template, autoscaling.TargetUtilizationPercentageKey, strconv.Itoa(target)) +} + // UpdateConcurrencyLimit updates container concurrency limit func UpdateConcurrencyLimit(template *servingv1.RevisionTemplateSpec, limit int64) error { if limit < 0 { diff --git a/plugins/source-github/vendor/knative.dev/client/pkg/serving/revision_template.go b/plugins/source-github/vendor/knative.dev/client/pkg/serving/revision_template.go index a42add6e..553ebc9e 100644 --- a/plugins/source-github/vendor/knative.dev/client/pkg/serving/revision_template.go +++ b/plugins/source-github/vendor/knative.dev/client/pkg/serving/revision_template.go @@ -63,6 +63,11 @@ func ConcurrencyTarget(m *metav1.ObjectMeta) *int { return ret } +func ConcurrencyTargetUtilization(m *metav1.ObjectMeta) *int { + ret, _ := annotationAsInt(m, autoscaling.TargetUtilizationPercentageKey) + return ret +} + func AutoscaleWindow(m *metav1.ObjectMeta) string { return m.Annotations[autoscaling.WindowAnnotationKey] } diff --git a/plugins/source-github/vendor/knative.dev/client/pkg/serving/v1/client.go b/plugins/source-github/vendor/knative.dev/client/pkg/serving/v1/client.go index a4bb53a1..ca2d0f59 100644 --- a/plugins/source-github/vendor/knative.dev/client/pkg/serving/v1/client.go +++ b/plugins/source-github/vendor/knative.dev/client/pkg/serving/v1/client.go @@ -237,6 +237,9 @@ func updateServiceWithRetry(cl KnServingClient, name string, updateFunc serviceU if err != nil { return err } + if service.GetDeletionTimestamp() != nil { + return fmt.Errorf("can't update service %s because it has been marked for deletion", name) + } updatedService, err := updateFunc(service.DeepCopy()) if err != nil { return err diff --git a/plugins/source-github/vendor/knative.dev/client/pkg/sources/v1alpha2/apiserver_client.go b/plugins/source-github/vendor/knative.dev/client/pkg/sources/v1alpha2/apiserver_client.go new file mode 100644 index 00000000..8fafb343 --- /dev/null +++ b/plugins/source-github/vendor/knative.dev/client/pkg/sources/v1alpha2/apiserver_client.go @@ -0,0 +1,189 @@ +// Copyright © 2019 The Knative 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 v1alpha2 + +import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + v1alpha2 "knative.dev/eventing/pkg/apis/sources/v1alpha2" + clientv1alpha2 "knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1alpha2" + duckv1 "knative.dev/pkg/apis/duck/v1" + + "knative.dev/eventing/pkg/client/clientset/versioned/scheme" + + knerrors "knative.dev/client/pkg/errors" + "knative.dev/client/pkg/util" +) + +// KnAPIServerSourcesClient interface for working with ApiServer sources +type KnAPIServerSourcesClient interface { + + // Get an ApiServerSource by name + GetAPIServerSource(name string) (*v1alpha2.ApiServerSource, error) + + // Create an ApiServerSource by object + CreateAPIServerSource(apiSource *v1alpha2.ApiServerSource) error + + // Update an ApiServerSource by object + UpdateAPIServerSource(apiSource *v1alpha2.ApiServerSource) error + + // Delete an ApiServerSource by name + DeleteAPIServerSource(name string) error + + // List ApiServerSource + // TODO: Support list configs like in service list + ListAPIServerSource() (*v1alpha2.ApiServerSourceList, error) + + // Get namespace for this client + Namespace() string +} + +// knSourcesClient is a combination of Sources client interface and namespace +// Temporarily help to add sources dependencies +// May be changed when adding real sources features +type apiServerSourcesClient struct { + client clientv1alpha2.ApiServerSourceInterface + namespace string +} + +// newKnAPIServerSourcesClient is to invoke Eventing Sources Client API to create object +func newKnAPIServerSourcesClient(client clientv1alpha2.ApiServerSourceInterface, namespace string) KnAPIServerSourcesClient { + return &apiServerSourcesClient{ + client: client, + namespace: namespace, + } +} + +//GetAPIServerSource returns apiSource object if present +func (c *apiServerSourcesClient) GetAPIServerSource(name string) (*v1alpha2.ApiServerSource, error) { + apiSource, err := c.client.Get(name, metav1.GetOptions{}) + if err != nil { + return nil, knerrors.GetError(err) + } + + return apiSource, nil +} + +//CreateAPIServerSource is used to create an instance of ApiServerSource +func (c *apiServerSourcesClient) CreateAPIServerSource(apiSource *v1alpha2.ApiServerSource) error { + _, err := c.client.Create(apiSource) + if err != nil { + return knerrors.GetError(err) + } + + return nil +} + +//UpdateAPIServerSource is used to update an instance of ApiServerSource +func (c *apiServerSourcesClient) UpdateAPIServerSource(apiSource *v1alpha2.ApiServerSource) error { + _, err := c.client.Update(apiSource) + if err != nil { + return knerrors.GetError(err) + } + + return nil +} + +//DeleteAPIServerSource is used to create an instance of ApiServerSource +func (c *apiServerSourcesClient) DeleteAPIServerSource(name string) error { + err := c.client.Delete(name, &metav1.DeleteOptions{}) + return err +} + +// Return the client's namespace +func (c *apiServerSourcesClient) Namespace() string { + return c.namespace +} + +// ListAPIServerSource returns the available ApiServer type sources +func (c *apiServerSourcesClient) ListAPIServerSource() (*v1alpha2.ApiServerSourceList, error) { + sourceList, err := c.client.List(metav1.ListOptions{}) + if err != nil { + return nil, err + } + + return updateAPIServerSourceListGVK(sourceList) +} + +func updateAPIServerSourceListGVK(sourceList *v1alpha2.ApiServerSourceList) (*v1alpha2.ApiServerSourceList, error) { + sourceListNew := sourceList.DeepCopy() + err := updateSourceGVK(sourceListNew) + if err != nil { + return nil, err + } + + sourceListNew.Items = make([]v1alpha2.ApiServerSource, len(sourceList.Items)) + for idx, source := range sourceList.Items { + sourceClone := source.DeepCopy() + err := updateSourceGVK(sourceClone) + if err != nil { + return nil, err + } + sourceListNew.Items[idx] = *sourceClone + } + return sourceListNew, nil +} + +func updateSourceGVK(obj runtime.Object) error { + return util.UpdateGroupVersionKindWithScheme(obj, v1alpha2.SchemeGroupVersion, scheme.Scheme) +} + +// APIServerSourceBuilder is for building the source +type APIServerSourceBuilder struct { + apiServerSource *v1alpha2.ApiServerSource +} + +// NewAPIServerSourceBuilder for building ApiServer source object +func NewAPIServerSourceBuilder(name string) *APIServerSourceBuilder { + return &APIServerSourceBuilder{apiServerSource: &v1alpha2.ApiServerSource{ + ObjectMeta: metav1.ObjectMeta{ + Name: name, + }, + }} +} + +// NewAPIServerSourceBuilderFromExisting for building the object from existing ApiServerSource object +func NewAPIServerSourceBuilderFromExisting(apiServerSource *v1alpha2.ApiServerSource) *APIServerSourceBuilder { + return &APIServerSourceBuilder{apiServerSource: apiServerSource.DeepCopy()} +} + +// Resources which should be streamed +func (b *APIServerSourceBuilder) Resources(resources []v1alpha2.APIVersionKindSelector) *APIServerSourceBuilder { + b.apiServerSource.Spec.Resources = resources + return b +} + +// ServiceAccount with which this source should operate +func (b *APIServerSourceBuilder) ServiceAccount(sa string) *APIServerSourceBuilder { + b.apiServerSource.Spec.ServiceAccountName = sa + return b +} + +// EventMode for whether to send resource 'Ref' or complete 'Resource' +func (b *APIServerSourceBuilder) EventMode(eventMode string) *APIServerSourceBuilder { + b.apiServerSource.Spec.EventMode = eventMode + return b +} + +// Sink or destination of the source +func (b *APIServerSourceBuilder) Sink(sink duckv1.Destination) *APIServerSourceBuilder { + b.apiServerSource.Spec.Sink = sink + return b +} + +// Build the ApiServerSource object +func (b *APIServerSourceBuilder) Build() *v1alpha2.ApiServerSource { + return b.apiServerSource +} diff --git a/plugins/source-github/vendor/knative.dev/client/pkg/sources/v1alpha2/apiserver_client_mock.go b/plugins/source-github/vendor/knative.dev/client/pkg/sources/v1alpha2/apiserver_client_mock.go new file mode 100644 index 00000000..9066182a --- /dev/null +++ b/plugins/source-github/vendor/knative.dev/client/pkg/sources/v1alpha2/apiserver_client_mock.go @@ -0,0 +1,120 @@ +// Copyright © 2019 The Knative 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 v1alpha2 + +import ( + "testing" + + v1alpha2 "knative.dev/eventing/pkg/apis/sources/v1alpha2" + + "knative.dev/client/pkg/util/mock" +) + +// MockKnAPIServerSourceClient for mocking the client +type MockKnAPIServerSourceClient struct { + t *testing.T + recorder *APIServerSourcesRecorder + namespace string +} + +// NewMockKnAPIServerSourceClient returns a new mock instance which you need to record for +func NewMockKnAPIServerSourceClient(t *testing.T, ns ...string) *MockKnAPIServerSourceClient { + namespace := "default" + if len(ns) > 0 { + namespace = ns[0] + } + return &MockKnAPIServerSourceClient{ + t: t, + recorder: &APIServerSourcesRecorder{mock.NewRecorder(t, namespace)}, + } +} + +// Ensure that the interface is implemented +var _ KnAPIServerSourcesClient = &MockKnAPIServerSourceClient{} + +// APIServerSourcesRecorder for recording actions on source +type APIServerSourcesRecorder struct { + r *mock.Recorder +} + +// Recorder returns the recorder for registering API calls +func (c *MockKnAPIServerSourceClient) Recorder() *APIServerSourcesRecorder { + return c.recorder +} + +// Namespace of this client +func (c *MockKnAPIServerSourceClient) Namespace() string { + return c.recorder.r.Namespace() +} + +// GetAPIServerSource records a call for GetApiServerSource with the expected object or error. Either apiServerSource or err should be nil +func (sr *APIServerSourcesRecorder) GetAPIServerSource(name interface{}, apiServerSource *v1alpha2.ApiServerSource, err error) { + sr.r.Add("GetApiServerSource", []interface{}{name}, []interface{}{apiServerSource, err}) +} + +// GetAPIServerSource performs a previously recorded action, failing if non has been registered +func (c *MockKnAPIServerSourceClient) GetAPIServerSource(name string) (*v1alpha2.ApiServerSource, error) { + call := c.recorder.r.VerifyCall("GetApiServerSource", name) + return call.Result[0].(*v1alpha2.ApiServerSource), mock.ErrorOrNil(call.Result[1]) +} + +// CreateAPIServerSource records a call for CreateApiServerSource with the expected error +func (sr *APIServerSourcesRecorder) CreateAPIServerSource(apiServerSource interface{}, err error) { + sr.r.Add("CreateApiServerSource", []interface{}{apiServerSource}, []interface{}{err}) +} + +// CreateAPIServerSource performs a previously recorded action, failing if non has been registered +func (c *MockKnAPIServerSourceClient) CreateAPIServerSource(apiServerSource *v1alpha2.ApiServerSource) error { + call := c.recorder.r.VerifyCall("CreateApiServerSource", apiServerSource) + return mock.ErrorOrNil(call.Result[0]) +} + +// UpdateAPIServerSource records a call for UpdateAPIServerSource with the expected error (nil if none) +func (sr *APIServerSourcesRecorder) UpdateAPIServerSource(apiServerSource interface{}, err error) { + sr.r.Add("UpdateAPIServerSource", []interface{}{apiServerSource}, []interface{}{err}) +} + +// UpdateAPIServerSource performs a previously recorded action, failing if non has been registered +func (c *MockKnAPIServerSourceClient) UpdateAPIServerSource(apiServerSource *v1alpha2.ApiServerSource) error { + call := c.recorder.r.VerifyCall("UpdateAPIServerSource", apiServerSource) + return mock.ErrorOrNil(call.Result[0]) +} + +// DeleteAPIServerSource records a call for DeleteAPIServerSource with the expected error (nil if none) +func (sr *APIServerSourcesRecorder) DeleteAPIServerSource(name interface{}, err error) { + sr.r.Add("DeleteAPIServerSource", []interface{}{name}, []interface{}{err}) +} + +// DeleteAPIServerSource performs a previously recorded action, failing if non has been registered +func (c *MockKnAPIServerSourceClient) DeleteAPIServerSource(name string) error { + call := c.recorder.r.VerifyCall("DeleteAPIServerSource", name) + return mock.ErrorOrNil(call.Result[0]) +} + +// ListAPIServerSource records a call for ListAPIServerSource with the expected error (nil if none) +func (sr *APIServerSourcesRecorder) ListAPIServerSource(apiJobSourceList *v1alpha2.ApiServerSourceList, err error) { + sr.r.Add("ListAPIServerSource", []interface{}{}, []interface{}{apiJobSourceList, err}) +} + +// ListAPIServerSource performs a previously recorded action, failing if non has been registered +func (c *MockKnAPIServerSourceClient) ListAPIServerSource() (*v1alpha2.ApiServerSourceList, error) { + call := c.recorder.r.VerifyCall("ListAPIServerSource") + return call.Result[0].(*v1alpha2.ApiServerSourceList), mock.ErrorOrNil(call.Result[1]) +} + +// Validate validates whether every recorded action has been called +func (sr *APIServerSourcesRecorder) Validate() { + sr.r.CheckThatAllRecordedMethodsHaveBeenCalled() +} diff --git a/plugins/source-github/vendor/knative.dev/client/pkg/sources/v1alpha2/client.go b/plugins/source-github/vendor/knative.dev/client/pkg/sources/v1alpha2/client.go index 5c946900..c97129a3 100644 --- a/plugins/source-github/vendor/knative.dev/client/pkg/sources/v1alpha2/client.go +++ b/plugins/source-github/vendor/knative.dev/client/pkg/sources/v1alpha2/client.go @@ -26,6 +26,9 @@ type KnSourcesClient interface { // Get client for sink binding sources SinkBindingClient() KnSinkBindingClient + + // Get client for ApiServer sources + APIServerSourcesClient() KnAPIServerSourcesClient } // sourcesClient is a combination of Sources client interface and namespace @@ -53,3 +56,8 @@ func (c *sourcesClient) PingSourcesClient() KnPingSourcesClient { func (c *sourcesClient) SinkBindingClient() KnSinkBindingClient { return newKnSinkBindingClient(c.client.SinkBindings(c.namespace), c.namespace) } + +// ApiServerSourcesClient for dealing with ApiServer sources +func (c *sourcesClient) APIServerSourcesClient() KnAPIServerSourcesClient { + return newKnAPIServerSourcesClient(c.client.ApiServerSources(c.namespace), c.namespace) +} diff --git a/plugins/source-github/vendor/knative.dev/client/pkg/sources/v1alpha2/ping_client.go b/plugins/source-github/vendor/knative.dev/client/pkg/sources/v1alpha2/ping_client.go index fc83ecfe..b8d307af 100644 --- a/plugins/source-github/vendor/knative.dev/client/pkg/sources/v1alpha2/ping_client.go +++ b/plugins/source-github/vendor/knative.dev/client/pkg/sources/v1alpha2/ping_client.go @@ -18,14 +18,10 @@ import ( "fmt" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" "knative.dev/eventing/pkg/apis/sources/v1alpha2" - "knative.dev/eventing/pkg/client/clientset/versioned/scheme" clientv1alpha2 "knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1alpha2" duckv1 "knative.dev/pkg/apis/duck/v1" - - "knative.dev/client/pkg/util" ) // Interface for interacting with a Ping source @@ -122,10 +118,6 @@ func updatePingSourceListGVK(sourceList *v1alpha2.PingSourceList) (*v1alpha2.Pin return sourceListNew, nil } -func updateSourceGVK(obj runtime.Object) error { - return util.UpdateGroupVersionKindWithScheme(obj, v1alpha2.SchemeGroupVersion, scheme.Scheme) -} - // Builder for building up Ping sources type PingSourceBuilder struct { diff --git a/plugins/source-github/vendor/knative.dev/client/pkg/util/unstructured.go b/plugins/source-github/vendor/knative.dev/client/pkg/util/unstructured.go new file mode 100644 index 00000000..717f347f --- /dev/null +++ b/plugins/source-github/vendor/knative.dev/client/pkg/util/unstructured.go @@ -0,0 +1,64 @@ +// Copyright © 2020 The Knative 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 util + +import ( + "encoding/json" + + "k8s.io/apimachinery/pkg/api/meta" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" +) + +// ToUnstructuredList is to converts an object to unstructured.UnstructuredList. +// If the object is not a list type, it will convert to a single item UnstructuredList. +func ToUnstructuredList(obj runtime.Object) (*unstructured.UnstructuredList, error) { + unstructuredList := &unstructured.UnstructuredList{} + if meta.IsListType(obj) { + unstructuredList.SetGroupVersionKind(obj.GetObjectKind().GroupVersionKind()) + items, err := meta.ExtractList(obj) + if err != nil { + return nil, err + } + for _, obji := range items { + ud, err := toUnstructured(obji) + if err != nil { + return nil, err + } + unstructuredList.Items = append(unstructuredList.Items, *ud) + } + + } else { + ud, err := toUnstructured(obj) + if err != nil { + return nil, err + } + unstructuredList.Items = append(unstructuredList.Items, *ud) + } + return unstructuredList, nil + +} + +func toUnstructured(obj runtime.Object) (*unstructured.Unstructured, error) { + b, err := json.Marshal(obj) + if err != nil { + return nil, err + } + ud := &unstructured.Unstructured{} + if err := json.Unmarshal(b, ud); err != nil { + return nil, err + } + return ud, nil +} diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/cron_job_defaults.go b/plugins/source-github/vendor/knative.dev/eventing-contrib/github/pkg/client/clientset/versioned/scheme/doc.go similarity index 68% rename from plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/cron_job_defaults.go rename to plugins/source-github/vendor/knative.dev/eventing-contrib/github/pkg/client/clientset/versioned/scheme/doc.go index 25a58dbf..7acc2dcf 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/cron_job_defaults.go +++ b/plugins/source-github/vendor/knative.dev/eventing-contrib/github/pkg/client/clientset/versioned/scheme/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2019 The Knative Authors +Copyright 2020 The Knative Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,16 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1alpha1 +// Code generated by client-gen. DO NOT EDIT. -import ( - "context" -) - -func (s *CronJobSource) SetDefaults(ctx context.Context) { - s.Spec.SetDefaults(ctx) -} - -func (ss *CronJobSourceSpec) SetDefaults(ctx context.Context) { - // TODO anything? -} +// This package contains the scheme of the automatically generated clientset. +package scheme diff --git a/plugins/source-github/vendor/knative.dev/eventing-contrib/github/pkg/client/clientset/versioned/scheme/register.go b/plugins/source-github/vendor/knative.dev/eventing-contrib/github/pkg/client/clientset/versioned/scheme/register.go new file mode 100644 index 00000000..61c9afd5 --- /dev/null +++ b/plugins/source-github/vendor/knative.dev/eventing-contrib/github/pkg/client/clientset/versioned/scheme/register.go @@ -0,0 +1,56 @@ +/* +Copyright 2020 The Knative 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. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package scheme + +import ( + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + runtime "k8s.io/apimachinery/pkg/runtime" + schema "k8s.io/apimachinery/pkg/runtime/schema" + serializer "k8s.io/apimachinery/pkg/runtime/serializer" + utilruntime "k8s.io/apimachinery/pkg/util/runtime" + sourcesv1alpha1 "knative.dev/eventing-contrib/github/pkg/apis/sources/v1alpha1" +) + +var Scheme = runtime.NewScheme() +var Codecs = serializer.NewCodecFactory(Scheme) +var ParameterCodec = runtime.NewParameterCodec(Scheme) +var localSchemeBuilder = runtime.SchemeBuilder{ + sourcesv1alpha1.AddToScheme, +} + +// AddToScheme adds all types of this clientset into the given scheme. This allows composition +// of clientsets, like in: +// +// import ( +// "k8s.io/client-go/kubernetes" +// clientsetscheme "k8s.io/client-go/kubernetes/scheme" +// aggregatorclientsetscheme "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset/scheme" +// ) +// +// kclientset, _ := kubernetes.NewForConfig(c) +// _ = aggregatorclientsetscheme.AddToScheme(clientsetscheme.Scheme) +// +// After this, RawExtensions in Kubernetes types will serialize kube-aggregator types +// correctly. +var AddToScheme = localSchemeBuilder.AddToScheme + +func init() { + v1.AddToGroupVersion(Scheme, schema.GroupVersion{Version: "v1"}) + utilruntime.Must(AddToScheme(Scheme)) +} diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/doc.go b/plugins/source-github/vendor/knative.dev/eventing-contrib/github/pkg/client/clientset/versioned/typed/sources/v1alpha1/doc.go similarity index 73% rename from plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/doc.go rename to plugins/source-github/vendor/knative.dev/eventing-contrib/github/pkg/client/clientset/versioned/typed/sources/v1alpha1/doc.go index 7d7f6738..41e872fe 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/doc.go +++ b/plugins/source-github/vendor/knative.dev/eventing-contrib/github/pkg/client/clientset/versioned/typed/sources/v1alpha1/doc.go @@ -1,5 +1,5 @@ /* -Copyright 2019 The Knative Authors +Copyright 2020 The Knative Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -// Package v1alpha1 contains API Schema definitions for the sources v1alpha1 API group -// +k8s:deepcopy-gen=package -// +groupName=sources.eventing.knative.dev +// Code generated by client-gen. DO NOT EDIT. + +// This package has the automatically generated typed clients. package v1alpha1 diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/register.go b/plugins/source-github/vendor/knative.dev/eventing-contrib/github/pkg/client/clientset/versioned/typed/sources/v1alpha1/generated_expansion.go similarity index 79% rename from plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/register.go rename to plugins/source-github/vendor/knative.dev/eventing-contrib/github/pkg/client/clientset/versioned/typed/sources/v1alpha1/generated_expansion.go index 94839954..9c4c2f9d 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/register.go +++ b/plugins/source-github/vendor/knative.dev/eventing-contrib/github/pkg/client/clientset/versioned/typed/sources/v1alpha1/generated_expansion.go @@ -1,5 +1,5 @@ /* -Copyright 2019 The Knative Authors +Copyright 2020 The Knative Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,8 +14,8 @@ See the License for the specific language governing permissions and limitations under the License. */ -package legacysources +// Code generated by client-gen. DO NOT EDIT. -const ( - GroupName = "sources.eventing.knative.dev" -) +package v1alpha1 + +type GitHubSourceExpansion interface{} diff --git a/plugins/source-github/vendor/knative.dev/eventing-contrib/github/pkg/client/clientset/versioned/typed/sources/v1alpha1/githubsource.go b/plugins/source-github/vendor/knative.dev/eventing-contrib/github/pkg/client/clientset/versioned/typed/sources/v1alpha1/githubsource.go new file mode 100644 index 00000000..ef0bc233 --- /dev/null +++ b/plugins/source-github/vendor/knative.dev/eventing-contrib/github/pkg/client/clientset/versioned/typed/sources/v1alpha1/githubsource.go @@ -0,0 +1,191 @@ +/* +Copyright 2020 The Knative 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. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + "time" + + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + rest "k8s.io/client-go/rest" + v1alpha1 "knative.dev/eventing-contrib/github/pkg/apis/sources/v1alpha1" + scheme "knative.dev/eventing-contrib/github/pkg/client/clientset/versioned/scheme" +) + +// GitHubSourcesGetter has a method to return a GitHubSourceInterface. +// A group's client should implement this interface. +type GitHubSourcesGetter interface { + GitHubSources(namespace string) GitHubSourceInterface +} + +// GitHubSourceInterface has methods to work with GitHubSource resources. +type GitHubSourceInterface interface { + Create(*v1alpha1.GitHubSource) (*v1alpha1.GitHubSource, error) + Update(*v1alpha1.GitHubSource) (*v1alpha1.GitHubSource, error) + UpdateStatus(*v1alpha1.GitHubSource) (*v1alpha1.GitHubSource, error) + Delete(name string, options *v1.DeleteOptions) error + DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error + Get(name string, options v1.GetOptions) (*v1alpha1.GitHubSource, error) + List(opts v1.ListOptions) (*v1alpha1.GitHubSourceList, error) + Watch(opts v1.ListOptions) (watch.Interface, error) + Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.GitHubSource, err error) + GitHubSourceExpansion +} + +// gitHubSources implements GitHubSourceInterface +type gitHubSources struct { + client rest.Interface + ns string +} + +// newGitHubSources returns a GitHubSources +func newGitHubSources(c *SourcesV1alpha1Client, namespace string) *gitHubSources { + return &gitHubSources{ + client: c.RESTClient(), + ns: namespace, + } +} + +// Get takes name of the gitHubSource, and returns the corresponding gitHubSource object, and an error if there is any. +func (c *gitHubSources) Get(name string, options v1.GetOptions) (result *v1alpha1.GitHubSource, err error) { + result = &v1alpha1.GitHubSource{} + err = c.client.Get(). + Namespace(c.ns). + Resource("githubsources"). + Name(name). + VersionedParams(&options, scheme.ParameterCodec). + Do(). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of GitHubSources that match those selectors. +func (c *gitHubSources) List(opts v1.ListOptions) (result *v1alpha1.GitHubSourceList, err error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + result = &v1alpha1.GitHubSourceList{} + err = c.client.Get(). + Namespace(c.ns). + Resource("githubsources"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Do(). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested gitHubSources. +func (c *gitHubSources) Watch(opts v1.ListOptions) (watch.Interface, error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + opts.Watch = true + return c.client.Get(). + Namespace(c.ns). + Resource("githubsources"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Watch() +} + +// Create takes the representation of a gitHubSource and creates it. Returns the server's representation of the gitHubSource, and an error, if there is any. +func (c *gitHubSources) Create(gitHubSource *v1alpha1.GitHubSource) (result *v1alpha1.GitHubSource, err error) { + result = &v1alpha1.GitHubSource{} + err = c.client.Post(). + Namespace(c.ns). + Resource("githubsources"). + Body(gitHubSource). + Do(). + Into(result) + return +} + +// Update takes the representation of a gitHubSource and updates it. Returns the server's representation of the gitHubSource, and an error, if there is any. +func (c *gitHubSources) Update(gitHubSource *v1alpha1.GitHubSource) (result *v1alpha1.GitHubSource, err error) { + result = &v1alpha1.GitHubSource{} + err = c.client.Put(). + Namespace(c.ns). + Resource("githubsources"). + Name(gitHubSource.Name). + Body(gitHubSource). + Do(). + Into(result) + return +} + +// UpdateStatus was generated because the type contains a Status member. +// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). + +func (c *gitHubSources) UpdateStatus(gitHubSource *v1alpha1.GitHubSource) (result *v1alpha1.GitHubSource, err error) { + result = &v1alpha1.GitHubSource{} + err = c.client.Put(). + Namespace(c.ns). + Resource("githubsources"). + Name(gitHubSource.Name). + SubResource("status"). + Body(gitHubSource). + Do(). + Into(result) + return +} + +// Delete takes name of the gitHubSource and deletes it. Returns an error if one occurs. +func (c *gitHubSources) Delete(name string, options *v1.DeleteOptions) error { + return c.client.Delete(). + Namespace(c.ns). + Resource("githubsources"). + Name(name). + Body(options). + Do(). + Error() +} + +// DeleteCollection deletes a collection of objects. +func (c *gitHubSources) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { + var timeout time.Duration + if listOptions.TimeoutSeconds != nil { + timeout = time.Duration(*listOptions.TimeoutSeconds) * time.Second + } + return c.client.Delete(). + Namespace(c.ns). + Resource("githubsources"). + VersionedParams(&listOptions, scheme.ParameterCodec). + Timeout(timeout). + Body(options). + Do(). + Error() +} + +// Patch applies the patch and returns the patched gitHubSource. +func (c *gitHubSources) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.GitHubSource, err error) { + result = &v1alpha1.GitHubSource{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("githubsources"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/plugins/source-github/vendor/knative.dev/eventing-contrib/github/pkg/client/clientset/versioned/typed/sources/v1alpha1/sources_client.go b/plugins/source-github/vendor/knative.dev/eventing-contrib/github/pkg/client/clientset/versioned/typed/sources/v1alpha1/sources_client.go new file mode 100644 index 00000000..0c553b92 --- /dev/null +++ b/plugins/source-github/vendor/knative.dev/eventing-contrib/github/pkg/client/clientset/versioned/typed/sources/v1alpha1/sources_client.go @@ -0,0 +1,89 @@ +/* +Copyright 2020 The Knative 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. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1alpha1 + +import ( + rest "k8s.io/client-go/rest" + v1alpha1 "knative.dev/eventing-contrib/github/pkg/apis/sources/v1alpha1" + "knative.dev/eventing-contrib/github/pkg/client/clientset/versioned/scheme" +) + +type SourcesV1alpha1Interface interface { + RESTClient() rest.Interface + GitHubSourcesGetter +} + +// SourcesV1alpha1Client is used to interact with features provided by the sources.knative.dev group. +type SourcesV1alpha1Client struct { + restClient rest.Interface +} + +func (c *SourcesV1alpha1Client) GitHubSources(namespace string) GitHubSourceInterface { + return newGitHubSources(c, namespace) +} + +// NewForConfig creates a new SourcesV1alpha1Client for the given config. +func NewForConfig(c *rest.Config) (*SourcesV1alpha1Client, error) { + config := *c + if err := setConfigDefaults(&config); err != nil { + return nil, err + } + client, err := rest.RESTClientFor(&config) + if err != nil { + return nil, err + } + return &SourcesV1alpha1Client{client}, nil +} + +// NewForConfigOrDie creates a new SourcesV1alpha1Client for the given config and +// panics if there is an error in the config. +func NewForConfigOrDie(c *rest.Config) *SourcesV1alpha1Client { + client, err := NewForConfig(c) + if err != nil { + panic(err) + } + return client +} + +// New creates a new SourcesV1alpha1Client for the given RESTClient. +func New(c rest.Interface) *SourcesV1alpha1Client { + return &SourcesV1alpha1Client{c} +} + +func setConfigDefaults(config *rest.Config) error { + gv := v1alpha1.SchemeGroupVersion + config.GroupVersion = &gv + config.APIPath = "/apis" + config.NegotiatedSerializer = scheme.Codecs.WithoutConversion() + + if config.UserAgent == "" { + config.UserAgent = rest.DefaultKubernetesUserAgent() + } + + return nil +} + +// RESTClient returns a RESTClient that is used to communicate +// with API server by this client implementation. +func (c *SourcesV1alpha1Client) RESTClient() rest.Interface { + if c == nil { + return nil + } + return c.restClient +} diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/config/defaults.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/config/defaults.go index d067ad44..c78b42a7 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/config/defaults.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/config/defaults.go @@ -70,11 +70,19 @@ func NewDefaultsConfigFromConfigMap(config *corev1.ConfigMap) (*Defaults, error) type Defaults struct { // NamespaceDefaultsConfig are the default Broker Configs for each namespace. // Namespace is the key, the value is the KReference to the config. - NamespaceDefaultsConfig map[string]*duckv1.KReference `json:"namespaceDefaults,omitempty"` + NamespaceDefaultsConfig map[string]*ClassAndKRef `json:"namespaceDefaults,omitempty"` // ClusterDefaultBrokerConfig is the default broker config for all the namespaces that // are not in NamespaceDefaultBrokerConfigs. - ClusterDefault *duckv1.KReference `json:"clusterDefault,omitempty"` + ClusterDefault *ClassAndKRef `json:"clusterDefault,omitempty"` +} + +// ClassAndKRef contains configuration for a given namespace for broker. Allows +// configuring both the Class of the Broker as well as the reference to the +// config it should use +type ClassAndKRef struct { + BrokerClass string `json:"brokerClass,omitempty"` + *duckv1.KReference `json:",inline"` } // GetBrokerConfig returns a namespace specific Broker Configuration, and if @@ -85,11 +93,28 @@ func (d *Defaults) GetBrokerConfig(ns string) (*duckv1.KReference, error) { return nil, errors.New("Defaults are nil") } value, present := d.NamespaceDefaultsConfig[ns] - if present { - return value, nil + if present && value.KReference != nil { + return value.KReference, nil } - if d.ClusterDefault != nil { - return d.ClusterDefault, nil + if d.ClusterDefault != nil && d.ClusterDefault.KReference != nil { + return d.ClusterDefault.KReference, nil } return nil, errors.New("Defaults for Broker Configurations have not been set up.") } + +// GetBrokerClass returns a namespace specific Broker Class, and if +// that doesn't exist, return a Cluster Default and if that doesn't exist +// return an error. +func (d *Defaults) GetBrokerClass(ns string) (string, error) { + if d == nil { + return "", errors.New("Defaults are nil") + } + value, present := d.NamespaceDefaultsConfig[ns] + if present && value.BrokerClass != "" { + return value.BrokerClass, nil + } + if d.ClusterDefault != nil && d.ClusterDefault.BrokerClass != "" { + return d.ClusterDefault.BrokerClass, nil + } + return "", errors.New("Defaults for Broker Configurations have not been set up.") +} diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/config/zz_generated.deepcopy.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/config/zz_generated.deepcopy.go index 59abf307..bb1f1cb1 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/config/zz_generated.deepcopy.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/config/zz_generated.deepcopy.go @@ -24,28 +24,49 @@ import ( v1 "knative.dev/pkg/apis/duck/v1" ) +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ClassAndKRef) DeepCopyInto(out *ClassAndKRef) { + *out = *in + if in.KReference != nil { + in, out := &in.KReference, &out.KReference + *out = new(v1.KReference) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClassAndKRef. +func (in *ClassAndKRef) DeepCopy() *ClassAndKRef { + if in == nil { + return nil + } + out := new(ClassAndKRef) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Defaults) DeepCopyInto(out *Defaults) { *out = *in if in.NamespaceDefaultsConfig != nil { in, out := &in.NamespaceDefaultsConfig, &out.NamespaceDefaultsConfig - *out = make(map[string]*v1.KReference, len(*in)) + *out = make(map[string]*ClassAndKRef, len(*in)) for key, val := range *in { - var outVal *v1.KReference + var outVal *ClassAndKRef if val == nil { (*out)[key] = nil } else { in, out := &val, &outVal - *out = new(v1.KReference) - **out = **in + *out = new(ClassAndKRef) + (*in).DeepCopyInto(*out) } (*out)[key] = outVal } } if in.ClusterDefault != nil { in, out := &in.ClusterDefault, &out.ClusterDefault - *out = new(v1.KReference) - **out = **in + *out = new(ClassAndKRef) + (*in).DeepCopyInto(*out) } return } diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/configs/v1alpha1/configmappropagation_types.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/configs/v1alpha1/configmappropagation_types.go index 7df9db31..ae6f7d50 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/configs/v1alpha1/configmappropagation_types.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/configs/v1alpha1/configmappropagation_types.go @@ -27,6 +27,7 @@ import ( ) // +genclient +// +genreconciler // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // ConfigMapPropagation is used to propagate configMaps from original namespace to current namespace diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/duck/lifecycle_helper.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/duck/lifecycle_helper.go index c1b06b2d..98888bbb 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/duck/lifecycle_helper.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/duck/lifecycle_helper.go @@ -18,6 +18,7 @@ package duck import ( appsv1 "k8s.io/api/apps/v1" + corev1 "k8s.io/api/core/v1" ) // DeploymentIsAvailable determines if the provided deployment is available. Note that if it cannot @@ -31,3 +32,13 @@ func DeploymentIsAvailable(d *appsv1.DeploymentStatus, def bool) bool { } return def } + +// EndpointsAreAvailable determines if the provided Endpoints are available. +func EndpointsAreAvailable(ep *corev1.Endpoints) bool { + for _, subset := range ep.Subsets { + if len(subset.Addresses) > 0 { + return true + } + } + return false +} diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/duck/v1alpha1/subscribable_types.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/duck/v1alpha1/subscribable_types.go index 742fa32f..c1817a08 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/duck/v1alpha1/subscribable_types.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/duck/v1alpha1/subscribable_types.go @@ -120,6 +120,8 @@ var ( // Verify SubscribableType resources meet duck contracts. _ duck.Populatable = (*SubscribableType)(nil) _ apis.Listable = (*SubscribableType)(nil) + + _ apis.Convertible = (*SubscribableType)(nil) ) // GetSubscribableTypeStatus method Returns the Default SubscribableStatus in this case it's SubscribableStatus diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/duck/v1alpha1/subscribable_types_conversion.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/duck/v1alpha1/subscribable_types_conversion.go new file mode 100644 index 00000000..5d95f69f --- /dev/null +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/duck/v1alpha1/subscribable_types_conversion.go @@ -0,0 +1,144 @@ +/* +Copyright 2020 The Knative 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 v1alpha1 + +import ( + "context" + "fmt" + + "knative.dev/pkg/apis" + duckv1 "knative.dev/pkg/apis/duck/v1" + + duckv1beta1 "knative.dev/eventing/pkg/apis/duck/v1beta1" +) + +// ConvertTo implements apis.Convertible +// Converts source (from v1alpha1.SubscribableType) into v1beta1.Subscribable +func (source *SubscribableType) ConvertTo(ctx context.Context, obj apis.Convertible) error { + switch sink := obj.(type) { + case *duckv1beta1.Subscribable: + sink.ObjectMeta = source.ObjectMeta + source.Status.ConvertTo(ctx, &sink.Status) + return source.Spec.ConvertTo(ctx, &sink.Spec) + default: + return fmt.Errorf("unknown version, got: %T", sink) + } +} + +// ConvertTo helps implement apis.Convertible +func (source *SubscribableTypeSpec) ConvertTo(ctx context.Context, sink *duckv1beta1.SubscribableSpec) error { + if source.Subscribable != nil { + sink.Subscribers = make([]duckv1beta1.SubscriberSpec, len(source.Subscribable.Subscribers)) + for i, s := range source.Subscribable.Subscribers { + s.ConvertTo(ctx, &sink.Subscribers[i]) + } + } + return nil +} + +func (source *SubscriberSpec) ConvertTo(ctx context.Context, sink *duckv1beta1.SubscriberSpec) { + sink.UID = source.UID + sink.Generation = source.Generation + sink.SubscriberURI = source.SubscriberURI + sink.ReplyURI = source.ReplyURI + + if source.Delivery != nil { + sink.Delivery = source.Delivery + } else { + // If however, there's a Deprecated DeadLetterSinkURI, convert that up + // to DeliverySpec. + sink.Delivery = &duckv1beta1.DeliverySpec{ + DeadLetterSink: &duckv1.Destination{ + URI: source.DeadLetterSinkURI, + }, + } + } +} + +// ConvertTo helps implement apis.Convertible +func (source *SubscribableTypeStatus) ConvertTo(ctx context.Context, sink *duckv1beta1.SubscribableStatus) { + if source.SubscribableStatus != nil && + len(source.SubscribableStatus.Subscribers) > 0 { + sink.Subscribers = make([]duckv1beta1.SubscriberStatus, len(source.SubscribableStatus.Subscribers)) + for i, ss := range source.SubscribableStatus.Subscribers { + sink.Subscribers[i] = duckv1beta1.SubscriberStatus{ + UID: ss.UID, + ObservedGeneration: ss.ObservedGeneration, + Ready: ss.Ready, + Message: ss.Message, + } + } + } +} + +// ConvertFrom implements apis.Convertible. +// Converts obj v1beta1.Subscribable into v1alpha1.Subscribable +func (sink *SubscribableType) ConvertFrom(ctx context.Context, obj apis.Convertible) error { + switch source := obj.(type) { + case *duckv1beta1.Subscribable: + sink.ObjectMeta = source.ObjectMeta + sink.Status.ConvertFrom(ctx, source.Status) + sink.Spec.ConvertFrom(ctx, source.Spec) + return nil + default: + return fmt.Errorf("unknown version, got: %T", source) + } +} + +// ConvertFrom helps implement apis.Convertible +func (sink *SubscribableTypeSpec) ConvertFrom(ctx context.Context, source duckv1beta1.SubscribableSpec) { + if len(source.Subscribers) > 0 { + sink.Subscribable = &Subscribable{ + Subscribers: make([]SubscriberSpec, len(source.Subscribers)), + } + for i, s := range source.Subscribers { + sink.Subscribable.Subscribers[i].ConvertFrom(ctx, s) + } + } +} + +func (sink *SubscriberSpec) ConvertFrom(ctx context.Context, source duckv1beta1.SubscriberSpec) { + var deadLetterSinkURI *apis.URL + if source.Delivery != nil && source.Delivery.DeadLetterSink != nil { + deadLetterSinkURI = source.Delivery.DeadLetterSink.URI + } + sink.UID = source.UID + sink.Generation = source.Generation + sink.SubscriberURI = source.SubscriberURI + sink.ReplyURI = source.ReplyURI + sink.Delivery = source.Delivery + sink.DeadLetterSinkURI = deadLetterSinkURI + +} + +// ConvertFrom helps implement apis.Convertible +func (sink *SubscribableTypeStatus) ConvertFrom(ctx context.Context, source duckv1beta1.SubscribableStatus) error { + if len(source.Subscribers) > 0 { + sink.SubscribableStatus = &SubscribableStatus{ + Subscribers: make([]SubscriberStatus, len(source.Subscribers)), + } + for i, ss := range source.Subscribers { + sink.SubscribableStatus.Subscribers[i] = SubscriberStatus{ + UID: ss.UID, + ObservedGeneration: ss.ObservedGeneration, + Ready: ss.Ready, + Message: ss.Message, + } + } + } + return nil +} diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/duck/v1beta1/subscribable_types.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/duck/v1beta1/subscribable_types.go index 24290188..e99a6be2 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/duck/v1beta1/subscribable_types.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/duck/v1beta1/subscribable_types.go @@ -105,6 +105,8 @@ var ( // Verify SubscribableType resources meet duck contracts. _ duck.Populatable = (*Subscribable)(nil) _ apis.Listable = (*Subscribable)(nil) + + _ apis.Convertible = (*Subscribable)(nil) ) // GetFullType implements duck.Implementable diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/sinkbinding_defaults.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/duck/v1beta1/subscribable_types_conversion.go similarity index 54% rename from plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/sinkbinding_defaults.go rename to plugins/source-github/vendor/knative.dev/eventing/pkg/apis/duck/v1beta1/subscribable_types_conversion.go index fc006ec1..f25a6755 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/sinkbinding_defaults.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/duck/v1beta1/subscribable_types_conversion.go @@ -1,5 +1,5 @@ /* -Copyright 2019 The Knative Authors +Copyright 2020 The Knative Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,20 +14,21 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1alpha1 +package v1beta1 import ( "context" + "fmt" "knative.dev/pkg/apis" ) -// SetDefaults implements apis.Defaultable -func (fb *SinkBinding) SetDefaults(ctx context.Context) { - withNS := apis.WithinParent(ctx, fb.ObjectMeta) - fb.Spec.Sink.SetDefaults(withNS) - if fb.Spec.Subject.Namespace == "" { - // Default the subject's namespace to our namespace. - fb.Spec.Subject.Namespace = fb.Namespace - } +// ConvertTo implements apis.Convertible +func (source *Subscribable) ConvertTo(ctx context.Context, sink apis.Convertible) error { + return fmt.Errorf("v1beta1 is the highest known version, got: %T", sink) +} + +// ConvertFrom implements apis.Convertible +func (sink *Subscribable) ConvertFrom(ctx context.Context, source apis.Convertible) error { + return fmt.Errorf("v1beta1 is the highest known version, got: %T", source) } diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/defaults.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/defaults.go new file mode 100644 index 00000000..d2b52e8f --- /dev/null +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/defaults.go @@ -0,0 +1,40 @@ +/* +Copyright 2020 The Knative 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 eventing + +import ( + "context" + + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "knative.dev/eventing/pkg/apis/config" +) + +// DefaultBrokerClassIfUnset sets default broker class annotation if unset. +func DefaultBrokerClassIfUnset(ctx context.Context, obj *metav1.ObjectMeta) { + annotations := obj.GetAnnotations() + if annotations == nil { + annotations = make(map[string]string, 1) + } + if _, present := annotations[BrokerClassKey]; !present { + cfg := config.FromContextOrDefaults(ctx) + c, err := cfg.Defaults.GetBrokerClass(obj.Namespace) + if err == nil { + annotations[BrokerClassKey] = c + obj.SetAnnotations(annotations) + } + } +} diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/register.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/register.go index c789e7a0..802e5f02 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/register.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/register.go @@ -29,10 +29,37 @@ const ( // which Controller is responsible for them. BrokerClassKey = GroupName + "/broker.class" + // ChannelBrokerClassValue is the value we use to specify the + // Broker using channels. As in Broker from this repository + // pkg/reconciler/broker + ChannelBrokerClassValue = "ChannelBasedBroker" + + // MTChannelBrokerClassValue is the value we use to specify the + // Broker using channels, but the resources (ingress,filter) run + // in the system namespace. As in Broker from this repository + // pkg/reconciler/mtbroker + MTChannelBrokerClassValue = "MTChannelBasedBroker" + // ScopeAnnotationKey is the annotation key to indicate // the scope of the component handling a given resource. // Valid values are: cluster, namespace, resource. ScopeAnnotationKey = GroupName + "/scope" + + // ScopeResource indicates that the resource + // must be handled by a dedicated component + ScopeResource = "resource" + + // ScopeNamespace indicates that the resource + // must be handled by the namespace-scoped component + ScopeNamespace = "namespace" + + // ScopeCluster indicates the resource must be + // handled by the cluster-scoped component + ScopeCluster = "cluster" + + // EventTypesAnnotationKey is the annotation key to specify + // if a Source has event types defines in its CRD. + EventTypesAnnotationKey = "registry.knative.dev/eventTypes" ) var ( diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/broker_defaults.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/broker_defaults.go index c8ccbbd6..53a1d1a7 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/broker_defaults.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/broker_defaults.go @@ -19,7 +19,8 @@ package v1alpha1 import ( "context" - "knative.dev/eventing/pkg/apis/messaging/config" + "knative.dev/eventing/pkg/apis/eventing" + messagingconfig "knative.dev/eventing/pkg/apis/messaging/config" messagingv1beta1 "knative.dev/eventing/pkg/apis/messaging/v1beta1" "knative.dev/pkg/apis" ) @@ -27,6 +28,7 @@ import ( func (b *Broker) SetDefaults(ctx context.Context) { withNS := apis.WithinParent(ctx, b.ObjectMeta) b.Spec.SetDefaults(withNS) + eventing.DefaultBrokerClassIfUnset(withNS, &b.ObjectMeta) } func (bs *BrokerSpec) SetDefaults(ctx context.Context) { @@ -34,13 +36,13 @@ func (bs *BrokerSpec) SetDefaults(ctx context.Context) { // If we haven't configured the new channelTemplate, // then set the default channel to the new channelTemplate. if bs.ChannelTemplate == nil { - cfg := config.FromContextOrDefaults(ctx) - c, err := cfg.ChannelDefaults.GetChannelConfig(apis.ParentMeta(ctx).Namespace) + channelCfg := messagingconfig.FromContextOrDefaults(ctx) + c, err := channelCfg.ChannelDefaults.GetChannelConfig(apis.ParentMeta(ctx).Namespace) if err == nil { bs.ChannelTemplate = &messagingv1beta1.ChannelTemplateSpec{ - c.TypeMeta, - c.Spec, + TypeMeta: c.TypeMeta, + Spec: c.Spec, } } } diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/broker_lifecycle.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/broker_lifecycle.go index 54e4c23d..d99fabf8 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/broker_lifecycle.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/broker_lifecycle.go @@ -17,9 +17,9 @@ limitations under the License. package v1alpha1 import ( - appsv1 "k8s.io/api/apps/v1" "knative.dev/pkg/apis" + corev1 "k8s.io/api/core/v1" "knative.dev/eventing/pkg/apis/duck" duckv1alpha1 "knative.dev/eventing/pkg/apis/duck/v1alpha1" ) @@ -63,13 +63,11 @@ func (bs *BrokerStatus) MarkIngressFailed(reason, format string, args ...interfa brokerCondSet.Manage(bs).MarkFalse(BrokerConditionIngress, reason, format, args...) } -func (bs *BrokerStatus) PropagateIngressDeploymentAvailability(d *appsv1.Deployment) { - if duck.DeploymentIsAvailable(&d.Status, true) { +func (bs *BrokerStatus) PropagateIngressAvailability(ep *corev1.Endpoints) { + if duck.EndpointsAreAvailable(ep) { brokerCondSet.Manage(bs).MarkTrue(BrokerConditionIngress) } else { - // I don't know how to propagate the status well, so just give the name of the Deployment - // for now. - bs.MarkIngressFailed("DeploymentUnavailable", "The Deployment '%s' is unavailable.", d.Name) + bs.MarkIngressFailed("EndpointsUnavailable", "Endpoints %q are unavailable.", ep.Name) } } @@ -91,13 +89,11 @@ func (bs *BrokerStatus) MarkFilterFailed(reason, format string, args ...interfac brokerCondSet.Manage(bs).MarkFalse(BrokerConditionFilter, reason, format, args...) } -func (bs *BrokerStatus) PropagateFilterDeploymentAvailability(d *appsv1.Deployment) { - if duck.DeploymentIsAvailable(&d.Status, true) { +func (bs *BrokerStatus) PropagateFilterAvailability(ep *corev1.Endpoints) { + if duck.EndpointsAreAvailable(ep) { brokerCondSet.Manage(bs).MarkTrue(BrokerConditionFilter) } else { - // I don't know how to propagate the status well, so just give the name of the Deployment - // for now. - bs.MarkFilterFailed("DeploymentUnavailable", "The Deployment '%s' is unavailable.", d.Name) + bs.MarkFilterFailed("EndpointsUnavailable", "Endpoints %q are unavailable.", ep.Name) } } diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/broker_types.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/broker_types.go index 155b9da3..f34581f9 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/broker_types.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/broker_types.go @@ -30,7 +30,7 @@ import ( ) // +genclient -// +genreconciler +// +genreconciler:class=eventing.knative.dev/broker.class // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // Broker collects a pool of events that are consumable using Triggers. Brokers diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/eventtype_types.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/eventtype_types.go index 0d736990..4bfa7316 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/eventtype_types.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/eventtype_types.go @@ -40,6 +40,7 @@ type EventType struct { // Status represents the current state of the EventType. // This data may be out of date. // +optional + // TODO might be removed https://github.com/knative/eventing/issues/2750 Status EventTypeStatus `json:"status,omitempty"` } @@ -61,13 +62,16 @@ type EventTypeSpec struct { // Type represents the CloudEvents type. It is authoritative. Type string `json:"type"` // Source is a URI, it represents the CloudEvents source. - Source string `json:"source"` + // +optional + Source string `json:"source,omitempty"` // Schema is a URI, it represents the CloudEvents schemaurl extension attribute. // It may be a JSON schema, a protobuf schema, etc. It is optional. // +optional Schema string `json:"schema,omitempty"` + // TODO remove https://github.com/knative/eventing/issues/2750 // Broker refers to the Broker that can provide the EventType. - Broker string `json:"broker"` + // +optional + Broker string `json:"broker,omitempty"` // Description is an optional field used to describe the EventType, in any meaningful way. // +optional Description string `json:"description,omitempty"` diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/eventtype_validation.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/eventtype_validation.go index 8bc9fa6f..20234c69 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/eventtype_validation.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/eventtype_validation.go @@ -19,8 +19,6 @@ package v1alpha1 import ( "context" - "github.com/google/go-cmp/cmp/cmpopts" - "knative.dev/pkg/apis" "knative.dev/pkg/kmp" ) @@ -35,15 +33,6 @@ func (ets *EventTypeSpec) Validate(ctx context.Context) *apis.FieldError { fe := apis.ErrMissingField("type") errs = errs.Also(fe) } - if ets.Source == "" { - // TODO validate is a valid URI. - fe := apis.ErrMissingField("source") - errs = errs.Also(fe) - } - if ets.Broker == "" { - fe := apis.ErrMissingField("broker") - errs = errs.Also(fe) - } // TODO validate Schema is a valid URI. return errs } @@ -53,9 +42,8 @@ func (et *EventType) CheckImmutableFields(ctx context.Context, original *EventTy return nil } - // All but Description field immutable. - ignoreArguments := cmpopts.IgnoreFields(EventTypeSpec{}, "Description") - if diff, err := kmp.ShortDiff(original.Spec, et.Spec, ignoreArguments); err != nil { + // All fields immutable + if diff, err := kmp.ShortDiff(original.Spec, et.Spec); err != nil { return &apis.FieldError{ Message: "Failed to diff EventType", Paths: []string{"spec"}, diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/test_helper.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/test_helper.go index 3324427c..93ea443e 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/test_helper.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/test_helper.go @@ -17,8 +17,7 @@ limitations under the License. package v1alpha1 import ( - v1 "k8s.io/api/apps/v1" - "knative.dev/eventing/pkg/apis/legacysources/v1alpha1" + corev1 "k8s.io/api/core/v1" "knative.dev/pkg/apis" pkgduckv1alpha1 "knative.dev/pkg/apis/duck/v1alpha1" @@ -69,9 +68,9 @@ func (testHelper) FalseSubscriptionStatus() *messagingv1alpha1.SubscriptionStatu func (t testHelper) ReadyBrokerStatus() *BrokerStatus { bs := &BrokerStatus{} - bs.PropagateIngressDeploymentAvailability(t.AvailableDeployment()) + bs.PropagateIngressAvailability(t.AvailableEndpoints()) bs.PropagateTriggerChannelReadiness(t.ReadyChannelStatus()) - bs.PropagateFilterDeploymentAvailability(t.AvailableDeployment()) + bs.PropagateFilterAvailability(t.AvailableEndpoints()) bs.SetAddress(&apis.URL{Scheme: "http", Host: "foo"}) return bs } @@ -100,32 +99,24 @@ func (t testHelper) ReadyTriggerStatus() *TriggerStatus { return ts } -func (testHelper) UnavailableDeployment() *v1.Deployment { - d := &v1.Deployment{} - d.Name = "unavailable" - d.Status.Conditions = []v1.DeploymentCondition{ - { - Type: v1.DeploymentAvailable, - Status: "False", - }, - } - return d -} - -func (t testHelper) AvailableDeployment() *v1.Deployment { - d := t.UnavailableDeployment() - d.Name = "available" - d.Status.Conditions = []v1.DeploymentCondition{ - { - Type: v1.DeploymentAvailable, - Status: "True", - }, - } - return d +func (t testHelper) UnavailableEndpoints() *corev1.Endpoints { + ep := &corev1.Endpoints{} + ep.Name = "unavailable" + ep.Subsets = []corev1.EndpointSubset{{ + NotReadyAddresses: []corev1.EndpointAddress{{ + IP: "127.0.0.1", + }}, + }} + return ep } -func (t testHelper) UnknownCronJobSourceStatus() *v1alpha1.CronJobSourceStatus { - cjss := &v1alpha1.CronJobSourceStatus{} - cjss.InitializeConditions() - return cjss +func (t testHelper) AvailableEndpoints() *corev1.Endpoints { + ep := &corev1.Endpoints{} + ep.Name = "available" + ep.Subsets = []corev1.EndpointSubset{{ + Addresses: []corev1.EndpointAddress{{ + IP: "127.0.0.1", + }}, + }} + return ep } diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/trigger_conversion.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/trigger_conversion.go index aa6adea0..bb3a7fee 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/trigger_conversion.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/trigger_conversion.go @@ -33,8 +33,7 @@ func (source *Trigger) ConvertTo(ctx context.Context, obj apis.Convertible) erro sink.Spec.Broker = source.Spec.Broker sink.Spec.Subscriber = source.Spec.Subscriber if source.Spec.Filter != nil { - sink.Spec.Filter = &v1beta1.TriggerFilter{ - } + sink.Spec.Filter = &v1beta1.TriggerFilter{} if source.Spec.Filter.Attributes != nil { sink.Spec.Filter = &v1beta1.TriggerFilter{ Attributes: make(v1beta1.TriggerFilterAttributes, len(*source.Spec.Filter.Attributes)), diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/trigger_lifecycle.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/trigger_lifecycle.go index aa87b211..cff1ab92 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/trigger_lifecycle.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/trigger_lifecycle.go @@ -31,7 +31,7 @@ const ( TriggerConditionBroker apis.ConditionType = "BrokerReady" - TriggerConditionSubscribed apis.ConditionType = "Subscribed" + TriggerConditionSubscribed apis.ConditionType = "SubscriptionReady" TriggerConditionDependency apis.ConditionType = "DependencyReady" @@ -154,7 +154,7 @@ func (ts *TriggerStatus) MarkDependencyUnknown(reason, messageFormat string, mes } func (ts *TriggerStatus) MarkDependencyNotConfigured() { - triggerCondSet.Manage(ts).MarkUnknown(EventTypeConditionBrokerReady, + triggerCondSet.Manage(ts).MarkUnknown(TriggerConditionDependency, "DependencyNotConfigured", "Dependency has not yet been reconciled.") } diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/trigger_types.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/trigger_types.go index 55e7ba0b..0e7f95fd 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/trigger_types.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1alpha1/trigger_types.go @@ -35,6 +35,7 @@ const ( ) // +genclient +// +genreconciler // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // Trigger represents a request to have events delivered to a consumer from a diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1beta1/broker_defaults.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1beta1/broker_defaults.go index 217bda3d..ff78bd3b 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1beta1/broker_defaults.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1beta1/broker_defaults.go @@ -20,13 +20,15 @@ import ( "context" "knative.dev/eventing/pkg/apis/config" + "knative.dev/eventing/pkg/apis/eventing" "knative.dev/pkg/apis" ) func (b *Broker) SetDefaults(ctx context.Context) { - // TODO(vaikas): Set the default class annotation if not specified + // Default Spec fields. withNS := apis.WithinParent(ctx, b.ObjectMeta) b.Spec.SetDefaults(withNS) + eventing.DefaultBrokerClassIfUnset(withNS, &b.ObjectMeta) } func (bs *BrokerSpec) SetDefaults(ctx context.Context) { diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1beta1/eventtype_types.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1beta1/eventtype_types.go index 328f35bf..dbdf3f76 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1beta1/eventtype_types.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1beta1/eventtype_types.go @@ -39,6 +39,7 @@ type EventType struct { // Status represents the current state of the EventType. // This data may be out of date. // +optional + // TODO might be removed https://github.com/knative/eventing/issues/2750 Status EventTypeStatus `json:"status,omitempty"` } @@ -60,13 +61,21 @@ type EventTypeSpec struct { // Type represents the CloudEvents type. It is authoritative. Type string `json:"type"` // Source is a URI, it represents the CloudEvents source. - Source apis.URL `json:"source"` + // +optional + Source *apis.URL `json:"source,omitempty"` // Schema is a URI, it represents the CloudEvents schemaurl extension attribute. // It may be a JSON schema, a protobuf schema, etc. It is optional. // +optional Schema *apis.URL `json:"schema,omitempty"` + // SchemaData allows the CloudEvents schema to be stored directly in the + // EventType. Content is dependent on the encoding. Optional attribute. + // The contents are not validated or manipulated by the system. + // +optional + SchemaData string `json:"schemaData,omitempty"` + // TODO remove https://github.com/knative/eventing/issues/2750 // Broker refers to the Broker that can provide the EventType. - Broker string `json:"broker"` + // +optional + Broker string `json:"broker,omitempty"` // Description is an optional field used to describe the EventType, in any meaningful way. // +optional Description string `json:"description,omitempty"` diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1beta1/eventtype_validation.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1beta1/eventtype_validation.go index 2827d1eb..ae5419f3 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1beta1/eventtype_validation.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1beta1/eventtype_validation.go @@ -19,8 +19,6 @@ package v1beta1 import ( "context" - "github.com/google/go-cmp/cmp/cmpopts" - "knative.dev/pkg/apis" "knative.dev/pkg/kmp" ) @@ -35,16 +33,9 @@ func (ets *EventTypeSpec) Validate(ctx context.Context) *apis.FieldError { fe := apis.ErrMissingField("type") errs = errs.Also(fe) } - if ets.Source.IsEmpty() { - // TODO validate is a valid URI. - fe := apis.ErrMissingField("source") - errs = errs.Also(fe) - } - if ets.Broker == "" { - fe := apis.ErrMissingField("broker") - errs = errs.Also(fe) - } + // TODO validate Source is a valid URI. // TODO validate Schema is a valid URI. + // There is no validation of the SchemaData, it is application specific data. return errs } @@ -53,9 +44,8 @@ func (et *EventType) CheckImmutableFields(ctx context.Context, original *EventTy return nil } - // All but Description field immutable. - ignoreArguments := cmpopts.IgnoreFields(EventTypeSpec{}, "Description") - if diff, err := kmp.ShortDiff(original.Spec, et.Spec, ignoreArguments); err != nil { + // All fields are immutable. + if diff, err := kmp.ShortDiff(original.Spec, et.Spec); err != nil { return &apis.FieldError{ Message: "Failed to diff EventType", Paths: []string{"spec"}, diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1beta1/trigger_lifecycle.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1beta1/trigger_lifecycle.go index 31d6db50..0e122a37 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1beta1/trigger_lifecycle.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1beta1/trigger_lifecycle.go @@ -31,7 +31,7 @@ const ( TriggerConditionBroker apis.ConditionType = "BrokerReady" - TriggerConditionSubscribed apis.ConditionType = "Subscribed" + TriggerConditionSubscribed apis.ConditionType = "SubscriptionReady" TriggerConditionDependency apis.ConditionType = "DependencyReady" diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1beta1/zz_generated.deepcopy.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1beta1/zz_generated.deepcopy.go index e38b3d7f..38bdb083 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1beta1/zz_generated.deepcopy.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/eventing/v1beta1/zz_generated.deepcopy.go @@ -196,7 +196,11 @@ func (in *EventTypeList) DeepCopyObject() runtime.Object { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *EventTypeSpec) DeepCopyInto(out *EventTypeSpec) { *out = *in - in.Source.DeepCopyInto(&out.Source) + if in.Source != nil { + in, out := &in.Source, &out.Source + *out = new(apis.URL) + (*in).DeepCopyInto(*out) + } if in.Schema != nil { in, out := &in.Schema, &out.Schema *out = new(apis.URL) diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/flows/v1alpha1/parallel_defaults.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/flows/v1alpha1/parallel_defaults.go index d4eaa968..5fe963ab 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/flows/v1alpha1/parallel_defaults.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/flows/v1alpha1/parallel_defaults.go @@ -32,8 +32,8 @@ func (p *Parallel) SetDefaults(ctx context.Context) { if err == nil { p.Spec.ChannelTemplate = &messagingv1beta1.ChannelTemplateSpec{ - c.TypeMeta, - c.Spec, + TypeMeta: c.TypeMeta, + Spec: c.Spec, } } } diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/flows/v1alpha1/sequence_defaults.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/flows/v1alpha1/sequence_defaults.go index 52e3c40b..e7e48da1 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/flows/v1alpha1/sequence_defaults.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/flows/v1alpha1/sequence_defaults.go @@ -32,8 +32,8 @@ func (s *Sequence) SetDefaults(ctx context.Context) { if err == nil { s.Spec.ChannelTemplate = &messagingv1beta1.ChannelTemplateSpec{ - c.TypeMeta, - c.Spec, + TypeMeta: c.TypeMeta, + Spec: c.Spec, } } } diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/flows/v1beta1/parallel_defaults.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/flows/v1beta1/parallel_defaults.go index c291bb0d..8efef077 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/flows/v1beta1/parallel_defaults.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/flows/v1beta1/parallel_defaults.go @@ -32,8 +32,8 @@ func (p *Parallel) SetDefaults(ctx context.Context) { if err == nil { p.Spec.ChannelTemplate = &messagingv1beta1.ChannelTemplateSpec{ - c.TypeMeta, - c.Spec, + TypeMeta: c.TypeMeta, + Spec: c.Spec, } } } diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/flows/v1beta1/sequence_defaults.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/flows/v1beta1/sequence_defaults.go index 9b55a5c5..7c63a65b 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/flows/v1beta1/sequence_defaults.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/flows/v1beta1/sequence_defaults.go @@ -32,8 +32,8 @@ func (s *Sequence) SetDefaults(ctx context.Context) { if err == nil { s.Spec.ChannelTemplate = &messagingv1beta1.ChannelTemplateSpec{ - c.TypeMeta, - c.Spec, + TypeMeta: c.TypeMeta, + Spec: c.Spec, } } } diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/flows/v1beta1/test_helpers.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/flows/v1beta1/test_helpers.go index e49a52ad..b3387117 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/flows/v1beta1/test_helpers.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/flows/v1beta1/test_helpers.go @@ -17,11 +17,9 @@ package v1beta1 import ( - "github.com/google/go-cmp/cmp/cmpopts" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" messagingv1beta1 "knative.dev/eventing/pkg/apis/messaging/v1beta1" - "knative.dev/pkg/apis" ) var ( @@ -31,8 +29,4 @@ var ( Kind: "InMemoryChannel", }, } - - ignoreAllButTypeAndStatus = cmpopts.IgnoreFields( - apis.Condition{}, - "LastTransitionTime", "Message", "Reason", "Severity") ) diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/apiserver_defaults.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/apiserver_defaults.go deleted file mode 100644 index 18891cdb..00000000 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/apiserver_defaults.go +++ /dev/null @@ -1,29 +0,0 @@ -/* -Copyright 2019 The Knative 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 v1alpha1 - -import ( - "context" -) - -func (s *ApiServerSource) SetDefaults(ctx context.Context) { - s.Spec.SetDefaults(ctx) -} - -func (ss *ApiServerSourceSpec) SetDefaults(ctx context.Context) { - // TODO anything? -} diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/apiserver_lifecycle.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/apiserver_lifecycle.go deleted file mode 100644 index d18d72eb..00000000 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/apiserver_lifecycle.go +++ /dev/null @@ -1,127 +0,0 @@ -/* -Copyright 2019 The Knative 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 v1alpha1 - -import ( - appsv1 "k8s.io/api/apps/v1" - corev1 "k8s.io/api/core/v1" - - "knative.dev/pkg/apis" - - "knative.dev/eventing/pkg/apis/duck" -) - -const ( - // ApiServerConditionReady has status True when the ApiServerSource is ready to send events. - ApiServerConditionReady = apis.ConditionReady - - // ApiServerConditionSinkProvided has status True when the ApiServerSource has been configured with a sink target. - ApiServerConditionSinkProvided apis.ConditionType = "SinkProvided" - - // ApiServerConditionDeployed has status True when the ApiServerSource has had it's deployment created. - ApiServerConditionDeployed apis.ConditionType = "Deployed" - - // ApiServerConditionSufficientPermissions has status True when the ApiServerSource has sufficient permissions to access resources. - ApiServerConditionSufficientPermissions apis.ConditionType = "SufficientPermissions" - - // ApiServerConditionEventTypeProvided has status True when the ApiServerSource has been configured with its event types. - ApiServerConditionEventTypeProvided apis.ConditionType = "EventTypesProvided" -) - -var apiserverCondSet = apis.NewLivingConditionSet( - ApiServerConditionSinkProvided, - ApiServerConditionDeployed, - ApiServerConditionSufficientPermissions, -) - -// GetCondition returns the condition currently associated with the given type, or nil. -func (s *ApiServerSourceStatus) GetCondition(t apis.ConditionType) *apis.Condition { - return apiserverCondSet.Manage(s).GetCondition(t) -} - -// InitializeConditions sets relevant unset conditions to Unknown state. -func (s *ApiServerSourceStatus) InitializeConditions() { - apiserverCondSet.Manage(s).InitializeConditions() -} - -// MarkSink sets the condition that the source has a sink configured. -func (s *ApiServerSourceStatus) MarkSink(uri string) { - s.SinkURI = uri - if len(uri) > 0 { - apiserverCondSet.Manage(s).MarkTrue(ApiServerConditionSinkProvided) - } else { - apiserverCondSet.Manage(s).MarkFalse(ApiServerConditionSinkProvided, "SinkEmpty", "Sink has resolved to empty.%s", "") - } -} - -// MarkSinkWarnDeprecated sets the condition that the source has a sink configured and warns ref is deprecated. -func (s *ApiServerSourceStatus) MarkSinkWarnRefDeprecated(uri string) { - s.SinkURI = uri - if len(uri) > 0 { - c := apis.Condition{ - Type: ApiServerConditionSinkProvided, - Status: corev1.ConditionTrue, - Severity: apis.ConditionSeverityError, - Message: "Using deprecated object ref fields when specifying spec.sink. Update to spec.sink.ref. These will be removed in the future.", - } - apiserverCondSet.Manage(s).SetCondition(c) - } else { - apiserverCondSet.Manage(s).MarkUnknown(ApiServerConditionSinkProvided, "SinkEmpty", "Sink has resolved to empty.%s", "") - } -} - -// MarkNoSink sets the condition that the source does not have a sink configured. -func (s *ApiServerSourceStatus) MarkNoSink(reason, messageFormat string, messageA ...interface{}) { - apiserverCondSet.Manage(s).MarkFalse(ApiServerConditionSinkProvided, reason, messageFormat, messageA...) -} - -// PropagateDeploymentAvailability uses the availability of the provided Deployment to determine if -// ApiServerConditionDeployed should be marked as true or false. -func (s *ApiServerSourceStatus) PropagateDeploymentAvailability(d *appsv1.Deployment) { - if duck.DeploymentIsAvailable(&d.Status, false) { - apiserverCondSet.Manage(s).MarkTrue(ApiServerConditionDeployed) - } else { - // I don't know how to propagate the status well, so just give the name of the Deployment - // for now. - apiserverCondSet.Manage(s).MarkFalse(ApiServerConditionDeployed, "DeploymentUnavailable", "The Deployment '%s' is unavailable.", d.Name) - } -} - -// MarkEventTypes sets the condition that the source has set its event type. -func (s *ApiServerSourceStatus) MarkEventTypes() { - apiserverCondSet.Manage(s).MarkTrue(ApiServerConditionEventTypeProvided) -} - -// MarkNoEventTypes sets the condition that the source does not its event type configured. -func (s *ApiServerSourceStatus) MarkNoEventTypes(reason, messageFormat string, messageA ...interface{}) { - apiserverCondSet.Manage(s).MarkFalse(ApiServerConditionEventTypeProvided, reason, messageFormat, messageA...) -} - -// MarkSufficientPermissions sets the condition that the source has enough permissions to access the resources. -func (s *ApiServerSourceStatus) MarkSufficientPermissions() { - apiserverCondSet.Manage(s).MarkTrue(ApiServerConditionSufficientPermissions) -} - -// MarkNoSufficientPermissions sets the condition that the source does not have enough permissions to access the resources -func (s *ApiServerSourceStatus) MarkNoSufficientPermissions(reason, messageFormat string, messageA ...interface{}) { - apiserverCondSet.Manage(s).MarkFalse(ApiServerConditionSufficientPermissions, reason, messageFormat, messageA...) -} - -// IsReady returns true if the resource is ready overall. -func (s *ApiServerSourceStatus) IsReady() bool { - return apiserverCondSet.Manage(s).IsHappy() -} diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/apiserver_types.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/apiserver_types.go deleted file mode 100644 index 34232838..00000000 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/apiserver_types.go +++ /dev/null @@ -1,137 +0,0 @@ -/* -Copyright 2019 The Knative 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 v1alpha1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime/schema" - "knative.dev/pkg/apis" - duckv1 "knative.dev/pkg/apis/duck/v1" - duckv1beta1 "knative.dev/pkg/apis/duck/v1beta1" - "knative.dev/pkg/kmeta" -) - -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// ApiServerSource is the Schema for the apiserversources API -type ApiServerSource struct { - // Deprecated allows ApiServerSource to have a deprecated message. - Deprecated - - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - Spec ApiServerSourceSpec `json:"spec,omitempty"` - Status ApiServerSourceStatus `json:"status,omitempty"` -} - -var ( - // Check that we can create OwnerReferences to an ApiServerSource. - _ kmeta.OwnerRefable = (*ApiServerSource)(nil) - - // Check that ApiServerSource can return its spec untyped. - _ apis.HasSpec = (*ApiServerSource)(nil) -) - -const ( - // ApiServerSourceAddEventType is the ApiServerSource CloudEvent type for adds. - ApiServerSourceAddEventType = "dev.knative.apiserver.resource.add" - // ApiServerSourceUpdateEventType is the ApiServerSource CloudEvent type for updates. - ApiServerSourceUpdateEventType = "dev.knative.apiserver.resource.update" - // ApiServerSourceDeleteEventType is the ApiServerSource CloudEvent type for deletions. - ApiServerSourceDeleteEventType = "dev.knative.apiserver.resource.delete" - - // ApiServerSourceAddRefEventType is the ApiServerSource CloudEvent type for ref adds. - ApiServerSourceAddRefEventType = "dev.knative.apiserver.ref.add" - // ApiServerSourceUpdateRefEventType is the ApiServerSource CloudEvent type for ref updates. - ApiServerSourceUpdateRefEventType = "dev.knative.apiserver.ref.update" - // ApiServerSourceDeleteRefEventType is the ApiServerSource CloudEvent type for ref deletions. - ApiServerSourceDeleteRefEventType = "dev.knative.apiserver.ref.delete" -) - -// GetGroupVersionKind returns the GroupVersionKind. -func (s *ApiServerSource) GetGroupVersionKind() schema.GroupVersionKind { - return SchemeGroupVersion.WithKind("ApiServerSource") -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// ApiServerSourceList contains a list of ApiServerSource -type ApiServerSourceList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata,omitempty"` - Items []ApiServerSource `json:"items"` -} - -// ApiServerSourceSpec defines the desired state of ApiServerSource -type ApiServerSourceSpec struct { - // Resources is the list of resources to watch - Resources []ApiServerResource `json:"resources"` - - // ServiceAccountName is the name of the ServiceAccount to use to run this - // source. - // +optional - ServiceAccountName string `json:"serviceAccountName,omitempty"` - - // Sink is a reference to an object that will resolve to a domain name to use as the sink. - // +optional - Sink *duckv1beta1.Destination `json:"sink,omitempty"` - - // Mode is the mode the receive adapter controller runs under: Ref or Resource. - // `Ref` sends only the reference to the resource. - // `Resource` send the full resource. - Mode string `json:"mode,omitempty"` -} - -// ApiServerSourceStatus defines the observed state of ApiServerSource -type ApiServerSourceStatus struct { - // inherits duck/v1 Status, which currently provides: - // * ObservedGeneration - the 'Generation' of the Service that was last processed by the controller. - // * Conditions - the latest available observations of a resource's current state. - duckv1.Status `json:",inline"` - - // SinkURI is the current active sink URI that has been configured for the ApiServerSource. - // +optional - SinkURI string `json:"sinkUri,omitempty"` -} - -// ApiServerResource defines the resource to watch -type ApiServerResource struct { - // API version of the resource to watch. - APIVersion string `json:"apiVersion"` - - // Kind of the resource to watch. - // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds - Kind string `json:"kind"` - - // LabelSelector restricts this source to objects with the selected labels - // More info: http://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors - LabelSelector metav1.LabelSelector `json:"labelSelector"` - - // ControllerSelector restricts this source to objects with a controlling owner reference of the specified kind. - // Only apiVersion and kind are used. Both are optional. - ControllerSelector metav1.OwnerReference `json:"controllerSelector"` - - // If true, send an event referencing the object controlling the resource - Controller bool `json:"controller"` -} - -// GetUntypedSpec returns the spec of the ApiServerSource. -func (a *ApiServerSource) GetUntypedSpec() interface{} { - return a.Spec -} diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/apiserver_validation.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/apiserver_validation.go deleted file mode 100644 index 0987c190..00000000 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/apiserver_validation.go +++ /dev/null @@ -1,56 +0,0 @@ -/* -Copyright 2019 The Knative 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 v1alpha1 - -import ( - "context" - - "knative.dev/pkg/apis" -) - -const ( - // RefMode produces payloads of ObjectReference - RefMode = "Ref" - // ResourceMode produces payloads of ResourceEvent - ResourceMode = "Resource" -) - -func (c *ApiServerSource) Validate(ctx context.Context) *apis.FieldError { - return c.Spec.Validate(ctx).ViaField("spec") -} - -func (cs *ApiServerSourceSpec) Validate(ctx context.Context) *apis.FieldError { - var errs *apis.FieldError - - // Validate mode, if can be empty or set as certain value - if cs.Mode != "" && cs.Mode != RefMode && cs.Mode != ResourceMode { - fe := &apis.FieldError{ - Message: "Mode is not valid", - Paths: []string{"mode"}, - } - errs = errs.Also(fe) - } - - // Validate sink - if cs.Sink == nil { - fe := apis.ErrMissingField("sink") - errs = errs.Also(fe) - } else if fe := cs.Sink.Validate(ctx); fe != nil { - errs = errs.Also(fe.ViaField("sink")) - } - return errs -} diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/containersource_lifecycle.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/containersource_lifecycle.go deleted file mode 100644 index efe7d7ef..00000000 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/containersource_lifecycle.go +++ /dev/null @@ -1,109 +0,0 @@ -/* -Copyright 2019 The Knative 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 v1alpha1 - -import ( - corev1 "k8s.io/api/core/v1" - "knative.dev/pkg/apis" -) - -const ( - // ContainerSourceConditionReady has status True when the ContainerSource is ready to send events. - ContainerConditionReady = apis.ConditionReady - - // ContainerConditionSinkProvided has status True when the ContainerSource has been configured with a sink target. - ContainerConditionSinkProvided apis.ConditionType = "SinkProvided" - - // ContainerConditionDeployed has status True when the ContainerSource has had it's deployment created. - ContainerConditionDeployed apis.ConditionType = "Deployed" -) - -var containerCondSet = apis.NewLivingConditionSet( - ContainerConditionSinkProvided, - ContainerConditionDeployed, -) - -// GetCondition returns the condition currently associated with the given type, or nil. -func (s *ContainerSourceStatus) GetCondition(t apis.ConditionType) *apis.Condition { - return containerCondSet.Manage(s).GetCondition(t) -} - -// IsReady returns true if the resource is ready overall. -func (s *ContainerSourceStatus) IsReady() bool { - return containerCondSet.Manage(s).IsHappy() -} - -// InitializeConditions sets relevant unset conditions to Unknown state. -func (s *ContainerSourceStatus) InitializeConditions() { - containerCondSet.Manage(s).InitializeConditions() -} - -// MarkSink sets the condition that the source has a sink configured. -func (s *ContainerSourceStatus) MarkSink(uri string) { - s.SinkURI = uri - if len(uri) > 0 { - containerCondSet.Manage(s).MarkTrue(ContainerConditionSinkProvided) - } else { - containerCondSet.Manage(s).MarkFalse(ContainerConditionSinkProvided, "SinkEmpty", "Sink has resolved to empty.%s", "") - } -} - -// MarkSinkWarnDeprecated sets the condition that the source has a sink configured and warns ref is deprecated. -func (s *ContainerSourceStatus) MarkSinkWarnRefDeprecated(uri string) { - s.SinkURI = uri - if len(uri) > 0 { - c := apis.Condition{ - Type: ContainerConditionSinkProvided, - Status: corev1.ConditionTrue, - Severity: apis.ConditionSeverityError, - Message: "Using deprecated object ref fields when specifying spec.sink. Update to spec.sink.ref. These will be removed in the future.", - } - apiserverCondSet.Manage(s).SetCondition(c) - } else { - apiserverCondSet.Manage(s).MarkUnknown(ContainerConditionSinkProvided, "SinkEmpty", "Sink has resolved to empty.%s", "") - } -} - -// MarkNoSink sets the condition that the source does not have a sink configured. -func (s *ContainerSourceStatus) MarkNoSink(reason, messageFormat string, messageA ...interface{}) { - containerCondSet.Manage(s).MarkFalse(ContainerConditionSinkProvided, reason, messageFormat, messageA...) -} - -// IsDeployed returns true if the Deployed condition has status true, otherwise -// false. -func (s *ContainerSourceStatus) IsDeployed() bool { - c := containerCondSet.Manage(s).GetCondition(ContainerConditionDeployed) - if c != nil { - return c.IsTrue() - } - return false -} - -// MarkDeployed sets the condition that the source has been deployed. -func (s *ContainerSourceStatus) MarkDeployed() { - containerCondSet.Manage(s).MarkTrue(ContainerConditionDeployed) -} - -// MarkDeploying sets the condition that the source is deploying. -func (s *ContainerSourceStatus) MarkDeploying(reason, messageFormat string, messageA ...interface{}) { - containerCondSet.Manage(s).MarkUnknown(ContainerConditionDeployed, reason, messageFormat, messageA...) -} - -// MarkNotDeployed sets the condition that the source has not been deployed. -func (s *ContainerSourceStatus) MarkNotDeployed(reason, messageFormat string, messageA ...interface{}) { - containerCondSet.Manage(s).MarkFalse(ContainerConditionDeployed, reason, messageFormat, messageA...) -} diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/cron_job_lifecycle.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/cron_job_lifecycle.go deleted file mode 100644 index 319c738c..00000000 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/cron_job_lifecycle.go +++ /dev/null @@ -1,141 +0,0 @@ -/* -Copyright 2019 The Knative 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 v1alpha1 - -import ( - appsv1 "k8s.io/api/apps/v1" - corev1 "k8s.io/api/core/v1" - - "knative.dev/pkg/apis" - - "knative.dev/eventing/pkg/apis/duck" -) - -const ( - // CronJobConditionReady has status True when the CronJobSource is ready to send events. - CronJobConditionReady = apis.ConditionReady - - // CronJobConditionValidSchedule has status True when the CronJobSource has been configured with a valid schedule. - CronJobConditionValidSchedule apis.ConditionType = "ValidSchedule" - - // CronJobConditionSinkProvided has status True when the CronJobSource has been configured with a sink target. - CronJobConditionSinkProvided apis.ConditionType = "SinkProvided" - - // CronJobConditionDeployed has status True when the CronJobSource has had it's receive adapter deployment created. - CronJobConditionDeployed apis.ConditionType = "Deployed" - - // CronJobConditionEventTypeProvided has status True when the CronJobSource has been configured with its event type. - CronJobConditionEventTypeProvided apis.ConditionType = "EventTypeProvided" - - // CronJobConditionResources is True when the resources listed for the CronJobSource have been properly - // parsed and match specified syntax for resource quantities - CronJobConditionResources apis.ConditionType = "ResourcesCorrect" -) - -var cronJobSourceCondSet = apis.NewLivingConditionSet( - CronJobConditionValidSchedule, - CronJobConditionSinkProvided, - CronJobConditionDeployed) - -// GetCondition returns the condition currently associated with the given type, or nil. -func (s *CronJobSourceStatus) GetCondition(t apis.ConditionType) *apis.Condition { - return cronJobSourceCondSet.Manage(s).GetCondition(t) -} - -// IsReady returns true if the resource is ready overall. -func (s *CronJobSourceStatus) IsReady() bool { - return cronJobSourceCondSet.Manage(s).IsHappy() -} - -// InitializeConditions sets relevant unset conditions to Unknown state. -func (s *CronJobSourceStatus) InitializeConditions() { - cronJobSourceCondSet.Manage(s).InitializeConditions() -} - -// TODO: this is a bad method name, change it. -// MarkSchedule sets the condition that the source has a valid schedule configured. -func (s *CronJobSourceStatus) MarkSchedule() { - cronJobSourceCondSet.Manage(s).MarkTrue(CronJobConditionValidSchedule) -} - -// MarkInvalidSchedule sets the condition that the source does not have a valid schedule configured. -func (s *CronJobSourceStatus) MarkInvalidSchedule(reason, messageFormat string, messageA ...interface{}) { - cronJobSourceCondSet.Manage(s).MarkFalse(CronJobConditionValidSchedule, reason, messageFormat, messageA...) -} - -// MarkSink sets the condition that the source has a sink configured. -func (s *CronJobSourceStatus) MarkSink(uri string) { - s.SinkURI = uri - if len(uri) > 0 { - cronJobSourceCondSet.Manage(s).MarkTrue(CronJobConditionSinkProvided) - } else { - cronJobSourceCondSet.Manage(s).MarkFalse(CronJobConditionSinkProvided, "SinkEmpty", "Sink has resolved to empty.%s", "") - } -} - -// MarkSinkWarnDeprecated sets the condition that the source has a sink configured and warns ref is deprecated. -func (s *CronJobSourceStatus) MarkSinkWarnRefDeprecated(uri string) { - s.SinkURI = uri - if len(uri) > 0 { - c := apis.Condition{ - Type: CronJobConditionSinkProvided, - Status: corev1.ConditionTrue, - Severity: apis.ConditionSeverityError, - Message: "Using deprecated object ref fields when specifying spec.sink. Update to spec.sink.ref. These will be removed in the future.", - } - apiserverCondSet.Manage(s).SetCondition(c) - } else { - apiserverCondSet.Manage(s).MarkUnknown(CronJobConditionSinkProvided, "SinkEmpty", "Sink has resolved to empty.%s", "") - } -} - -// MarkNoSink sets the condition that the source does not have a sink configured. -func (s *CronJobSourceStatus) MarkNoSink(reason, messageFormat string, messageA ...interface{}) { - cronJobSourceCondSet.Manage(s).MarkFalse(CronJobConditionSinkProvided, reason, messageFormat, messageA...) -} - -// PropagateDeploymentAvailability uses the availability of the provided Deployment to determine if -// CronJobConditionDeployed should be marked as true or false. -func (s *CronJobSourceStatus) PropagateDeploymentAvailability(d *appsv1.Deployment) { - if duck.DeploymentIsAvailable(&d.Status, false) { - cronJobSourceCondSet.Manage(s).MarkTrue(CronJobConditionDeployed) - } else { - // I don't know how to propagate the status well, so just give the name of the Deployment - // for now. - cronJobSourceCondSet.Manage(s).MarkFalse(CronJobConditionDeployed, "DeploymentUnavailable", "The Deployment '%s' is unavailable.", d.Name) - } -} - -// MarkEventType sets the condition that the source has set its event type. -func (s *CronJobSourceStatus) MarkEventType() { - cronJobSourceCondSet.Manage(s).MarkTrue(CronJobConditionEventTypeProvided) -} - -// MarkNoEventType sets the condition that the source does not its event type configured. -func (s *CronJobSourceStatus) MarkNoEventType(reason, messageFormat string, messageA ...interface{}) { - cronJobSourceCondSet.Manage(s).MarkFalse(CronJobConditionEventTypeProvided, reason, messageFormat, messageA...) -} - -// MarkResourcesCorrect sets the condition that the source resources are properly parsable quantities -func (s *CronJobSourceStatus) MarkResourcesCorrect() { - cronJobSourceCondSet.Manage(s).MarkTrue(CronJobConditionResources) -} - -// MarkResourcesIncorrect sets the condition that the source resources are not properly parsable quantities -func (s *CronJobSourceStatus) MarkResourcesIncorrect(reason, messageFormat string, messageA ...interface{}) { - cronJobSourceCondSet.Manage(s).MarkFalse(CronJobConditionResources, reason, messageFormat, messageA...) -} diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/cron_job_types.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/cron_job_types.go deleted file mode 100644 index 510a145c..00000000 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/cron_job_types.go +++ /dev/null @@ -1,135 +0,0 @@ -/* -Copyright 2019 The Knative 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 v1alpha1 - -import ( - "fmt" - - "knative.dev/pkg/apis" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" - duckv1 "knative.dev/pkg/apis/duck/v1" - duckv1beta1 "knative.dev/pkg/apis/duck/v1beta1" - "knative.dev/pkg/kmeta" -) - -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +k8s:defaulter-gen=true - -// CronJobSource is the Schema for the cronjobsources API. -type CronJobSource struct { - // Deprecated allows CronJobSource to have a deprecated message. - Deprecated - - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - Spec CronJobSourceSpec `json:"spec,omitempty"` - Status CronJobSourceStatus `json:"status,omitempty"` -} - -// TODO: Check that CronJobSource can be validated and can be defaulted. - -var ( - // Check that it is a runtime object. - _ runtime.Object = (*CronJobSource)(nil) - - // Check that we can create OwnerReferences to a CronJobSource. - _ kmeta.OwnerRefable = (*CronJobSource)(nil) - - // Check that CronJobSource can return its spec untyped. - _ apis.HasSpec = (*CronJobSource)(nil) -) - -const ( - // CronJobEventType is the CronJob CloudEvent type. - CronJobEventType = "dev.knative.cronjob.event" -) - -// CronJobEventSource returns the CronJob CloudEvent source. -func CronJobEventSource(namespace, cronJobName string) string { - return fmt.Sprintf("/apis/v1/namespaces/%s/cronjobsources/%s", namespace, cronJobName) -} - -type CronJobRequestsSpec struct { - ResourceCPU string `json:"cpu,omitempty"` - ResourceMemory string `json:"memory,omitempty"` -} - -type CronJobLimitsSpec struct { - ResourceCPU string `json:"cpu,omitempty"` - ResourceMemory string `json:"memory,omitempty"` -} - -type CronJobResourceSpec struct { - Requests CronJobRequestsSpec `json:"requests,omitempty"` - Limits CronJobLimitsSpec `json:"limits,omitempty"` -} - -// CronJobSourceSpec defines the desired state of the CronJobSource. -type CronJobSourceSpec struct { - // Schedule is the cronjob schedule. - // +required - Schedule string `json:"schedule"` - - // Data is the data posted to the target function. - Data string `json:"data,omitempty"` - - // Sink is a reference to an object that will resolve to a domain name to use as the sink. - Sink *duckv1beta1.Destination `json:"sink,omitempty"` - - // ServiceAccoutName is the name of the ServiceAccount that will be used to run the Receive - // Adapter Deployment. - ServiceAccountName string `json:"serviceAccountName,omitempty"` - - // Resource limits and Request specifications of the Receive Adapter Deployment - Resources CronJobResourceSpec `json:"resources,omitempty"` -} - -// GetGroupVersionKind returns the GroupVersionKind. -func (s *CronJobSource) GetGroupVersionKind() schema.GroupVersionKind { - return SchemeGroupVersion.WithKind("CronJobSource") -} - -// CronJobSourceStatus defines the observed state of CronJobSource. -type CronJobSourceStatus struct { - // inherits duck/v1 Status, which currently provides: - // * ObservedGeneration - the 'Generation' of the Service that was last processed by the controller. - // * Conditions - the latest available observations of a resource's current state. - duckv1.Status `json:",inline"` - - // SinkURI is the current active sink URI that has been configured for the CronJobSource. - // +optional - SinkURI string `json:"sinkUri,omitempty"` -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// CronJobSourceList contains a list of CronJobSources. -type CronJobSourceList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata,omitempty"` - Items []CronJobSource `json:"items"` -} - -// GetUntypedSpec returns the spec of the CronJobSource. -func (c *CronJobSource) GetUntypedSpec() interface{} { - return c.Spec -} diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/cron_job_validation.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/cron_job_validation.go deleted file mode 100644 index d268f531..00000000 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/cron_job_validation.go +++ /dev/null @@ -1,45 +0,0 @@ -/* -Copyright 2019 The Knative 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 v1alpha1 - -import ( - "context" - - "github.com/robfig/cron" - "knative.dev/pkg/apis" -) - -func (c *CronJobSource) Validate(ctx context.Context) *apis.FieldError { - return c.Spec.Validate(ctx).ViaField("spec") -} - -func (cs *CronJobSourceSpec) Validate(ctx context.Context) *apis.FieldError { - var errs *apis.FieldError - - if _, err := cron.ParseStandard(cs.Schedule); err != nil { - fe := apis.ErrInvalidValue(cs.Schedule, "schedule") - errs = errs.Also(fe) - } - - if cs.Sink == nil { - fe := apis.ErrMissingField("sink") - errs = errs.Also(fe) - } else if fe := cs.Sink.Validate(ctx); fe != nil { - errs = errs.Also(fe.ViaField("sink")) - } - return errs -} diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/deprecated.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/deprecated.go deleted file mode 100644 index 145570bb..00000000 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/deprecated.go +++ /dev/null @@ -1,54 +0,0 @@ -/* -Copyright 2020 The Knative 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 v1alpha1 - -import ( - "time" - - corev1 "k8s.io/api/core/v1" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "knative.dev/pkg/apis" - duckv1 "knative.dev/pkg/apis/duck/v1" -) - -const ( - // StatusConditionTypeDeprecated is the status.conditions.type used to provide deprecation - // warnings. - StatusConditionTypeDeprecated = "Deprecated" -) - -type Deprecated struct{} - -// MarkDeprecated adds a warning condition that this object's spec is using deprecated fields -// and will stop working in the future. -func (d *Deprecated) MarkDeprecated(s *duckv1.Status, reason, msg string) { - dc := apis.Condition{ - Type: StatusConditionTypeDeprecated, - Reason: reason, - Status: corev1.ConditionTrue, - Severity: apis.ConditionSeverityWarning, - Message: msg, - LastTransitionTime: apis.VolatileTime{Inner: metav1.NewTime(time.Now())}, - } - for i, c := range s.Conditions { - if c.Type == dc.Type { - s.Conditions[i] = dc - return - } - } - s.Conditions = append(s.Conditions, dc) -} diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/register.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/register.go deleted file mode 100644 index a1affadb..00000000 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/register.go +++ /dev/null @@ -1,59 +0,0 @@ -/* -Copyright 2019 The Knative 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 v1alpha1 - -import ( - "knative.dev/eventing/pkg/apis/legacysources" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" -) - -// SchemeGroupVersion is group version used to register these objects -var SchemeGroupVersion = schema.GroupVersion{Group: legacysources.GroupName, Version: "v1alpha1"} - -// Kind takes an unqualified kind and returns back a Group qualified GroupKind -func Kind(kind string) schema.GroupKind { - return SchemeGroupVersion.WithKind(kind).GroupKind() -} - -// Resource takes an unqualified resource and returns a Group qualified GroupResource -func Resource(resource string) schema.GroupResource { - return SchemeGroupVersion.WithResource(resource).GroupResource() -} - -var ( - SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) - AddToScheme = SchemeBuilder.AddToScheme -) - -// Adds the list of known types to Scheme. -func addKnownTypes(scheme *runtime.Scheme) error { - scheme.AddKnownTypes(SchemeGroupVersion, - &CronJobSource{}, - &CronJobSourceList{}, - &ContainerSource{}, - &ContainerSourceList{}, - &ApiServerSource{}, - &ApiServerSourceList{}, - &SinkBinding{}, - &SinkBindingList{}, - ) - metav1.AddToGroupVersion(scheme, SchemeGroupVersion) - return nil -} diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/sinkbinding_context.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/sinkbinding_context.go deleted file mode 100644 index 420807fc..00000000 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/sinkbinding_context.go +++ /dev/null @@ -1,43 +0,0 @@ -/* -Copyright 2019 The Knative 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 v1alpha1 - -import ( - "context" - - "knative.dev/pkg/apis" -) - -// sinkURIKey is used as the key for associating information -// with a context.Context. -type sinkURIKey struct{} - -// WithSinkURI notes on the context for binding that the resolved SinkURI -// is the provided apis.URL. -func WithSinkURI(ctx context.Context, uri *apis.URL) context.Context { - return context.WithValue(ctx, sinkURIKey{}, uri) -} - -// GetSinkURI accesses the apis.URL for the Sink URI that has been associated -// with this context. -func GetSinkURI(ctx context.Context) *apis.URL { - value := ctx.Value(sinkURIKey{}) - if value == nil { - return nil - } - return value.(*apis.URL) -} diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/sinkbinding_lifecycle.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/sinkbinding_lifecycle.go deleted file mode 100644 index 283730d7..00000000 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/sinkbinding_lifecycle.go +++ /dev/null @@ -1,122 +0,0 @@ -/* -Copyright 2019 The Knative 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 v1alpha1 - -import ( - "context" - "fmt" - - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/runtime/schema" - "knative.dev/eventing/pkg/logging" - "knative.dev/pkg/apis" - "knative.dev/pkg/apis/duck" - duckv1 "knative.dev/pkg/apis/duck/v1" - "knative.dev/pkg/tracker" -) - -var sbCondSet = apis.NewLivingConditionSet() - -// GetGroupVersionKind returns the GroupVersionKind. -func (s *SinkBinding) GetGroupVersionKind() schema.GroupVersionKind { - return SchemeGroupVersion.WithKind("SinkBinding") -} - -// GetUntypedSpec implements apis.HasSpec -func (c *SinkBinding) GetUntypedSpec() interface{} { - return c.Spec -} - -// GetSubject implements psbinding.Bindable -func (fb *SinkBinding) GetSubject() tracker.Reference { - return fb.Spec.Subject -} - -// GetBindingStatus implements psbinding.Bindable -func (fb *SinkBinding) GetBindingStatus() duck.BindableStatus { - return &fb.Status -} - -// SetObservedGeneration implements psbinding.BindableStatus -func (fbs *SinkBindingStatus) SetObservedGeneration(gen int64) { - fbs.ObservedGeneration = gen -} - -// InitializeConditions populates the SinkBindingStatus's conditions field -// with all of its conditions configured to Unknown. -func (fbs *SinkBindingStatus) InitializeConditions() { - sbCondSet.Manage(fbs).InitializeConditions() -} - -// MarkBindingUnavailable marks the SinkBinding's Ready condition to False with -// the provided reason and message. -func (fbs *SinkBindingStatus) MarkBindingUnavailable(reason, message string) { - sbCondSet.Manage(fbs).MarkFalse(SinkBindingConditionReady, reason, message) -} - -// MarkBindingAvailable marks the SinkBinding's Ready condition to True. -func (fbs *SinkBindingStatus) MarkBindingAvailable() { - sbCondSet.Manage(fbs).MarkTrue(SinkBindingConditionReady) -} - -// Do implements psbinding.Bindable -func (fb *SinkBinding) Do(ctx context.Context, ps *duckv1.WithPod) { - fb.MarkDeprecated(&fb.Status.Status, "SinkBindingDeprecated", "sinkbindings.sources.eventing.knative.dev are deprecated and will be removed in the future. Use sinkbindings.sources.knative.dev instead.") - - // First undo so that we can just unconditionally append below. - fb.Undo(ctx, ps) - - uri := GetSinkURI(ctx) - if uri == nil { - logging.FromContext(ctx).Error(fmt.Sprintf("No sink URI associated with context for %+v", fb)) - return - } - - spec := ps.Spec.Template.Spec - for i := range spec.InitContainers { - spec.InitContainers[i].Env = append(spec.InitContainers[i].Env, corev1.EnvVar{ - Name: "K_SINK", - Value: uri.String(), - }) - } - for i := range spec.Containers { - spec.Containers[i].Env = append(spec.Containers[i].Env, corev1.EnvVar{ - Name: "K_SINK", - Value: uri.String(), - }) - } -} - -func (fb *SinkBinding) Undo(ctx context.Context, ps *duckv1.WithPod) { - spec := ps.Spec.Template.Spec - for i, c := range spec.InitContainers { - for j, ev := range c.Env { - if ev.Name == "K_SINK" { - spec.InitContainers[i].Env = append(spec.InitContainers[i].Env[:j], spec.InitContainers[i].Env[j+1:]...) - break - } - } - } - for i, c := range spec.Containers { - for j, ev := range c.Env { - if ev.Name == "K_SINK" { - spec.Containers[i].Env = append(spec.Containers[i].Env[:j], spec.Containers[i].Env[j+1:]...) - break - } - } - } -} diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/sinkbinding_types.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/sinkbinding_types.go deleted file mode 100644 index b9a1f0ea..00000000 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/sinkbinding_types.go +++ /dev/null @@ -1,82 +0,0 @@ -/* -Copyright 2019 The Knative 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 v1alpha1 - -import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/runtime" - "knative.dev/pkg/apis" - duckv1 "knative.dev/pkg/apis/duck/v1" - duckv1alpha1 "knative.dev/pkg/apis/duck/v1alpha1" - "knative.dev/pkg/kmeta" -) - -// +genclient -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +k8s:defaulter-gen=true - -// SinkBinding describes a Binding that is also a Source. -// The `sink` (from the Source duck) is resolved to a URL and -// then projected into the `subject` by augmenting the runtime -// contract of the referenced containers to have a `K_SINK` -// environment variable holding the endpoint to which to send -// cloud events. -type SinkBinding struct { - // Deprecated allows ApiServerSource to have a deprecated message. - Deprecated - - metav1.TypeMeta `json:",inline"` - metav1.ObjectMeta `json:"metadata,omitempty"` - - Spec SinkBindingSpec `json:"spec"` - Status SinkBindingStatus `json:"status"` -} - -// Check the interfaces that SinkBinding should be implementing. -var ( - _ runtime.Object = (*SinkBinding)(nil) - _ kmeta.OwnerRefable = (*SinkBinding)(nil) - _ apis.Validatable = (*SinkBinding)(nil) - _ apis.Defaultable = (*SinkBinding)(nil) - _ apis.HasSpec = (*SinkBinding)(nil) -) - -// SinkBindingSpec holds the desired state of the SinkBinding (from the client). -type SinkBindingSpec struct { - duckv1.SourceSpec `json:",inline"` - duckv1alpha1.BindingSpec `json:",inline"` -} - -const ( - // SinkBindingConditionReady is configured to indicate whether the Binding - // has been configured for resources subject to its runtime contract. - SinkBindingConditionReady = apis.ConditionReady -) - -// SinkBindingStatus communicates the observed state of the SinkBinding (from the controller). -type SinkBindingStatus struct { - duckv1.SourceStatus `json:",inline"` -} - -// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object - -// SinkBindingList contains a list of SinkBinding -type SinkBindingList struct { - metav1.TypeMeta `json:",inline"` - metav1.ListMeta `json:"metadata,omitempty"` - Items []SinkBinding `json:"items"` -} diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/sinkbinding_validation.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/sinkbinding_validation.go deleted file mode 100644 index e76f18ab..00000000 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/sinkbinding_validation.go +++ /dev/null @@ -1,38 +0,0 @@ -/* -Copyright 2019 The Knative 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 v1alpha1 - -import ( - "context" - - "knative.dev/pkg/apis" -) - -// Validate implements apis.Validatable -func (fb *SinkBinding) Validate(ctx context.Context) *apis.FieldError { - err := fb.Spec.Validate(ctx).ViaField("spec") - if fb.Spec.Subject.Namespace != "" && fb.Namespace != fb.Spec.Subject.Namespace { - err = err.Also(apis.ErrInvalidValue(fb.Spec.Subject.Namespace, "spec.subject.namespace")) - } - return err -} - -// Validate implements apis.Validatable -func (fbs *SinkBindingSpec) Validate(ctx context.Context) *apis.FieldError { - return fbs.Subject.Validate(ctx).ViaField("subject").Also( - fbs.Sink.Validate(ctx).ViaField("sink")) -} diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/zz_generated.deepcopy.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/zz_generated.deepcopy.go deleted file mode 100644 index 8167839f..00000000 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/zz_generated.deepcopy.go +++ /dev/null @@ -1,533 +0,0 @@ -// +build !ignore_autogenerated - -/* -Copyright 2020 The Knative 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. -*/ - -// Code generated by deepcopy-gen. DO NOT EDIT. - -package v1alpha1 - -import ( - v1 "k8s.io/api/core/v1" - runtime "k8s.io/apimachinery/pkg/runtime" - v1beta1 "knative.dev/pkg/apis/duck/v1beta1" -) - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ApiServerResource) DeepCopyInto(out *ApiServerResource) { - *out = *in - in.LabelSelector.DeepCopyInto(&out.LabelSelector) - in.ControllerSelector.DeepCopyInto(&out.ControllerSelector) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApiServerResource. -func (in *ApiServerResource) DeepCopy() *ApiServerResource { - if in == nil { - return nil - } - out := new(ApiServerResource) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ApiServerSource) DeepCopyInto(out *ApiServerSource) { - *out = *in - out.Deprecated = in.Deprecated - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApiServerSource. -func (in *ApiServerSource) DeepCopy() *ApiServerSource { - if in == nil { - return nil - } - out := new(ApiServerSource) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ApiServerSource) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ApiServerSourceList) DeepCopyInto(out *ApiServerSourceList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]ApiServerSource, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApiServerSourceList. -func (in *ApiServerSourceList) DeepCopy() *ApiServerSourceList { - if in == nil { - return nil - } - out := new(ApiServerSourceList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ApiServerSourceList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ApiServerSourceSpec) DeepCopyInto(out *ApiServerSourceSpec) { - *out = *in - if in.Resources != nil { - in, out := &in.Resources, &out.Resources - *out = make([]ApiServerResource, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.Sink != nil { - in, out := &in.Sink, &out.Sink - *out = new(v1beta1.Destination) - (*in).DeepCopyInto(*out) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApiServerSourceSpec. -func (in *ApiServerSourceSpec) DeepCopy() *ApiServerSourceSpec { - if in == nil { - return nil - } - out := new(ApiServerSourceSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ApiServerSourceStatus) DeepCopyInto(out *ApiServerSourceStatus) { - *out = *in - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ApiServerSourceStatus. -func (in *ApiServerSourceStatus) DeepCopy() *ApiServerSourceStatus { - if in == nil { - return nil - } - out := new(ApiServerSourceStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ContainerSource) DeepCopyInto(out *ContainerSource) { - *out = *in - out.Deprecated = in.Deprecated - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ContainerSource. -func (in *ContainerSource) DeepCopy() *ContainerSource { - if in == nil { - return nil - } - out := new(ContainerSource) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ContainerSource) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ContainerSourceList) DeepCopyInto(out *ContainerSourceList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]ContainerSource, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ContainerSourceList. -func (in *ContainerSourceList) DeepCopy() *ContainerSourceList { - if in == nil { - return nil - } - out := new(ContainerSourceList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *ContainerSourceList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ContainerSourceSpec) DeepCopyInto(out *ContainerSourceSpec) { - *out = *in - if in.Template != nil { - in, out := &in.Template, &out.Template - *out = new(v1.PodTemplateSpec) - (*in).DeepCopyInto(*out) - } - if in.DeprecatedArgs != nil { - in, out := &in.DeprecatedArgs, &out.DeprecatedArgs - *out = make([]string, len(*in)) - copy(*out, *in) - } - if in.DeprecatedEnv != nil { - in, out := &in.DeprecatedEnv, &out.DeprecatedEnv - *out = make([]v1.EnvVar, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - if in.Sink != nil { - in, out := &in.Sink, &out.Sink - *out = new(v1beta1.Destination) - (*in).DeepCopyInto(*out) - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ContainerSourceSpec. -func (in *ContainerSourceSpec) DeepCopy() *ContainerSourceSpec { - if in == nil { - return nil - } - out := new(ContainerSourceSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *ContainerSourceStatus) DeepCopyInto(out *ContainerSourceStatus) { - *out = *in - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ContainerSourceStatus. -func (in *ContainerSourceStatus) DeepCopy() *ContainerSourceStatus { - if in == nil { - return nil - } - out := new(ContainerSourceStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CronJobLimitsSpec) DeepCopyInto(out *CronJobLimitsSpec) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CronJobLimitsSpec. -func (in *CronJobLimitsSpec) DeepCopy() *CronJobLimitsSpec { - if in == nil { - return nil - } - out := new(CronJobLimitsSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CronJobRequestsSpec) DeepCopyInto(out *CronJobRequestsSpec) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CronJobRequestsSpec. -func (in *CronJobRequestsSpec) DeepCopy() *CronJobRequestsSpec { - if in == nil { - return nil - } - out := new(CronJobRequestsSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CronJobResourceSpec) DeepCopyInto(out *CronJobResourceSpec) { - *out = *in - out.Requests = in.Requests - out.Limits = in.Limits - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CronJobResourceSpec. -func (in *CronJobResourceSpec) DeepCopy() *CronJobResourceSpec { - if in == nil { - return nil - } - out := new(CronJobResourceSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CronJobSource) DeepCopyInto(out *CronJobSource) { - *out = *in - out.Deprecated = in.Deprecated - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CronJobSource. -func (in *CronJobSource) DeepCopy() *CronJobSource { - if in == nil { - return nil - } - out := new(CronJobSource) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *CronJobSource) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CronJobSourceList) DeepCopyInto(out *CronJobSourceList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]CronJobSource, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CronJobSourceList. -func (in *CronJobSourceList) DeepCopy() *CronJobSourceList { - if in == nil { - return nil - } - out := new(CronJobSourceList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *CronJobSourceList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CronJobSourceSpec) DeepCopyInto(out *CronJobSourceSpec) { - *out = *in - if in.Sink != nil { - in, out := &in.Sink, &out.Sink - *out = new(v1beta1.Destination) - (*in).DeepCopyInto(*out) - } - out.Resources = in.Resources - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CronJobSourceSpec. -func (in *CronJobSourceSpec) DeepCopy() *CronJobSourceSpec { - if in == nil { - return nil - } - out := new(CronJobSourceSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *CronJobSourceStatus) DeepCopyInto(out *CronJobSourceStatus) { - *out = *in - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CronJobSourceStatus. -func (in *CronJobSourceStatus) DeepCopy() *CronJobSourceStatus { - if in == nil { - return nil - } - out := new(CronJobSourceStatus) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Deprecated) DeepCopyInto(out *Deprecated) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Deprecated. -func (in *Deprecated) DeepCopy() *Deprecated { - if in == nil { - return nil - } - out := new(Deprecated) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *SinkBinding) DeepCopyInto(out *SinkBinding) { - *out = *in - out.Deprecated = in.Deprecated - out.TypeMeta = in.TypeMeta - in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) - in.Spec.DeepCopyInto(&out.Spec) - in.Status.DeepCopyInto(&out.Status) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SinkBinding. -func (in *SinkBinding) DeepCopy() *SinkBinding { - if in == nil { - return nil - } - out := new(SinkBinding) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *SinkBinding) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *SinkBindingList) DeepCopyInto(out *SinkBindingList) { - *out = *in - out.TypeMeta = in.TypeMeta - in.ListMeta.DeepCopyInto(&out.ListMeta) - if in.Items != nil { - in, out := &in.Items, &out.Items - *out = make([]SinkBinding, len(*in)) - for i := range *in { - (*in)[i].DeepCopyInto(&(*out)[i]) - } - } - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SinkBindingList. -func (in *SinkBindingList) DeepCopy() *SinkBindingList { - if in == nil { - return nil - } - out := new(SinkBindingList) - in.DeepCopyInto(out) - return out -} - -// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. -func (in *SinkBindingList) DeepCopyObject() runtime.Object { - if c := in.DeepCopy(); c != nil { - return c - } - return nil -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *SinkBindingSpec) DeepCopyInto(out *SinkBindingSpec) { - *out = *in - in.SourceSpec.DeepCopyInto(&out.SourceSpec) - in.BindingSpec.DeepCopyInto(&out.BindingSpec) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SinkBindingSpec. -func (in *SinkBindingSpec) DeepCopy() *SinkBindingSpec { - if in == nil { - return nil - } - out := new(SinkBindingSpec) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *SinkBindingStatus) DeepCopyInto(out *SinkBindingStatus) { - *out = *in - in.SourceStatus.DeepCopyInto(&out.SourceStatus) - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SinkBindingStatus. -func (in *SinkBindingStatus) DeepCopy() *SinkBindingStatus { - if in == nil { - return nil - } - out := new(SinkBindingStatus) - in.DeepCopyInto(out) - return out -} diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/messaging/v1alpha1/channel_defaults.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/messaging/v1alpha1/channel_defaults.go index 389694f5..f1df81f6 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/messaging/v1alpha1/channel_defaults.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/messaging/v1alpha1/channel_defaults.go @@ -30,8 +30,8 @@ func (c *Channel) SetDefaults(ctx context.Context) { defaultChannel, err := cfg.ChannelDefaults.GetChannelConfig(apis.ParentMeta(ctx).Namespace) if err == nil { c.Spec.ChannelTemplate = &v1beta1.ChannelTemplateSpec{ - defaultChannel.TypeMeta, - defaultChannel.Spec, + TypeMeta: defaultChannel.TypeMeta, + Spec: defaultChannel.Spec, } } } diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/messaging/v1alpha1/in_memory_channel_conversion.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/messaging/v1alpha1/in_memory_channel_conversion.go index 7434708d..468b84dd 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/messaging/v1alpha1/in_memory_channel_conversion.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/messaging/v1alpha1/in_memory_channel_conversion.go @@ -20,13 +20,14 @@ import ( "context" "fmt" + "knative.dev/pkg/apis" + duckv1 "knative.dev/pkg/apis/duck/v1" + pkgduckv1alpha1 "knative.dev/pkg/apis/duck/v1alpha1" + duckv1alpha1 "knative.dev/eventing/pkg/apis/duck/v1alpha1" eventingduck "knative.dev/eventing/pkg/apis/duck/v1alpha1" duckv1beta1 "knative.dev/eventing/pkg/apis/duck/v1beta1" "knative.dev/eventing/pkg/apis/messaging/v1beta1" - "knative.dev/pkg/apis" - duckv1 "knative.dev/pkg/apis/duck/v1" - pkgduckv1alpha1 "knative.dev/pkg/apis/duck/v1alpha1" ) // ConvertTo implements apis.Convertible @@ -48,24 +49,7 @@ func (source *InMemoryChannelSpec) ConvertTo(ctx context.Context, sink *v1beta1. if source.Subscribable != nil { sink.Subscribers = make([]duckv1beta1.SubscriberSpec, len(source.Subscribable.Subscribers)) for i, s := range source.Subscribable.Subscribers { - sink.Subscribers[i] = duckv1beta1.SubscriberSpec{ - UID: s.UID, - Generation: s.Generation, - SubscriberURI: s.SubscriberURI, - ReplyURI: s.ReplyURI, - } - // If the source has delivery, use it. - if s.Delivery != nil { - sink.Subscribers[i].Delivery = s.Delivery - } else { - // If however, there's a Deprecated DeadLetterSinkURI, convert that up - // to DeliverySpec. - sink.Subscribers[i].Delivery = &duckv1beta1.DeliverySpec{ - DeadLetterSink: &duckv1.Destination{ - URI: s.DeadLetterSinkURI, - }, - } - } + s.ConvertTo(ctx, &sink.Subscribers[i]) } } return nil @@ -114,18 +98,7 @@ func (sink *InMemoryChannelSpec) ConvertFrom(ctx context.Context, source v1beta1 Subscribers: make([]eventingduck.SubscriberSpec, len(source.Subscribers)), } for i, s := range source.Subscribers { - var deadLetterSinkURI *apis.URL - if s.Delivery != nil && s.Delivery.DeadLetterSink != nil { - deadLetterSinkURI = s.Delivery.DeadLetterSink.URI - } - sink.Subscribable.Subscribers[i] = eventingduck.SubscriberSpec{ - UID: s.UID, - Generation: s.Generation, - SubscriberURI: s.SubscriberURI, - ReplyURI: s.ReplyURI, - Delivery: s.Delivery, - DeadLetterSinkURI: deadLetterSinkURI, - } + sink.Subscribable.Subscribers[i].ConvertFrom(ctx, s) } } } diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/messaging/v1alpha1/in_memory_channel_validation.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/messaging/v1alpha1/in_memory_channel_validation.go index b5200f9e..f133d2ef 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/messaging/v1alpha1/in_memory_channel_validation.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/messaging/v1alpha1/in_memory_channel_validation.go @@ -30,7 +30,7 @@ func (imc *InMemoryChannel) Validate(ctx context.Context) *apis.FieldError { // Validate annotations if imc.Annotations != nil { if scope, ok := imc.Annotations[eventing.ScopeAnnotationKey]; ok { - if scope != "namespace" && scope != "cluster" { + if scope != eventing.ScopeNamespace && scope != eventing.ScopeCluster { iv := apis.ErrInvalidValue(scope, "") iv.Details = "expected either 'cluster' or 'namespace'" errs = errs.Also(iv.ViaFieldKey("annotations", eventing.ScopeAnnotationKey).ViaField("metadata")) diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/messaging/v1alpha1/subscription_lifecycle.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/messaging/v1alpha1/subscription_lifecycle.go index 0678f418..63a3ff7c 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/messaging/v1alpha1/subscription_lifecycle.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/messaging/v1alpha1/subscription_lifecycle.go @@ -29,7 +29,7 @@ const ( SubscriptionConditionReady = apis.ConditionReady // SubscriptionConditionReferencesResolved has status True when all the specified references have been successfully // resolved. - SubscriptionConditionReferencesResolved apis.ConditionType = "Resolved" + SubscriptionConditionReferencesResolved apis.ConditionType = "ReferencesResolved" // SubscriptionConditionAddedToChannel has status True when controller has successfully added a // subscription to the spec.channel resource. diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/messaging/v1beta1/in_memory_channel_validation.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/messaging/v1beta1/in_memory_channel_validation.go index d4366419..7ed4dc11 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/messaging/v1beta1/in_memory_channel_validation.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/messaging/v1beta1/in_memory_channel_validation.go @@ -31,7 +31,7 @@ func (imc *InMemoryChannel) Validate(ctx context.Context) *apis.FieldError { // Validate annotations if imc.Annotations != nil { if scope, ok := imc.Annotations[eventing.ScopeAnnotationKey]; ok { - if scope != "namespace" && scope != "cluster" { + if scope != eventing.ScopeNamespace && scope != eventing.ScopeCluster { iv := apis.ErrInvalidValue(scope, "") iv.Details = "expected either 'cluster' or 'namespace'" errs = errs.Also(iv.ViaFieldKey("annotations", eventing.ScopeAnnotationKey).ViaField("metadata")) diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/messaging/v1beta1/subscription_lifecycle.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/messaging/v1beta1/subscription_lifecycle.go index 0637356d..f5e6a90d 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/messaging/v1beta1/subscription_lifecycle.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/messaging/v1beta1/subscription_lifecycle.go @@ -29,7 +29,7 @@ const ( SubscriptionConditionReady = apis.ConditionReady // SubscriptionConditionReferencesResolved has status True when all the specified references have been successfully // resolved. - SubscriptionConditionReferencesResolved apis.ConditionType = "Resolved" + SubscriptionConditionReferencesResolved apis.ConditionType = "ReferencesResolved" // SubscriptionConditionAddedToChannel has status True when controller has successfully added a // subscription to the spec.channel resource. diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/register.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/register.go index 73f43e9d..55b4a748 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/register.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/register.go @@ -16,10 +16,22 @@ limitations under the License. package sources -import "k8s.io/apimachinery/pkg/runtime/schema" +import ( + "k8s.io/apimachinery/pkg/runtime/schema" + "knative.dev/pkg/apis/duck" +) const ( GroupName = "sources.knative.dev" + + // SourceDuckLabelKey is the label key to indicate + // whether the CRD is a Source duck type. + // Valid values: "true" or "false" + SourceDuckLabelKey = duck.GroupName + "/source" + + // SourceDuckLabelValue is the label value to indicate + // the CRD is a Source duck type. + SourceDuckLabelValue = "true" ) var ( @@ -38,4 +50,10 @@ var ( Group: GroupName, Resource: "sinkbindings", } + + // ContainerSourceResource respresents a Knative Eventing Sources ContainerSource + ContainerSourceResource = schema.GroupResource{ + Group: GroupName, + Resource: "containersources", + } ) diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha1/apiserver_conversion.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha1/apiserver_conversion.go index 62cf9227..970d25f3 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha1/apiserver_conversion.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha1/apiserver_conversion.go @@ -21,12 +21,14 @@ import ( "fmt" "reflect" + "github.com/google/go-cmp/cmp" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + corev1 "k8s.io/api/core/v1" "knative.dev/eventing/pkg/apis/sources/v1alpha2" "knative.dev/pkg/apis" duckv1 "knative.dev/pkg/apis/duck/v1" duckv1beta1 "knative.dev/pkg/apis/duck/v1beta1" - "knative.dev/pkg/ptr" ) // ConvertTo implements apis.Convertible. @@ -40,12 +42,17 @@ func (source *ApiServerSource) ConvertTo(ctx context.Context, obj apis.Convertib // Spec if len(source.Spec.Resources) > 0 { - sink.Spec.Resources = make([]v1alpha2.APIVersionKind, len(source.Spec.Resources)) + sink.Spec.Resources = make([]v1alpha2.APIVersionKindSelector, len(source.Spec.Resources)) } for i, v := range source.Spec.Resources { - sink.Spec.Resources[i] = v1alpha2.APIVersionKind{ - APIVersion: ptr.String(v.APIVersion), - Kind: ptr.String(v.Kind), + sink.Spec.Resources[i] = v1alpha2.APIVersionKindSelector{ + APIVersion: v.APIVersion, + Kind: v.Kind, + } + + if !cmp.Equal(v.LabelSelector, metav1.LabelSelector{}) { + sink.Spec.Resources[i].LabelSelector = &metav1.LabelSelector{} + v.LabelSelector.DeepCopyInto(sink.Spec.Resources[i].LabelSelector) } } @@ -58,10 +65,6 @@ func (source *ApiServerSource) ConvertTo(ctx context.Context, obj apis.Convertib // Optional Spec - if source.Spec.LabelSelector != nil { - sink.Spec.LabelSelector = source.Spec.LabelSelector - } - if source.Spec.ResourceOwner != nil { sink.Spec.ResourceOwner = source.Spec.ResourceOwner } @@ -135,20 +138,15 @@ func (sink *ApiServerSource) ConvertFrom(ctx context.Context, obj apis.Convertib } for i, v := range source.Spec.Resources { sink.Spec.Resources[i] = ApiServerResource{} - if v.APIVersion != nil { - sink.Spec.Resources[i].APIVersion = *v.APIVersion - } - if v.Kind != nil { - sink.Spec.Resources[i].Kind = *v.Kind + sink.Spec.Resources[i].APIVersion = v.APIVersion + sink.Spec.Resources[i].Kind = v.Kind + if v.LabelSelector != nil { + sink.Spec.Resources[i].LabelSelector = *v.LabelSelector } } // Spec Optionals - if source.Spec.LabelSelector != nil { - sink.Spec.LabelSelector = source.Spec.LabelSelector - } - if source.Spec.ResourceOwner != nil { sink.Spec.ResourceOwner = source.Spec.ResourceOwner } diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha1/apiserver_lifecycle.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha1/apiserver_lifecycle.go index 7e3240e8..72947aee 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha1/apiserver_lifecycle.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha1/apiserver_lifecycle.go @@ -37,9 +37,6 @@ const ( // ApiServerConditionSufficientPermissions has status True when the ApiServerSource has sufficient permissions to access resources. ApiServerConditionSufficientPermissions apis.ConditionType = "SufficientPermissions" - - // ApiServerConditionEventTypeProvided has status True when the ApiServerSource has been configured with its event types. - ApiServerConditionEventTypeProvided apis.ConditionType = "EventTypesProvided" ) var apiserverCondSet = apis.NewLivingConditionSet( @@ -121,16 +118,6 @@ func (s *ApiServerSourceStatus) PropagateDeploymentAvailability(d *appsv1.Deploy } } -// MarkEventTypes sets the condition that the source has set its event type. -func (s *ApiServerSourceStatus) MarkEventTypes() { - apiserverCondSet.Manage(s).MarkTrue(ApiServerConditionEventTypeProvided) -} - -// MarkNoEventTypes sets the condition that the source does not its event type configured. -func (s *ApiServerSourceStatus) MarkNoEventTypes(reason, messageFormat string, messageA ...interface{}) { - apiserverCondSet.Manage(s).MarkFalse(ApiServerConditionEventTypeProvided, reason, messageFormat, messageA...) -} - // MarkSufficientPermissions sets the condition that the source has enough permissions to access the resources. func (s *ApiServerSourceStatus) MarkSufficientPermissions() { apiserverCondSet.Manage(s).MarkTrue(ApiServerConditionSufficientPermissions) diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha1/apiserver_types.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha1/apiserver_types.go index 39b01dff..80440d05 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha1/apiserver_types.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha1/apiserver_types.go @@ -46,6 +46,16 @@ var ( _ apis.HasSpec = (*ApiServerSource)(nil) ) +// ApiServerSourceEventTypes is the list of CloudEvent types the ApiServerSource emits. +var ApiServerSourceEventTypes = []string{ + ApiServerSourceAddEventType, + ApiServerSourceDeleteEventType, + ApiServerSourceUpdateEventType, + ApiServerSourceAddRefEventType, + ApiServerSourceDeleteRefEventType, + ApiServerSourceUpdateRefEventType, +} + const ( // ApiServerSourceAddEventType is the ApiServerSource CloudEvent type for adds. ApiServerSourceAddEventType = "dev.knative.apiserver.resource.add" @@ -81,12 +91,6 @@ type ApiServerSourceSpec struct { // +optional CloudEventOverrides *duckv1.CloudEventOverrides `json:"ceOverrides,omitempty"` - // LabelSelector filters this source to objects to those resources pass the - // label selector. - // More info: http://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors - // +optional - LabelSelector *metav1.LabelSelector `json:"selector,omitempty"` - // ResourceOwner is an additional filter to only track resources that are // owned by a specific resource type. If ResourceOwner matches Resources[n] // then Resources[n] is allowed to pass the ResourceOwner filter. @@ -122,8 +126,6 @@ type ApiServerResource struct { // LabelSelector restricts this source to objects with the selected labels // More info: http://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors - // Deprecated: Per-resource label selectors will no longer be supported in - // v1alpha2, please use Spec.LabelSelector. LabelSelector metav1.LabelSelector `json:"labelSelector"` // ControllerSelector restricts this source to objects with a controlling owner reference of the specified kind. diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha1/ping_conversion.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha1/ping_conversion.go index 468c0d1b..b1c7c5ae 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha1/ping_conversion.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha1/ping_conversion.go @@ -38,8 +38,9 @@ func (source *PingSource) ConvertTo(ctx context.Context, obj apis.Convertible) e } sink.Status = v1alpha2.PingSourceStatus{ SourceStatus: duckv1.SourceStatus{ - Status: source.Status.Status, - SinkURI: source.Status.SinkURI, + Status: source.Status.Status, + SinkURI: source.Status.SinkURI, + CloudEventAttributes: source.Status.CloudEventAttributes, }, } // Optionals @@ -71,8 +72,11 @@ func (sink *PingSource) ConvertFrom(ctx context.Context, obj apis.Convertible) e CloudEventOverrides: source.Spec.CloudEventOverrides, } sink.Status = PingSourceStatus{ - Status: source.Status.Status, - SinkURI: source.Status.SinkURI, + SourceStatus: duckv1.SourceStatus{ + Status: source.Status.Status, + SinkURI: source.Status.SinkURI, + CloudEventAttributes: source.Status.CloudEventAttributes, + }, } if reflect.DeepEqual(*sink.Spec.Sink, duckv1.Destination{}) { sink.Spec.Sink = nil diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha1/ping_lifecycle.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha1/ping_lifecycle.go index 9fb0b313..0258ced0 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha1/ping_lifecycle.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha1/ping_lifecycle.go @@ -39,9 +39,6 @@ const ( // PingSourceConditionDeployed has status True when the PingSource has had it's receive adapter deployment created. PingSourceConditionDeployed apis.ConditionType = "Deployed" - // PingSourceConditionEventTypeProvided has status True when the PingSource has been configured with its event type. - PingSourceConditionEventTypeProvided apis.ConditionType = "EventTypeProvided" - // PingSourceConditionResources is True when the resources listed for the PingSource have been properly // parsed and match specified syntax for resource quantities PingSourceConditionResources apis.ConditionType = "ResourcesCorrect" @@ -131,16 +128,6 @@ func (s *PingSourceStatus) PropagateDeploymentAvailability(d *appsv1.Deployment) } } -// MarkEventType sets the condition that the source has set its event type. -func (s *PingSourceStatus) MarkEventType() { - PingSourceCondSet.Manage(s).MarkTrue(PingSourceConditionEventTypeProvided) -} - -// MarkNoEventType sets the condition that the source does not its event type configured. -func (s *PingSourceStatus) MarkNoEventType(reason, messageFormat string, messageA ...interface{}) { - PingSourceCondSet.Manage(s).MarkFalse(PingSourceConditionEventTypeProvided, reason, messageFormat, messageA...) -} - // MarkResourcesCorrect sets the condition that the source resources are properly parsable quantities func (s *PingSourceStatus) MarkResourcesCorrect() { PingSourceCondSet.Manage(s).MarkTrue(PingSourceConditionResources) diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha1/ping_types.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha1/ping_types.go index c500c305..578c792a 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha1/ping_types.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha1/ping_types.go @@ -96,14 +96,14 @@ type PingSourceSpec struct { // PingSourceStatus defines the observed state of PingSource. type PingSourceStatus struct { - // inherits duck/v1 Status, which currently provides: - // * ObservedGeneration - the 'Generation' of the Service that was last processed by the controller. - // * Conditions - the latest available observations of a resource's current state. - duckv1.Status `json:",inline"` - - // SinkURI is the current active sink URI that has been configured for the PingSource. - // +optional - SinkURI *apis.URL `json:"sinkUri,omitempty"` + // inherits duck/v1 SourceStatus, which currently provides: + // * ObservedGeneration - the 'Generation' of the Service that was last + // processed by the controller. + // * Conditions - the latest available observations of a resource's current + // state. + // * SinkURI - the current active sink URI that has been configured for the + // Source. + duckv1.SourceStatus `json:",inline"` } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha1/ping_validation.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha1/ping_validation.go index 5fbc1eeb..40cd8b95 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha1/ping_validation.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha1/ping_validation.go @@ -21,10 +21,13 @@ import ( "github.com/robfig/cron" "knative.dev/pkg/apis" + + "knative.dev/eventing/pkg/apis/sources/v1alpha2" ) func (c *PingSource) Validate(ctx context.Context) *apis.FieldError { - return c.Spec.Validate(ctx).ViaField("spec") + errs := c.Spec.Validate(ctx).ViaField("spec") + return v1alpha2.ValidateAnnotations(errs, c.Annotations) } func (cs *PingSourceSpec) Validate(ctx context.Context) *apis.FieldError { diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha1/zz_generated.deepcopy.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha1/zz_generated.deepcopy.go index 30c969b9..448fa4a8 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha1/zz_generated.deepcopy.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha1/zz_generated.deepcopy.go @@ -21,10 +21,8 @@ limitations under the License. package v1alpha1 import ( - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" v1alpha2 "knative.dev/eventing/pkg/apis/sources/v1alpha2" - apis "knative.dev/pkg/apis" v1 "knative.dev/pkg/apis/duck/v1" v1beta1 "knative.dev/pkg/apis/duck/v1beta1" ) @@ -128,15 +126,10 @@ func (in *ApiServerSourceSpec) DeepCopyInto(out *ApiServerSourceSpec) { *out = new(v1.CloudEventOverrides) (*in).DeepCopyInto(*out) } - if in.LabelSelector != nil { - in, out := &in.LabelSelector, &out.LabelSelector - *out = new(metav1.LabelSelector) - (*in).DeepCopyInto(*out) - } if in.ResourceOwner != nil { in, out := &in.ResourceOwner, &out.ResourceOwner *out = new(v1alpha2.APIVersionKind) - (*in).DeepCopyInto(*out) + **out = **in } return } @@ -309,12 +302,7 @@ func (in *PingSourceSpec) DeepCopy() *PingSourceSpec { // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PingSourceStatus) DeepCopyInto(out *PingSourceStatus) { *out = *in - in.Status.DeepCopyInto(&out.Status) - if in.SinkURI != nil { - in, out := &in.SinkURI, &out.SinkURI - *out = new(apis.URL) - (*in).DeepCopyInto(*out) - } + in.SourceStatus.DeepCopyInto(&out.SourceStatus) return } diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/apiserver_defaults.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/apiserver_defaults.go index c9cc12d2..11122974 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/apiserver_defaults.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/apiserver_defaults.go @@ -33,6 +33,4 @@ func (ss *ApiServerSourceSpec) SetDefaults(ctx context.Context) { if ss.ServiceAccountName == "" { ss.ServiceAccountName = "default" } - - // TODO anything? } diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/apiserver_types.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/apiserver_types.go index bb411ca4..f0fa827f 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/apiserver_types.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/apiserver_types.go @@ -25,6 +25,7 @@ import ( ) // +genclient +// +genreconciler // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +k8s:defaulter-gen=true @@ -62,6 +63,16 @@ const ( ApiServerSourceDeleteRefEventType = "dev.knative.apiserver.ref.delete" ) +// ApiServerSourceEventTypes is the list of CloudEvent types the ApiServerSource emits. +var ApiServerSourceEventTypes = []string{ + ApiServerSourceAddEventType, + ApiServerSourceDeleteEventType, + ApiServerSourceUpdateEventType, + ApiServerSourceAddRefEventType, + ApiServerSourceDeleteRefEventType, + ApiServerSourceUpdateRefEventType, +} + // ApiServerSourceSpec defines the desired state of ApiServerSource type ApiServerSourceSpec struct { // inherits duck/v1 SourceSpec, which currently provides: @@ -71,16 +82,11 @@ type ApiServerSourceSpec struct { // and modifications of the event sent to the sink. duckv1.SourceSpec `json:",inline"` - // Resource is the resource this source will track and send related - // lifecycle events from the Kubernetes ApiServer. + // Resource are the resources this source will track and send related + // lifecycle events from the Kubernetes ApiServer, with an optional label + // selector to help filter. // +required - Resources []APIVersionKind `json:"resources,omitempty"` - - // LabelSelector filters this source to objects to those resources pass the - // label selector. - // More info: http://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors - // +optional - LabelSelector *metav1.LabelSelector `json:"selector,omitempty"` + Resources []APIVersionKindSelector `json:"resources,omitempty"` // ResourceOwner is an additional filter to only track resources that are // owned by a specific resource type. If ResourceOwner matches Resources[n] @@ -116,13 +122,27 @@ type ApiServerSourceStatus struct { // APIVersionKind is an APIVersion and Kind tuple. type APIVersionKind struct { // APIVersion - the API version of the resource to watch. - // +optional - APIVersion *string `json:"apiVersion"` + APIVersion string `json:"apiVersion"` + + // Kind of the resource to watch. + // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + Kind string `json:"kind"` +} + +// APIVersionKindSelector is an APIVersion Kind tuple with a LabelSelector. +type APIVersionKindSelector struct { + // APIVersion - the API version of the resource to watch. + APIVersion string `json:"apiVersion"` // Kind of the resource to watch. // More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds + Kind string `json:"kind"` + + // LabelSelector filters this source to objects to those resources pass the + // label selector. + // More info: http://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors // +optional - Kind *string `json:"kind"` + LabelSelector *metav1.LabelSelector `json:"selector,omitempty"` } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/apiserver_validation.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/apiserver_validation.go index 0b19d438..9efcf2d7 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/apiserver_validation.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/apiserver_validation.go @@ -18,6 +18,9 @@ package v1alpha2 import ( "context" + "strings" + + "k8s.io/apimachinery/pkg/runtime/schema" "knative.dev/pkg/apis" ) @@ -36,10 +39,6 @@ func (c *ApiServerSource) Validate(ctx context.Context) *apis.FieldError { func (cs *ApiServerSourceSpec) Validate(ctx context.Context) *apis.FieldError { var errs *apis.FieldError - if len(cs.Resources) == 0 { - errs = errs.Also(apis.ErrMissingField("resources")) - } - // Validate mode, if can be empty or set as certain value switch cs.EventMode { case ReferenceMode, ResourceMode: @@ -51,5 +50,28 @@ func (cs *ApiServerSourceSpec) Validate(ctx context.Context) *apis.FieldError { // Validate sink errs = errs.Also(cs.Sink.Validate(ctx).ViaField("sink")) + if len(cs.Resources) == 0 { + errs = errs.Also(apis.ErrMissingField("resources")) + } + for i, res := range cs.Resources { + _, err := schema.ParseGroupVersion(res.APIVersion) + if err != nil { + errs = errs.Also(apis.ErrInvalidValue(res.APIVersion, "apiVersion").ViaFieldIndex("resources", i)) + } + if strings.TrimSpace(res.Kind) == "" { + errs = errs.Also(apis.ErrMissingField("kind").ViaFieldIndex("resources", i)) + } + } + + if cs.ResourceOwner != nil { + _, err := schema.ParseGroupVersion(cs.ResourceOwner.APIVersion) + if err != nil { + errs = errs.Also(apis.ErrInvalidValue(cs.ResourceOwner.APIVersion, "apiVersion").ViaField("owner")) + } + if strings.TrimSpace(cs.ResourceOwner.Kind) == "" { + errs = errs.Also(apis.ErrMissingField("kind").ViaField("owner")) + } + } + return errs } diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/containersource_defaults.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/container_defaults.go similarity index 54% rename from plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/containersource_defaults.go rename to plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/container_defaults.go index d9918e38..adaadb3f 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/containersource_defaults.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/container_defaults.go @@ -1,5 +1,5 @@ /* -Copyright 2019 The Knative Authors +Copyright 2020 The Knative Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,16 +14,29 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1alpha1 +package v1alpha2 import ( "context" + "fmt" + + corev1 "k8s.io/api/core/v1" + "knative.dev/pkg/apis" ) func (s *ContainerSource) SetDefaults(ctx context.Context) { - s.Spec.SetDefaults(ctx) + withName := apis.WithinParent(ctx, s.ObjectMeta) + s.Spec.SetDefaults(withName) } func (ss *ContainerSourceSpec) SetDefaults(ctx context.Context) { - // TODO anything? + containers := make([]corev1.Container, 0, len(ss.Template.Spec.Containers)) + for i, c := range ss.Template.Spec.Containers { + // If the Container specified has no name, then default to "_". + if c.Name == "" { + c.Name = fmt.Sprintf("%s-%d", apis.ParentMeta(ctx).Name, i) + } + containers = append(containers, c) + } + ss.Template.Spec.Containers = containers } diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/container_lifecycle.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/container_lifecycle.go new file mode 100644 index 00000000..7cecfd38 --- /dev/null +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/container_lifecycle.go @@ -0,0 +1,92 @@ +/* +Copyright 2020 The Knative 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 v1alpha2 + +import ( + appsv1 "k8s.io/api/apps/v1" + corev1 "k8s.io/api/core/v1" + "knative.dev/eventing/pkg/apis/duck" + "knative.dev/pkg/apis" +) + +const ( + // ContainerSourceConditionReady has status True when the ContainerSource is ready to send events. + ContainerSourceConditionReady = apis.ConditionReady + + // ContainerSourceConditionSinkBindingReady has status True when the ContainerSource's SinkBinding is ready. + ContainerSourceConditionSinkBindingReady apis.ConditionType = "SinkBindingReady" + + // ContainerSourceConditionReceiveAdapterReady has status True when the ContainerSource's ReceiveAdapter is ready. + ContainerSourceConditionReceiveAdapterReady apis.ConditionType = "ReceiveAdapterReady" +) + +var containerCondSet = apis.NewLivingConditionSet( + ContainerSourceConditionSinkBindingReady, + ContainerSourceConditionReceiveAdapterReady, +) + +// GetCondition returns the condition currently associated with the given type, or nil. +func (s *ContainerSourceStatus) GetCondition(t apis.ConditionType) *apis.Condition { + return containerCondSet.Manage(s).GetCondition(t) +} + +// IsReady returns true if the resource is ready overall. +func (s *ContainerSourceStatus) IsReady() bool { + return containerCondSet.Manage(s).IsHappy() +} + +// InitializeConditions sets relevant unset conditions to Unknown state. +func (s *ContainerSourceStatus) InitializeConditions() { + containerCondSet.Manage(s).InitializeConditions() +} + +// PropagateSinkBindingStatus uses the availability of the provided Deployment to determine if +// ContainerSourceConditionSinkBindingReady should be marked as true, false or unknown. +func (s *ContainerSourceStatus) PropagateSinkBindingStatus(status *SinkBindingStatus) { + // Do not copy conditions nor observedGeneration + conditions := s.Conditions + observedGeneration := s.ObservedGeneration + s.SourceStatus = status.SourceStatus + s.Conditions = conditions + s.ObservedGeneration = observedGeneration + + cond := status.GetCondition(apis.ConditionReady) + switch { + case cond == nil: + containerCondSet.Manage(s).MarkUnknown(ContainerSourceConditionSinkBindingReady, "", "") + case cond.Status == corev1.ConditionTrue: + containerCondSet.Manage(s).MarkTrue(ContainerSourceConditionSinkBindingReady) + case cond.Status == corev1.ConditionFalse: + containerCondSet.Manage(s).MarkFalse(ContainerSourceConditionSinkBindingReady, cond.Reason, cond.Message) + case cond.Status == corev1.ConditionUnknown: + containerCondSet.Manage(s).MarkUnknown(ContainerSourceConditionSinkBindingReady, cond.Reason, cond.Message) + default: + containerCondSet.Manage(s).MarkUnknown(ContainerSourceConditionSinkBindingReady, cond.Reason, cond.Message) + } +} + +// PropagateReceiveAdapterStatus uses the availability of the provided Deployment to determine if +// ContainerSourceConditionReceiveAdapterReady should be marked as true or false. +func (s *ContainerSourceStatus) PropagateReceiveAdapterStatus(d *appsv1.Deployment) { + if duck.DeploymentIsAvailable(&d.Status, false) { + containerCondSet.Manage(s).MarkTrue(ContainerSourceConditionReceiveAdapterReady) + } else { + // I don't know how to propagate the status well, so just give the name of the Deployment + // for now. + containerCondSet.Manage(s).MarkFalse(ContainerSourceConditionReceiveAdapterReady, "DeploymentUnavailable", "The Deployment '%s' is unavailable.", d.Name) + } +} diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/containersource_types.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/container_types.go similarity index 51% rename from plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/containersource_types.go rename to plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/container_types.go index 1b010984..795fdd97 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/containersource_types.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/container_types.go @@ -1,5 +1,5 @@ /* -Copyright 2019 The Knative Authors +Copyright 2020 The Knative Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,7 +14,7 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1alpha1 +package v1alpha2 import ( corev1 "k8s.io/api/core/v1" @@ -23,19 +23,15 @@ import ( "k8s.io/apimachinery/pkg/runtime/schema" "knative.dev/pkg/apis" duckv1 "knative.dev/pkg/apis/duck/v1" - duckv1beta1 "knative.dev/pkg/apis/duck/v1beta1" "knative.dev/pkg/kmeta" ) // +genclient +// +genreconciler // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object -// +k8s:defaulter-gen=true // ContainerSource is the Schema for the containersources API type ContainerSource struct { - // Deprecated allows ContainerSource to have a deprecated message. - Deprecated - metav1.TypeMeta `json:",inline"` metav1.ObjectMeta `json:"metadata,omitempty"` @@ -44,50 +40,24 @@ type ContainerSource struct { } var ( - _ runtime.Object = (*ContainerSource)(nil) - - // Check that we can create OwnerReferences to a ContainerSource. + _ runtime.Object = (*ContainerSource)(nil) _ kmeta.OwnerRefable = (*ContainerSource)(nil) - - // Check that ContainerSource can return its spec untyped. - _ apis.HasSpec = (*ContainerSource)(nil) + _ apis.Validatable = (*ContainerSource)(nil) + _ apis.Defaultable = (*ContainerSource)(nil) + _ apis.HasSpec = (*ContainerSource)(nil) ) // ContainerSourceSpec defines the desired state of ContainerSource type ContainerSourceSpec struct { + // inherits duck/v1 SourceSpec, which currently provides: + // * Sink - a reference to an object that will resolve to a domain name or + // a URI directly to use as the sink. + // * CloudEventOverrides - defines overrides to control the output format + // and modifications of the event sent to the sink. + duckv1.SourceSpec `json:",inline"` + // Template describes the pods that will be created - // +optional - Template *corev1.PodTemplateSpec `json:"template,omitempty"` - - // DeprecatedImage is the image to run inside of the container. - // This field is to be deprecated. Use `Template` instead. - // When `Template` is set, this field is ignored. - // +kubebuilder:validation:MinLength=1 - DeprecatedImage string `json:"image,omitempty"` - - // DeprecatedArgs are passed to the ContainerSpec as they are. - // This field is to be deprecated. Use `Template` instead. - // When `Template` is set, this field is ignored. - DeprecatedArgs []string `json:"args,omitempty"` - - // DeprecatedEnv is the list of environment variables to set in the container. - // Cannot be updated. - // This field is to be deprecated. Use `Template` instead. - // When `Template` is set, this field is ignored. - // +optional - // +patchMergeKey=name - // +patchStrategy=merge - DeprecatedEnv []corev1.EnvVar `json:"env,omitempty" patchStrategy:"merge" patchMergeKey:"name"` - - // DeprecatedServiceAccountName is the name of the ServiceAccount to use to run this - // source. - // This field is to be deprecated. Use `Template` instead. - // When `Template` is set, this field is ignored. - // +optional - DeprecatedServiceAccountName string `json:"serviceAccountName,omitempty"` - - // Sink is a reference to an object that will resolve to a domain name to use as the sink. - Sink *duckv1beta1.Destination `json:"sink,omitempty"` + Template corev1.PodTemplateSpec `json:"template"` } // GetGroupVersionKind returns the GroupVersionKind. @@ -97,14 +67,14 @@ func (s *ContainerSource) GetGroupVersionKind() schema.GroupVersionKind { // ContainerSourceStatus defines the observed state of ContainerSource type ContainerSourceStatus struct { - // inherits duck/v1 Status, which currently provides: - // * ObservedGeneration - the 'Generation' of the Service that was last processed by the controller. - // * Conditions - the latest available observations of a resource's current state. - duckv1.Status `json:",inline"` - - // SinkURI is the current active sink URI that has been configured for the ContainerSource. - // +optional - SinkURI string `json:"sinkUri,omitempty"` + // inherits duck/v1 SourceStatus, which currently provides: + // * ObservedGeneration - the 'Generation' of the Service that was last + // processed by the controller. + // * Conditions - the latest available observations of a resource's current + // state. + // * SinkURI - the current active sink URI that has been configured for the + // Source. + duckv1.SourceStatus `json:",inline"` } // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/containersource_validation.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/container_validation.go similarity index 55% rename from plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/containersource_validation.go rename to plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/container_validation.go index 5d4f9c6d..167435bf 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/legacysources/v1alpha1/containersource_validation.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/container_validation.go @@ -1,5 +1,5 @@ /* -Copyright 2019 The Knative Authors +Copyright 2020 The Knative Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. @@ -14,11 +14,12 @@ See the License for the specific language governing permissions and limitations under the License. */ -package v1alpha1 +package v1alpha2 import ( "context" + corev1 "k8s.io/api/core/v1" "knative.dev/pkg/apis" ) @@ -28,11 +29,31 @@ func (c *ContainerSource) Validate(ctx context.Context) *apis.FieldError { func (cs *ContainerSourceSpec) Validate(ctx context.Context) *apis.FieldError { var errs *apis.FieldError - if cs.Sink == nil { - fe := apis.ErrMissingField("sink") - errs = errs.Also(fe) - } else if fe := cs.Sink.Validate(ctx); fe != nil { + if fe := cs.Sink.Validate(ctx); fe != nil { errs = errs.Also(fe.ViaField("sink")) } + + // Validate there is at least a container + if cs.Template.Spec.Containers == nil || len(cs.Template.Spec.Containers) == 0 { + fe := apis.ErrMissingField("containers") + errs = errs.Also(fe) + } else { + for i, c := range cs.Template.Spec.Containers { + if ce := isValidContainer(&c); ce != nil { + errs = errs.Also(ce.ViaFieldIndex("containers", i)) + } + } + } + return errs +} + +func isValidContainer(c *corev1.Container) *apis.FieldError { + var errs *apis.FieldError + if c.Name == "" { + errs = errs.Also(apis.ErrMissingField("name")) + } + if c.Image == "" { + errs = errs.Also(apis.ErrMissingField("image")) + } return errs } diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/ping_types.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/ping_types.go index 737dcad3..bd5823ae 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/ping_types.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/ping_types.go @@ -26,6 +26,7 @@ import ( ) // +genclient +// +genreconciler // +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object // +k8s:defaulter-gen=true diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/ping_validation.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/ping_validation.go index 589d708b..826c5ed4 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/ping_validation.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/ping_validation.go @@ -21,10 +21,13 @@ import ( "github.com/robfig/cron" "knative.dev/pkg/apis" + + "knative.dev/eventing/pkg/apis/eventing" ) func (c *PingSource) Validate(ctx context.Context) *apis.FieldError { - return c.Spec.Validate(ctx).ViaField("spec") + errs := c.Spec.Validate(ctx).ViaField("spec") + return ValidateAnnotations(errs, c.Annotations) } func (cs *PingSourceSpec) Validate(ctx context.Context) *apis.FieldError { @@ -40,3 +43,16 @@ func (cs *PingSourceSpec) Validate(ctx context.Context) *apis.FieldError { } return errs } + +func ValidateAnnotations(errs *apis.FieldError, annotations map[string]string) *apis.FieldError { + if annotations != nil { + if scope, ok := annotations[eventing.ScopeAnnotationKey]; ok { + if scope != eventing.ScopeResource && scope != eventing.ScopeCluster { + iv := apis.ErrInvalidValue(scope, "") + iv.Details = "expected either 'cluster' or 'resource'" + errs = errs.Also(iv.ViaFieldKey("annotations", eventing.ScopeAnnotationKey).ViaField("metadata")) + } + } + } + return errs +} diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/register.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/register.go index 9f57ddeb..3e19edcf 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/register.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/register.go @@ -45,12 +45,14 @@ var ( // Adds the list of known types to Scheme. func addKnownTypes(scheme *runtime.Scheme) error { scheme.AddKnownTypes(SchemeGroupVersion, - //&ApiServerSource{}, - //&ApiServerSourceList{}, + &ApiServerSource{}, + &ApiServerSourceList{}, &PingSource{}, &PingSourceList{}, &SinkBinding{}, &SinkBindingList{}, + &ContainerSource{}, + &ContainerSourceList{}, ) metav1.AddToGroupVersion(scheme, SchemeGroupVersion) return nil diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/zz_generated.deepcopy.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/zz_generated.deepcopy.go index eb0f9f70..9be2e52e 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/zz_generated.deepcopy.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/apis/sources/v1alpha2/zz_generated.deepcopy.go @@ -28,16 +28,6 @@ import ( // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *APIVersionKind) DeepCopyInto(out *APIVersionKind) { *out = *in - if in.APIVersion != nil { - in, out := &in.APIVersion, &out.APIVersion - *out = new(string) - **out = **in - } - if in.Kind != nil { - in, out := &in.Kind, &out.Kind - *out = new(string) - **out = **in - } return } @@ -51,6 +41,27 @@ func (in *APIVersionKind) DeepCopy() *APIVersionKind { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *APIVersionKindSelector) DeepCopyInto(out *APIVersionKindSelector) { + *out = *in + if in.LabelSelector != nil { + in, out := &in.LabelSelector, &out.LabelSelector + *out = new(v1.LabelSelector) + (*in).DeepCopyInto(*out) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new APIVersionKindSelector. +func (in *APIVersionKindSelector) DeepCopy() *APIVersionKindSelector { + if in == nil { + return nil + } + out := new(APIVersionKindSelector) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ApiServerSource) DeepCopyInto(out *ApiServerSource) { *out = *in @@ -118,20 +129,15 @@ func (in *ApiServerSourceSpec) DeepCopyInto(out *ApiServerSourceSpec) { in.SourceSpec.DeepCopyInto(&out.SourceSpec) if in.Resources != nil { in, out := &in.Resources, &out.Resources - *out = make([]APIVersionKind, len(*in)) + *out = make([]APIVersionKindSelector, len(*in)) for i := range *in { (*in)[i].DeepCopyInto(&(*out)[i]) } } - if in.LabelSelector != nil { - in, out := &in.LabelSelector, &out.LabelSelector - *out = new(v1.LabelSelector) - (*in).DeepCopyInto(*out) - } if in.ResourceOwner != nil { in, out := &in.ResourceOwner, &out.ResourceOwner *out = new(APIVersionKind) - (*in).DeepCopyInto(*out) + **out = **in } return } @@ -163,6 +169,102 @@ func (in *ApiServerSourceStatus) DeepCopy() *ApiServerSourceStatus { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ContainerSource) DeepCopyInto(out *ContainerSource) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ObjectMeta.DeepCopyInto(&out.ObjectMeta) + in.Spec.DeepCopyInto(&out.Spec) + in.Status.DeepCopyInto(&out.Status) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ContainerSource. +func (in *ContainerSource) DeepCopy() *ContainerSource { + if in == nil { + return nil + } + out := new(ContainerSource) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ContainerSource) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ContainerSourceList) DeepCopyInto(out *ContainerSourceList) { + *out = *in + out.TypeMeta = in.TypeMeta + in.ListMeta.DeepCopyInto(&out.ListMeta) + if in.Items != nil { + in, out := &in.Items, &out.Items + *out = make([]ContainerSource, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ContainerSourceList. +func (in *ContainerSourceList) DeepCopy() *ContainerSourceList { + if in == nil { + return nil + } + out := new(ContainerSourceList) + in.DeepCopyInto(out) + return out +} + +// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object. +func (in *ContainerSourceList) DeepCopyObject() runtime.Object { + if c := in.DeepCopy(); c != nil { + return c + } + return nil +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ContainerSourceSpec) DeepCopyInto(out *ContainerSourceSpec) { + *out = *in + in.SourceSpec.DeepCopyInto(&out.SourceSpec) + in.Template.DeepCopyInto(&out.Template) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ContainerSourceSpec. +func (in *ContainerSourceSpec) DeepCopy() *ContainerSourceSpec { + if in == nil { + return nil + } + out := new(ContainerSourceSpec) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ContainerSourceStatus) DeepCopyInto(out *ContainerSourceStatus) { + *out = *in + in.SourceStatus.DeepCopyInto(&out.SourceStatus) + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ContainerSourceStatus. +func (in *ContainerSourceStatus) DeepCopy() *ContainerSourceStatus { + if in == nil { + return nil + } + out := new(ContainerSourceStatus) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *PingSource) DeepCopyInto(out *PingSource) { *out = *in diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1alpha2/containersource.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1alpha2/containersource.go new file mode 100644 index 00000000..1e884bf2 --- /dev/null +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1alpha2/containersource.go @@ -0,0 +1,191 @@ +/* +Copyright 2020 The Knative 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. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package v1alpha2 + +import ( + "time" + + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + rest "k8s.io/client-go/rest" + v1alpha2 "knative.dev/eventing/pkg/apis/sources/v1alpha2" + scheme "knative.dev/eventing/pkg/client/clientset/versioned/scheme" +) + +// ContainerSourcesGetter has a method to return a ContainerSourceInterface. +// A group's client should implement this interface. +type ContainerSourcesGetter interface { + ContainerSources(namespace string) ContainerSourceInterface +} + +// ContainerSourceInterface has methods to work with ContainerSource resources. +type ContainerSourceInterface interface { + Create(*v1alpha2.ContainerSource) (*v1alpha2.ContainerSource, error) + Update(*v1alpha2.ContainerSource) (*v1alpha2.ContainerSource, error) + UpdateStatus(*v1alpha2.ContainerSource) (*v1alpha2.ContainerSource, error) + Delete(name string, options *v1.DeleteOptions) error + DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error + Get(name string, options v1.GetOptions) (*v1alpha2.ContainerSource, error) + List(opts v1.ListOptions) (*v1alpha2.ContainerSourceList, error) + Watch(opts v1.ListOptions) (watch.Interface, error) + Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha2.ContainerSource, err error) + ContainerSourceExpansion +} + +// containerSources implements ContainerSourceInterface +type containerSources struct { + client rest.Interface + ns string +} + +// newContainerSources returns a ContainerSources +func newContainerSources(c *SourcesV1alpha2Client, namespace string) *containerSources { + return &containerSources{ + client: c.RESTClient(), + ns: namespace, + } +} + +// Get takes name of the containerSource, and returns the corresponding containerSource object, and an error if there is any. +func (c *containerSources) Get(name string, options v1.GetOptions) (result *v1alpha2.ContainerSource, err error) { + result = &v1alpha2.ContainerSource{} + err = c.client.Get(). + Namespace(c.ns). + Resource("containersources"). + Name(name). + VersionedParams(&options, scheme.ParameterCodec). + Do(). + Into(result) + return +} + +// List takes label and field selectors, and returns the list of ContainerSources that match those selectors. +func (c *containerSources) List(opts v1.ListOptions) (result *v1alpha2.ContainerSourceList, err error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + result = &v1alpha2.ContainerSourceList{} + err = c.client.Get(). + Namespace(c.ns). + Resource("containersources"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Do(). + Into(result) + return +} + +// Watch returns a watch.Interface that watches the requested containerSources. +func (c *containerSources) Watch(opts v1.ListOptions) (watch.Interface, error) { + var timeout time.Duration + if opts.TimeoutSeconds != nil { + timeout = time.Duration(*opts.TimeoutSeconds) * time.Second + } + opts.Watch = true + return c.client.Get(). + Namespace(c.ns). + Resource("containersources"). + VersionedParams(&opts, scheme.ParameterCodec). + Timeout(timeout). + Watch() +} + +// Create takes the representation of a containerSource and creates it. Returns the server's representation of the containerSource, and an error, if there is any. +func (c *containerSources) Create(containerSource *v1alpha2.ContainerSource) (result *v1alpha2.ContainerSource, err error) { + result = &v1alpha2.ContainerSource{} + err = c.client.Post(). + Namespace(c.ns). + Resource("containersources"). + Body(containerSource). + Do(). + Into(result) + return +} + +// Update takes the representation of a containerSource and updates it. Returns the server's representation of the containerSource, and an error, if there is any. +func (c *containerSources) Update(containerSource *v1alpha2.ContainerSource) (result *v1alpha2.ContainerSource, err error) { + result = &v1alpha2.ContainerSource{} + err = c.client.Put(). + Namespace(c.ns). + Resource("containersources"). + Name(containerSource.Name). + Body(containerSource). + Do(). + Into(result) + return +} + +// UpdateStatus was generated because the type contains a Status member. +// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). + +func (c *containerSources) UpdateStatus(containerSource *v1alpha2.ContainerSource) (result *v1alpha2.ContainerSource, err error) { + result = &v1alpha2.ContainerSource{} + err = c.client.Put(). + Namespace(c.ns). + Resource("containersources"). + Name(containerSource.Name). + SubResource("status"). + Body(containerSource). + Do(). + Into(result) + return +} + +// Delete takes name of the containerSource and deletes it. Returns an error if one occurs. +func (c *containerSources) Delete(name string, options *v1.DeleteOptions) error { + return c.client.Delete(). + Namespace(c.ns). + Resource("containersources"). + Name(name). + Body(options). + Do(). + Error() +} + +// DeleteCollection deletes a collection of objects. +func (c *containerSources) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { + var timeout time.Duration + if listOptions.TimeoutSeconds != nil { + timeout = time.Duration(*listOptions.TimeoutSeconds) * time.Second + } + return c.client.Delete(). + Namespace(c.ns). + Resource("containersources"). + VersionedParams(&listOptions, scheme.ParameterCodec). + Timeout(timeout). + Body(options). + Do(). + Error() +} + +// Patch applies the patch and returns the patched containerSource. +func (c *containerSources) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha2.ContainerSource, err error) { + result = &v1alpha2.ContainerSource{} + err = c.client.Patch(pt). + Namespace(c.ns). + Resource("containersources"). + SubResource(subresources...). + Name(name). + Body(data). + Do(). + Into(result) + return +} diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1alpha2/fake/fake_containersource.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1alpha2/fake/fake_containersource.go new file mode 100644 index 00000000..c990e643 --- /dev/null +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1alpha2/fake/fake_containersource.go @@ -0,0 +1,140 @@ +/* +Copyright 2020 The Knative 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. +*/ + +// Code generated by client-gen. DO NOT EDIT. + +package fake + +import ( + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + labels "k8s.io/apimachinery/pkg/labels" + schema "k8s.io/apimachinery/pkg/runtime/schema" + types "k8s.io/apimachinery/pkg/types" + watch "k8s.io/apimachinery/pkg/watch" + testing "k8s.io/client-go/testing" + v1alpha2 "knative.dev/eventing/pkg/apis/sources/v1alpha2" +) + +// FakeContainerSources implements ContainerSourceInterface +type FakeContainerSources struct { + Fake *FakeSourcesV1alpha2 + ns string +} + +var containersourcesResource = schema.GroupVersionResource{Group: "sources.knative.dev", Version: "v1alpha2", Resource: "containersources"} + +var containersourcesKind = schema.GroupVersionKind{Group: "sources.knative.dev", Version: "v1alpha2", Kind: "ContainerSource"} + +// Get takes name of the containerSource, and returns the corresponding containerSource object, and an error if there is any. +func (c *FakeContainerSources) Get(name string, options v1.GetOptions) (result *v1alpha2.ContainerSource, err error) { + obj, err := c.Fake. + Invokes(testing.NewGetAction(containersourcesResource, c.ns, name), &v1alpha2.ContainerSource{}) + + if obj == nil { + return nil, err + } + return obj.(*v1alpha2.ContainerSource), err +} + +// List takes label and field selectors, and returns the list of ContainerSources that match those selectors. +func (c *FakeContainerSources) List(opts v1.ListOptions) (result *v1alpha2.ContainerSourceList, err error) { + obj, err := c.Fake. + Invokes(testing.NewListAction(containersourcesResource, containersourcesKind, c.ns, opts), &v1alpha2.ContainerSourceList{}) + + if obj == nil { + return nil, err + } + + label, _, _ := testing.ExtractFromListOptions(opts) + if label == nil { + label = labels.Everything() + } + list := &v1alpha2.ContainerSourceList{ListMeta: obj.(*v1alpha2.ContainerSourceList).ListMeta} + for _, item := range obj.(*v1alpha2.ContainerSourceList).Items { + if label.Matches(labels.Set(item.Labels)) { + list.Items = append(list.Items, item) + } + } + return list, err +} + +// Watch returns a watch.Interface that watches the requested containerSources. +func (c *FakeContainerSources) Watch(opts v1.ListOptions) (watch.Interface, error) { + return c.Fake. + InvokesWatch(testing.NewWatchAction(containersourcesResource, c.ns, opts)) + +} + +// Create takes the representation of a containerSource and creates it. Returns the server's representation of the containerSource, and an error, if there is any. +func (c *FakeContainerSources) Create(containerSource *v1alpha2.ContainerSource) (result *v1alpha2.ContainerSource, err error) { + obj, err := c.Fake. + Invokes(testing.NewCreateAction(containersourcesResource, c.ns, containerSource), &v1alpha2.ContainerSource{}) + + if obj == nil { + return nil, err + } + return obj.(*v1alpha2.ContainerSource), err +} + +// Update takes the representation of a containerSource and updates it. Returns the server's representation of the containerSource, and an error, if there is any. +func (c *FakeContainerSources) Update(containerSource *v1alpha2.ContainerSource) (result *v1alpha2.ContainerSource, err error) { + obj, err := c.Fake. + Invokes(testing.NewUpdateAction(containersourcesResource, c.ns, containerSource), &v1alpha2.ContainerSource{}) + + if obj == nil { + return nil, err + } + return obj.(*v1alpha2.ContainerSource), err +} + +// UpdateStatus was generated because the type contains a Status member. +// Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). +func (c *FakeContainerSources) UpdateStatus(containerSource *v1alpha2.ContainerSource) (*v1alpha2.ContainerSource, error) { + obj, err := c.Fake. + Invokes(testing.NewUpdateSubresourceAction(containersourcesResource, "status", c.ns, containerSource), &v1alpha2.ContainerSource{}) + + if obj == nil { + return nil, err + } + return obj.(*v1alpha2.ContainerSource), err +} + +// Delete takes name of the containerSource and deletes it. Returns an error if one occurs. +func (c *FakeContainerSources) Delete(name string, options *v1.DeleteOptions) error { + _, err := c.Fake. + Invokes(testing.NewDeleteAction(containersourcesResource, c.ns, name), &v1alpha2.ContainerSource{}) + + return err +} + +// DeleteCollection deletes a collection of objects. +func (c *FakeContainerSources) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { + action := testing.NewDeleteCollectionAction(containersourcesResource, c.ns, listOptions) + + _, err := c.Fake.Invokes(action, &v1alpha2.ContainerSourceList{}) + return err +} + +// Patch applies the patch and returns the patched containerSource. +func (c *FakeContainerSources) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha2.ContainerSource, err error) { + obj, err := c.Fake. + Invokes(testing.NewPatchSubresourceAction(containersourcesResource, c.ns, name, pt, data, subresources...), &v1alpha2.ContainerSource{}) + + if obj == nil { + return nil, err + } + return obj.(*v1alpha2.ContainerSource), err +} diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1alpha2/fake/fake_sources_client.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1alpha2/fake/fake_sources_client.go index 3459a1a0..fb6365ba 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1alpha2/fake/fake_sources_client.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1alpha2/fake/fake_sources_client.go @@ -32,6 +32,10 @@ func (c *FakeSourcesV1alpha2) ApiServerSources(namespace string) v1alpha2.ApiSer return &FakeApiServerSources{c, namespace} } +func (c *FakeSourcesV1alpha2) ContainerSources(namespace string) v1alpha2.ContainerSourceInterface { + return &FakeContainerSources{c, namespace} +} + func (c *FakeSourcesV1alpha2) PingSources(namespace string) v1alpha2.PingSourceInterface { return &FakePingSources{c, namespace} } diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1alpha2/generated_expansion.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1alpha2/generated_expansion.go index c4f05376..b2816d38 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1alpha2/generated_expansion.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1alpha2/generated_expansion.go @@ -20,6 +20,8 @@ package v1alpha2 type ApiServerSourceExpansion interface{} +type ContainerSourceExpansion interface{} + type PingSourceExpansion interface{} type SinkBindingExpansion interface{} diff --git a/plugins/source-github/vendor/knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1alpha2/sources_client.go b/plugins/source-github/vendor/knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1alpha2/sources_client.go index 1061b14e..e573e6dc 100644 --- a/plugins/source-github/vendor/knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1alpha2/sources_client.go +++ b/plugins/source-github/vendor/knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1alpha2/sources_client.go @@ -27,6 +27,7 @@ import ( type SourcesV1alpha2Interface interface { RESTClient() rest.Interface ApiServerSourcesGetter + ContainerSourcesGetter PingSourcesGetter SinkBindingsGetter } @@ -40,6 +41,10 @@ func (c *SourcesV1alpha2Client) ApiServerSources(namespace string) ApiServerSour return newApiServerSources(c, namespace) } +func (c *SourcesV1alpha2Client) ContainerSources(namespace string) ContainerSourceInterface { + return newContainerSources(c, namespace) +} + func (c *SourcesV1alpha2Client) PingSources(namespace string) PingSourceInterface { return newPingSources(c, namespace) } diff --git a/plugins/source-github/vendor/knative.dev/pkg/apis/contexts.go b/plugins/source-github/vendor/knative.dev/pkg/apis/contexts.go index abb5706a..735c6191 100644 --- a/plugins/source-github/vendor/knative.dev/pkg/apis/contexts.go +++ b/plugins/source-github/vendor/knative.dev/pkg/apis/contexts.go @@ -198,3 +198,16 @@ func AllowDifferentNamespace(ctx context.Context) context.Context { func IsDifferentNamespaceAllowed(ctx context.Context) bool { return ctx.Value(allowDifferentNamespace{}) != nil } + +// This is attached to contexts passed to webhook interfaces when the user has request DryRun mode. +type isDryRun struct{} + +// WithDryRun is used to indicate that this call is in DryRun mode. +func WithDryRun(ctx context.Context) context.Context { + return context.WithValue(ctx, isDryRun{}, struct{}{}) +} + +// IsDryRun indicates that this request is in DryRun mode. +func IsDryRun(ctx context.Context) bool { + return ctx.Value(isDryRun{}) != nil +} diff --git a/plugins/source-github/vendor/knative.dev/pkg/apis/duck/ABOUT.md b/plugins/source-github/vendor/knative.dev/pkg/apis/duck/ABOUT.md new file mode 100644 index 00000000..0c6edabd --- /dev/null +++ b/plugins/source-github/vendor/knative.dev/pkg/apis/duck/ABOUT.md @@ -0,0 +1,325 @@ +# Knative Duck Typing + +![A Trojan Duck](images/Knative-Duck0.png) + +**Figure 1:** How to integrate with Knative. + +## Problem statement + +In Knative, we want to support +[loose coupling](https://docs.google.com/presentation/d/1KxKAcIZyblkXbpdGVCgmzfDDIhqgUcwsa0zlABfvaXI/edit#slide=id.p) +of the building blocks we are releasing. We want users to be able to use these +building blocks together, but also support composing them with non-Knative +components as well. + +Unlike Knative’s +[pluggability story](https://docs.google.com/presentation/d/10KWynvAJYuOEWy69VBa6bHJVCqIsz1TNdEKosNvcpPY/edit#slide=id.p) +(for replacing subsystems within a building block), we do not want to require +that the systems with which we compose have **identical** APIs (distinct +implementations). However, we do need a way of accessing (reading / writing) +certain **_pieces_** of information in a structured way. + +**Enter [duck typing](https://en.wikipedia.org/wiki/Duck_typing)**. We will +define a partial schema, to which resource authors will adhere if they want to +participate within certain contexts of Knative. + +For instance, consider the partial schema: + +```yaml +foo: + bar: +``` + +Both of these resources implement the above duck type: + +```yaml +baz: 1234 +foo: + bar: asdf +blah: + blurp: true +``` + +```yaml +field: running out of ideas +foo: + bar: a different string +another: you get the point +``` + +### Reading duck-typed data + +At a high-level, reading duck-typed data is very straightforward: using the +partial object schema deserialize the resource ignoring unknown fields. The +fields we care about can then be accessed through the structured object that +represents the duck type. + +### Writing duck-typed data + +How to write duck-typed data is less straightforward because we do not want to +clobber every field we do not know about. To accomplish this, we will lean on +Kubernetes’ well established patching model. + +First, we read the resource we intend to modify as our duck type. Keeping a copy +of the original, we then modify the fields of this duck typed resource to +reflect the change we want. Lastly, we synthesize a JSON Patch of the changes +between the original and the final version and issue a Patch to the Kubernetes +API with the delta. + +Since the duck type inherently contains a subset of the fields in the resource, +the resulting JSON Patch can only contain fields relevant to the resource. + +## Example: Reading Knative-style Conditions + +In Knative, we follow the Kubernetes API principles of using `conditions` as a +key part of our resources’ status, but we go a step further in +[defining particular conventions](https://github.com/knative/serving/blob/master/docs/spec/errors.md#error-conditions-and-reporting) +on how these are used. + +To support this, we define: + +```golang +type KResource struct { +        metav1.TypeMeta   `json:",inline"` +        metav1.ObjectMeta `json:"metadata,omitempty"` + +        Status KResourceStatus `json:"status"` +} + +type KResourceStatus struct { +        Conditions Conditions `json:"conditions,omitempty"` +} + +type Conditions []Condition + +type Condition struct { +  // structure adhering to K8s API principles +  ... +} +``` + +We can now deserialize and reason about the status of any Knative-compatible +resource using this partial schema. + +## Example: Mutating Knative CRD Generations + +In Knative, all of our resources define a `.spec.generation` field, which we use +in place of `.metadata.generation` because the latter was not properly managed +by Kubernetes (prior to 1.11 with `/status` subresource). We manage bumping this +generation field in our webhook if and only if the `.spec` changed. + +To support this, we define: + +```golang +type Generational struct { +        metav1.TypeMeta   `json:",inline"` +        metav1.ObjectMeta `json:"metadata,omitempty"` + +        Spec GenerationalSpec `json:"spec"` +} + +type GenerationalSpec struct { +        Generation Generation `json:"generation,omitempty"` +} + +type Generation int64 +``` + +Using this our webhook can read the current resource’s generation, increment it, +and generate a patch to apply it. + +## Example: Mutating Core Kubernetes Resources + +Kubernetes already uses duck typing, in a way. Consider that `Deployment`, +`ReplicaSet`, `DaemonSet`, `StatefulSet`, and `Job` all embed a +`corev1.PodTemplateSpec` at the exact path: `.spec.template`. + +Consider the example duck type: + +```yaml +type PodSpecable corev1.PodTemplateSpec + +type WithPod struct { metav1.TypeMeta   `json:",inline"` metav1.ObjectMeta +`json:"metadata,omitempty"` + +Spec WithPodSpec `json:"spec,omitempty"` } + +type WithPodSpec struct { Template PodSpecable `json:"template,omitempty"` } +``` + +Using this, we can access the PodSpec of arbitrary higher-level Kubernetes +resources in a very structured way and generate patches to mutate them. +[See examples](https://github.com/knative/pkg/blob/07104dad53e803457a95306e5b1322024bd69af3/apis/duck/podspec_test.go#L49-L53). + +_You can also see a sample controller that reconciles duck-typed resources +[here](https://github.com/mattmoor/cachier)._ + +## Conventions + +Each of our duck types will consist of a single structured field that must be +enclosed within the containing resource in a particular way. + +1. This structured field will be named Fooable, +2. Fooable will be directly included via a field named + fooable, +3. Additional skeletal layers around Fooable will be defined to + fully define Fooable’s position within complete resources. + +_You can see parts of these in the examples above, however, those special cases +have been exempted from the first condition for legacy compatibility reasons._ + +For example: + +1. `type Conditions []Condition` +2. Conditions Conditions + `json:"conditions,omitempty"` +3. KResource -> KResourceStatus -> Conditions + +## Supporting Mechanics + +We will provide a number of tools to enable working with duck types without +blowing off feet. + +### Verification + +To verify that a particular resource implements a particular duck type, resource +authors are strongly encouraged to add the following as test code adjacent to +resource definitions. + +`myresource_types.go`: + +```golang +package v1alpha1 + +type MyResource struct { + ... +} +``` + +`myresource_types_test.go`: + +```golang +package v1alpha1 + +import ( + "testing" + + // This is where supporting tools for duck-typing will live. + "github.com/knative/pkg/apis/duck" + + // This is where Knative-provided duck types will live. + duckv1alpha1 "github.com/knative/pkg/apis/duck/v1alpha1" +) + +// This verifies that MyResource contains all the necessary fields for the +// given implementable duck type. +func TestType(t *testing.T) { + err := duck.VerifyType(&MyResource{}, &duckv1alpha1.Conditions{}) + if err != nil { + t.Errorf("VerifyType() = %v", err) + } +} +``` + +\_This call will create a fully populated instance of the skeletal resource +containing the Conditions and ensure that the fields can 100% roundtrip through +MyResource. + +### Patching + +To produce a patch of a particular resource modification suitable for use with +k8s.io/client-[go/dynamic](https://goto.google.com/dynamic), +developers can write: + +```golang +before := … +after := before.DeepCopy() +// modify "after" + +patch, err := duck.CreatePatch(before, after) +// check err + +bytes, err := patch.MarshalJSON() +// check err + +dynamicClient.Patch(bytes) +``` + +### Informers / Listers + +To be able to efficiently access / monitor arbitrary duck-typed resources, we +want to be able to produce an Informer / Lister for interpreting particular +resource groups as a particular duck type. + +To facilitate this, we provide several composable implementations of +`duck.InformerFactory`. + +```golang +type InformerFactory interface { +        // Get an informer/lister pair for the given resource group. +        Get(GroupVersionResource) (SharedIndexInformer, GenericLister, error) +} + + +// This produces informer/lister pairs that interpret objects in the resource group +// as the provided duck "Type" +dif := &duck.TypedInformerFactory{ +        Client:       dynaClient, +        Type:         &duckv1alpha1.Foo{}, +        ResyncPeriod: 30 * time.Second, +        StopChannel:  stopCh, +} + +// This registers the provided EventHandler with the informer each time an +// informer/lister pair is produced. +eif := &duck.EnqueueInformerFactory{ + Delegate: dif, + EventHandler: cache.ResourceEventHandlerFuncs{ + AddFunc: impl.EnqueueControllerOf, + UpdateFunc: controller.PassNew(impl.EnqueueControllerOf), + }, +} + +// This caches informer/lister pairs so that we only produce one for each GVR. +cif := &duck.CachedInformerFactory{ + Delegate: eif, +} +``` + +### Trackers + +Informers are great when you have something like an `OwnerReference` to key off +of for the association (e.g. `impl.EnqueueControllerOf`), however, when the +association is looser e.g. `corev1.ObjectReference`, then we need a way of +configuring a reconciliation trigger for the cross-reference. + +For this (generally) we have the `knative/pkg/tracker` package. Here is how it +is used with duck types: + +```golang +        c := &Reconciler{ +                Base:             reconciler.NewBase(opt, controllerAgentName), +                ... +        } +        impl := controller.NewImpl(c, c.Logger, "Revisions") + + // Calls to Track create a 30 minute lease before they must be renewed. + // Coordinate this value with controller resync periods. +        t := tracker.New(impl.EnqueueKey, 30*time.Minute) +        cif := &duck.CachedInformerFactory{ +                Delegate: &duck.EnqueueInformerFactory{ +                        Delegate: buildInformerFactory, +                        EventHandler: cache.ResourceEventHandlerFuncs{ +                                AddFunc:    t.OnChanged, +                                UpdateFunc: controller.PassNew(t.OnChanged), +                        }, +                }, +        } + +        // Now use: c.buildInformerFactory.Get() to access ObjectReferences. +        c.buildInformerFactory = buildInformerFactory + +        // Now use: c.tracker.Track(rev.Spec.BuildRef, rev) to queue rev +        // each time rev.Spec.BuildRef changes. +        c.tracker = t +``` diff --git a/plugins/source-github/vendor/knative.dev/pkg/logging/config b/plugins/source-github/vendor/knative.dev/pkg/logging/config new file mode 100644 index 00000000..2480fc6d --- /dev/null +++ b/plugins/source-github/vendor/knative.dev/pkg/logging/config @@ -0,0 +1,4 @@ +# The OWNERS file is used by prow to automatically merge approved PRs. + +approvers: +- configmap-approvers diff --git a/plugins/source-github/vendor/knative.dev/pkg/logging/config.go b/plugins/source-github/vendor/knative.dev/pkg/logging/config.go index 6f59bdec..a0fb96e2 100644 --- a/plugins/source-github/vendor/knative.dev/pkg/logging/config.go +++ b/plugins/source-github/vendor/knative.dev/pkg/logging/config.go @@ -38,7 +38,10 @@ const ( fallbackLoggerName = "fallback-logger" ) -var errEmptyLoggerConfig = errors.New("empty logger configuration") +var ( + errEmptyLoggerConfig = errors.New("empty logger configuration") + errEmptyJSONLogginString = errors.New("json logging string is empty") +) // NewLogger creates a logger with the supplied configuration. // In addition to the logger, it returns AtomicLevel that can @@ -150,17 +153,21 @@ const defaultZLC = `{ } }` +func defaultConfig() *Config { + return &Config{ + LoggingConfig: defaultZLC, + LoggingLevel: make(map[string]zapcore.Level), + } +} + // NewConfigFromMap creates a LoggingConfig from the supplied map, // expecting the given list of components. func NewConfigFromMap(data map[string]string) (*Config, error) { - lc := &Config{} + lc := defaultConfig() if zlc, ok := data[loggerConfigKey]; ok { lc.LoggingConfig = zlc - } else { - lc.LoggingConfig = defaultZLC } - lc.LoggingLevel = make(map[string]zapcore.Level) for k, v := range data { if component := strings.TrimPrefix(k, "loglevel."); component != k && component != "" { if len(v) > 0 { @@ -237,7 +244,7 @@ func ConfigMapName() string { // Returns a non-nil Config always. func JsonToLoggingConfig(jsonCfg string) (*Config, error) { if jsonCfg == "" { - return nil, errors.New("json logging string is empty") + return nil, errEmptyJSONLogginString } var configMap map[string]string @@ -248,9 +255,7 @@ func JsonToLoggingConfig(jsonCfg string) (*Config, error) { cfg, err := NewConfigFromMap(configMap) if err != nil { // Get the default config from logging package. - if cfg, err = NewConfigFromMap(nil); err != nil { - return nil, err - } + return NewConfigFromConfigMap(nil) } return cfg, nil } @@ -264,9 +269,5 @@ func LoggingConfigToJson(cfg *Config) (string, error) { jsonCfg, err := json.Marshal(map[string]string{ loggerConfigKey: cfg.LoggingConfig, }) - if err != nil { - return "", err - } - - return string(jsonCfg), nil + return string(jsonCfg), err } diff --git a/plugins/source-github/vendor/knative.dev/pkg/tracker/enqueue.go b/plugins/source-github/vendor/knative.dev/pkg/tracker/enqueue.go index a8f02ea6..fc036466 100644 --- a/plugins/source-github/vendor/knative.dev/pkg/tracker/enqueue.go +++ b/plugins/source-github/vendor/knative.dev/pkg/tracker/enqueue.go @@ -159,7 +159,7 @@ func (i *impl) TrackReference(ref Reference, obj interface{}) error { // doesn't create problems: // foo, err := lister.Get(key) // // Later... - // err := tracker.Track(fooRef, parent) + // err := tracker.TrackReference(fooRef, parent) // In this example, "Later" represents a window where "foo" may // have changed or been created while the Track is not active. // The simplest way of eliminating such a window is to call the @@ -192,7 +192,7 @@ func (i *impl) TrackReference(ref Reference, obj interface{}) error { // doesn't create problems: // foo, err := lister.Get(key) // // Later... - // err := tracker.Track(fooRef, parent) + // err := tracker.TrackReference(fooRef, parent) // In this example, "Later" represents a window where "foo" may // have changed or been created while the Track is not active. // The simplest way of eliminating such a window is to call the diff --git a/plugins/source-github/vendor/modules.txt b/plugins/source-github/vendor/modules.txt index 6caa7541..c7803214 100644 --- a/plugins/source-github/vendor/modules.txt +++ b/plugins/source-github/vendor/modules.txt @@ -2,6 +2,8 @@ github.com/PuerkitoBio/purell # github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 github.com/PuerkitoBio/urlesc +# github.com/cpuguy83/go-md2man/v2 v2.0.0 +github.com/cpuguy83/go-md2man/v2/md2man # github.com/davecgh/go-spew v1.1.1 github.com/davecgh/go-spew/spew # github.com/emicklei/go-restful v2.9.5+incompatible @@ -39,7 +41,7 @@ github.com/google/go-cmp/cmp/internal/diff github.com/google/go-cmp/cmp/internal/flags github.com/google/go-cmp/cmp/internal/function github.com/google/go-cmp/cmp/internal/value -# github.com/google/go-containerregistry v0.0.0-20200304201134-fcc8ea80e26f +# github.com/google/go-containerregistry v0.0.0-20200413145205-82d30a103c0a github.com/google/go-containerregistry/pkg/name # github.com/google/gofuzz v1.0.0 github.com/google/gofuzz @@ -80,8 +82,17 @@ github.com/magiconair/properties github.com/mailru/easyjson/buffer github.com/mailru/easyjson/jlexer github.com/mailru/easyjson/jwriter -# github.com/maximilien/kn-source-pkg v0.4.0 +# github.com/maximilien/kn-source-pkg v0.4.7 +github.com/maximilien/kn-source-pkg/pkg/client +github.com/maximilien/kn-source-pkg/pkg/commands/source +github.com/maximilien/kn-source-pkg/pkg/core +github.com/maximilien/kn-source-pkg/pkg/factories github.com/maximilien/kn-source-pkg/pkg/types +github.com/maximilien/kn-source-pkg/pkg/types/typesfakes +github.com/maximilien/kn-source-pkg/pkg/util +github.com/maximilien/kn-source-pkg/test/e2e +# github.com/mitchellh/go-homedir v1.1.0 +github.com/mitchellh/go-homedir # github.com/mitchellh/mapstructure v1.1.2 github.com/mitchellh/mapstructure # github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd @@ -96,6 +107,10 @@ github.com/peterbourgon/diskv github.com/pkg/errors # github.com/robfig/cron v1.2.0 github.com/robfig/cron +# github.com/russross/blackfriday/v2 v2.0.1 +github.com/russross/blackfriday/v2 +# github.com/shurcooL/sanitized_anchor_name v1.0.0 +github.com/shurcooL/sanitized_anchor_name # github.com/spf13/afero v1.2.2 github.com/spf13/afero github.com/spf13/afero/mem @@ -103,6 +118,7 @@ github.com/spf13/afero/mem github.com/spf13/cast # github.com/spf13/cobra v1.0.0 github.com/spf13/cobra +github.com/spf13/cobra/doc # github.com/spf13/jwalterweatherman v1.0.0 github.com/spf13/jwalterweatherman # github.com/spf13/pflag v1.0.5 @@ -120,7 +136,7 @@ go.uber.org/zap/internal/bufferpool go.uber.org/zap/internal/color go.uber.org/zap/internal/exit go.uber.org/zap/zapcore -# golang.org/x/crypto v0.0.0-20191206172530-e9b2fee46413 +# golang.org/x/crypto v0.0.0-20200220183623-bac4c82f6975 golang.org/x/crypto/ssh/terminal # golang.org/x/net v0.0.0-20191004110552-13f9640d40b9 golang.org/x/net/context @@ -161,7 +177,7 @@ google.golang.org/appengine/internal/urlfetch google.golang.org/appengine/urlfetch # gopkg.in/inf.v0 v0.9.1 gopkg.in/inf.v0 -# gopkg.in/yaml.v2 v2.2.4 +# gopkg.in/yaml.v2 v2.2.8 gopkg.in/yaml.v2 # gotest.tools v2.2.0+incompatible gotest.tools/assert @@ -169,7 +185,7 @@ gotest.tools/assert/cmp gotest.tools/internal/difflib gotest.tools/internal/format gotest.tools/internal/source -# k8s.io/api v0.17.0 +# k8s.io/api v0.17.4 k8s.io/api/admissionregistration/v1 k8s.io/api/admissionregistration/v1beta1 k8s.io/api/apps/v1 @@ -210,7 +226,7 @@ k8s.io/api/settings/v1alpha1 k8s.io/api/storage/v1 k8s.io/api/storage/v1alpha1 k8s.io/api/storage/v1beta1 -# k8s.io/apimachinery v0.17.0 +# k8s.io/apimachinery v0.17.4 k8s.io/apimachinery/pkg/api/apitesting/fuzzer k8s.io/apimachinery/pkg/api/equality k8s.io/apimachinery/pkg/api/errors @@ -272,7 +288,7 @@ k8s.io/cli-runtime/pkg/kustomize/k8sdeps/transformer/patch k8s.io/cli-runtime/pkg/kustomize/k8sdeps/validator k8s.io/cli-runtime/pkg/printers k8s.io/cli-runtime/pkg/resource -# k8s.io/client-go v0.17.0 +# k8s.io/client-go v0.17.4 k8s.io/client-go/discovery k8s.io/client-go/discovery/cached/disk k8s.io/client-go/dynamic @@ -448,7 +464,8 @@ k8s.io/kube-openapi/pkg/util/proto k8s.io/utils/buffer k8s.io/utils/integer k8s.io/utils/trace -# knative.dev/client v0.13.1-0.20200406212659-8a60d2ebf8e2 +# knative.dev/client v0.14.0 +knative.dev/client/lib/test knative.dev/client/pkg/dynamic knative.dev/client/pkg/errors knative.dev/client/pkg/eventing/v1alpha1 @@ -462,7 +479,7 @@ knative.dev/client/pkg/sources/v1alpha2 knative.dev/client/pkg/util knative.dev/client/pkg/util/mock knative.dev/client/pkg/wait -# knative.dev/eventing v0.13.5 +# knative.dev/eventing v0.14.1 knative.dev/eventing/pkg/apis/config knative.dev/eventing/pkg/apis/configs knative.dev/eventing/pkg/apis/configs/v1alpha1 @@ -475,8 +492,6 @@ knative.dev/eventing/pkg/apis/eventing/v1beta1 knative.dev/eventing/pkg/apis/flows knative.dev/eventing/pkg/apis/flows/v1alpha1 knative.dev/eventing/pkg/apis/flows/v1beta1 -knative.dev/eventing/pkg/apis/legacysources -knative.dev/eventing/pkg/apis/legacysources/v1alpha1 knative.dev/eventing/pkg/apis/messaging knative.dev/eventing/pkg/apis/messaging/config knative.dev/eventing/pkg/apis/messaging/v1alpha1 @@ -490,9 +505,11 @@ knative.dev/eventing/pkg/client/clientset/versioned/typed/eventing/v1alpha1/fake knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1alpha2 knative.dev/eventing/pkg/client/clientset/versioned/typed/sources/v1alpha2/fake knative.dev/eventing/pkg/logging -# knative.dev/eventing-contrib v0.14.0 +# knative.dev/eventing-contrib v0.14.1 knative.dev/eventing-contrib/github/pkg/apis/sources/v1alpha1 -# knative.dev/pkg v0.0.0-20200404181734-92cdec5b3593 +knative.dev/eventing-contrib/github/pkg/client/clientset/versioned/scheme +knative.dev/eventing-contrib/github/pkg/client/clientset/versioned/typed/sources/v1alpha1 +# knative.dev/pkg v0.0.0-20200414233146-0eed424fa4ee knative.dev/pkg/apis knative.dev/pkg/apis/duck knative.dev/pkg/apis/duck/v1 @@ -509,7 +526,7 @@ knative.dev/pkg/profiling knative.dev/pkg/ptr knative.dev/pkg/tracker knative.dev/pkg/webhook/resourcesemantics -# knative.dev/serving v0.13.1-0.20200403170819-0e8f7a9e34f0 +# knative.dev/serving v0.14.0 knative.dev/serving/pkg/apis/autoscaling knative.dev/serving/pkg/apis/autoscaling/v1alpha1 knative.dev/serving/pkg/apis/config