diff --git a/pkg/js/static.go b/pkg/js/static.go index a9916b07b..42d8f42dd 100644 --- a/pkg/js/static.go +++ b/pkg/js/static.go @@ -1,3 +1,5 @@ +// Code generated by "esc "; DO NOT EDIT. + package js import ( @@ -156,7 +158,7 @@ func _escFSByte(useLocal bool, name string) ([]byte, error) { return nil, err } b, err := ioutil.ReadAll(f) - f.Close() + _ = f.Close() return b, err } f, err := _escStatic.prepare(name) @@ -193,72 +195,71 @@ var _escData = map[string]*_escFile{ size: 14682, modtime: 0, compressed: ` -H4sIAAAAAAAA/+w7a3PbOJLf/St6UndDyVYo2Zlkt+Rob7V+bLnOr5KVnLd0OhcsQhISvg4A5fHllN9+ -hRcJkKDlSd3Ofll9SEiw0d3obnQ3Gu2gYBgYp2TBg+O9vQ2isMjSJYzg2x4AAMUrwjhFlA1hNu/JsShl -DznNNiTCznCWIJLqga1GFuElKmI+pisGI5jNj/f2lkW64CRLgaSEExST/8Gdribn0G6j/wIPDT7EwPZY -8ddgZWsxc42fJoZWJ0UJ7gF/znEPEsyRYY8soSNGuxaH4h1GIwiuxtefxpeBIraV/woJULwSKwKBcwgV -5qGFfyj/NYwKIYTVwsO8YOsOxavusVYJL2gqMTWWcJqyWy2VnYvIlorqSDCfPX7BCx7Azz9DQPKHRZZu -MGUkS1kAJHXmi594D104GMEyowniD5x3PN+7dcFELP8RwTiaV7KJWL5LNil+OpV2ocVSirdbGrqcWS3R -YqtpjcPqsecIZQjftjb8IqNR03RvK8u1wbWFTqeXQxj0HE4YphvH0rfu+nKaLTBjp4iuWCfp6U1gFtfv -C90ARos1JFlElgTTnjAEwoEwQGEYlnAa4xAWKI4FwBPha43PACFK0fPQEBXLLCgjGxw/GwhlT0J9dIUl -mZRnUkIR4qi0w4eQsHNNsZN0HRPr6DVouwEcM1xOGgsOajPEEjvCsr5Ik7U/iZ8rotmXeSml4xJu66N1 -I9dSI/YQ4l85TiPNZSiW1oPE5dbyEmuaPUHwH+PJ9cX1X4eacqkM5UWKlBV5nlGOoyEEcOCwb7ZsbTgA -ZdfNCZoxtRfU4rZ7e/0+nKo9UG2BIZxQjDgGBKfXdxphCJ8YBr7GkCOKEswxZYCYsWlAaSTYZ2FlhKdt -m0tud7Xi0QtbUbFZqpHACAbHQOCj7bvDGKcrvj4GcnBgK8RRrwU/I3VFb5tkjhQZRFdFglPeSkTAJzCq -AGdkfuxnIfFSVS5MRSjtvAyQVs7Z+fjT5fQOtI9jgIBhDtnSCKEiDjwDlOfxs3yIY1gWvKDYRMBQ4DsT -e15uZZ5VyJ9IHMMixogCSp8hp3hDsoLBBsUFZoKgrVY9q4zSzUjapredArUVK8VhS7br2u10etnZdIdw -h7m0y+n0UhJVVqvs0mJbgVtBT+zlO05JuupsnL28gZHMgdLVNDstKJLeaOPoTYcHg7xD7fk05DyGEWyO -fa7Zg9naFgniizUWctyE8rnT/6/Of0YH3c6MJevoKX2e/1v3X/qaGbGMcsYI0iKOuw0vs4EDCIRfTzMO -SOiURBBp6podJ00pUsJhBAELGlRmR3ObgIasPjpBHUbCVzB8kfJy/qHRolhsIQM+G8JhD5IhfBj0YD2E -dx8GAxPii1kQBXMYQRGuYR+OfimHn/RwBPvwh3I0tUbfDcrhZ3v4w3vNAeyPoJiJNcyddGFTbr4yADuG -ZjaeMTg5ppyktUvsuX8nq4ucrRNW+UKr8SXoKz4Zj89jtOrIzV3LdyqDltvHsWq1oRYILWO0gv8dKe9g -k+n34WQ8fjiZXEwvTsaXIo4QThYoFsMgpslDgA0jrafi6RA+foRB91iJ38pe35gc7xol+E0PBl0BkbKT -rEilNxxAglHKIMrSgIM4xmRUxxKsvJqVN4X2ZLEtDHaNRExHcWyrs5FJ6+meNNoglpl0kUZ4SVIcBbYw -SxB4e/hbNGzlijPBhjBrjaumiLFik+Q9rbkrnVuwMAy7Ug9jGOlvfylILFYWjAMt+/F4/BoM47EPyXhc -4bm8GN8pRBzRFeYvIBOgHmxi2KA7MVxxtOpJ+2vHd+Lj7WQ8DnpVGjy9Ob3p8Jgk3SFccGDrrIgjeMSA -UsCUZlToVdIxDnQg7Orw6I8qQxahfQizWSCYCnpQ7e55D2YBR6vmoETnDusknlOUMnFqGtY3Yk9S6pUJ -IvPsTMGCykWYleW5W5ejlQHhaNWAUCoyEPb+Vgwa8tdF8oiph0vHpzS9Bqu7jd7e1mj2enx19jpDkaAe -1YphYyi308nrkN1OJ01Ut9OJQXQ3+awQ5ZRklPDn3hMmqzXvicR8J/a7yecm9rvJ59IGtQGV8vJakvXV -cKEhlCIcCMVe+3fBd/tXtSAf/d/HRhndmCUaOPPug1WLNZDqzYszoyWUeN5h+eqtYaPK8RcMrXAPGI7x -gme0p9Ifkq5UnWKBKSdLskAcSxOYXt55/JAY/WEjkBy069Bw1g5hc/wbbQH6fWcpkGIsjn/wRoG/KZP8 -39FqeMyQFIqBki9eMCMcA2nevcC2nMwEe+zHzGh6P32db5reTz2Wcz81vunqvuaadiG8um/iu7r/Ozqj -f7Q7SX7NKV5iitMF3ulPdiuvTAcXa7z4Kk6pHfnEDLMRZgs7I0RVhQI+qlnmvXlQE5NbSxL6BO2gaByf -BcmfFMiMzCV1cW6ul74qcvJo+LbcshDAARD7vLjIKMULLstNQaMwpnPN61dmeNee9O66zO1E+L47m3w+ -cyJ31ypo1wBAQ7QcYWq5s53+y9JCrdQscQ31/7Dtes9PVUm7NNwHjh5jbJVWp4KL2SzOnuTBdk1W6yEc -9SDFT39BDA/hnUgD5edfzOf38vPF7RA+zOcGkayRvjmE73AE3+EdfD+GX+A7vIfvAN/hw5vyHB2TFO8q -vdT4famiRXIY1eGdwpYAkuzCCEgeysdjxwjlUN3s3GKtAqnDiJ9B/RAmKFdwvUqtxDfF0n9aJEdRxjvE -quOWZtsNv2Qk7QS9oPa1UaGtM2PQKrZrk/eaT1pGQuOllMRLQ05icKekJFCLrDSJUlri/R8qL82QJTHJ -/utkJjzTCGYlV3kYZ0/dHlgDYst0y/2kd45lnnI76Guy7EmvAL5D0PVVUxS0BjqGoCy9Xlzd3kymD9PJ -+Pru/GZypbZ8LAszalOUJV3p3erwTV9Xh6gH3lnQIBHII6Mio545j914+/8ZSYM/BzvComKlGWgxR5r9 -ymnIqlvlMlVYra+w2yQoq6cKmseN9On20+SvZx0rLqiB0t1H4b9jnH9Kv6bZUyoYQDHDRqnXNw+N+eVY -KwpOC41hf38P9uHPEc4pFil+tAf7/QrVCvMy7HWU1BlHlDsl3ixqddYSuKyVt8Z5edFi6uNOadwybAFk -Mz2R0lVXS4/KJOVa5H0OfFO1x636bsH6YLKcs1CSns8Gcxib9EFYkQ1v5DJypxzO4SYX4yhW5WjEM/rS -vNKuwNwOVncdzvWHqfrDvhHVFH3F0LIRuoCYdScB4/S52iTqUuQRW7gEQYIjeMTLjGLga8LKvRZa9aOk -4Iiry7IV2eDUZqtVNGIxxnY8y6z44pnErHC65uf6G3UeFdiN7YhnGSp0qZh1vm0VRM+yrp1FLZnTC79T -JbA/5nxAJToKUgl8jTbYWiyKKUbRsxF9fabAbRQFKNX3zHJPWdeUugLrTN55ggArDitP27HOBd5gXHeY -JmbZ814ZRnceSUoMVRy19OFYk0cnrdrwpY4lcJs7Mj/t3WBUTZF5YwOwedefRV6JgnJ25jrCk6H47+Zf -QNfvg2pD4ZXVyk2lnBvzTpJXYFlkOaKffwar8cD+1EpZL8ZC4vTIODiaKwVH2fav7D2wYrFUcbu8/Azq -roSzyeRmMgQT/pymhMCDst0e5X9dbQD181n92CHvCiN9i/xt6x43Ko+g28bMR33Kdq6V4WMVbjynbYOz -nHZJmNhj5ZzGEmVqXWXUHDe6ScxPL1KAzAZzX0bdRK5TbKjn2EodMh4fNGYFxmtS/N8FoZg1Gj5AO3xb -DF5EVQTt+HC4YvIg6IZwk8bPXgYaqvEx8IQpBlYoF1+zMCVQu/JQPsqdHMfC4Zdkyo8+R1aXhteRacs4 -FTGDyKhqWYZzDDbQ6n6orQsEKiOtcBpp/AkOfZYkYmKRVrmRQGDk43WmPznYZ4dzfbvbZqYvmlalGG1i -PsWan0t4MH8RX1ln0iuTJRVE4obW4QW/In6Vr5jVGRBnDuuKCVptpnQpfpvxGMtrOljAuiZr72GpcfVi -6QrKzlGpjJFHpVafZONbsw2xnMXjodM24IJsa4G7maZ60onj5pQyqJXglfbcqc7cKNStZabh1ZMBaLmp -b5ZknbvwHUc2FEXqtNOJTHusXRGUHDKrvEeWpkZImMjwHjHtAWKsSDCQXKCjmLGwTDIIV1fFtVzSk0Y2 -8kYnZbRbiBeOFfi072tXdUuc1ni7HZhaudOA6lqUFra/pzTCCxJheEQMRyCOM4JVA/+2POaY7lKmukur -4404oIk3505JTr3xdpQKWKerVMKa6+qLc7i6rzArlUk9mnWWmrKVDu158c5Ikqhk2B8SXmh3LWUtDN9/ -aHixH9X8+v3fluzKtbemua9IcpO29PbF5LaZ2NpJba2b9jeCtaa8iyxlWYzDOFt1vGup+nOvWhtzg6Zf -Bas91/816Nx9JXlO0tVP3aABsaNSutUlqrp7dHveKV7omhfJoeq7L2MMgyXNElhzng/7fcbR4mu2wXQZ -Z0/hIkv6qP/Hw8H7P/wy6B8eHX74MNjr92FDkJnwBW0QW1CS8xA9ZgWXc2LySBF97j/GJNdmF655Uvna -i9tOlDnFMBHPooyHLI8J7wShyYH7fcgp5pxg+pas0oxie3Ed+TuIZoN5F/bh6P2HLhyAGDicd2sjR42R -d/Nu7a8BTKW6SOzLu7RIZA9X2cLl1k0lJ4HTOVlr8BP4PHPSImn88YPy+vCvgk9PXfCd8Dh/ko7n7Vun -kUzwCFeIr8NlnGVUMt2Xq62syMEOBxCEARxA5KkZRmUfX5wV0TJGFAOKCWKYDdWVM+ayAZkL7yF5JGlE -NiQqUGx6wUPVpXP+cDu5uf/bw835uezzXJQoH3Ka/fo8hCBbLgPYHgtt34ohiAhDjzGO6iiuWzGkLgKc -+uaff7q8bMOwLOLYwXEwQSReFWmFS3zB9K1p0rdFMNyreNdtodlyqUJhyknZfQ0dq3O0O3TZ0x3VrZJ6 -0PMqiXmopk2ibWT80rSpSKkqQ/h0N7256sHt5ObzxenZBO5uz04uzi9OYHJ2cjM5henfbs/urM30oHN7 -LE3oXOCf4IhQEaOc9jB5brHbYRsnFpMWqwJ+w1jlhJCkEf71ZinvqOR2fXsojVgvfXJ2ejE5O/E0Ulgf -X+iAYFlBF7IK2r4up+UhwoyTVJ5tXjXr972+UcsRPqAnfIC60qk4di9btAinZ1e3L8vRgfinMH3C/L8A -AAD//4nEKeNaOQAA +H4sIAAAAAAAC/+w7a3MbOXLf+St6XckOKdFDSd71XVHm5Xh6XKmiV1G04yuGUUEckIQ9rwAYahWH/u0p +vGaAGQyp3crtfTl92OUAjUaj32i0g4JhYJySBQ9OO50NorDI0iWM4FsHAIDiFWGcIsqGMJv35ViUssec +ZhsSYWc4SxBJ9cBWI4vwEhUxH9MVgxHM5qedzrJIF5xkKZCUcIJi8j+429PbOXu37b+DhgYdYmB7quhr +kLK1iLnFzxOzVzdFCe4Df8lxHxLMkSGPLKErRnsWheIbRiMIbsa3H8fXgdpsK/8rOEDxSpwIBM4hVJiH +Fv6h/K8hVDAhrA4e5gVbdyle9U61SHhBU4mpcYTzlN1rruw9RLZUu44E8dnTF7zgAfz4IwQkf1xk6QZT +RrKUBUBSZ734E9+hCwcjWGY0QfyR865nvldnTMTy38IYR/KKNxHL9/Emxc/nUi80W0r29kpFlyurI1pk +NbVxWP3sO0wZwretDb/IaNRU3ftKc21wraHT6fUQjvoOJQzTjaPpW/d8Oc0WmLFzRFesm/S1EZjDDQZC +NoDRYg1JFpElwbQvFIFwIAxQGIYlnMY4hAWKYwHwTPha4zNAiFL0MjSbimMWlJENjl8MhNInIT66wnKb +lGeSQxHiqNTDx5CwS71jN+k5KtbVZ9B6AzhmuFw0FhTUVogjdoVmfZEqa0+JP5dFsy/zkkunJdzWt9ed +PEtts8cQ/8JxGmkqQ3G0PiQutZaXWNPsGYL/GE9ur27/OtQ7l8JQXqRIWZHnGeU4GkIAhw75xmRrwwEo +vW4u0IQpW1CH23Y6gwGcKxuoTGAIZxQjjgHB+e2DRhjCR4aBrzHkiKIEc0wZIGZ0GlAaCfJZWCnheZtx +SXNXJx7tMEVFZilGAiM4OgUCH2zfHcY4XfH1KZDDQ1sgjngt+BmpC3rb3OZEbYPoqkhwyls3EfAJjCrA +GZmf+klIvLsqF6YilHZeBkgL5+Jy/PF6+gDaxzFAwDCHbGmYUG0OPAOU5/GL/BHHsCx4QbGJgKHAdyFs +XpoyzyrkzySOYRFjRAGlL5BTvCFZwWCD4gIzsaEtVr2qjNLNSNomt70MtQUr2WFztufq7XR63d30hvCA +udTL6fRabqq0VumlRbYCt4KesOUHTkm66m4cW97ASOZA6WqanRcUSW+0ceSmw4NB3qX2ehpyHsMINqc+ +1+zBbJlFgvhijQUfN6H83R38V/c/o8Ned8aSdfScvsz/rfcvA02MOEa5YgRpEce9hpfZwCEEwq+nGQck +ZEoiiPTumhwnTSlSwmEEAQsau8xO5vYGGrKadII6jISvYPgq5eX6YyNFcdhCBnw2hOM+JEN4f9SH9RDe +vT86MiG+mAVRMIcRFOEaDuDkp3L4WQ9HcAB/KEdTa/TdUTn8Yg+//1lTAAcjKGbiDHMnXdiUxlcGYEfR +jOEZhZNjyklaVmKv/TtpXeSYTljlC63Kl6Cv+Gw8vozRqiuNu5bvVAotzcfRamVQC4SWMVrB/46Ud7C3 +GQzgbDx+PJtcTa/OxtcijhBOFigWwyCWyUuADSO1p6LpGD58gKPeqWK/lb2+MTneLUrwmz4c9QREys6y +IpXe8AgSjFIGUZYGHMQ1JqM6lmDl1ay8KbQXC7Mw2DUSsRzFsS3ORiatl3vSaINYZtJFGuElSXEU2Mws +QeDt8a+RsJUrzgQZQq01rpogxopMkve15G50bsHCMOxJOYxhpOf+UpBYnCwYB5r34/H4NRjGYx+S8bjC +c301flCIOKIrzHcgE6AebGLYoDszVHG06kv9a8d35qPtbDwO+lUaPL07v+vymCS9IVxxYOusiCN4woBS +wJRmVMhV7mMc6JHQq+OTP6oMWYT2IcxmgSAq6ENl3fM+zAKOVs1Bic4d1kk8pyhl4tY0rBtiX+7ULxNE +5rFMQYLKRZiV5bmmy9HKgHC0akAoERkI274VgWb72yJ5wtRDpeNTml6D1d1Gv7M1kr0d31y8TlEkqEe0 +Ytgoyv108jpk99NJE9X9dGIQPUw+KUQ5JRkl/KX/jMlqzfsiMd+L/WHyqYn9YfKp1EGtQCW/vJpkzRoq +NIQShAOhyGufF3S3z6oD+fb/fXSU0Y05ooEz3z5YdVgDqb68ODNaQonfezRffTV0VDn+gqEV7gPDMV7w +jPZV+kPSlapTLDDlZEkWiGOpAtPrB48fEqO/WQkkBe0yNJS1Q9gU/0pdgMHAOQqkGIvrH7xR4G/KJP93 +1BoeMySZYqDkhxfMMMdAmm8vsM0ns8Ae+21qNP08fZ1vmn6eejTn89T4ppvPNde0D+HN5ya+m89/R2f0 +j3YnyS85xUtMcbrAe/3JfuGV6eBijRdfxS21K38xQ2yE2cLOCFFVoYAPapX5bl7UxOLWkoS+QTsoGtdn +seUPCmRG5nJ3cW+ul76q7eTV8G1pshDAIRD7vrjIKMULLstNQaMwpnPN21dmeLee9O62zO1E+H64mHy6 +cCJ3zypo1wBAQ7RcYWq5s53+y9JCrdQscQ31/2Hb896fqpJ2qbiPHD3F2CqtTgUVs1mcPcuL7Zqs1kM4 +6UOKn/+CGB7CO5EGyumfzPTPcvrqfgjv53ODSNZI3xzDdziB7/AOvp/CT/AdfobvAN/h/ZvyHh2TFO8r +vdTo3VXRIjmM6vBOYUsASXJhBCQP5c9TRwnlUF3t3GKtAqnDyMuRRv0YJihXcP1KrMS3xC72F8lJlPEu +seq4pdr2wi8ZSbtBP6jNNiq0dWIMWkV2bXGn+UvzSEi85JL4aPBJDO7llARq4ZXeouSW+P6H8ksTZHFM +kv86ngnPNIJZSVUextlzrw/WgDCZXmlP2nIs9ZTmoJ/Jsmd9AvgOQc9XTVHQGugUgrL0enVzfzeZPk4n +49uHy7vJjTL5WBZmlFGUJV3p3erwTV9Xh6gH3lnQ2CKQV0a1jfrNeezG2//PSBr8OdgTFhUpzUCLOdLk +V05DVt0ql6nCav2EveaGsnqqoHncSJ/uP07+etG14oIaKN19FP47xvnH9GuaPaeCABQzbIR6e/fYWF+O +taLgtNAYDg46cAB/jnBOsUjxow4cDCpUK8zLsNdVXGccUe6UeLOo1VlL4LJW3hrn5UOLqY87pXFLsQWQ +TfREclc9LT0plZRnke858E3VHrdq3oL1wWQ5Z6Hcej47msPYpA9Ci2x4w5eRu+R4Dne5GEexKkcjntFd +60q9AvM6WL11OM8fpuoPB4ZVU/QVQ4sh9AAx600CxulLZSTqUeQJW7jEhgRH8ISXGcXA14SVthZa9aOk +4Iirx7IV2eDUJquVNeIwRnc8x6zo4pnErHC66uf6G3UfFdiN7ojfMlToUjHrftsqiL6lXXuLWjKnF36n +SmB/m/PRiY6CVAxfow22DotiilH0YlhfXylwG0EBSvU7s7Qp65lSV2A7bvTbc4Ow47DytF3rXuANxnWH +aWKWve6VYXTvlcQTRy15ONrkkUmrNHypYwnc5o6c59AsglG1ROaNDcDmW38W9drylCSLzHOEJ0Pxv83v +QDcYgGpD4ZXWSqNSzo15F8knsCyyHNGPP4LVeGBPte6sD2MhcXpkHBynXgxb72jZe2DFYinidn75CdRd +CReTyd1kCCb8OU0JgQdluz6qHFIrQP1+Vr92yLfCSL8if9u6143KI+i2MVsy9Wdl+FCFG89t2+Asl10T +JmysXNM4okytq4ya42RPUi1AZkdzX0bdRK5TbKjn2EocMh4fNlYFxmtS/N8FoZg1Gj6Mw7fZ4EVURdCu +D4fLJg+CXgh3afwCOxfvIuAZUwysUC6+pmGKoXbloeNYchwLh19u09nlyOrc8DoyrRnnImYQGVUtzXCu +wQZavQ+1dYFYSlrhNNz4Exz7NEnExCKtciOBwPDH60x/cLDPjuf6dbe309JbVKuhYsEOIHfjo/lOfGWd +SZ9MllQQiRtS3+VXZGtN6StmdQLEncN6YmrXmdKl+HXGoyyv6WCxn8nae1hqVO0sXVWdo1IYI49IrT7J +xlyzDbFcxeOh0zbggmxrgbuZpnrSidPmkjKoleCV9Nylbr9aqFvLTMOrJwPQfFNzFmedt/A9VzYUReq2 +041Me6xdEZQUMqu8R5amRkiYyPCeMO0DYqxIMJBcoKOYsbBMMggPO55c0pNGNvJGJ2W0W4gXjhb4pO9r +V3VLnNZ4ux6YWrnTgOpqlGa2v6c0wgsSYXhCDEcgrjOCVAP/trzmmO5SprpLq+uNuKCJL+dNSS6983aU +Clinq1TCmufqq0u4+VxhViKTcjTn7FjJHvM2k7p58d5Ikqhk2B8SdrS7Vm2vFC/8l4ad/aiVv/t1ya48 +e2ua+4okN2lLb3cmt83E1k5qa920vxKsNeVdZCnLYhzG2arrPUvVn3vT2pgb9P0BVrfn+meD7sNXkuck +Xf3QCxoQeyql247fPbo97xQvdM2L5FD13ZcxhsGSZgmsOc+HgwHjaPE122C6jLPncJElAzT44/HRz3/4 +6WhwfHL8/v1RZzCADUFmwRe0QWxBSc5D9JQVXK6JyRNF9GXwFJNcq1245knla6/uu1HmFMNEPIsyHrI8 +JrwbhCYHHgwgp5hzgulbskoziu3DdeXfYTQ7mvfgAE5+ft+DQxADx/NebeSkMfJu3qv9awBTqS4S+/Eu +LRLZw1W2cLl1U0lJ4HRO1hr8BD7PmrRIGv/4QXl9+FdBp6cu+E54nD9Jx/P2rdNIJmiEG8TX4TLOMiqJ +HsjTVlrkYIdDCMIADiHy1Ayjso8vzopoGSOKAcUEMcyG6skZc9mAzIX3kDSSNCIbEhUoNr3goerSuXy8 +n9x9/tvj3eWl7PNclCgfc5r98jKEIFsuA9ieCmnfiyGICENPMY7qKG5bMaQuApz61l9+vL5uw7As4tjB +cThBJF4VaYVLzGD61jTp2ywYdiradVtotlyqUJhyUnZfQ9fqHO0NXfJ0R3Urpx71uopjnl3T5qZt29zu +3UVyVSnCx4fp3U0f7id3n67OLybwcH9xdnV5dQaTi7O7yTlM/3Z/8WAZ06PO7bFUoUuBf4IjQkWMctrD +5L3Fbodt3FhMWqwK+A1llQtCkkb4l7ulfKOS5vr2WCqxPvrk4vxqcnHmaaSwJnd0QLCsoAtZBW0/l9Py +EGHGSSrvNq9a9fs+36jjCB/QFz5APelUFLuPLZqF04ub+918dCD+yUwfM/8vAAD//4nEKeNaOQAA `, }, diff --git a/vendor/github.com/NYTimes/gziphandler/LICENSE.md b/vendor/github.com/NYTimes/gziphandler/LICENSE.md deleted file mode 100644 index b7e2ecb63..000000000 --- a/vendor/github.com/NYTimes/gziphandler/LICENSE.md +++ /dev/null @@ -1,13 +0,0 @@ -Copyright (c) 2015 The New York Times Company - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this library 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. diff --git a/vendor/github.com/NYTimes/gziphandler/README.md b/vendor/github.com/NYTimes/gziphandler/README.md deleted file mode 100644 index b1d55e26e..000000000 --- a/vendor/github.com/NYTimes/gziphandler/README.md +++ /dev/null @@ -1,52 +0,0 @@ -Gzip Handler -============ - -This is a tiny Go package which wraps HTTP handlers to transparently gzip the -response body, for clients which support it. Although it's usually simpler to -leave that to a reverse proxy (like nginx or Varnish), this package is useful -when that's undesirable. - - -## Usage - -Call `GzipHandler` with any handler (an object which implements the -`http.Handler` interface), and it'll return a new handler which gzips the -response. For example: - -```go -package main - -import ( - "io" - "net/http" - "github.com/NYTimes/gziphandler" -) - -func main() { - withoutGz := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "text/plain") - io.WriteString(w, "Hello, World") - }) - - withGz := gziphandler.GzipHandler(withoutGz) - - http.Handle("/", withGz) - http.ListenAndServe("0.0.0.0:8000", nil) -} -``` - - -## Documentation - -The docs can be found at [godoc.org] [docs], as usual. - - -## License - -[Apache 2.0] [license]. - - - - -[docs]: https://godoc.org/github.com/nytimes/gziphandler -[license]: https://github.com/nytimes/gziphandler/blob/master/LICENSE.md diff --git a/vendor/github.com/NYTimes/gziphandler/gzip.go b/vendor/github.com/NYTimes/gziphandler/gzip.go deleted file mode 100644 index 87a841f66..000000000 --- a/vendor/github.com/NYTimes/gziphandler/gzip.go +++ /dev/null @@ -1,200 +0,0 @@ -package gziphandler - -import ( - "compress/gzip" - "fmt" - "net/http" - "strconv" - "strings" - "sync" -) - -const ( - vary = "Vary" - acceptEncoding = "Accept-Encoding" - contentEncoding = "Content-Encoding" -) - -type codings map[string]float64 - -// The default qvalue to assign to an encoding if no explicit qvalue is set. -// This is actually kind of ambiguous in RFC 2616, so hopefully it's correct. -// The examples seem to indicate that it is. -const DEFAULT_QVALUE = 1.0 - -// gzipWriterPools stores a sync.Pool for each compression level for re-uze of gzip.Writers. -// Use poolIndex to covert a compression level to an index into gzipWriterPools. -var gzipWriterPools [gzip.BestCompression - gzip.BestSpeed + 2]*sync.Pool - -func init() { - for i := gzip.BestSpeed; i <= gzip.BestCompression; i++ { - addLevelPool(i) - } - addLevelPool(gzip.DefaultCompression) -} - -// poolIndex maps a compression level to its index into gzipWriterPools. It assumes that -// level is a valid gzip compression level. -func poolIndex(level int) int { - // gzip.DefaultCompression == -1, so we need to treat it special. - if level == gzip.DefaultCompression { - return gzip.BestCompression - gzip.BestSpeed + 1 - } - return level - gzip.BestSpeed -} - -func addLevelPool(level int) { - gzipWriterPools[poolIndex(level)] = &sync.Pool{ - New: func() interface{} { - // NewWriterLevel only returns error on a bad level, we are guaranteeing - // that this will be a valid level so it is okay to ignore the returned - // error. - w, _ := gzip.NewWriterLevel(nil, level) - return w - }, - } -} - -// GzipResponseWriter provides an http.ResponseWriter interface, which gzips -// bytes before writing them to the underlying response. This doesn't set the -// Content-Encoding header, nor close the writers, so don't forget to do that. -type GzipResponseWriter struct { - gw *gzip.Writer - http.ResponseWriter -} - -// Write appends data to the gzip writer. -func (w GzipResponseWriter) Write(b []byte) (int, error) { - if _, ok := w.Header()["Content-Type"]; !ok { - // If content type is not set, infer it from the uncompressed body. - w.Header().Set("Content-Type", http.DetectContentType(b)) - } - return w.gw.Write(b) -} - -// Flush flushes the underlying *gzip.Writer and then the underlying -// http.ResponseWriter if it is an http.Flusher. This makes GzipResponseWriter -// an http.Flusher. -func (w GzipResponseWriter) Flush() { - w.gw.Flush() - if fw, ok := w.ResponseWriter.(http.Flusher); ok { - fw.Flush() - } -} - -// MustNewGzipLevelHandler behaves just like NewGzipLevelHandler except that in an error case -// it panics rather than returning an error. -func MustNewGzipLevelHandler(level int) func(http.Handler) http.Handler { - wrap, err := NewGzipLevelHandler(level) - if err != nil { - panic(err) - } - return wrap -} - -// NewGzipLevelHandler returns a wrapper function (often known as middleware) -// which can be used to wrap an HTTP handler to transparently gzip the response -// body if the client supports it (via the Accept-Encoding header). Responses will -// be encoded at the given gzip compression level. An error will be returned only -// if an invalid gzip compression level is given, so if one can ensure the level -// is valid, the returned error can be safely ignored. -func NewGzipLevelHandler(level int) (func(http.Handler) http.Handler, error) { - if level != gzip.DefaultCompression && (level < gzip.BestSpeed || level > gzip.BestCompression) { - return nil, fmt.Errorf("invalid compression level requested: %d", level) - } - return func(h http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Add(vary, acceptEncoding) - - if acceptsGzip(r) { - // Bytes written during ServeHTTP are redirected to this gzip writer - // before being written to the underlying response. - gzw := gzipWriterPools[poolIndex(level)].Get().(*gzip.Writer) - defer gzipWriterPools[poolIndex(level)].Put(gzw) - gzw.Reset(w) - defer gzw.Close() - - w.Header().Set(contentEncoding, "gzip") - h.ServeHTTP(GzipResponseWriter{gzw, w}, r) - } else { - h.ServeHTTP(w, r) - } - }) - }, nil -} - -// GzipHandler wraps an HTTP handler, to transparently gzip the response body if -// the client supports it (via the Accept-Encoding header). This will compress at -// the default compression level. -func GzipHandler(h http.Handler) http.Handler { - wrapper, _ := NewGzipLevelHandler(gzip.DefaultCompression) - return wrapper(h) -} - -// acceptsGzip returns true if the given HTTP request indicates that it will -// accept a gzippped response. -func acceptsGzip(r *http.Request) bool { - acceptedEncodings, _ := parseEncodings(r.Header.Get(acceptEncoding)) - return acceptedEncodings["gzip"] > 0.0 -} - -// parseEncodings attempts to parse a list of codings, per RFC 2616, as might -// appear in an Accept-Encoding header. It returns a map of content-codings to -// quality values, and an error containing the errors encounted. It's probably -// safe to ignore those, because silently ignoring errors is how the internet -// works. -// -// See: http://tools.ietf.org/html/rfc2616#section-14.3 -func parseEncodings(s string) (codings, error) { - c := make(codings) - e := make([]string, 0) - - for _, ss := range strings.Split(s, ",") { - coding, qvalue, err := parseCoding(ss) - - if err != nil { - e = append(e, err.Error()) - - } else { - c[coding] = qvalue - } - } - - // TODO (adammck): Use a proper multi-error struct, so the individual errors - // can be extracted if anyone cares. - if len(e) > 0 { - return c, fmt.Errorf("errors while parsing encodings: %s", strings.Join(e, ", ")) - } - - return c, nil -} - -// parseCoding parses a single conding (content-coding with an optional qvalue), -// as might appear in an Accept-Encoding header. It attempts to forgive minor -// formatting errors. -func parseCoding(s string) (coding string, qvalue float64, err error) { - for n, part := range strings.Split(s, ";") { - part = strings.TrimSpace(part) - qvalue = DEFAULT_QVALUE - - if n == 0 { - coding = strings.ToLower(part) - - } else if strings.HasPrefix(part, "q=") { - qvalue, err = strconv.ParseFloat(strings.TrimPrefix(part, "q="), 64) - - if qvalue < 0.0 { - qvalue = 0.0 - - } else if qvalue > 1.0 { - qvalue = 1.0 - } - } - } - - if coding == "" { - err = fmt.Errorf("empty content-coding") - } - - return -} diff --git a/vendor/github.com/TomOnTime/utfutil/README.md b/vendor/github.com/TomOnTime/utfutil/README.md index b821c85c4..815822469 100644 --- a/vendor/github.com/TomOnTime/utfutil/README.md +++ b/vendor/github.com/TomOnTime/utfutil/README.md @@ -2,13 +2,34 @@ Utilities to make it easier to read text encoded as UTF-16. -## Dealing with UTF-16 files from Windows. +## Dealing with UTF-16 files you receive from Windows. -Ever have code that worked for years until you received a file from a MS-Windows system that just didn't work at all? Looking at a hex dump you realize every other byte is \0. WTF? No, UTF. More specifically UTF-16LE with an optional BOM. +Have you encountered this situation? Code that has worked for years +suddenly breaks. It turns out someone tried to use it with a file +that came from a MS-Windows system. Now this perfectly good code stops +working. + +Looking at a hex dump you realize every other byte is \0. WTF? +No, UTF. More specifically UTF-16LE with an optional BOM. What does all that mean? Well, first you should read ["The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)"](http://www.joelonsoftware.com/articles/Unicode.html) by Joel Spolsky. -Now you are an expert. You can spend an afternoon trying to figure out how the heck to put all that together and use `golang.org/x/text/encoding/unicode` to decode UTF-16LE. However I've already done that for you. Now you can take the easy way out change ioutil.ReadFile() to utfutil.ReadFile(). Everything will just work. +Now you understand what the problem is, but how do you fix it? +Well, you can spend a week trying to figure out how to use +`golang.org/x/text/encoding/unicode` and you'll be able to +decode UTF-16LE files. (No offense to the authors of that +module. It is a fantastic module but if you aren't already +an expert in Unicode encoding, it is pretty difficult to use.) + +If you don't have a week, you can just use this module. +Take the easy way out! Just change `ioutil.ReadFile()` to +`utfutil.ReadFile()`. +Everything will just work. + +The goal of `utfutl` is to provide replacement functions +that magically do the right thing. There is a demo +program that shows how to use it called [catutf](https://github.com/TomOnTime/utfutil/blob/master/catutf/main.go). + ### utfutil.ReadFile() is the equivalent of ioutil.ReadFile() @@ -46,14 +67,13 @@ It works like os.Open(): s, err := utfutil.NewScanner(filename, utfutil.HTML5) ``` - ## Encoding hints: -What's that second argument all about? +What's that second argument all about? utfutil.UTF8? utfutil.HTML5? -Since it is impossible to guess 100% correctly if there is no BOM, -the functions take a 2nd parameter of type "EncodingHint" where you -specify the default encoding for BOM-less files. +If a file has no BOM, it is impossible to guess the file encoding with +100% accuracy. Therefore, the 2nd parameter is an +"EncodingHint" that specifies what to assume for BOM-less files. ``` UTF8 No BOM? Assume UTF-8 diff --git a/vendor/github.com/billputer/go-namecheap/dns.go b/vendor/github.com/billputer/go-namecheap/dns.go index 6592f9b40..92234a8fa 100644 --- a/vendor/github.com/billputer/go-namecheap/dns.go +++ b/vendor/github.com/billputer/go-namecheap/dns.go @@ -60,13 +60,15 @@ func (client *Client) DomainDNSSetHosts( requestInfo.params.Set("SLD", sld) requestInfo.params.Set("TLD", tld) - for i := range hosts { - requestInfo.params.Set(fmt.Sprintf("HostName%v", i+1), hosts[i].Name) - requestInfo.params.Set(fmt.Sprintf("RecordType%v", i+1), hosts[i].Type) - requestInfo.params.Set(fmt.Sprintf("Address%v", i+1), hosts[i].Address) - requestInfo.params.Set(fmt.Sprintf("MXPref%v", i+1), strconv.Itoa(hosts[i].MXPref)) - requestInfo.params.Set(fmt.Sprintf("TTL%v", i+1), strconv.Itoa(hosts[i].TTL)) - + for i, h := range hosts { + requestInfo.params.Set(fmt.Sprintf("HostName%v", i+1), h.Name) + requestInfo.params.Set(fmt.Sprintf("RecordType%v", i+1), h.Type) + requestInfo.params.Set(fmt.Sprintf("Address%v", i+1), h.Address) + if h.Type == "MX" { + requestInfo.params.Set(fmt.Sprintf("MXPref%v", i+1), strconv.Itoa(h.MXPref)) + requestInfo.params.Set("EmailType", "MX") + } + requestInfo.params.Set(fmt.Sprintf("TTL%v", i+1), strconv.Itoa(h.TTL)) } resp, err := client.do(requestInfo) diff --git a/vendor/github.com/dnsimple/dnsimple-go/LICENSE.txt b/vendor/github.com/dnsimple/dnsimple-go/LICENSE.txt index 0bf65d53a..9d8e840fa 100644 --- a/vendor/github.com/dnsimple/dnsimple-go/LICENSE.txt +++ b/vendor/github.com/dnsimple/dnsimple-go/LICENSE.txt @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2014-2016 Aetrion LLC +Copyright (c) 2014-2017 Aetrion LLC dba DNSimple Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/collaborators.go b/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains_collaborators.go similarity index 100% rename from vendor/github.com/dnsimple/dnsimple-go/dnsimple/collaborators.go rename to vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains_collaborators.go diff --git a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/registrar.go b/vendor/github.com/dnsimple/dnsimple-go/dnsimple/registrar.go index 69e602ed8..e89b1a429 100644 --- a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/registrar.go +++ b/vendor/github.com/dnsimple/dnsimple-go/dnsimple/registrar.go @@ -128,7 +128,7 @@ type DomainRegisterRequest struct { // // See https://developer.dnsimple.com/v2/registrar/#register func (s *RegistrarService) RegisterDomain(accountID string, domainName string, request *DomainRegisterRequest) (*domainRegistrationResponse, error) { - path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/registration", accountID, domainName)) + path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/registrations", accountID, domainName)) registrationResponse := &domainRegistrationResponse{} // TODO: validate mandatory attributes RegistrantID @@ -181,7 +181,7 @@ type DomainTransferRequest struct { // // See https://developer.dnsimple.com/v2/registrar/#transfer func (s *RegistrarService) TransferDomain(accountID string, domainName string, request *DomainTransferRequest) (*domainTransferResponse, error) { - path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/transfer", accountID, domainName)) + path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/transfers", accountID, domainName)) transferResponse := &domainTransferResponse{} // TODO: validate mandatory attributes RegistrantID @@ -205,7 +205,7 @@ type domainTransferOutResponse struct { // // See https://developer.dnsimple.com/v2/registrar/#transfer-out func (s *RegistrarService) TransferDomainOut(accountID string, domainName string) (*domainTransferOutResponse, error) { - path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/transfer_out", accountID, domainName)) + path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/authorize_transfer_out", accountID, domainName)) transferResponse := &domainTransferOutResponse{} resp, err := s.client.post(path, nil, nil) @@ -245,7 +245,7 @@ type DomainRenewRequest struct { // // See https://developer.dnsimple.com/v2/registrar/#register func (s *RegistrarService) RenewDomain(accountID string, domainName string, request *DomainRenewRequest) (*domainRenewalResponse, error) { - path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/renewal", accountID, domainName)) + path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/renewals", accountID, domainName)) renewalResponse := &domainRenewalResponse{} resp, err := s.client.post(path, request, renewalResponse) diff --git a/vendor/github.com/golang/protobuf/proto/Makefile b/vendor/github.com/golang/protobuf/proto/Makefile index f1f06564a..e2e0651a9 100644 --- a/vendor/github.com/golang/protobuf/proto/Makefile +++ b/vendor/github.com/golang/protobuf/proto/Makefile @@ -39,5 +39,5 @@ test: install generate-test-pbs generate-test-pbs: make install make -C testdata - protoc --go_out=Mtestdata/test.proto=github.com/golang/protobuf/proto/testdata:. proto3_proto/proto3.proto + protoc --go_out=Mtestdata/test.proto=github.com/golang/protobuf/proto/testdata,Mgoogle/protobuf/any.proto=github.com/golang/protobuf/ptypes/any:. proto3_proto/proto3.proto make diff --git a/vendor/github.com/golang/protobuf/proto/clone.go b/vendor/github.com/golang/protobuf/proto/clone.go index e98ddec98..e392575b3 100644 --- a/vendor/github.com/golang/protobuf/proto/clone.go +++ b/vendor/github.com/golang/protobuf/proto/clone.go @@ -84,9 +84,15 @@ func mergeStruct(out, in reflect.Value) { mergeAny(out.Field(i), in.Field(i), false, sprop.Prop[i]) } - if emIn, ok := in.Addr().Interface().(extendableProto); ok { - emOut := out.Addr().Interface().(extendableProto) - mergeExtension(emOut.ExtensionMap(), emIn.ExtensionMap()) + if emIn, ok := extendable(in.Addr().Interface()); ok { + emOut, _ := extendable(out.Addr().Interface()) + mIn, muIn := emIn.extensionsRead() + if mIn != nil { + mOut := emOut.extensionsWrite() + muIn.Lock() + mergeExtension(mOut, mIn) + muIn.Unlock() + } } uf := in.FieldByName("XXX_unrecognized") diff --git a/vendor/github.com/golang/protobuf/proto/decode.go b/vendor/github.com/golang/protobuf/proto/decode.go index 5810782fd..aa207298f 100644 --- a/vendor/github.com/golang/protobuf/proto/decode.go +++ b/vendor/github.com/golang/protobuf/proto/decode.go @@ -61,7 +61,6 @@ var ErrInternalBadWireType = errors.New("proto: internal error: bad wiretype for // int32, int64, uint32, uint64, bool, and enum // protocol buffer types. func DecodeVarint(buf []byte) (x uint64, n int) { - // x, n already 0 for shift := uint(0); shift < 64; shift += 7 { if n >= len(buf) { return 0, 0 @@ -78,13 +77,7 @@ func DecodeVarint(buf []byte) (x uint64, n int) { return 0, 0 } -// DecodeVarint reads a varint-encoded integer from the Buffer. -// This is the format for the -// int32, int64, uint32, uint64, bool, and enum -// protocol buffer types. -func (p *Buffer) DecodeVarint() (x uint64, err error) { - // x, err already 0 - +func (p *Buffer) decodeVarintSlow() (x uint64, err error) { i := p.index l := len(p.buf) @@ -107,6 +100,107 @@ func (p *Buffer) DecodeVarint() (x uint64, err error) { return } +// DecodeVarint reads a varint-encoded integer from the Buffer. +// This is the format for the +// int32, int64, uint32, uint64, bool, and enum +// protocol buffer types. +func (p *Buffer) DecodeVarint() (x uint64, err error) { + i := p.index + buf := p.buf + + if i >= len(buf) { + return 0, io.ErrUnexpectedEOF + } else if buf[i] < 0x80 { + p.index++ + return uint64(buf[i]), nil + } else if len(buf)-i < 10 { + return p.decodeVarintSlow() + } + + var b uint64 + // we already checked the first byte + x = uint64(buf[i]) - 0x80 + i++ + + b = uint64(buf[i]) + i++ + x += b << 7 + if b&0x80 == 0 { + goto done + } + x -= 0x80 << 7 + + b = uint64(buf[i]) + i++ + x += b << 14 + if b&0x80 == 0 { + goto done + } + x -= 0x80 << 14 + + b = uint64(buf[i]) + i++ + x += b << 21 + if b&0x80 == 0 { + goto done + } + x -= 0x80 << 21 + + b = uint64(buf[i]) + i++ + x += b << 28 + if b&0x80 == 0 { + goto done + } + x -= 0x80 << 28 + + b = uint64(buf[i]) + i++ + x += b << 35 + if b&0x80 == 0 { + goto done + } + x -= 0x80 << 35 + + b = uint64(buf[i]) + i++ + x += b << 42 + if b&0x80 == 0 { + goto done + } + x -= 0x80 << 42 + + b = uint64(buf[i]) + i++ + x += b << 49 + if b&0x80 == 0 { + goto done + } + x -= 0x80 << 49 + + b = uint64(buf[i]) + i++ + x += b << 56 + if b&0x80 == 0 { + goto done + } + x -= 0x80 << 56 + + b = uint64(buf[i]) + i++ + x += b << 63 + if b&0x80 == 0 { + goto done + } + // x -= 0x80 << 63 // Always zero. + + return 0, errOverflow + +done: + p.index = i + return x, nil +} + // DecodeFixed64 reads a 64-bit integer from the Buffer. // This is the format for the // fixed64, sfixed64, and double protocol buffer types. @@ -340,6 +434,8 @@ func (p *Buffer) DecodeGroup(pb Message) error { // Buffer and places the decoded result in pb. If the struct // underlying pb does not match the data in the buffer, the results can be // unpredictable. +// +// Unlike proto.Unmarshal, this does not reset pb before starting to unmarshal. func (p *Buffer) Unmarshal(pb Message) error { // If the object can unmarshal itself, let it. if u, ok := pb.(Unmarshaler); ok { @@ -378,6 +474,11 @@ func (o *Buffer) unmarshalType(st reflect.Type, prop *StructProperties, is_group wire := int(u & 0x7) if wire == WireEndGroup { if is_group { + if required > 0 { + // Not enough information to determine the exact field. + // (See below.) + return &RequiredNotSetError{"{Unknown}"} + } return nil // input is satisfied } return fmt.Errorf("proto: %s: wiretype end group for non-group", st) @@ -390,11 +491,12 @@ func (o *Buffer) unmarshalType(st reflect.Type, prop *StructProperties, is_group if !ok { // Maybe it's an extension? if prop.extendable { - if e := structPointer_Interface(base, st).(extendableProto); isExtensionField(e, int32(tag)) { + if e, _ := extendable(structPointer_Interface(base, st)); isExtensionField(e, int32(tag)) { if err = o.skip(st, tag, wire); err == nil { - ext := e.ExtensionMap()[int32(tag)] // may be missing + extmap := e.extensionsWrite() + ext := extmap[int32(tag)] // may be missing ext.enc = append(ext.enc, o.buf[oi:o.index]...) - e.ExtensionMap()[int32(tag)] = ext + extmap[int32(tag)] = ext } continue } @@ -768,10 +870,11 @@ func (o *Buffer) dec_new_map(p *Properties, base structPointer) error { } } keyelem, valelem := keyptr.Elem(), valptr.Elem() - if !keyelem.IsValid() || !valelem.IsValid() { - // We did not decode the key or the value in the map entry. - // Either way, it's an invalid map entry. - return fmt.Errorf("proto: bad map data: missing key/val") + if !keyelem.IsValid() { + keyelem = reflect.Zero(p.mtype.Key()) + } + if !valelem.IsValid() { + valelem = reflect.Zero(p.mtype.Elem()) } v.SetMapIndex(keyelem, valelem) diff --git a/vendor/github.com/golang/protobuf/proto/encode.go b/vendor/github.com/golang/protobuf/proto/encode.go index 231b07401..8b84d1b22 100644 --- a/vendor/github.com/golang/protobuf/proto/encode.go +++ b/vendor/github.com/golang/protobuf/proto/encode.go @@ -64,8 +64,16 @@ var ( // a struct with a repeated field containing a nil element. errRepeatedHasNil = errors.New("proto: repeated field has nil element") + // errOneofHasNil is the error returned if Marshal is called with + // a struct with a oneof field containing a nil element. + errOneofHasNil = errors.New("proto: oneof field has nil value") + // ErrNil is the error returned if Marshal is called with nil. ErrNil = errors.New("proto: Marshal called with nil") + + // ErrTooLarge is the error returned if Marshal is called with a + // message that encodes to >2GB. + ErrTooLarge = errors.New("proto: message encodes to over 2 GB") ) // The fundamental encoders that put bytes on the wire. @@ -74,6 +82,10 @@ var ( const maxVarintBytes = 10 // maximum length of a varint +// maxMarshalSize is the largest allowed size of an encoded protobuf, +// since C++ and Java use signed int32s for the size. +const maxMarshalSize = 1<<31 - 1 + // EncodeVarint returns the varint encoding of x. // This is the format for the // int32, int64, uint32, uint64, bool, and enum @@ -162,11 +174,11 @@ func sizeFixed32(x uint64) int { // This is the format used for the sint64 protocol buffer type. func (p *Buffer) EncodeZigzag64(x uint64) error { // use signed number to get arithmetic right shift. - return p.EncodeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63)))) + return p.EncodeVarint((x << 1) ^ uint64((int64(x) >> 63))) } func sizeZigzag64(x uint64) int { - return sizeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63)))) + return sizeVarint((x << 1) ^ uint64((int64(x) >> 63))) } // EncodeZigzag32 writes a zigzag-encoded 32-bit integer @@ -222,10 +234,6 @@ func Marshal(pb Message) ([]byte, error) { } p := NewBuffer(nil) err := p.Marshal(pb) - var state errorState - if err != nil && !state.shouldContinue(err, nil) { - return nil, err - } if p.buf == nil && err == nil { // Return a non-nil slice on success. return []byte{}, nil @@ -254,11 +262,8 @@ func (p *Buffer) Marshal(pb Message) error { // Can the object marshal itself? if m, ok := pb.(Marshaler); ok { data, err := m.Marshal() - if err != nil { - return err - } p.buf = append(p.buf, data...) - return nil + return err } t, base, err := getbase(pb) @@ -270,9 +275,12 @@ func (p *Buffer) Marshal(pb Message) error { } if collectStats { - stats.Encode++ + (stats).Encode++ // Parens are to work around a goimports bug. } + if len(p.buf) > maxMarshalSize { + return ErrTooLarge + } return err } @@ -294,7 +302,7 @@ func Size(pb Message) (n int) { } if collectStats { - stats.Size++ + (stats).Size++ // Parens are to work around a goimports bug. } return @@ -999,7 +1007,6 @@ func size_slice_struct_message(p *Properties, base structPointer) (n int) { if p.isMarshaler { m := structPointer_Interface(structp, p.stype).(Marshaler) data, _ := m.Marshal() - n += len(p.tagcode) n += sizeRawBytes(data) continue } @@ -1058,10 +1065,32 @@ func size_slice_struct_group(p *Properties, base structPointer) (n int) { // Encode an extension map. func (o *Buffer) enc_map(p *Properties, base structPointer) error { - v := *structPointer_ExtMap(base, p.field) - if err := encodeExtensionMap(v); err != nil { + exts := structPointer_ExtMap(base, p.field) + if err := encodeExtensionsMap(*exts); err != nil { return err } + + return o.enc_map_body(*exts) +} + +func (o *Buffer) enc_exts(p *Properties, base structPointer) error { + exts := structPointer_Extensions(base, p.field) + + v, mu := exts.extensionsRead() + if v == nil { + return nil + } + + mu.Lock() + defer mu.Unlock() + if err := encodeExtensionsMap(v); err != nil { + return err + } + + return o.enc_map_body(v) +} + +func (o *Buffer) enc_map_body(v map[int32]Extension) error { // Fast-path for common cases: zero or one extensions. if len(v) <= 1 { for _, e := range v { @@ -1084,8 +1113,13 @@ func (o *Buffer) enc_map(p *Properties, base structPointer) error { } func size_map(p *Properties, base structPointer) int { - v := *structPointer_ExtMap(base, p.field) - return sizeExtensionMap(v) + v := structPointer_ExtMap(base, p.field) + return extensionsMapSize(*v) +} + +func size_exts(p *Properties, base structPointer) int { + v := structPointer_Extensions(base, p.field) + return extensionsSize(v) } // Encode a map field. @@ -1114,7 +1148,7 @@ func (o *Buffer) enc_new_map(p *Properties, base structPointer) error { if err := p.mkeyprop.enc(o, p.mkeyprop, keybase); err != nil { return err } - if err := p.mvalprop.enc(o, p.mvalprop, valbase); err != nil { + if err := p.mvalprop.enc(o, p.mvalprop, valbase); err != nil && err != ErrNil { return err } return nil @@ -1124,11 +1158,6 @@ func (o *Buffer) enc_new_map(p *Properties, base structPointer) error { for _, key := range v.MapKeys() { val := v.MapIndex(key) - // The only illegal map entry values are nil message pointers. - if val.Kind() == reflect.Ptr && val.IsNil() { - return errors.New("proto: map has nil element") - } - keycopy.Set(key) valcopy.Set(val) @@ -1216,13 +1245,18 @@ func (o *Buffer) enc_struct(prop *StructProperties, base structPointer) error { return err } } + if len(o.buf) > maxMarshalSize { + return ErrTooLarge + } } } // Do oneof fields. if prop.oneofMarshaler != nil { m := structPointer_Interface(base, prop.stype).(Message) - if err := prop.oneofMarshaler(m, o); err != nil { + if err := prop.oneofMarshaler(m, o); err == ErrNil { + return errOneofHasNil + } else if err != nil { return err } } @@ -1230,6 +1264,9 @@ func (o *Buffer) enc_struct(prop *StructProperties, base structPointer) error { // Add unrecognized fields at the end. if prop.unrecField.IsValid() { v := *structPointer_Bytes(base, prop.unrecField) + if len(o.buf)+len(v) > maxMarshalSize { + return ErrTooLarge + } if len(v) > 0 { o.buf = append(o.buf, v...) } diff --git a/vendor/github.com/golang/protobuf/proto/equal.go b/vendor/github.com/golang/protobuf/proto/equal.go index f5db1def3..2ed1cf596 100644 --- a/vendor/github.com/golang/protobuf/proto/equal.go +++ b/vendor/github.com/golang/protobuf/proto/equal.go @@ -54,13 +54,17 @@ Equality is defined in this way: in a proto3 .proto file, fields are not "set"; specifically, zero length proto3 "bytes" fields are equal (nil == {}). - Two repeated fields are equal iff their lengths are the same, - and their corresponding elements are equal (a "bytes" field, - although represented by []byte, is not a repeated field) + and their corresponding elements are equal. Note a "bytes" field, + although represented by []byte, is not a repeated field and the + rule for the scalar fields described above applies. - Two unset fields are equal. - Two unknown field sets are equal if their current encoded state is equal. - Two extension sets are equal iff they have corresponding elements that are pairwise equal. + - Two map fields are equal iff their lengths are the same, + and they contain the same set of elements. Zero-length map + fields are equal. - Every other combination of things are not equal. The return value is undefined if a and b are not protocol buffers. @@ -121,9 +125,16 @@ func equalStruct(v1, v2 reflect.Value) bool { } } + if em1 := v1.FieldByName("XXX_InternalExtensions"); em1.IsValid() { + em2 := v2.FieldByName("XXX_InternalExtensions") + if !equalExtensions(v1.Type(), em1.Interface().(XXX_InternalExtensions), em2.Interface().(XXX_InternalExtensions)) { + return false + } + } + if em1 := v1.FieldByName("XXX_extensions"); em1.IsValid() { em2 := v2.FieldByName("XXX_extensions") - if !equalExtensions(v1.Type(), em1.Interface().(map[int32]Extension), em2.Interface().(map[int32]Extension)) { + if !equalExtMap(v1.Type(), em1.Interface().(map[int32]Extension), em2.Interface().(map[int32]Extension)) { return false } } @@ -184,6 +195,13 @@ func equalAny(v1, v2 reflect.Value, prop *Properties) bool { } return true case reflect.Ptr: + // Maps may have nil values in them, so check for nil. + if v1.IsNil() && v2.IsNil() { + return true + } + if v1.IsNil() != v2.IsNil() { + return false + } return equalAny(v1.Elem(), v2.Elem(), prop) case reflect.Slice: if v1.Type().Elem().Kind() == reflect.Uint8 { @@ -223,8 +241,14 @@ func equalAny(v1, v2 reflect.Value, prop *Properties) bool { } // base is the struct type that the extensions are based on. -// em1 and em2 are extension maps. -func equalExtensions(base reflect.Type, em1, em2 map[int32]Extension) bool { +// x1 and x2 are InternalExtensions. +func equalExtensions(base reflect.Type, x1, x2 XXX_InternalExtensions) bool { + em1, _ := x1.extensionsRead() + em2, _ := x2.extensionsRead() + return equalExtMap(base, em1, em2) +} + +func equalExtMap(base reflect.Type, em1, em2 map[int32]Extension) bool { if len(em1) != len(em2) { return false } diff --git a/vendor/github.com/golang/protobuf/proto/extensions.go b/vendor/github.com/golang/protobuf/proto/extensions.go index 054f4f1df..eaad21831 100644 --- a/vendor/github.com/golang/protobuf/proto/extensions.go +++ b/vendor/github.com/golang/protobuf/proto/extensions.go @@ -52,14 +52,99 @@ type ExtensionRange struct { Start, End int32 // both inclusive } -// extendableProto is an interface implemented by any protocol buffer that may be extended. +// extendableProto is an interface implemented by any protocol buffer generated by the current +// proto compiler that may be extended. type extendableProto interface { + Message + ExtensionRangeArray() []ExtensionRange + extensionsWrite() map[int32]Extension + extensionsRead() (map[int32]Extension, sync.Locker) +} + +// extendableProtoV1 is an interface implemented by a protocol buffer generated by the previous +// version of the proto compiler that may be extended. +type extendableProtoV1 interface { Message ExtensionRangeArray() []ExtensionRange ExtensionMap() map[int32]Extension } +// extensionAdapter is a wrapper around extendableProtoV1 that implements extendableProto. +type extensionAdapter struct { + extendableProtoV1 +} + +func (e extensionAdapter) extensionsWrite() map[int32]Extension { + return e.ExtensionMap() +} + +func (e extensionAdapter) extensionsRead() (map[int32]Extension, sync.Locker) { + return e.ExtensionMap(), notLocker{} +} + +// notLocker is a sync.Locker whose Lock and Unlock methods are nops. +type notLocker struct{} + +func (n notLocker) Lock() {} +func (n notLocker) Unlock() {} + +// extendable returns the extendableProto interface for the given generated proto message. +// If the proto message has the old extension format, it returns a wrapper that implements +// the extendableProto interface. +func extendable(p interface{}) (extendableProto, bool) { + if ep, ok := p.(extendableProto); ok { + return ep, ok + } + if ep, ok := p.(extendableProtoV1); ok { + return extensionAdapter{ep}, ok + } + return nil, false +} + +// XXX_InternalExtensions is an internal representation of proto extensions. +// +// Each generated message struct type embeds an anonymous XXX_InternalExtensions field, +// thus gaining the unexported 'extensions' method, which can be called only from the proto package. +// +// The methods of XXX_InternalExtensions are not concurrency safe in general, +// but calls to logically read-only methods such as has and get may be executed concurrently. +type XXX_InternalExtensions struct { + // The struct must be indirect so that if a user inadvertently copies a + // generated message and its embedded XXX_InternalExtensions, they + // avoid the mayhem of a copied mutex. + // + // The mutex serializes all logically read-only operations to p.extensionMap. + // It is up to the client to ensure that write operations to p.extensionMap are + // mutually exclusive with other accesses. + p *struct { + mu sync.Mutex + extensionMap map[int32]Extension + } +} + +// extensionsWrite returns the extension map, creating it on first use. +func (e *XXX_InternalExtensions) extensionsWrite() map[int32]Extension { + if e.p == nil { + e.p = new(struct { + mu sync.Mutex + extensionMap map[int32]Extension + }) + e.p.extensionMap = make(map[int32]Extension) + } + return e.p.extensionMap +} + +// extensionsRead returns the extensions map for read-only use. It may be nil. +// The caller must hold the returned mutex's lock when accessing Elements within the map. +func (e *XXX_InternalExtensions) extensionsRead() (map[int32]Extension, sync.Locker) { + if e.p == nil { + return nil, nil + } + return e.p.extensionMap, &e.p.mu +} + var extendableProtoType = reflect.TypeOf((*extendableProto)(nil)).Elem() +var extendableProtoV1Type = reflect.TypeOf((*extendableProtoV1)(nil)).Elem() // ExtensionDesc represents an extension specification. // Used in generated code from the protocol compiler. @@ -69,6 +154,7 @@ type ExtensionDesc struct { Field int32 // field number Name string // fully-qualified name of extension, for text formatting Tag string // protobuf tag style + Filename string // name of the file in which the extension is defined } func (ed *ExtensionDesc) repeated() bool { @@ -92,8 +178,13 @@ type Extension struct { } // SetRawExtension is for testing only. -func SetRawExtension(base extendableProto, id int32, b []byte) { - base.ExtensionMap()[id] = Extension{enc: b} +func SetRawExtension(base Message, id int32, b []byte) { + epb, ok := extendable(base) + if !ok { + return + } + extmap := epb.extensionsWrite() + extmap[id] = Extension{enc: b} } // isExtensionField returns true iff the given field number is in an extension range. @@ -108,8 +199,12 @@ func isExtensionField(pb extendableProto, field int32) bool { // checkExtensionTypes checks that the given extension is valid for pb. func checkExtensionTypes(pb extendableProto, extension *ExtensionDesc) error { + var pbi interface{} = pb // Check the extended type. - if a, b := reflect.TypeOf(pb), reflect.TypeOf(extension.ExtendedType); a != b { + if ea, ok := pbi.(extensionAdapter); ok { + pbi = ea.extendableProtoV1 + } + if a, b := reflect.TypeOf(pbi), reflect.TypeOf(extension.ExtendedType); a != b { return errors.New("proto: bad extended type; " + b.String() + " does not extend " + a.String()) } // Check the range. @@ -155,8 +250,19 @@ func extensionProperties(ed *ExtensionDesc) *Properties { return prop } -// encodeExtensionMap encodes any unmarshaled (unencoded) extensions in m. -func encodeExtensionMap(m map[int32]Extension) error { +// encode encodes any unmarshaled (unencoded) extensions in e. +func encodeExtensions(e *XXX_InternalExtensions) error { + m, mu := e.extensionsRead() + if m == nil { + return nil // fast path + } + mu.Lock() + defer mu.Unlock() + return encodeExtensionsMap(m) +} + +// encode encodes any unmarshaled (unencoded) extensions in e. +func encodeExtensionsMap(m map[int32]Extension) error { for k, e := range m { if e.value == nil || e.desc == nil { // Extension is only in its encoded form. @@ -184,7 +290,17 @@ func encodeExtensionMap(m map[int32]Extension) error { return nil } -func sizeExtensionMap(m map[int32]Extension) (n int) { +func extensionsSize(e *XXX_InternalExtensions) (n int) { + m, mu := e.extensionsRead() + if m == nil { + return 0 + } + mu.Lock() + defer mu.Unlock() + return extensionsMapSize(m) +} + +func extensionsMapSize(m map[int32]Extension) (n int) { for _, e := range m { if e.value == nil || e.desc == nil { // Extension is only in its encoded form. @@ -209,26 +325,51 @@ func sizeExtensionMap(m map[int32]Extension) (n int) { } // HasExtension returns whether the given extension is present in pb. -func HasExtension(pb extendableProto, extension *ExtensionDesc) bool { +func HasExtension(pb Message, extension *ExtensionDesc) bool { // TODO: Check types, field numbers, etc.? - _, ok := pb.ExtensionMap()[extension.Field] + epb, ok := extendable(pb) + if !ok { + return false + } + extmap, mu := epb.extensionsRead() + if extmap == nil { + return false + } + mu.Lock() + _, ok = extmap[extension.Field] + mu.Unlock() return ok } // ClearExtension removes the given extension from pb. -func ClearExtension(pb extendableProto, extension *ExtensionDesc) { +func ClearExtension(pb Message, extension *ExtensionDesc) { + epb, ok := extendable(pb) + if !ok { + return + } // TODO: Check types, field numbers, etc.? - delete(pb.ExtensionMap(), extension.Field) + extmap := epb.extensionsWrite() + delete(extmap, extension.Field) } // GetExtension parses and returns the given extension of pb. // If the extension is not present and has no default value it returns ErrMissingExtension. -func GetExtension(pb extendableProto, extension *ExtensionDesc) (interface{}, error) { - if err := checkExtensionTypes(pb, extension); err != nil { +func GetExtension(pb Message, extension *ExtensionDesc) (interface{}, error) { + epb, ok := extendable(pb) + if !ok { + return nil, errors.New("proto: not an extendable proto") + } + + if err := checkExtensionTypes(epb, extension); err != nil { return nil, err } - emap := pb.ExtensionMap() + emap, mu := epb.extensionsRead() + if emap == nil { + return defaultExtensionValue(extension) + } + mu.Lock() + defer mu.Unlock() e, ok := emap[extension.Field] if !ok { // defaultExtensionValue returns the default value or @@ -332,10 +473,9 @@ func decodeExtension(b []byte, extension *ExtensionDesc) (interface{}, error) { // GetExtensions returns a slice of the extensions present in pb that are also listed in es. // The returned slice has the same length as es; missing extensions will appear as nil elements. func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, err error) { - epb, ok := pb.(extendableProto) + epb, ok := extendable(pb) if !ok { - err = errors.New("proto: not an extendable proto") - return + return nil, errors.New("proto: not an extendable proto") } extensions = make([]interface{}, len(es)) for i, e := range es { @@ -350,9 +490,44 @@ func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, e return } +// ExtensionDescs returns a new slice containing pb's extension descriptors, in undefined order. +// For non-registered extensions, ExtensionDescs returns an incomplete descriptor containing +// just the Field field, which defines the extension's field number. +func ExtensionDescs(pb Message) ([]*ExtensionDesc, error) { + epb, ok := extendable(pb) + if !ok { + return nil, fmt.Errorf("proto: %T is not an extendable proto.Message", pb) + } + registeredExtensions := RegisteredExtensions(pb) + + emap, mu := epb.extensionsRead() + if emap == nil { + return nil, nil + } + mu.Lock() + defer mu.Unlock() + extensions := make([]*ExtensionDesc, 0, len(emap)) + for extid, e := range emap { + desc := e.desc + if desc == nil { + desc = registeredExtensions[extid] + if desc == nil { + desc = &ExtensionDesc{Field: extid} + } + } + + extensions = append(extensions, desc) + } + return extensions, nil +} + // SetExtension sets the specified extension of pb to the specified value. -func SetExtension(pb extendableProto, extension *ExtensionDesc, value interface{}) error { - if err := checkExtensionTypes(pb, extension); err != nil { +func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error { + epb, ok := extendable(pb) + if !ok { + return errors.New("proto: not an extendable proto") + } + if err := checkExtensionTypes(epb, extension); err != nil { return err } typ := reflect.TypeOf(extension.ExtensionType) @@ -368,10 +543,23 @@ func SetExtension(pb extendableProto, extension *ExtensionDesc, value interface{ return fmt.Errorf("proto: SetExtension called with nil value of type %T", value) } - pb.ExtensionMap()[extension.Field] = Extension{desc: extension, value: value} + extmap := epb.extensionsWrite() + extmap[extension.Field] = Extension{desc: extension, value: value} return nil } +// ClearAllExtensions clears all extensions from pb. +func ClearAllExtensions(pb Message) { + epb, ok := extendable(pb) + if !ok { + return + } + m := epb.extensionsWrite() + for k := range m { + delete(m, k) + } +} + // A global registry of extensions. // The generated code will register the generated descriptors by calling RegisterExtension. diff --git a/vendor/github.com/golang/protobuf/proto/lib.go b/vendor/github.com/golang/protobuf/proto/lib.go index 0de8f8dff..1c225504a 100644 --- a/vendor/github.com/golang/protobuf/proto/lib.go +++ b/vendor/github.com/golang/protobuf/proto/lib.go @@ -73,7 +73,6 @@ for a protocol buffer variable v: When the .proto file specifies `syntax="proto3"`, there are some differences: - Non-repeated fields of non-message type are values instead of pointers. - - Getters are only generated for message and oneof fields. - Enum types do not get an Enum method. The simplest way to describe this is to see an example. @@ -308,7 +307,7 @@ func GetStats() Stats { return stats } // temporary Buffer and are fine for most applications. type Buffer struct { buf []byte // encode/decode byte stream - index int // write point + index int // read point // pools of basic types to amortize allocation. bools []bool @@ -889,6 +888,10 @@ func isProto3Zero(v reflect.Value) bool { return false } +// ProtoPackageIsVersion2 is referenced from generated protocol buffer files +// to assert that that code is compatible with this version of the proto package. +const ProtoPackageIsVersion2 = true + // ProtoPackageIsVersion1 is referenced from generated protocol buffer files // to assert that that code is compatible with this version of the proto package. const ProtoPackageIsVersion1 = true diff --git a/vendor/github.com/golang/protobuf/proto/message_set.go b/vendor/github.com/golang/protobuf/proto/message_set.go index e25e01e63..fd982decd 100644 --- a/vendor/github.com/golang/protobuf/proto/message_set.go +++ b/vendor/github.com/golang/protobuf/proto/message_set.go @@ -149,9 +149,21 @@ func skipVarint(buf []byte) []byte { // MarshalMessageSet encodes the extension map represented by m in the message set wire format. // It is called by generated Marshal methods on protocol buffer messages with the message_set_wire_format option. -func MarshalMessageSet(m map[int32]Extension) ([]byte, error) { - if err := encodeExtensionMap(m); err != nil { - return nil, err +func MarshalMessageSet(exts interface{}) ([]byte, error) { + var m map[int32]Extension + switch exts := exts.(type) { + case *XXX_InternalExtensions: + if err := encodeExtensions(exts); err != nil { + return nil, err + } + m, _ = exts.extensionsRead() + case map[int32]Extension: + if err := encodeExtensionsMap(exts); err != nil { + return nil, err + } + m = exts + default: + return nil, errors.New("proto: not an extension map") } // Sort extension IDs to provide a deterministic encoding. @@ -178,7 +190,17 @@ func MarshalMessageSet(m map[int32]Extension) ([]byte, error) { // UnmarshalMessageSet decodes the extension map encoded in buf in the message set wire format. // It is called by generated Unmarshal methods on protocol buffer messages with the message_set_wire_format option. -func UnmarshalMessageSet(buf []byte, m map[int32]Extension) error { +func UnmarshalMessageSet(buf []byte, exts interface{}) error { + var m map[int32]Extension + switch exts := exts.(type) { + case *XXX_InternalExtensions: + m = exts.extensionsWrite() + case map[int32]Extension: + m = exts + default: + return errors.New("proto: not an extension map") + } + ms := new(messageSet) if err := Unmarshal(buf, ms); err != nil { return err @@ -209,7 +231,16 @@ func UnmarshalMessageSet(buf []byte, m map[int32]Extension) error { // MarshalMessageSetJSON encodes the extension map represented by m in JSON format. // It is called by generated MarshalJSON methods on protocol buffer messages with the message_set_wire_format option. -func MarshalMessageSetJSON(m map[int32]Extension) ([]byte, error) { +func MarshalMessageSetJSON(exts interface{}) ([]byte, error) { + var m map[int32]Extension + switch exts := exts.(type) { + case *XXX_InternalExtensions: + m, _ = exts.extensionsRead() + case map[int32]Extension: + m = exts + default: + return nil, errors.New("proto: not an extension map") + } var b bytes.Buffer b.WriteByte('{') @@ -252,7 +283,7 @@ func MarshalMessageSetJSON(m map[int32]Extension) ([]byte, error) { // UnmarshalMessageSetJSON decodes the extension map encoded in buf in JSON format. // It is called by generated UnmarshalJSON methods on protocol buffer messages with the message_set_wire_format option. -func UnmarshalMessageSetJSON(buf []byte, m map[int32]Extension) error { +func UnmarshalMessageSetJSON(buf []byte, exts interface{}) error { // Common-case fast path. if len(buf) == 0 || bytes.Equal(buf, []byte("{}")) { return nil diff --git a/vendor/github.com/golang/protobuf/proto/pointer_reflect.go b/vendor/github.com/golang/protobuf/proto/pointer_reflect.go index 749919d25..fb512e2e1 100644 --- a/vendor/github.com/golang/protobuf/proto/pointer_reflect.go +++ b/vendor/github.com/golang/protobuf/proto/pointer_reflect.go @@ -29,7 +29,7 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// +build appengine +// +build appengine js // This file contains an implementation of proto field accesses using package reflect. // It is slower than the code in pointer_unsafe.go but it avoids package unsafe and can @@ -139,6 +139,11 @@ func structPointer_StringSlice(p structPointer, f field) *[]string { return structPointer_ifield(p, f).(*[]string) } +// Extensions returns the address of an extension map field in the struct. +func structPointer_Extensions(p structPointer, f field) *XXX_InternalExtensions { + return structPointer_ifield(p, f).(*XXX_InternalExtensions) +} + // ExtMap returns the address of an extension map field in the struct. func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension { return structPointer_ifield(p, f).(*map[int32]Extension) diff --git a/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go b/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go index e9be0fe92..6b5567d47 100644 --- a/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go +++ b/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go @@ -29,7 +29,7 @@ // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// +build !appengine +// +build !appengine,!js // This file contains the implementation of the proto field accesses using package unsafe. @@ -126,6 +126,10 @@ func structPointer_StringSlice(p structPointer, f field) *[]string { } // ExtMap returns the address of an extension map field in the struct. +func structPointer_Extensions(p structPointer, f field) *XXX_InternalExtensions { + return (*XXX_InternalExtensions)(unsafe.Pointer(uintptr(p) + uintptr(f))) +} + func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension { return (*map[int32]Extension)(unsafe.Pointer(uintptr(p) + uintptr(f))) } diff --git a/vendor/github.com/golang/protobuf/proto/properties.go b/vendor/github.com/golang/protobuf/proto/properties.go index 4fe2ec22e..ec2289c00 100644 --- a/vendor/github.com/golang/protobuf/proto/properties.go +++ b/vendor/github.com/golang/protobuf/proto/properties.go @@ -473,17 +473,13 @@ func (p *Properties) setEncAndDec(typ reflect.Type, f *reflect.StructField, lock p.dec = (*Buffer).dec_slice_int64 p.packedDec = (*Buffer).dec_slice_packed_int64 case reflect.Uint8: - p.enc = (*Buffer).enc_slice_byte p.dec = (*Buffer).dec_slice_byte - p.size = size_slice_byte - // This is a []byte, which is either a bytes field, - // or the value of a map field. In the latter case, - // we always encode an empty []byte, so we should not - // use the proto3 enc/size funcs. - // f == nil iff this is the key/value of a map field. - if p.proto3 && f != nil { + if p.proto3 { p.enc = (*Buffer).enc_proto3_slice_byte p.size = size_proto3_slice_byte + } else { + p.enc = (*Buffer).enc_slice_byte + p.size = size_slice_byte } case reflect.Float32, reflect.Float64: switch t2.Bits() { @@ -682,7 +678,8 @@ func getPropertiesLocked(t reflect.Type) *StructProperties { propertiesMap[t] = prop // build properties - prop.extendable = reflect.PtrTo(t).Implements(extendableProtoType) + prop.extendable = reflect.PtrTo(t).Implements(extendableProtoType) || + reflect.PtrTo(t).Implements(extendableProtoV1Type) prop.unrecField = invalidField prop.Prop = make([]*Properties, t.NumField()) prop.order = make([]int, t.NumField()) @@ -693,15 +690,22 @@ func getPropertiesLocked(t reflect.Type) *StructProperties { name := f.Name p.init(f.Type, name, f.Tag.Get("protobuf"), &f, false) - if f.Name == "XXX_extensions" { // special case + if f.Name == "XXX_InternalExtensions" { // special case + p.enc = (*Buffer).enc_exts + p.dec = nil // not needed + p.size = size_exts + } else if f.Name == "XXX_extensions" { // special case p.enc = (*Buffer).enc_map p.dec = nil // not needed p.size = size_map - } - if f.Name == "XXX_unrecognized" { // special case + } else if f.Name == "XXX_unrecognized" { // special case prop.unrecField = toField(&f) } - oneof := f.Tag.Get("protobuf_oneof") != "" // special case + oneof := f.Tag.Get("protobuf_oneof") // special case + if oneof != "" { + // Oneof fields don't use the traditional protobuf tag. + p.OrigName = oneof + } prop.Prop[i] = p prop.order[i] = i if debug { @@ -711,7 +715,7 @@ func getPropertiesLocked(t reflect.Type) *StructProperties { } print("\n") } - if p.enc == nil && !strings.HasPrefix(f.Name, "XXX_") && !oneof { + if p.enc == nil && !strings.HasPrefix(f.Name, "XXX_") && oneof == "" { fmt.Fprintln(os.Stderr, "proto: no encoder for", f.Name, f.Type.String(), "[GetProperties]") } } @@ -840,7 +844,29 @@ func RegisterType(x Message, name string) { } // MessageName returns the fully-qualified proto name for the given message type. -func MessageName(x Message) string { return revProtoTypes[reflect.TypeOf(x)] } +func MessageName(x Message) string { + type xname interface { + XXX_MessageName() string + } + if m, ok := x.(xname); ok { + return m.XXX_MessageName() + } + return revProtoTypes[reflect.TypeOf(x)] +} // MessageType returns the message type (pointer to struct) for a named message. func MessageType(name string) reflect.Type { return protoTypes[name] } + +// A registry of all linked proto files. +var ( + protoFiles = make(map[string][]byte) // file name => fileDescriptor +) + +// RegisterFile is called from generated code and maps from the +// full file name of a .proto file to its compressed FileDescriptorProto. +func RegisterFile(filename string, fileDescriptor []byte) { + protoFiles[filename] = fileDescriptor +} + +// FileDescriptor returns the compressed FileDescriptorProto for a .proto file. +func FileDescriptor(filename string) []byte { return protoFiles[filename] } diff --git a/vendor/github.com/golang/protobuf/proto/text.go b/vendor/github.com/golang/protobuf/proto/text.go index 1cbaf86d3..965876bf0 100644 --- a/vendor/github.com/golang/protobuf/proto/text.go +++ b/vendor/github.com/golang/protobuf/proto/text.go @@ -154,7 +154,7 @@ func (w *textWriter) indent() { w.ind++ } func (w *textWriter) unindent() { if w.ind == 0 { - log.Printf("proto: textWriter unindented too far") + log.Print("proto: textWriter unindented too far") return } w.ind-- @@ -175,7 +175,93 @@ type raw interface { Bytes() []byte } -func writeStruct(w *textWriter, sv reflect.Value) error { +func requiresQuotes(u string) bool { + // When type URL contains any characters except [0-9A-Za-z./\-]*, it must be quoted. + for _, ch := range u { + switch { + case ch == '.' || ch == '/' || ch == '_': + continue + case '0' <= ch && ch <= '9': + continue + case 'A' <= ch && ch <= 'Z': + continue + case 'a' <= ch && ch <= 'z': + continue + default: + return true + } + } + return false +} + +// isAny reports whether sv is a google.protobuf.Any message +func isAny(sv reflect.Value) bool { + type wkt interface { + XXX_WellKnownType() string + } + t, ok := sv.Addr().Interface().(wkt) + return ok && t.XXX_WellKnownType() == "Any" +} + +// writeProto3Any writes an expanded google.protobuf.Any message. +// +// It returns (false, nil) if sv value can't be unmarshaled (e.g. because +// required messages are not linked in). +// +// It returns (true, error) when sv was written in expanded format or an error +// was encountered. +func (tm *TextMarshaler) writeProto3Any(w *textWriter, sv reflect.Value) (bool, error) { + turl := sv.FieldByName("TypeUrl") + val := sv.FieldByName("Value") + if !turl.IsValid() || !val.IsValid() { + return true, errors.New("proto: invalid google.protobuf.Any message") + } + + b, ok := val.Interface().([]byte) + if !ok { + return true, errors.New("proto: invalid google.protobuf.Any message") + } + + parts := strings.Split(turl.String(), "/") + mt := MessageType(parts[len(parts)-1]) + if mt == nil { + return false, nil + } + m := reflect.New(mt.Elem()) + if err := Unmarshal(b, m.Interface().(Message)); err != nil { + return false, nil + } + w.Write([]byte("[")) + u := turl.String() + if requiresQuotes(u) { + writeString(w, u) + } else { + w.Write([]byte(u)) + } + if w.compact { + w.Write([]byte("]:<")) + } else { + w.Write([]byte("]: <\n")) + w.ind++ + } + if err := tm.writeStruct(w, m.Elem()); err != nil { + return true, err + } + if w.compact { + w.Write([]byte("> ")) + } else { + w.ind-- + w.Write([]byte(">\n")) + } + return true, nil +} + +func (tm *TextMarshaler) writeStruct(w *textWriter, sv reflect.Value) error { + if tm.ExpandAny && isAny(sv) { + if canExpand, err := tm.writeProto3Any(w, sv); canExpand { + return err + } + } st := sv.Type() sprops := GetProperties(st) for i := 0; i < sv.NumField(); i++ { @@ -227,7 +313,7 @@ func writeStruct(w *textWriter, sv reflect.Value) error { } continue } - if err := writeAny(w, v, props); err != nil { + if err := tm.writeAny(w, v, props); err != nil { return err } if err := w.WriteByte('\n'); err != nil { @@ -269,7 +355,7 @@ func writeStruct(w *textWriter, sv reflect.Value) error { return err } } - if err := writeAny(w, key, props.mkeyprop); err != nil { + if err := tm.writeAny(w, key, props.mkeyprop); err != nil { return err } if err := w.WriteByte('\n'); err != nil { @@ -286,7 +372,7 @@ func writeStruct(w *textWriter, sv reflect.Value) error { return err } } - if err := writeAny(w, val, props.mvalprop); err != nil { + if err := tm.writeAny(w, val, props.mvalprop); err != nil { return err } if err := w.WriteByte('\n'); err != nil { @@ -358,7 +444,7 @@ func writeStruct(w *textWriter, sv reflect.Value) error { } // Enums have a String method, so writeAny will work fine. - if err := writeAny(w, fv, props); err != nil { + if err := tm.writeAny(w, fv, props); err != nil { return err } @@ -369,8 +455,8 @@ func writeStruct(w *textWriter, sv reflect.Value) error { // Extensions (the XXX_extensions field). pv := sv.Addr() - if pv.Type().Implements(extendableProtoType) { - if err := writeExtensions(w, pv); err != nil { + if _, ok := extendable(pv.Interface()); ok { + if err := tm.writeExtensions(w, pv); err != nil { return err } } @@ -400,7 +486,7 @@ func writeRaw(w *textWriter, b []byte) error { } // writeAny writes an arbitrary field. -func writeAny(w *textWriter, v reflect.Value, props *Properties) error { +func (tm *TextMarshaler) writeAny(w *textWriter, v reflect.Value, props *Properties) error { v = reflect.Indirect(v) // Floats have special cases. @@ -427,7 +513,7 @@ func writeAny(w *textWriter, v reflect.Value, props *Properties) error { switch v.Kind() { case reflect.Slice: // Should only be a []byte; repeated fields are handled in writeStruct. - if err := writeString(w, string(v.Interface().([]byte))); err != nil { + if err := writeString(w, string(v.Bytes())); err != nil { return err } case reflect.String: @@ -449,15 +535,15 @@ func writeAny(w *textWriter, v reflect.Value, props *Properties) error { } } w.indent() - if tm, ok := v.Interface().(encoding.TextMarshaler); ok { - text, err := tm.MarshalText() + if etm, ok := v.Interface().(encoding.TextMarshaler); ok { + text, err := etm.MarshalText() if err != nil { return err } if _, err = w.Write(text); err != nil { return err } - } else if err := writeStruct(w, v); err != nil { + } else if err := tm.writeStruct(w, v); err != nil { return err } w.unindent() @@ -601,19 +687,24 @@ func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } // writeExtensions writes all the extensions in pv. // pv is assumed to be a pointer to a protocol message struct that is extendable. -func writeExtensions(w *textWriter, pv reflect.Value) error { +func (tm *TextMarshaler) writeExtensions(w *textWriter, pv reflect.Value) error { emap := extensionMaps[pv.Type().Elem()] - ep := pv.Interface().(extendableProto) + ep, _ := extendable(pv.Interface()) // Order the extensions by ID. // This isn't strictly necessary, but it will give us // canonical output, which will also make testing easier. - m := ep.ExtensionMap() + m, mu := ep.extensionsRead() + if m == nil { + return nil + } + mu.Lock() ids := make([]int32, 0, len(m)) for id := range m { ids = append(ids, id) } sort.Sort(int32Slice(ids)) + mu.Unlock() for _, extNum := range ids { ext := m[extNum] @@ -636,13 +727,13 @@ func writeExtensions(w *textWriter, pv reflect.Value) error { // Repeated extensions will appear as a slice. if !desc.repeated() { - if err := writeExtension(w, desc.Name, pb); err != nil { + if err := tm.writeExtension(w, desc.Name, pb); err != nil { return err } } else { v := reflect.ValueOf(pb) for i := 0; i < v.Len(); i++ { - if err := writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil { + if err := tm.writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil { return err } } @@ -651,7 +742,7 @@ func writeExtensions(w *textWriter, pv reflect.Value) error { return nil } -func writeExtension(w *textWriter, name string, pb interface{}) error { +func (tm *TextMarshaler) writeExtension(w *textWriter, name string, pb interface{}) error { if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil { return err } @@ -660,7 +751,7 @@ func writeExtension(w *textWriter, name string, pb interface{}) error { return err } } - if err := writeAny(w, reflect.ValueOf(pb), nil); err != nil { + if err := tm.writeAny(w, reflect.ValueOf(pb), nil); err != nil { return err } if err := w.WriteByte('\n'); err != nil { @@ -687,12 +778,13 @@ func (w *textWriter) writeIndent() { // TextMarshaler is a configurable text format marshaler. type TextMarshaler struct { - Compact bool // use compact text format (one line). + Compact bool // use compact text format (one line). + ExpandAny bool // expand google.protobuf.Any messages of known types } // Marshal writes a given protocol buffer in text format. // The only errors returned are from w. -func (m *TextMarshaler) Marshal(w io.Writer, pb Message) error { +func (tm *TextMarshaler) Marshal(w io.Writer, pb Message) error { val := reflect.ValueOf(pb) if pb == nil || val.IsNil() { w.Write([]byte("")) @@ -707,11 +799,11 @@ func (m *TextMarshaler) Marshal(w io.Writer, pb Message) error { aw := &textWriter{ w: ww, complete: true, - compact: m.Compact, + compact: tm.Compact, } - if tm, ok := pb.(encoding.TextMarshaler); ok { - text, err := tm.MarshalText() + if etm, ok := pb.(encoding.TextMarshaler); ok { + text, err := etm.MarshalText() if err != nil { return err } @@ -725,7 +817,7 @@ func (m *TextMarshaler) Marshal(w io.Writer, pb Message) error { } // Dereference the received pointer so we don't have outer < and >. v := reflect.Indirect(val) - if err := writeStruct(aw, v); err != nil { + if err := tm.writeStruct(aw, v); err != nil { return err } if bw != nil { @@ -735,9 +827,9 @@ func (m *TextMarshaler) Marshal(w io.Writer, pb Message) error { } // Text is the same as Marshal, but returns the string directly. -func (m *TextMarshaler) Text(pb Message) string { +func (tm *TextMarshaler) Text(pb Message) string { var buf bytes.Buffer - m.Marshal(&buf, pb) + tm.Marshal(&buf, pb) return buf.String() } diff --git a/vendor/github.com/golang/protobuf/proto/text_parser.go b/vendor/github.com/golang/protobuf/proto/text_parser.go index 451323262..5e14513f2 100644 --- a/vendor/github.com/golang/protobuf/proto/text_parser.go +++ b/vendor/github.com/golang/protobuf/proto/text_parser.go @@ -44,6 +44,9 @@ import ( "unicode/utf8" ) +// Error string emitted when deserializing Any and fields are already set +const anyRepeatedlyUnpacked = "Any message unpacked multiple times, or %q already set" + type ParseError struct { Message string Line int // 1-based line number @@ -163,7 +166,7 @@ func (p *textParser) advance() { p.cur.offset, p.cur.line = p.offset, p.line p.cur.unquoted = "" switch p.s[0] { - case '<', '>', '{', '}', ':', '[', ']', ';', ',': + case '<', '>', '{', '}', ':', '[', ']', ';', ',', '/': // Single symbol p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)] case '"', '\'': @@ -451,7 +454,10 @@ func (p *textParser) readStruct(sv reflect.Value, terminator string) error { fieldSet := make(map[string]bool) // A struct is a sequence of "name: value", terminated by one of // '>' or '}', or the end of the input. A name may also be - // "[extension]". + // "[extension]" or "[type/url]". + // + // The whole struct can also be an expanded Any message, like: + // [type/url] < ... struct contents ... > for { tok := p.next() if tok.err != nil { @@ -461,33 +467,74 @@ func (p *textParser) readStruct(sv reflect.Value, terminator string) error { break } if tok.value == "[" { - // Looks like an extension. + // Looks like an extension or an Any. // // TODO: Check whether we need to handle // namespace rooted names (e.g. ".something.Foo"). - tok = p.next() - if tok.err != nil { - return tok.err + extName, err := p.consumeExtName() + if err != nil { + return err } + + if s := strings.LastIndex(extName, "/"); s >= 0 { + // If it contains a slash, it's an Any type URL. + messageName := extName[s+1:] + mt := MessageType(messageName) + if mt == nil { + return p.errorf("unrecognized message %q in google.protobuf.Any", messageName) + } + tok = p.next() + if tok.err != nil { + return tok.err + } + // consume an optional colon + if tok.value == ":" { + tok = p.next() + if tok.err != nil { + return tok.err + } + } + var terminator string + switch tok.value { + case "<": + terminator = ">" + case "{": + terminator = "}" + default: + return p.errorf("expected '{' or '<', found %q", tok.value) + } + v := reflect.New(mt.Elem()) + if pe := p.readStruct(v.Elem(), terminator); pe != nil { + return pe + } + b, err := Marshal(v.Interface().(Message)) + if err != nil { + return p.errorf("failed to marshal message of type %q: %v", messageName, err) + } + if fieldSet["type_url"] { + return p.errorf(anyRepeatedlyUnpacked, "type_url") + } + if fieldSet["value"] { + return p.errorf(anyRepeatedlyUnpacked, "value") + } + sv.FieldByName("TypeUrl").SetString(extName) + sv.FieldByName("Value").SetBytes(b) + fieldSet["type_url"] = true + fieldSet["value"] = true + continue + } + var desc *ExtensionDesc // This could be faster, but it's functional. // TODO: Do something smarter than a linear scan. for _, d := range RegisteredExtensions(reflect.New(st).Interface().(Message)) { - if d.Name == tok.value { + if d.Name == extName { desc = d break } } if desc == nil { - return p.errorf("unrecognized extension %q", tok.value) - } - // Check the extension terminator. - tok = p.next() - if tok.err != nil { - return tok.err - } - if tok.value != "]" { - return p.errorf("unrecognized extension terminator %q", tok.value) + return p.errorf("unrecognized extension %q", extName) } props := &Properties{} @@ -514,7 +561,7 @@ func (p *textParser) readStruct(sv reflect.Value, terminator string) error { } reqFieldErr = err } - ep := sv.Addr().Interface().(extendableProto) + ep := sv.Addr().Interface().(Message) if !rep { SetExtension(ep, desc, ext.Interface()) } else { @@ -545,7 +592,11 @@ func (p *textParser) readStruct(sv reflect.Value, terminator string) error { props = oop.Prop nv := reflect.New(oop.Type.Elem()) dst = nv.Elem().Field(0) - sv.Field(oop.Field).Set(nv) + field := sv.Field(oop.Field) + if !field.IsNil() { + return p.errorf("field '%s' would overwrite already parsed oneof '%s'", name, sv.Type().Field(oop.Field).Name) + } + field.Set(nv) } if !dst.IsValid() { return p.errorf("unknown field name %q in %v", name, st) @@ -566,8 +617,9 @@ func (p *textParser) readStruct(sv reflect.Value, terminator string) error { // The map entry should be this sequence of tokens: // < key : KEY value : VALUE > - // Technically the "key" and "value" could come in any order, - // but in practice they won't. + // However, implementations may omit key or value, and technically + // we should support them in any order. See b/28924776 for a time + // this went wrong. tok := p.next() var terminator string @@ -579,32 +631,39 @@ func (p *textParser) readStruct(sv reflect.Value, terminator string) error { default: return p.errorf("expected '{' or '<', found %q", tok.value) } - if err := p.consumeToken("key"); err != nil { - return err - } - if err := p.consumeToken(":"); err != nil { - return err - } - if err := p.readAny(key, props.mkeyprop); err != nil { - return err - } - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - if err := p.consumeToken("value"); err != nil { - return err - } - if err := p.checkForColon(props.mvalprop, dst.Type().Elem()); err != nil { - return err - } - if err := p.readAny(val, props.mvalprop); err != nil { - return err - } - if err := p.consumeOptionalSeparator(); err != nil { - return err - } - if err := p.consumeToken(terminator); err != nil { - return err + for { + tok := p.next() + if tok.err != nil { + return tok.err + } + if tok.value == terminator { + break + } + switch tok.value { + case "key": + if err := p.consumeToken(":"); err != nil { + return err + } + if err := p.readAny(key, props.mkeyprop); err != nil { + return err + } + if err := p.consumeOptionalSeparator(); err != nil { + return err + } + case "value": + if err := p.checkForColon(props.mvalprop, dst.Type().Elem()); err != nil { + return err + } + if err := p.readAny(val, props.mvalprop); err != nil { + return err + } + if err := p.consumeOptionalSeparator(); err != nil { + return err + } + default: + p.back() + return p.errorf(`expected "key", "value", or %q, found %q`, terminator, tok.value) + } } dst.SetMapIndex(key, val) @@ -627,7 +686,8 @@ func (p *textParser) readStruct(sv reflect.Value, terminator string) error { return err } reqFieldErr = err - } else if props.Required { + } + if props.Required { reqCount-- } @@ -643,6 +703,35 @@ func (p *textParser) readStruct(sv reflect.Value, terminator string) error { return reqFieldErr } +// consumeExtName consumes extension name or expanded Any type URL and the +// following ']'. It returns the name or URL consumed. +func (p *textParser) consumeExtName() (string, error) { + tok := p.next() + if tok.err != nil { + return "", tok.err + } + + // If extension name or type url is quoted, it's a single token. + if len(tok.value) > 2 && isQuote(tok.value[0]) && tok.value[len(tok.value)-1] == tok.value[0] { + name, err := unquoteC(tok.value[1:len(tok.value)-1], rune(tok.value[0])) + if err != nil { + return "", err + } + return name, p.consumeToken("]") + } + + // Consume everything up to "]" + var parts []string + for tok.value != "]" { + parts = append(parts, tok.value) + tok = p.next() + if tok.err != nil { + return "", p.errorf("unrecognized type_url or extension name: %s", tok.err) + } + } + return strings.Join(parts, ""), nil +} + // consumeOptionalSeparator consumes an optional semicolon or comma. // It is used in readStruct to provide backward compatibility. func (p *textParser) consumeOptionalSeparator() error { @@ -707,12 +796,12 @@ func (p *textParser) readAny(v reflect.Value, props *Properties) error { fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem())) return p.readAny(fv.Index(fv.Len()-1), props) case reflect.Bool: - // Either "true", "false", 1 or 0. + // true/1/t/True or false/f/0/False. switch tok.value { - case "true", "1": + case "true", "1", "t", "True": fv.SetBool(true) return nil - case "false", "0": + case "false", "0", "f", "False": fv.SetBool(false) return nil } @@ -776,7 +865,7 @@ func (p *textParser) readAny(v reflect.Value, props *Properties) error { return p.readStruct(fv, terminator) case reflect.Uint32: if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil { - fv.SetUint(uint64(x)) + fv.SetUint(x) return nil } case reflect.Uint64: diff --git a/vendor/github.com/google/go-github/github/activity_events.go b/vendor/github.com/google/go-github/github/activity_events.go index 78219f8ab..6b35056f4 100644 --- a/vendor/github.com/google/go-github/github/activity_events.go +++ b/vendor/github.com/google/go-github/github/activity_events.go @@ -46,10 +46,10 @@ func (e *Event) ParsePayload() (payload interface{}, err error) { payload = &ForkEvent{} case "GollumEvent": payload = &GollumEvent{} - case "IntegrationInstallationEvent": - payload = &IntegrationInstallationEvent{} - case "IntegrationInstallationRepositoriesEvent": - payload = &IntegrationInstallationRepositoriesEvent{} + case "InstallationEvent": + payload = &InstallationEvent{} + case "InstallationRepositoriesEvent": + payload = &InstallationRepositoriesEvent{} case "IssueCommentEvent": payload = &IssueCommentEvent{} case "IssuesEvent": @@ -64,6 +64,8 @@ func (e *Event) ParsePayload() (payload interface{}, err error) { payload = &MilestoneEvent{} case "OrganizationEvent": payload = &OrganizationEvent{} + case "OrgBlockEvent": + payload = &OrgBlockEvent{} case "PageBuildEvent": payload = &PageBuildEvent{} case "PingEvent": @@ -90,6 +92,8 @@ func (e *Event) ParsePayload() (payload interface{}, err error) { payload = &RepositoryEvent{} case "StatusEvent": payload = &StatusEvent{} + case "TeamEvent": + payload = &TeamEvent{} case "TeamAddEvent": payload = &TeamAddEvent{} case "WatchEvent": diff --git a/vendor/github.com/google/go-github/github/integration.go b/vendor/github.com/google/go-github/github/apps.go similarity index 54% rename from vendor/github.com/google/go-github/github/integration.go rename to vendor/github.com/google/go-github/github/apps.go index 6d74e44f0..ff3389382 100644 --- a/vendor/github.com/google/go-github/github/integration.go +++ b/vendor/github.com/google/go-github/github/apps.go @@ -7,17 +7,17 @@ package github import "context" -// IntegrationsService provides access to the installation related functions +// AppsService provides access to the installation related functions // in the GitHub API. // -// GitHub API docs: https://developer.github.com/v3/integrations/ -type IntegrationsService service +// GitHub API docs: https://developer.github.com/v3/apps/ +type AppsService service -// ListInstallations lists the installations that the current integration has. +// ListInstallations lists the installations that the current GitHub App has. // -// GitHub API docs: https://developer.github.com/v3/integrations/#find-installations -func (s *IntegrationsService) ListInstallations(ctx context.Context, opt *ListOptions) ([]*Installation, *Response, error) { - u, err := addOptions("integration/installations", opt) +// GitHub API docs: https://developer.github.com/v3/apps/#find-installations +func (s *AppsService) ListInstallations(ctx context.Context, opt *ListOptions) ([]*Installation, *Response, error) { + u, err := addOptions("app/installations", opt) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/github/integration_installation.go b/vendor/github.com/google/go-github/github/apps_installation.go similarity index 75% rename from vendor/github.com/google/go-github/github/integration_installation.go rename to vendor/github.com/google/go-github/github/apps_installation.go index 0836d86d1..6a2779953 100644 --- a/vendor/github.com/google/go-github/github/integration_installation.go +++ b/vendor/github.com/google/go-github/github/apps_installation.go @@ -7,7 +7,7 @@ package github import "context" -// Installation represents a GitHub integration installation. +// Installation represents a GitHub Apps installation. type Installation struct { ID *int `json:"id,omitempty"` Account *User `json:"account,omitempty"` @@ -20,10 +20,10 @@ func (i Installation) String() string { return Stringify(i) } -// ListRepos lists the repositories that the current installation has access to. +// ListRepos lists the repositories that are accessible to the authenticated installation. // -// GitHub API docs: https://developer.github.com/v3/integrations/installations/#list-repositories -func (s *IntegrationsService) ListRepos(ctx context.Context, opt *ListOptions) ([]*Repository, *Response, error) { +// GitHub API docs: https://developer.github.com/v3/apps/installations/#list-repositories +func (s *AppsService) ListRepos(ctx context.Context, opt *ListOptions) ([]*Repository, *Response, error) { u, err := addOptions("installation/repositories", opt) if err != nil { return nil, nil, err diff --git a/vendor/github.com/google/go-github/github/authorizations.go b/vendor/github.com/google/go-github/github/authorizations.go index 181e83dfe..638745ac1 100644 --- a/vendor/github.com/google/go-github/github/authorizations.go +++ b/vendor/github.com/google/go-github/github/authorizations.go @@ -63,7 +63,7 @@ type Authorization struct { App *AuthorizationApp `json:"app,omitempty"` Note *string `json:"note,omitempty"` NoteURL *string `json:"note_url,omitempty"` - UpdateAt *Timestamp `json:"updated_at,omitempty"` + UpdatedAt *Timestamp `json:"updated_at,omitempty"` CreatedAt *Timestamp `json:"created_at,omitempty"` Fingerprint *string `json:"fingerprint,omitempty"` @@ -343,8 +343,13 @@ func (s *AuthorizationsService) Revoke(ctx context.Context, clientID string, tok // tokens an application has generated for the user. // // GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#list-your-grants -func (s *AuthorizationsService) ListGrants(ctx context.Context) ([]*Grant, *Response, error) { - req, err := s.client.NewRequest("GET", "applications/grants", nil) +func (s *AuthorizationsService) ListGrants(ctx context.Context, opt *ListOptions) ([]*Grant, *Response, error) { + u, err := addOptions("applications/grants", opt) + if err != nil { + return nil, nil, err + } + + req, err := s.client.NewRequest("GET", u, nil) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/github/doc.go b/vendor/github.com/google/go-github/github/doc.go index 0acf3281f..4ba03cb3c 100644 --- a/vendor/github.com/google/go-github/github/doc.go +++ b/vendor/github.com/google/go-github/github/doc.go @@ -63,19 +63,38 @@ See the oauth2 docs for complete instructions on using that library. For API methods that require HTTP Basic Authentication, use the BasicAuthTransport. +GitHub Apps authentication can be provided by the +https://github.com/bradleyfalzon/ghinstallation package. + + import "github.com/bradleyfalzon/ghinstallation" + + func main() { + // Wrap the shared transport for use with the integration ID 1 authenticating with installation ID 99. + itr, err := ghinstallation.NewKeyFromFile(http.DefaultTransport, 1, 99, "2016-10-19.private-key.pem") + if err != nil { + // Handle error. + } + + // Use installation transport with client + client := github.NewClient(&http.Client{Transport: itr}) + + // Use client... + } + Rate Limiting GitHub imposes a rate limit on all API clients. Unauthenticated clients are limited to 60 requests per hour, while authenticated clients can make up to -5,000 requests per hour. To receive the higher rate limit when making calls -that are not issued on behalf of a user, use the -UnauthenticatedRateLimitedTransport. +5,000 requests per hour. The Search API has a custom rate limit. Unauthenticated +clients are limited to 10 requests per minute, while authenticated clients +can make up to 30 requests per minute. To receive the higher rate limit when +making calls that are not issued on behalf of a user, +use UnauthenticatedRateLimitedTransport. -The Rate method on a client returns the rate limit information based on the most -recent API call. This is updated on every call, but may be out of date if it's -been some time since the last API call and other clients have made subsequent -requests since then. You can always call RateLimits() directly to get the most -up-to-date rate limit data for the client. +The returned Response.Rate value contains the rate limit information +from the most recent API call. If a recent enough response isn't +available, you can use RateLimits to fetch the most up-to-date rate +limit data for the client. To detect an API rate limit error, you can check if its type is *github.RateLimitError: @@ -154,7 +173,7 @@ github.Response struct. if resp.NextPage == 0 { break } - opt.ListOptions.Page = resp.NextPage + opt.Page = resp.NextPage } Google App Engine @@ -164,7 +183,7 @@ the "context" import and still relies on "golang.org/x/net/context". As a result, if you wish to continue to use "go-github" on App Engine Classic, you will need to rewrite all the "context" imports using the following command: - gofmt -w -r '"context" -> "golang.org/x/net/context"' *.go + gofmt -w -r '"context" -> "golang.org/x/net/context"' *.go See "with_appengine.go" for more details. diff --git a/vendor/github.com/google/go-github/github/event_types.go b/vendor/github.com/google/go-github/github/event_types.go index acf139b1e..c6b29b9a2 100644 --- a/vendor/github.com/google/go-github/github/event_types.go +++ b/vendor/github.com/google/go-github/github/event_types.go @@ -165,28 +165,49 @@ type ProjectColumnChange struct { } `json:"name,omitempty"` } -// IntegrationInstallationEvent is triggered when an integration is created or deleted. -// The Webhook event name is "integration_installation". +// TeamChange represents the changes when a team has been edited. +type TeamChange struct { + Description *struct { + From *string `json:"from,omitempty"` + } `json:"description,omitempty"` + Name *struct { + From *string `json:"from,omitempty"` + } `json:"name,omitempty"` + Privacy *struct { + From *string `json:"from,omitempty"` + } `json:"privacy,omitempty"` + Repository *struct { + Permissions *struct { + From *struct { + Admin *bool `json:"admin,omitempty"` + Pull *bool `json:"pull,omitempty"` + Push *bool `json:"push,omitempty"` + } `json:"from,omitempty"` + } `json:"permissions,omitempty"` + } `json:"repository,omitempty"` +} + +// InstallationEvent is triggered when a GitHub App has been installed or uninstalled. +// The Webhook event name is "installation". // -// GitHub API docs: https://developer.github.com/early-access/integrations/webhooks/#integrationinstallationevent -type IntegrationInstallationEvent struct { - // The action that was performed. Possible values for an "integration_installation" - // event are: "created", "deleted". +// GitHub API docs: https://developer.github.com/v3/activity/events/types/#installationevent +type InstallationEvent struct { + // The action that was performed. Can be either "created" or "deleted". Action *string `json:"action,omitempty"` Sender *User `json:"sender,omitempty"` Installation *Installation `json:"installation,omitempty"` } -// IntegrationInstallationRepositoriesEvent is triggered when an integration repository -// is added or removed. The Webhook event name is "integration_installation_repositories". +// InstallationRepositoriesEvent is triggered when a repository is added or +// removed from an installation. The Webhook event name is "installation_repositories". // -// GitHub API docs: https://developer.github.com/early-access/integrations/webhooks/#integrationinstallationrepositoriesevent -type IntegrationInstallationRepositoriesEvent struct { - // The action that was performed. Possible values for an "integration_installation_repositories" - // event are: "added", "removed". +// GitHub API docs: https://developer.github.com/v3/activity/events/types/#installationrepositoriesevent +type InstallationRepositoriesEvent struct { + // The action that was performed. Can be either "added" or "removed". Action *string `json:"action,omitempty"` RepositoriesAdded []*Repository `json:"repositories_added,omitempty"` RepositoriesRemoved []*Repository `json:"repositories_removed,omitempty"` + RepositorySelection *string `json:"repository_selection,omitempty"` Sender *User `json:"sender,omitempty"` Installation *Installation `json:"installation,omitempty"` } @@ -323,6 +344,22 @@ type OrganizationEvent struct { Installation *Installation `json:"installation,omitempty"` } +// OrgBlockEvent is triggered when an organization blocks or unblocks a user. +// The Webhook event name is "org_block". +// +// GitHub API docs: https://developer.github.com/v3/activity/events/types/#orgblockevent +type OrgBlockEvent struct { + // Action is the action that was performed. + // Can be "blocked" or "unblocked". + Action *string `json:"action,omitempty"` + BlockedUser *User `json:"blocked_user,omitempty"` + Organization *Organization `json:"organization,omitempty"` + Sender *User `json:"sender,omitempty"` + + // The following fields are only populated by Webhook events. + Installation *Installation `json:"installation,omitempty"` +} + // PageBuildEvent represents an attempted build of a GitHub Pages site, whether // successful or not. // The Webhook event name is "page_build". @@ -637,6 +674,25 @@ type StatusEvent struct { Installation *Installation `json:"installation,omitempty"` } +// TeamEvent is triggered when an organization's team is created, modified or deleted. +// The Webhook event name is "team". +// +// Events of this type are not visible in timelines. These events are only used +// to trigger hooks. +// +// GitHub API docs: https://developer.github.com/v3/activity/events/types/#teamevent +type TeamEvent struct { + Action *string `json:"action,omitempty"` + Team *Team `json:"team,omitempty"` + Changes *TeamChange `json:"changes,omitempty"` + Repo *Repository `json:"repository,omitempty"` + + // The following fields are only populated by Webhook events. + Org *Organization `json:"organization,omitempty"` + Sender *User `json:"sender,omitempty"` + Installation *Installation `json:"installation,omitempty"` +} + // TeamAddEvent is triggered when a repository is added to a team. // The Webhook event name is "team_add". // diff --git a/vendor/github.com/google/go-github/github/gen-accessors.go b/vendor/github.com/google/go-github/github/gen-accessors.go deleted file mode 100644 index 131c56cbf..000000000 --- a/vendor/github.com/google/go-github/github/gen-accessors.go +++ /dev/null @@ -1,299 +0,0 @@ -// Copyright 2017 The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// gen-accessors generates accessor methods for structs with pointer fields. -// -// It is meant to be used by the go-github authors in conjunction with the -// go generate tool before sending a commit to GitHub. -package main - -import ( - "bytes" - "flag" - "fmt" - "go/ast" - "go/format" - "go/parser" - "go/token" - "io/ioutil" - "log" - "os" - "sort" - "strings" - "text/template" - "time" -) - -const ( - fileSuffix = "-accessors.go" -) - -var ( - verbose = flag.Bool("v", false, "Print verbose log messages") - - sourceTmpl = template.Must(template.New("source").Parse(source)) - - // blacklist lists which "struct.method" combos to not generate. - blacklist = map[string]bool{ - "RepositoryContent.GetContent": true, - "Client.GetBaseURL": true, - "Client.GetUploadURL": true, - "ErrorResponse.GetResponse": true, - "RateLimitError.GetResponse": true, - "AbuseRateLimitError.GetResponse": true, - } -) - -func logf(fmt string, args ...interface{}) { - if *verbose { - log.Printf(fmt, args...) - } -} - -func main() { - flag.Parse() - fset := token.NewFileSet() - - pkgs, err := parser.ParseDir(fset, ".", sourceFilter, 0) - if err != nil { - log.Fatal(err) - return - } - - for pkgName, pkg := range pkgs { - t := &templateData{ - filename: pkgName + fileSuffix, - Year: time.Now().Year(), - Package: pkgName, - Imports: map[string]string{}, - } - for filename, f := range pkg.Files { - logf("Processing %v...", filename) - if err := t.processAST(f); err != nil { - log.Fatal(err) - } - } - if err := t.dump(); err != nil { - log.Fatal(err) - } - } - logf("Done.") -} - -func (t *templateData) processAST(f *ast.File) error { - for _, decl := range f.Decls { - gd, ok := decl.(*ast.GenDecl) - if !ok { - continue - } - for _, spec := range gd.Specs { - ts, ok := spec.(*ast.TypeSpec) - if !ok { - continue - } - st, ok := ts.Type.(*ast.StructType) - if !ok { - continue - } - for _, field := range st.Fields.List { - se, ok := field.Type.(*ast.StarExpr) - if len(field.Names) == 0 || !ok { - continue - } - - fieldName := field.Names[0] - if key := fmt.Sprintf("%v.Get%v", ts.Name, fieldName); blacklist[key] { - logf("Method %v blacklisted; skipping.", key) - continue - } - - switch x := se.X.(type) { - case *ast.ArrayType: - t.addArrayType(x, ts.Name.String(), fieldName.String()) - case *ast.Ident: - t.addIdent(x, ts.Name.String(), fieldName.String()) - case *ast.MapType: - t.addMapType(x, ts.Name.String(), fieldName.String()) - case *ast.SelectorExpr: - t.addSelectorExpr(x, ts.Name.String(), fieldName.String()) - default: - logf("processAST: type %q, field %q, unknown %T: %+v", ts.Name, fieldName, x, x) - } - } - } - } - return nil -} - -func sourceFilter(fi os.FileInfo) bool { - return !strings.HasSuffix(fi.Name(), "_test.go") && !strings.HasSuffix(fi.Name(), fileSuffix) -} - -func (t *templateData) dump() error { - if len(t.Getters) == 0 { - logf("No getters for %v; skipping.", t.filename) - return nil - } - - // Sort getters by ReceiverType.FieldName - sort.Sort(byName(t.Getters)) - - var buf bytes.Buffer - if err := sourceTmpl.Execute(&buf, t); err != nil { - return err - } - clean, err := format.Source(buf.Bytes()) - if err != nil { - return err - } - - logf("Writing %v...", t.filename) - return ioutil.WriteFile(t.filename, clean, 0644) -} - -func newGetter(receiverType, fieldName, fieldType, zeroValue string) *getter { - return &getter{ - sortVal: strings.ToLower(receiverType) + "." + strings.ToLower(fieldName), - ReceiverVar: strings.ToLower(receiverType[:1]), - ReceiverType: receiverType, - FieldName: fieldName, - FieldType: fieldType, - ZeroValue: zeroValue, - } -} - -func (t *templateData) addArrayType(x *ast.ArrayType, receiverType, fieldName string) { - var eltType string - switch elt := x.Elt.(type) { - case *ast.Ident: - eltType = elt.String() - default: - logf("addArrayType: type %q, field %q: unknown elt type: %T %+v; skipping.", receiverType, fieldName, elt, elt) - return - } - - t.Getters = append(t.Getters, newGetter(receiverType, fieldName, "[]"+eltType, "nil")) -} - -func (t *templateData) addIdent(x *ast.Ident, receiverType, fieldName string) { - var zeroValue string - switch x.String() { - case "int": - zeroValue = "0" - case "string": - zeroValue = `""` - case "bool": - zeroValue = "false" - case "Timestamp": - zeroValue = "Timestamp{}" - default: // other structs handled by their receivers directly. - return - } - - t.Getters = append(t.Getters, newGetter(receiverType, fieldName, x.String(), zeroValue)) -} - -func (t *templateData) addMapType(x *ast.MapType, receiverType, fieldName string) { - var keyType string - switch key := x.Key.(type) { - case *ast.Ident: - keyType = key.String() - default: - logf("addMapType: type %q, field %q: unknown key type: %T %+v; skipping.", receiverType, fieldName, key, key) - return - } - - var valueType string - switch value := x.Value.(type) { - case *ast.Ident: - valueType = value.String() - default: - logf("addMapType: type %q, field %q: unknown value type: %T %+v; skipping.", receiverType, fieldName, value, value) - return - } - - fieldType := fmt.Sprintf("map[%v]%v", keyType, valueType) - zeroValue := fmt.Sprintf("map[%v]%v{}", keyType, valueType) - t.Getters = append(t.Getters, newGetter(receiverType, fieldName, fieldType, zeroValue)) -} - -func (t *templateData) addSelectorExpr(x *ast.SelectorExpr, receiverType, fieldName string) { - if strings.ToLower(fieldName[:1]) == fieldName[:1] { // non-exported field - return - } - - var xX string - if xx, ok := x.X.(*ast.Ident); ok { - xX = xx.String() - } - - switch xX { - case "time", "json": - if xX == "json" { - t.Imports["encoding/json"] = "encoding/json" - } else { - t.Imports[xX] = xX - } - fieldType := fmt.Sprintf("%v.%v", xX, x.Sel.Name) - zeroValue := fmt.Sprintf("%v.%v{}", xX, x.Sel.Name) - if xX == "time" && x.Sel.Name == "Duration" { - zeroValue = "0" - } - t.Getters = append(t.Getters, newGetter(receiverType, fieldName, fieldType, zeroValue)) - default: - logf("addSelectorExpr: xX %q, type %q, field %q: unknown x=%+v; skipping.", xX, receiverType, fieldName, x) - } -} - -type templateData struct { - filename string - Year int - Package string - Imports map[string]string - Getters []*getter -} - -type getter struct { - sortVal string // lower-case version of "ReceiverType.FieldName" - ReceiverVar string // the one-letter variable name to match the ReceiverType - ReceiverType string - FieldName string - FieldType string - ZeroValue string -} - -type byName []*getter - -func (b byName) Len() int { return len(b) } -func (b byName) Less(i, j int) bool { return b[i].sortVal < b[j].sortVal } -func (b byName) Swap(i, j int) { b[i], b[j] = b[j], b[i] } - -const source = `// Copyright {{.Year}} The go-github AUTHORS. All rights reserved. -// -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Code generated by gen-accessors; DO NOT EDIT. - -package {{.Package}} -{{with .Imports}} -import ( - {{- range . -}} - "{{.}}" - {{end -}} -) -{{end}} -{{range .Getters}} -// Get{{.FieldName}} returns the {{.FieldName}} field if it's non-nil, zero value otherwise. -func ({{.ReceiverVar}} *{{.ReceiverType}}) Get{{.FieldName}}() {{.FieldType}} { - if {{.ReceiverVar}} == nil || {{.ReceiverVar}}.{{.FieldName}} == nil { - return {{.ZeroValue}} - } - return *{{.ReceiverVar}}.{{.FieldName}} -} -{{end}} -` diff --git a/vendor/github.com/google/go-github/github/gists.go b/vendor/github.com/google/go-github/github/gists.go index e7d6586c6..15276ea1d 100644 --- a/vendor/github.com/google/go-github/github/gists.go +++ b/vendor/github.com/google/go-github/github/gists.go @@ -241,8 +241,13 @@ func (s *GistsService) Edit(ctx context.Context, id string, gist *Gist) (*Gist, // ListCommits lists commits of a gist. // // GitHub API docs: https://developer.github.com/v3/gists/#list-gist-commits -func (s *GistsService) ListCommits(ctx context.Context, id string) ([]*GistCommit, *Response, error) { +func (s *GistsService) ListCommits(ctx context.Context, id string, opt *ListOptions) ([]*GistCommit, *Response, error) { u := fmt.Sprintf("gists/%v/commits", id) + u, err := addOptions(u, opt) + if err != nil { + return nil, nil, err + } + req, err := s.client.NewRequest("GET", u, nil) if err != nil { return nil, nil, err diff --git a/vendor/github.com/google/go-github/github/git_refs.go b/vendor/github.com/google/go-github/github/git_refs.go index bd5df3f72..e78fdc6c0 100644 --- a/vendor/github.com/google/go-github/github/git_refs.go +++ b/vendor/github.com/google/go-github/github/git_refs.go @@ -7,6 +7,8 @@ package github import ( "context" + "encoding/json" + "errors" "fmt" "strings" ) @@ -45,7 +47,11 @@ type updateRefRequest struct { Force *bool `json:"force"` } -// GetRef fetches the Reference object for a given Git ref. +// GetRef fetches a single Reference object for a given Git ref. +// If there is no exact match, GetRef will return an error. +// +// Note: The GitHub API can return multiple matches. +// If you wish to use this functionality please use the GetRefs() method. // // GitHub API docs: https://developer.github.com/v3/git/refs/#get-a-reference func (s *GitService) GetRef(ctx context.Context, owner string, repo string, ref string) (*Reference, *Response, error) { @@ -58,13 +64,61 @@ func (s *GitService) GetRef(ctx context.Context, owner string, repo string, ref r := new(Reference) resp, err := s.client.Do(ctx, req, r) - if err != nil { + if _, ok := err.(*json.UnmarshalTypeError); ok { + // Multiple refs, means there wasn't an exact match. + return nil, resp, errors.New("no exact match found for this ref") + } else if err != nil { return nil, resp, err } return r, resp, nil } +// GetRefs fetches a slice of Reference objects for a given Git ref. +// If there is an exact match, only that ref is returned. +// If there is no exact match, GitHub returns all refs that start with ref. +// If returned error is nil, there will be at least 1 ref returned. +// For example: +// +// "heads/featureA" -> ["refs/heads/featureA"] // Exact match, single ref is returned. +// "heads/feature" -> ["refs/heads/featureA", "refs/heads/featureB"] // All refs that start with ref. +// "heads/notexist" -> [] // Returns an error. +// +// GitHub API docs: https://developer.github.com/v3/git/refs/#get-a-reference +func (s *GitService) GetRefs(ctx context.Context, owner string, repo string, ref string) ([]*Reference, *Response, error) { + ref = strings.TrimPrefix(ref, "refs/") + u := fmt.Sprintf("repos/%v/%v/git/refs/%v", owner, repo, ref) + req, err := s.client.NewRequest("GET", u, nil) + if err != nil { + return nil, nil, err + } + + var rawJSON json.RawMessage + resp, err := s.client.Do(ctx, req, &rawJSON) + if err != nil { + return nil, resp, err + } + + // Prioritize the most common case: a single returned ref. + r := new(Reference) + singleUnmarshalError := json.Unmarshal(rawJSON, r) + if singleUnmarshalError == nil { + return []*Reference{r}, resp, nil + } + + // Attempt to unmarshal multiple refs. + var rs []*Reference + multipleUnmarshalError := json.Unmarshal(rawJSON, &rs) + if multipleUnmarshalError == nil { + if len(rs) == 0 { + return nil, resp, fmt.Errorf("unexpected response from GitHub API: an array of refs with length 0") + } + return rs, resp, nil + } + + return nil, resp, fmt.Errorf("unmarshalling failed for both single and multiple refs: %s and %s", singleUnmarshalError, multipleUnmarshalError) +} + // ReferenceListOptions specifies optional parameters to the // GitService.ListRefs method. type ReferenceListOptions struct { diff --git a/vendor/github.com/google/go-github/github/git_trees.go b/vendor/github.com/google/go-github/github/git_trees.go index bdd481f1e..4d6809a88 100644 --- a/vendor/github.com/google/go-github/github/git_trees.go +++ b/vendor/github.com/google/go-github/github/git_trees.go @@ -30,6 +30,7 @@ type TreeEntry struct { Type *string `json:"type,omitempty"` Size *int `json:"size,omitempty"` Content *string `json:"content,omitempty"` + URL *string `json:"url,omitempty"` } func (t TreeEntry) String() string { diff --git a/vendor/github.com/google/go-github/github/github-accessors.go b/vendor/github.com/google/go-github/github/github-accessors.go index c74c02548..4fed8e50a 100644 --- a/vendor/github.com/google/go-github/github/github-accessors.go +++ b/vendor/github.com/google/go-github/github/github-accessors.go @@ -20,6 +20,14 @@ func (a *AbuseRateLimitError) GetRetryAfter() time.Duration { return *a.RetryAfter } +// GetURL returns the URL field if it's non-nil, zero value otherwise. +func (a *AdminEnforcement) GetURL() string { + if a == nil || a.URL == nil { + return "" + } + return *a.URL +} + // GetVerifiablePasswordAuthentication returns the VerifiablePasswordAuthentication field if it's non-nil, zero value otherwise. func (a *APIMeta) GetVerifiablePasswordAuthentication() bool { if a == nil || a.VerifiablePasswordAuthentication == nil { @@ -92,12 +100,12 @@ func (a *Authorization) GetTokenLastEight() string { return *a.TokenLastEight } -// GetUpdateAt returns the UpdateAt field if it's non-nil, zero value otherwise. -func (a *Authorization) GetUpdateAt() Timestamp { - if a == nil || a.UpdateAt == nil { +// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. +func (a *Authorization) GetUpdatedAt() Timestamp { + if a == nil || a.UpdatedAt == nil { return Timestamp{} } - return *a.UpdateAt + return *a.UpdatedAt } // GetURL returns the URL field if it's non-nil, zero value otherwise. @@ -252,6 +260,38 @@ func (b *Branch) GetProtected() bool { return *b.Protected } +// GetBody returns the Body field if it's non-nil, zero value otherwise. +func (c *CodeOfConduct) GetBody() string { + if c == nil || c.Body == nil { + return "" + } + return *c.Body +} + +// GetKey returns the Key field if it's non-nil, zero value otherwise. +func (c *CodeOfConduct) GetKey() string { + if c == nil || c.Key == nil { + return "" + } + return *c.Key +} + +// GetName returns the Name field if it's non-nil, zero value otherwise. +func (c *CodeOfConduct) GetName() string { + if c == nil || c.Name == nil { + return "" + } + return *c.Name +} + +// GetURL returns the URL field if it's non-nil, zero value otherwise. +func (c *CodeOfConduct) GetURL() string { + if c == nil || c.URL == nil { + return "" + } + return *c.URL +} + // GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. func (c *CodeResult) GetHTMLURL() string { if c == nil || c.HTMLURL == nil { @@ -556,6 +596,38 @@ func (c *CommitsComparison) GetBehindBy() int { return *c.BehindBy } +// GetDiffURL returns the DiffURL field if it's non-nil, zero value otherwise. +func (c *CommitsComparison) GetDiffURL() string { + if c == nil || c.DiffURL == nil { + return "" + } + return *c.DiffURL +} + +// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. +func (c *CommitsComparison) GetHTMLURL() string { + if c == nil || c.HTMLURL == nil { + return "" + } + return *c.HTMLURL +} + +// GetPatchURL returns the PatchURL field if it's non-nil, zero value otherwise. +func (c *CommitsComparison) GetPatchURL() string { + if c == nil || c.PatchURL == nil { + return "" + } + return *c.PatchURL +} + +// GetPermalinkURL returns the PermalinkURL field if it's non-nil, zero value otherwise. +func (c *CommitsComparison) GetPermalinkURL() string { + if c == nil || c.PermalinkURL == nil { + return "" + } + return *c.PermalinkURL +} + // GetStatus returns the Status field if it's non-nil, zero value otherwise. func (c *CommitsComparison) GetStatus() string { if c == nil || c.Status == nil { @@ -572,6 +644,14 @@ func (c *CommitsComparison) GetTotalCommits() int { return *c.TotalCommits } +// GetURL returns the URL field if it's non-nil, zero value otherwise. +func (c *CommitsComparison) GetURL() string { + if c == nil || c.URL == nil { + return "" + } + return *c.URL +} + // GetIncompleteResults returns the IncompleteResults field if it's non-nil, zero value otherwise. func (c *CommitsSearchResult) GetIncompleteResults() bool { if c == nil || c.IncompleteResults == nil { @@ -612,6 +692,22 @@ func (c *CommitStats) GetTotal() int { return *c.Total } +// GetHealthPercentage returns the HealthPercentage field if it's non-nil, zero value otherwise. +func (c *CommunityHealthMetrics) GetHealthPercentage() int { + if c == nil || c.HealthPercentage == nil { + return 0 + } + return *c.HealthPercentage +} + +// GetUpdatedAt returns the UpdatedAt field if it's non-nil, zero value otherwise. +func (c *CommunityHealthMetrics) GetUpdatedAt() time.Time { + if c == nil || c.UpdatedAt == nil { + return time.Time{} + } + return *c.UpdatedAt +} + // GetAvatarURL returns the AvatarURL field if it's non-nil, zero value otherwise. func (c *Contributor) GetAvatarURL() string { if c == nil || c.AvatarURL == nil { @@ -1917,7 +2013,7 @@ func (i *Installation) GetRepositoriesURL() string { } // GetAction returns the Action field if it's non-nil, zero value otherwise. -func (i *IntegrationInstallationEvent) GetAction() string { +func (i *InstallationEvent) GetAction() string { if i == nil || i.Action == nil { return "" } @@ -1925,13 +2021,21 @@ func (i *IntegrationInstallationEvent) GetAction() string { } // GetAction returns the Action field if it's non-nil, zero value otherwise. -func (i *IntegrationInstallationRepositoriesEvent) GetAction() string { +func (i *InstallationRepositoriesEvent) GetAction() string { if i == nil || i.Action == nil { return "" } return *i.Action } +// GetRepositorySelection returns the RepositorySelection field if it's non-nil, zero value otherwise. +func (i *InstallationRepositoriesEvent) GetRepositorySelection() string { + if i == nil || i.RepositorySelection == nil { + return "" + } + return *i.RepositorySelection +} + // GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. func (i *Invitation) GetCreatedAt() time.Time { if i == nil || i.CreatedAt == nil { @@ -2548,6 +2652,38 @@ func (m *MembershipEvent) GetScope() string { return *m.Scope } +// GetHTMLURL returns the HTMLURL field if it's non-nil, zero value otherwise. +func (m *Metric) GetHTMLURL() string { + if m == nil || m.HTMLURL == nil { + return "" + } + return *m.HTMLURL +} + +// GetKey returns the Key field if it's non-nil, zero value otherwise. +func (m *Metric) GetKey() string { + if m == nil || m.Key == nil { + return "" + } + return *m.Key +} + +// GetName returns the Name field if it's non-nil, zero value otherwise. +func (m *Metric) GetName() string { + if m == nil || m.Name == nil { + return "" + } + return *m.Name +} + +// GetURL returns the URL field if it's non-nil, zero value otherwise. +func (m *Metric) GetURL() string { + if m == nil || m.URL == nil { + return "" + } + return *m.URL +} + // GetCreatedAt returns the CreatedAt field if it's non-nil, zero value otherwise. func (m *Migration) GetCreatedAt() string { if m == nil || m.CreatedAt == nil { @@ -3108,6 +3244,14 @@ func (o *OrganizationEvent) GetAction() string { return *o.Action } +// GetAction returns the Action field if it's non-nil, zero value otherwise. +func (o *OrgBlockEvent) GetAction() string { + if o == nil || o.Action == nil { + return "" + } + return *o.Action +} + // GetAction returns the Action field if it's non-nil, zero value otherwise. func (p *Page) GetAction() string { if p == nil || p.Action == nil { @@ -3372,6 +3516,14 @@ func (p *Project) GetURL() string { return *p.URL } +// GetColumnID returns the ColumnID field if it's non-nil, zero value otherwise. +func (p *ProjectCard) GetColumnID() int { + if p == nil || p.ColumnID == nil { + return 0 + } + return *p.ColumnID +} + // GetColumnURL returns the ColumnURL field if it's non-nil, zero value otherwise. func (p *ProjectCard) GetColumnURL() string { if p == nil || p.ColumnURL == nil { @@ -3420,6 +3572,14 @@ func (p *ProjectCard) GetUpdatedAt() Timestamp { return *p.UpdatedAt } +// GetURL returns the URL field if it's non-nil, zero value otherwise. +func (p *ProjectCard) GetURL() string { + if p == nil || p.URL == nil { + return "" + } + return *p.URL +} + // GetAction returns the Action field if it's non-nil, zero value otherwise. func (p *ProjectCardEvent) GetAction() string { if p == nil || p.Action == nil { @@ -3612,6 +3772,14 @@ func (p *PullRequest) GetMergeable() bool { return *p.Mergeable } +// GetMergeCommitSHA returns the MergeCommitSHA field if it's non-nil, zero value otherwise. +func (p *PullRequest) GetMergeCommitSHA() string { + if p == nil || p.MergeCommitSHA == nil { + return "" + } + return *p.MergeCommitSHA +} + // GetMerged returns the Merged field if it's non-nil, zero value otherwise. func (p *PullRequest) GetMerged() bool { if p == nil || p.Merged == nil { @@ -3996,6 +4164,14 @@ func (p *PullRequestReviewRequest) GetBody() string { return *p.Body } +// GetCommitID returns the CommitID field if it's non-nil, zero value otherwise. +func (p *PullRequestReviewRequest) GetCommitID() string { + if p == nil || p.CommitID == nil { + return "" + } + return *p.CommitID +} + // GetEvent returns the Event field if it's non-nil, zero value otherwise. func (p *PullRequestReviewRequest) GetEvent() string { if p == nil || p.Event == nil { @@ -4004,6 +4180,14 @@ func (p *PullRequestReviewRequest) GetEvent() string { return *p.Event } +// GetDismissStaleReviews returns the DismissStaleReviews field if it's non-nil, zero value otherwise. +func (p *PullRequestReviewsEnforcementUpdate) GetDismissStaleReviews() bool { + if p == nil || p.DismissStaleReviews == nil { + return false + } + return *p.DismissStaleReviews +} + // GetBase returns the Base field if it's non-nil, zero value otherwise. func (p *pullRequestUpdate) GetBase() string { if p == nil || p.Base == nil { @@ -6292,6 +6476,14 @@ func (t *Team) GetURL() string { return *t.URL } +// GetAction returns the Action field if it's non-nil, zero value otherwise. +func (t *TeamEvent) GetAction() string { + if t == nil || t.Action == nil { + return "" + } + return *t.Action +} + // GetDescription returns the Description field if it's non-nil, zero value otherwise. func (t *TeamLDAPMapping) GetDescription() string { if t == nil || t.Description == nil { @@ -6620,6 +6812,14 @@ func (t *TreeEntry) GetType() string { return *t.Type } +// GetURL returns the URL field if it's non-nil, zero value otherwise. +func (t *TreeEntry) GetURL() string { + if t == nil || t.URL == nil { + return "" + } + return *t.URL +} + // GetForce returns the Force field if it's non-nil, zero value otherwise. func (u *updateRefRequest) GetForce() bool { if u == nil || u.Force == nil { diff --git a/vendor/github.com/google/go-github/github/github.go b/vendor/github.com/google/go-github/github/github.go index decdaaae6..99ad8d078 100644 --- a/vendor/github.com/google/go-github/github/github.go +++ b/vendor/github.com/google/go-github/github/github.go @@ -27,7 +27,7 @@ import ( ) const ( - libraryVersion = "6" + libraryVersion = "11" defaultBaseURL = "https://api.github.com/" uploadBaseURL = "https://uploads.github.com/" userAgent = "go-github/" + libraryVersion @@ -67,10 +67,6 @@ const ( // https://developer.github.com/changes/2016-05-12-reactions-api-preview/ mediaTypeReactionsPreview = "application/vnd.github.squirrel-girl-preview" - // https://developer.github.com/changes/2016-04-01-squash-api-preview/ - // https://developer.github.com/changes/2016-09-26-pull-request-merge-api-update/ - mediaTypeSquashPreview = "application/vnd.github.polaris-preview+json" - // https://developer.github.com/changes/2016-04-04-git-signing-api-preview/ mediaTypeGitSigningPreview = "application/vnd.github.cryptographer-preview+json" @@ -92,11 +88,20 @@ const ( // https://developer.github.com/changes/2017-01-05-commit-search-api/ mediaTypeCommitSearchPreview = "application/vnd.github.cloak-preview+json" - // https://developer.github.com/changes/2016-12-14-reviews-api/ - mediaTypePullRequestReviewsPreview = "application/vnd.github.black-cat-preview+json" - // https://developer.github.com/changes/2017-02-28-user-blocking-apis-and-webhook/ mediaTypeBlockUsersPreview = "application/vnd.github.giant-sentry-fist-preview+json" + + // https://developer.github.com/changes/2017-02-09-community-health/ + mediaTypeRepositoryCommunityHealthMetricsPreview = "application/vnd.github.black-panther-preview+json" + + // https://developer.github.com/changes/2017-05-23-coc-api/ + mediaTypeCodesOfConductPreview = "application/vnd.github.scarlet-witch-preview+json" + + // https://developer.github.com/changes/2017-07-17-update-topics-on-repositories/ + mediaTypeTopicsPreview = "application/vnd.github.mercy-preview+json" + + // https://developer.github.com/changes/2017-07-26-team-review-request-thor-preview/ + mediaTypeTeamReviewPreview = "application/vnd.github.thor-preview+json" ) // A Client manages communication with the GitHub API. @@ -123,11 +128,11 @@ type Client struct { // Services used for talking to different parts of the GitHub API. Activity *ActivityService Admin *AdminService + Apps *AppsService Authorizations *AuthorizationsService Gists *GistsService Git *GitService Gitignores *GitignoresService - Integrations *IntegrationsService Issues *IssuesService Organizations *OrganizationsService Projects *ProjectsService @@ -212,11 +217,11 @@ func NewClient(httpClient *http.Client) *Client { c.common.client = c c.Activity = (*ActivityService)(&c.common) c.Admin = (*AdminService)(&c.common) + c.Apps = (*AppsService)(&c.common) c.Authorizations = (*AuthorizationsService)(&c.common) c.Gists = (*GistsService)(&c.common) c.Git = (*GitService)(&c.common) c.Gitignores = (*GitignoresService)(&c.common) - c.Integrations = (*IntegrationsService)(&c.common) c.Issues = (*IssuesService)(&c.common) c.Licenses = (*LicensesService)(&c.common) c.Migrations = (*MigrationService)(&c.common) @@ -236,13 +241,14 @@ func NewClient(httpClient *http.Client) *Client { // specified, the value pointed to by body is JSON encoded and included as the // request body. func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error) { - rel, err := url.Parse(urlStr) + if !strings.HasSuffix(c.BaseURL.Path, "/") { + return nil, fmt.Errorf("BaseURL must have a trailing slash, but %q does not", c.BaseURL) + } + u, err := c.BaseURL.Parse(urlStr) if err != nil { return nil, err } - u := c.BaseURL.ResolveReference(rel) - var buf io.ReadWriter if body != nil { buf = new(bytes.Buffer) @@ -271,12 +277,14 @@ func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Requ // urlStr, in which case it is resolved relative to the UploadURL of the Client. // Relative URLs should always be specified without a preceding slash. func (c *Client) NewUploadRequest(urlStr string, reader io.Reader, size int64, mediaType string) (*http.Request, error) { - rel, err := url.Parse(urlStr) + if !strings.HasSuffix(c.UploadURL.Path, "/") { + return nil, fmt.Errorf("UploadURL must have a trailing slash, but %q does not", c.UploadURL) + } + u, err := c.UploadURL.Parse(urlStr) if err != nil { return nil, err } - u := c.UploadURL.ResolveReference(rel) req, err := http.NewRequest("POST", u.String(), reader) if err != nil { return nil, err @@ -312,6 +320,7 @@ type Response struct { } // newResponse creates a new Response for the provided http.Response. +// r must not be nil. func newResponse(r *http.Response) *Response { response := &Response{Response: r} response.populatePageValues() @@ -390,13 +399,16 @@ func parseRate(r *http.Response) Rate { // The provided ctx must be non-nil. If it is canceled or times out, // ctx.Err() will be returned. func (c *Client) Do(ctx context.Context, req *http.Request, v interface{}) (*Response, error) { - ctx, req = withContext(ctx, req) + req = withContext(ctx, req) rateLimitCategory := category(req.URL.Path) // If we've hit rate limit, don't make further requests before Reset time. if err := c.checkRateLimitBeforeDo(req, rateLimitCategory); err != nil { - return nil, err + return &Response{ + Response: err.Response, + Rate: err.Rate, + }, err } resp, err := c.client.Do(req) @@ -457,7 +469,7 @@ func (c *Client) Do(ctx context.Context, req *http.Request, v interface{}) (*Res // current client state in order to quickly check if *RateLimitError can be immediately returned // from Client.Do, and if so, returns it so that Client.Do can skip making a network API call unnecessarily. // Otherwise it returns nil, and Client.Do should proceed normally. -func (c *Client) checkRateLimitBeforeDo(req *http.Request, rateLimitCategory rateLimitCategory) error { +func (c *Client) checkRateLimitBeforeDo(req *http.Request, rateLimitCategory rateLimitCategory) *RateLimitError { c.rateMu.Lock() rate := c.rateLimits[rateLimitCategory] c.rateMu.Unlock() @@ -524,9 +536,9 @@ type RateLimitError struct { } func (r *RateLimitError) Error() string { - return fmt.Sprintf("%v %v: %d %v; rate reset in %v", + return fmt.Sprintf("%v %v: %d %v %v", r.Response.Request.Method, sanitizeURL(r.Response.Request.URL), - r.Response.StatusCode, r.Message, r.Rate.Reset.Time.Sub(time.Now())) + r.Response.StatusCode, r.Message, formatRateReset(r.Rate.Reset.Time.Sub(time.Now()))) } // AcceptedError occurs when GitHub returns 202 Accepted response with an @@ -874,6 +886,31 @@ func cloneRequest(r *http.Request) *http.Request { return r2 } +// formatRateReset formats d to look like "[rate reset in 2s]" or +// "[rate reset in 87m02s]" for the positive durations. And like "[rate limit was reset 87m02s ago]" +// for the negative cases. +func formatRateReset(d time.Duration) string { + isNegative := d < 0 + if isNegative { + d *= -1 + } + secondsTotal := int(0.5 + d.Seconds()) + minutes := secondsTotal / 60 + seconds := secondsTotal - minutes*60 + + var timeString string + if minutes > 0 { + timeString = fmt.Sprintf("%dm%02ds", minutes, seconds) + } else { + timeString = fmt.Sprintf("%ds", seconds) + } + + if isNegative { + return fmt.Sprintf("[rate limit was reset %v ago]", timeString) + } + return fmt.Sprintf("[rate reset in %v]", timeString) +} + // Bool is a helper routine that allocates a new bool value // to store v and returns a pointer to it. func Bool(v bool) *bool { return &v } diff --git a/vendor/github.com/google/go-github/github/issues_events.go b/vendor/github.com/google/go-github/github/issues_events.go index 2d5e19a1c..93e5d66fb 100644 --- a/vendor/github.com/google/go-github/github/issues_events.go +++ b/vendor/github.com/google/go-github/github/issues_events.go @@ -44,7 +44,7 @@ type IssueEvent struct { // Someone unspecified @mentioned the Actor [sic] in an issue comment body. // // assigned, unassigned - // The Actor assigned the issue to or removed the assignment from the Assignee. + // The Assigner assigned the issue to or removed the assignment from the Assignee. // // labeled, unlabeled // The Actor added or removed the Label from the issue. diff --git a/vendor/github.com/google/go-github/github/issues_labels.go b/vendor/github.com/google/go-github/github/issues_labels.go index a39001d66..b0e34c40f 100644 --- a/vendor/github.com/google/go-github/github/issues_labels.go +++ b/vendor/github.com/google/go-github/github/issues_labels.go @@ -19,7 +19,7 @@ type Label struct { } func (l Label) String() string { - return fmt.Sprint(*l.Name) + return Stringify(l) } // ListLabels lists all labels for a repository. diff --git a/vendor/github.com/google/go-github/github/messages.go b/vendor/github.com/google/go-github/github/messages.go index a7ec65fba..c0f315a77 100644 --- a/vendor/github.com/google/go-github/github/messages.go +++ b/vendor/github.com/google/go-github/github/messages.go @@ -33,42 +33,46 @@ const ( signatureHeader = "X-Hub-Signature" // eventTypeHeader is the GitHub header key used to pass the event type. eventTypeHeader = "X-Github-Event" + // deliveryIDHeader is the GitHub header key used to pass the unique ID for the webhook event. + deliveryIDHeader = "X-Github-Delivery" ) var ( // eventTypeMapping maps webhooks types to their corresponding go-github struct types. eventTypeMapping = map[string]string{ - "commit_comment": "CommitCommentEvent", - "create": "CreateEvent", - "delete": "DeleteEvent", - "deployment": "DeploymentEvent", - "deployment_status": "DeploymentStatusEvent", - "fork": "ForkEvent", - "gollum": "GollumEvent", - "integration_installation": "IntegrationInstallationEvent", - "integration_installation_repositories": "IntegrationInstallationRepositoriesEvent", - "issue_comment": "IssueCommentEvent", - "issues": "IssuesEvent", - "label": "LabelEvent", - "member": "MemberEvent", - "membership": "MembershipEvent", - "milestone": "MilestoneEvent", - "organization": "OrganizationEvent", - "page_build": "PageBuildEvent", - "ping": "PingEvent", - "project": "ProjectEvent", - "project_card": "ProjectCardEvent", - "project_column": "ProjectColumnEvent", - "public": "PublicEvent", - "pull_request_review": "PullRequestReviewEvent", - "pull_request_review_comment": "PullRequestReviewCommentEvent", - "pull_request": "PullRequestEvent", - "push": "PushEvent", - "repository": "RepositoryEvent", - "release": "ReleaseEvent", - "status": "StatusEvent", - "team_add": "TeamAddEvent", - "watch": "WatchEvent", + "commit_comment": "CommitCommentEvent", + "create": "CreateEvent", + "delete": "DeleteEvent", + "deployment": "DeploymentEvent", + "deployment_status": "DeploymentStatusEvent", + "fork": "ForkEvent", + "gollum": "GollumEvent", + "installation": "InstallationEvent", + "installation_repositories": "InstallationRepositoriesEvent", + "issue_comment": "IssueCommentEvent", + "issues": "IssuesEvent", + "label": "LabelEvent", + "member": "MemberEvent", + "membership": "MembershipEvent", + "milestone": "MilestoneEvent", + "organization": "OrganizationEvent", + "org_block": "OrgBlockEvent", + "page_build": "PageBuildEvent", + "ping": "PingEvent", + "project": "ProjectEvent", + "project_card": "ProjectCardEvent", + "project_column": "ProjectColumnEvent", + "public": "PublicEvent", + "pull_request_review": "PullRequestReviewEvent", + "pull_request_review_comment": "PullRequestReviewCommentEvent", + "pull_request": "PullRequestEvent", + "push": "PushEvent", + "repository": "RepositoryEvent", + "release": "ReleaseEvent", + "status": "StatusEvent", + "team": "TeamEvent", + "team_add": "TeamAddEvent", + "watch": "WatchEvent", } ) @@ -159,10 +163,19 @@ func validateSignature(signature string, payload, secretKey []byte) error { } // WebHookType returns the event type of webhook request r. +// +// GitHub API docs: https://developer.github.com/v3/repos/hooks/#webhook-headers func WebHookType(r *http.Request) string { return r.Header.Get(eventTypeHeader) } +// DeliveryID returns the unique delivery ID of webhook request r. +// +// GitHub API docs: https://developer.github.com/v3/repos/hooks/#webhook-headers +func DeliveryID(r *http.Request) string { + return r.Header.Get(deliveryIDHeader) +} + // ParseWebHook parses the event payload. For recognized event types, a // value of the corresponding struct type will be returned (as returned // by Event.ParsePayload()). An error will be returned for unrecognized event diff --git a/vendor/github.com/google/go-github/github/misc.go b/vendor/github.com/google/go-github/github/misc.go index 42d0d3033..5b8082d3c 100644 --- a/vendor/github.com/google/go-github/github/misc.go +++ b/vendor/github.com/google/go-github/github/misc.go @@ -83,6 +83,61 @@ func (c *Client) ListEmojis(ctx context.Context) (map[string]string, *Response, return emoji, resp, nil } +// CodeOfConduct represents a code of conduct. +type CodeOfConduct struct { + Name *string `json:"name,omitempty"` + Key *string `json:"key,omitempty"` + URL *string `json:"url,omitempty"` + Body *string `json:"body,omitempty"` +} + +func (c *CodeOfConduct) String() string { + return Stringify(c) +} + +// ListCodesOfConduct returns all codes of conduct. +// +// GitHub API docs: https://developer.github.com/v3/codes_of_conduct/#list-all-codes-of-conduct +func (c *Client) ListCodesOfConduct(ctx context.Context) ([]*CodeOfConduct, *Response, error) { + req, err := c.NewRequest("GET", "codes_of_conduct", nil) + if err != nil { + return nil, nil, err + } + + // TODO: remove custom Accept header when this API fully launches. + req.Header.Set("Accept", mediaTypeCodesOfConductPreview) + + var cs []*CodeOfConduct + resp, err := c.Do(ctx, req, &cs) + if err != nil { + return nil, resp, err + } + + return cs, resp, nil +} + +// GetCodeOfConduct returns an individual code of conduct. +// +// https://developer.github.com/v3/codes_of_conduct/#get-an-individual-code-of-conduct +func (c *Client) GetCodeOfConduct(ctx context.Context, key string) (*CodeOfConduct, *Response, error) { + u := fmt.Sprintf("codes_of_conduct/%s", key) + req, err := c.NewRequest("GET", u, nil) + if err != nil { + return nil, nil, err + } + + // TODO: remove custom Accept header when this API fully launches. + req.Header.Set("Accept", mediaTypeCodesOfConductPreview) + + coc := new(CodeOfConduct) + resp, err := c.Do(ctx, req, coc) + if err != nil { + return nil, resp, err + } + + return coc, resp, nil +} + // APIMeta represents metadata about the GitHub API. type APIMeta struct { // An Array of IP addresses in CIDR format specifying the addresses diff --git a/vendor/github.com/google/go-github/github/orgs.go b/vendor/github.com/google/go-github/github/orgs.go index 8b126f00f..e6947c96c 100644 --- a/vendor/github.com/google/go-github/github/orgs.go +++ b/vendor/github.com/google/go-github/github/orgs.go @@ -154,6 +154,25 @@ func (s *OrganizationsService) Get(ctx context.Context, org string) (*Organizati return organization, resp, nil } +// GetByID fetches an organization. +// +// Note: GetByID uses the undocumented GitHub API endpoint /organizations/:id. +func (s *OrganizationsService) GetByID(ctx context.Context, id int) (*Organization, *Response, error) { + u := fmt.Sprintf("organizations/%d", id) + req, err := s.client.NewRequest("GET", u, nil) + if err != nil { + return nil, nil, err + } + + organization := new(Organization) + resp, err := s.client.Do(ctx, req, organization) + if err != nil { + return nil, resp, err + } + + return organization, resp, nil +} + // Edit an organization. // // GitHub API docs: https://developer.github.com/v3/orgs/#edit-an-organization diff --git a/vendor/github.com/google/go-github/github/orgs_teams.go b/vendor/github.com/google/go-github/github/orgs_teams.go index 70b090d0d..684e2daff 100644 --- a/vendor/github.com/google/go-github/github/orgs_teams.go +++ b/vendor/github.com/google/go-github/github/orgs_teams.go @@ -223,6 +223,9 @@ func (s *OrganizationsService) ListTeamRepos(ctx context.Context, team int, opt return nil, nil, err } + // TODO: remove custom Accept header when topics API fully launches. + req.Header.Set("Accept", mediaTypeTopicsPreview) + var repos []*Repository resp, err := s.client.Do(ctx, req, &repos) if err != nil { diff --git a/vendor/github.com/google/go-github/github/orgs_users_blocking.go b/vendor/github.com/google/go-github/github/orgs_users_blocking.go new file mode 100644 index 000000000..b1aecf445 --- /dev/null +++ b/vendor/github.com/google/go-github/github/orgs_users_blocking.go @@ -0,0 +1,91 @@ +// Copyright 2017 The go-github AUTHORS. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package github + +import ( + "context" + "fmt" +) + +// ListBlockedUsers lists all the users blocked by an organization. +// +// GitHub API docs: https://developer.github.com/v3/orgs/blocking/#list-blocked-users +func (s *OrganizationsService) ListBlockedUsers(ctx context.Context, org string, opt *ListOptions) ([]*User, *Response, error) { + u := fmt.Sprintf("orgs/%v/blocks", org) + u, err := addOptions(u, opt) + if err != nil { + return nil, nil, err + } + + req, err := s.client.NewRequest("GET", u, nil) + if err != nil { + return nil, nil, err + } + + // TODO: remove custom Accept header when this API fully launches. + req.Header.Set("Accept", mediaTypeBlockUsersPreview) + + var blockedUsers []*User + resp, err := s.client.Do(ctx, req, &blockedUsers) + if err != nil { + return nil, resp, err + } + + return blockedUsers, resp, nil +} + +// IsBlocked reports whether specified user is blocked from an organization. +// +// GitHub API docs: https://developer.github.com/v3/orgs/blocking/#check-whether-a-user-is-blocked-from-an-organization +func (s *OrganizationsService) IsBlocked(ctx context.Context, org string, user string) (bool, *Response, error) { + u := fmt.Sprintf("orgs/%v/blocks/%v", org, user) + + req, err := s.client.NewRequest("GET", u, nil) + if err != nil { + return false, nil, err + } + + // TODO: remove custom Accept header when this API fully launches. + req.Header.Set("Accept", mediaTypeBlockUsersPreview) + + resp, err := s.client.Do(ctx, req, nil) + isBlocked, err := parseBoolResponse(err) + return isBlocked, resp, err +} + +// BlockUser blocks specified user from an organization. +// +// GitHub API docs: https://developer.github.com/v3/orgs/blocking/#block-a-user +func (s *OrganizationsService) BlockUser(ctx context.Context, org string, user string) (*Response, error) { + u := fmt.Sprintf("orgs/%v/blocks/%v", org, user) + + req, err := s.client.NewRequest("PUT", u, nil) + if err != nil { + return nil, err + } + + // TODO: remove custom Accept header when this API fully launches. + req.Header.Set("Accept", mediaTypeBlockUsersPreview) + + return s.client.Do(ctx, req, nil) +} + +// UnblockUser unblocks specified user from an organization. +// +// GitHub API docs: https://developer.github.com/v3/orgs/blocking/#unblock-a-user +func (s *OrganizationsService) UnblockUser(ctx context.Context, org string, user string) (*Response, error) { + u := fmt.Sprintf("orgs/%v/blocks/%v", org, user) + + req, err := s.client.NewRequest("DELETE", u, nil) + if err != nil { + return nil, err + } + + // TODO: remove custom Accept header when this API fully launches. + req.Header.Set("Accept", mediaTypeBlockUsersPreview) + + return s.client.Do(ctx, req, nil) +} diff --git a/vendor/github.com/google/go-github/github/projects.go b/vendor/github.com/google/go-github/github/projects.go index 58b638eb8..89685c9d7 100644 --- a/vendor/github.com/google/go-github/github/projects.go +++ b/vendor/github.com/google/go-github/github/projects.go @@ -259,14 +259,19 @@ func (s *ProjectsService) MoveProjectColumn(ctx context.Context, columnID int, o // ProjectCard represents a card in a column of a GitHub Project. // -// GitHub API docs: https://developer.github.com/v3/repos/projects/ +// GitHub API docs: https://developer.github.com/v3/projects/cards/#get-a-project-card type ProjectCard struct { + URL *string `json:"url,omitempty"` ColumnURL *string `json:"column_url,omitempty"` ContentURL *string `json:"content_url,omitempty"` ID *int `json:"id,omitempty"` Note *string `json:"note,omitempty"` + Creator *User `json:"creator,omitempty"` CreatedAt *Timestamp `json:"created_at,omitempty"` UpdatedAt *Timestamp `json:"updated_at,omitempty"` + + // The following fields are only populated by Webhook events. + ColumnID *int `json:"column_id,omitempty"` } // ListProjectCards lists the cards in a column of a GitHub Project. @@ -324,10 +329,10 @@ func (s *ProjectsService) GetProjectCard(ctx context.Context, columnID int) (*Pr type ProjectCardOptions struct { // The note of the card. Note and ContentID are mutually exclusive. Note string `json:"note,omitempty"` - // The ID (not Number) of the Issue or Pull Request to associate with this card. + // The ID (not Number) of the Issue to associate with this card. // Note and ContentID are mutually exclusive. ContentID int `json:"content_id,omitempty"` - // The type of content to associate with this card. Possible values are: "Issue", "PullRequest". + // The type of content to associate with this card. Possible values are: "Issue". ContentType string `json:"content_type,omitempty"` } diff --git a/vendor/github.com/google/go-github/github/pulls.go b/vendor/github.com/google/go-github/github/pulls.go index 0fdb4cd21..bc46081fc 100644 --- a/vendor/github.com/google/go-github/github/pulls.go +++ b/vendor/github.com/google/go-github/github/pulls.go @@ -33,6 +33,7 @@ type PullRequest struct { Merged *bool `json:"merged,omitempty"` Mergeable *bool `json:"mergeable,omitempty"` MergedBy *User `json:"merged_by,omitempty"` + MergeCommitSHA *string `json:"merge_commit_sha,omitempty"` Comments *int `json:"comments,omitempty"` Commits *int `json:"commits,omitempty"` Additions *int `json:"additions,omitempty"` @@ -253,6 +254,9 @@ func (s *PullRequestsService) ListCommits(ctx context.Context, owner string, rep return nil, nil, err } + // TODO: remove custom Accept header when this API fully launches. + req.Header.Set("Accept", mediaTypeGitSigningPreview) + var commits []*RepositoryCommit resp, err := s.client.Do(ctx, req, &commits) if err != nil { @@ -342,9 +346,6 @@ func (s *PullRequestsService) Merge(ctx context.Context, owner string, repo stri return nil, nil, err } - // TODO: This header will be unnecessary when the API is no longer in preview. - req.Header.Set("Accept", mediaTypeSquashPreview) - mergeResult := new(PullRequestMergeResult) resp, err := s.client.Do(ctx, req, mergeResult) if err != nil { diff --git a/vendor/github.com/google/go-github/github/pulls_reviewers.go b/vendor/github.com/google/go-github/github/pulls_reviewers.go index efa388896..15b0d8464 100644 --- a/vendor/github.com/google/go-github/github/pulls_reviewers.go +++ b/vendor/github.com/google/go-github/github/pulls_reviewers.go @@ -10,24 +10,30 @@ import ( "fmt" ) -// RequestReviewers creates a review request for the provided GitHub users for the specified pull request. +// ReviewersRequest specifies users and teams for a pull request review request. +type ReviewersRequest struct { + Reviewers []string `json:"reviewers,omitempty"` + TeamReviewers []string `json:"team_reviewers,omitempty"` +} + +// Reviewers represents reviewers of a pull request. +type Reviewers struct { + Users []*User `json:"users,omitempty"` + Teams []*Team `json:"teams,omitempty"` +} + +// RequestReviewers creates a review request for the provided reviewers for the specified pull request. // // GitHub API docs: https://developer.github.com/v3/pulls/review_requests/#create-a-review-request -func (s *PullRequestsService) RequestReviewers(ctx context.Context, owner, repo string, number int, logins []string) (*PullRequest, *Response, error) { +func (s *PullRequestsService) RequestReviewers(ctx context.Context, owner, repo string, number int, reviewers ReviewersRequest) (*PullRequest, *Response, error) { u := fmt.Sprintf("repos/%s/%s/pulls/%d/requested_reviewers", owner, repo, number) - - reviewers := struct { - Reviewers []string `json:"reviewers,omitempty"` - }{ - Reviewers: logins, - } req, err := s.client.NewRequest("POST", u, &reviewers) if err != nil { return nil, nil, err } - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypePullRequestReviewsPreview) + // TODO: remove custom Accept header when this API fully launches. + req.Header.Set("Accept", mediaTypeTeamReviewPreview) r := new(PullRequest) resp, err := s.client.Do(ctx, req, r) @@ -38,47 +44,45 @@ func (s *PullRequestsService) RequestReviewers(ctx context.Context, owner, repo return r, resp, nil } -// ListReviewers lists users whose reviews have been requested on the specified pull request. +// ListReviewers lists reviewers whose reviews have been requested on the specified pull request. // // GitHub API docs: https://developer.github.com/v3/pulls/review_requests/#list-review-requests -func (s *PullRequestsService) ListReviewers(ctx context.Context, owner, repo string, number int) ([]*User, *Response, error) { +func (s *PullRequestsService) ListReviewers(ctx context.Context, owner, repo string, number int, opt *ListOptions) (*Reviewers, *Response, error) { u := fmt.Sprintf("repos/%v/%v/pulls/%d/requested_reviewers", owner, repo, number) + u, err := addOptions(u, opt) + if err != nil { + return nil, nil, err + } req, err := s.client.NewRequest("GET", u, nil) if err != nil { return nil, nil, err } - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypePullRequestReviewsPreview) + // TODO: remove custom Accept header when this API fully launches. + req.Header.Set("Accept", mediaTypeTeamReviewPreview) - var users []*User - resp, err := s.client.Do(ctx, req, &users) + reviewers := new(Reviewers) + resp, err := s.client.Do(ctx, req, reviewers) if err != nil { return nil, resp, err } - return users, resp, nil + return reviewers, resp, nil } -// RemoveReviewers removes the review request for the provided GitHub users for the specified pull request. +// RemoveReviewers removes the review request for the provided reviewers for the specified pull request. // // GitHub API docs: https://developer.github.com/v3/pulls/review_requests/#delete-a-review-request -func (s *PullRequestsService) RemoveReviewers(ctx context.Context, owner, repo string, number int, logins []string) (*Response, error) { +func (s *PullRequestsService) RemoveReviewers(ctx context.Context, owner, repo string, number int, reviewers ReviewersRequest) (*Response, error) { u := fmt.Sprintf("repos/%s/%s/pulls/%d/requested_reviewers", owner, repo, number) - - reviewers := struct { - Reviewers []string `json:"reviewers,omitempty"` - }{ - Reviewers: logins, - } req, err := s.client.NewRequest("DELETE", u, &reviewers) if err != nil { return nil, err } - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypePullRequestReviewsPreview) + // TODO: remove custom Accept header when this API fully launches. + req.Header.Set("Accept", mediaTypeTeamReviewPreview) return s.client.Do(ctx, req, reviewers) } diff --git a/vendor/github.com/google/go-github/github/pulls_reviews.go b/vendor/github.com/google/go-github/github/pulls_reviews.go index c27b6a8c4..7d2acc414 100644 --- a/vendor/github.com/google/go-github/github/pulls_reviews.go +++ b/vendor/github.com/google/go-github/github/pulls_reviews.go @@ -40,6 +40,7 @@ func (c DraftReviewComment) String() string { // PullRequestReviewRequest represents a request to create a review. type PullRequestReviewRequest struct { + CommitID *string `json:"commit_id,omitempty"` Body *string `json:"body,omitempty"` Event *string `json:"event,omitempty"` Comments []*DraftReviewComment `json:"comments,omitempty"` @@ -65,17 +66,18 @@ func (r PullRequestReviewDismissalRequest) String() string { // Read more about it here - https://github.com/google/go-github/issues/540 // // GitHub API docs: https://developer.github.com/v3/pulls/reviews/#list-reviews-on-a-pull-request -func (s *PullRequestsService) ListReviews(ctx context.Context, owner, repo string, number int) ([]*PullRequestReview, *Response, error) { +func (s *PullRequestsService) ListReviews(ctx context.Context, owner, repo string, number int, opt *ListOptions) ([]*PullRequestReview, *Response, error) { u := fmt.Sprintf("repos/%v/%v/pulls/%d/reviews", owner, repo, number) + u, err := addOptions(u, opt) + if err != nil { + return nil, nil, err + } req, err := s.client.NewRequest("GET", u, nil) if err != nil { return nil, nil, err } - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypePullRequestReviewsPreview) - var reviews []*PullRequestReview resp, err := s.client.Do(ctx, req, &reviews) if err != nil { @@ -100,9 +102,6 @@ func (s *PullRequestsService) GetReview(ctx context.Context, owner, repo string, return nil, nil, err } - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypePullRequestReviewsPreview) - review := new(PullRequestReview) resp, err := s.client.Do(ctx, req, review) if err != nil { @@ -127,9 +126,6 @@ func (s *PullRequestsService) DeletePendingReview(ctx context.Context, owner, re return nil, nil, err } - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypePullRequestReviewsPreview) - review := new(PullRequestReview) resp, err := s.client.Do(ctx, req, review) if err != nil { @@ -145,18 +141,19 @@ func (s *PullRequestsService) DeletePendingReview(ctx context.Context, owner, re // returned error format and remove this comment once it's fixed. // Read more about it here - https://github.com/google/go-github/issues/540 // -// GitHub API docs: https://developer.github.com/v3/pulls/reviews/#get-a-single-reviews-comments -func (s *PullRequestsService) ListReviewComments(ctx context.Context, owner, repo string, number, reviewID int) ([]*PullRequestComment, *Response, error) { +// GitHub API docs: https://developer.github.com/v3/pulls/reviews/#get-comments-for-a-single-review +func (s *PullRequestsService) ListReviewComments(ctx context.Context, owner, repo string, number, reviewID int, opt *ListOptions) ([]*PullRequestComment, *Response, error) { u := fmt.Sprintf("repos/%v/%v/pulls/%d/reviews/%d/comments", owner, repo, number, reviewID) + u, err := addOptions(u, opt) + if err != nil { + return nil, nil, err + } req, err := s.client.NewRequest("GET", u, nil) if err != nil { return nil, nil, err } - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypePullRequestReviewsPreview) - var comments []*PullRequestComment resp, err := s.client.Do(ctx, req, &comments) if err != nil { @@ -181,9 +178,6 @@ func (s *PullRequestsService) CreateReview(ctx context.Context, owner, repo stri return nil, nil, err } - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypePullRequestReviewsPreview) - r := new(PullRequestReview) resp, err := s.client.Do(ctx, req, r) if err != nil { @@ -208,9 +202,6 @@ func (s *PullRequestsService) SubmitReview(ctx context.Context, owner, repo stri return nil, nil, err } - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypePullRequestReviewsPreview) - r := new(PullRequestReview) resp, err := s.client.Do(ctx, req, r) if err != nil { @@ -235,9 +226,6 @@ func (s *PullRequestsService) DismissReview(ctx context.Context, owner, repo str return nil, nil, err } - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypePullRequestReviewsPreview) - r := new(PullRequestReview) resp, err := s.client.Do(ctx, req, r) if err != nil { diff --git a/vendor/github.com/google/go-github/github/repos.go b/vendor/github.com/google/go-github/github/repos.go index 058f149dd..b6d98cc16 100644 --- a/vendor/github.com/google/go-github/github/repos.go +++ b/vendor/github.com/google/go-github/github/repos.go @@ -7,6 +7,7 @@ package github import ( "context" + "encoding/json" "fmt" "strings" ) @@ -25,6 +26,7 @@ type Repository struct { FullName *string `json:"full_name,omitempty"` Description *string `json:"description,omitempty"` Homepage *string `json:"homepage,omitempty"` + CodeOfConduct *CodeOfConduct `json:"code_of_conduct,omitempty"` DefaultBranch *string `json:"default_branch,omitempty"` MasterBranch *string `json:"master_branch,omitempty"` CreatedAt *Timestamp `json:"created_at,omitempty"` @@ -53,6 +55,7 @@ type Repository struct { AllowRebaseMerge *bool `json:"allow_rebase_merge,omitempty"` AllowSquashMerge *bool `json:"allow_squash_merge,omitempty"` AllowMergeCommit *bool `json:"allow_merge_commit,omitempty"` + Topics []string `json:"topics,omitempty"` // Only provided when using RepositoriesService.Get while in preview License *License `json:"license,omitempty"` @@ -173,8 +176,9 @@ func (s *RepositoriesService) List(ctx context.Context, user string, opt *Reposi return nil, nil, err } - // TODO: remove custom Accept header when license support fully launches - req.Header.Set("Accept", mediaTypeLicensesPreview) + // TODO: remove custom Accept headers when APIs fully launch. + acceptHeaders := []string{mediaTypeLicensesPreview, mediaTypeCodesOfConductPreview, mediaTypeTopicsPreview} + req.Header.Set("Accept", strings.Join(acceptHeaders, ", ")) var repos []*Repository resp, err := s.client.Do(ctx, req, &repos) @@ -210,8 +214,9 @@ func (s *RepositoriesService) ListByOrg(ctx context.Context, org string, opt *Re return nil, nil, err } - // TODO: remove custom Accept header when license support fully launches - req.Header.Set("Accept", mediaTypeLicensesPreview) + // TODO: remove custom Accept headers when APIs fully launch. + acceptHeaders := []string{mediaTypeLicensesPreview, mediaTypeCodesOfConductPreview, mediaTypeTopicsPreview} + req.Header.Set("Accept", strings.Join(acceptHeaders, ", ")) var repos []*Repository resp, err := s.client.Do(ctx, req, &repos) @@ -293,7 +298,7 @@ func (s *RepositoriesService) Get(ctx context.Context, owner, repo string) (*Rep // TODO: remove custom Accept header when the license support fully launches // https://developer.github.com/v3/licenses/#get-a-repositorys-license - acceptHeaders := []string{mediaTypeLicensesPreview, mediaTypeSquashPreview} + acceptHeaders := []string{mediaTypeLicensesPreview, mediaTypeCodesOfConductPreview, mediaTypeTopicsPreview} req.Header.Set("Accept", strings.Join(acceptHeaders, ", ")) repository := new(Repository) @@ -305,6 +310,28 @@ func (s *RepositoriesService) Get(ctx context.Context, owner, repo string) (*Rep return repository, resp, nil } +// GetCodeOfConduct gets the contents of a repository's code of conduct. +// +// GitHub API docs: https://developer.github.com/v3/codes_of_conduct/#get-the-contents-of-a-repositorys-code-of-conduct +func (s *RepositoriesService) GetCodeOfConduct(ctx context.Context, owner, repo string) (*CodeOfConduct, *Response, error) { + u := fmt.Sprintf("repos/%v/%v/community/code_of_conduct", owner, repo) + req, err := s.client.NewRequest("GET", u, nil) + if err != nil { + return nil, nil, err + } + + // TODO: remove custom Accept header when this API fully launches. + req.Header.Set("Accept", mediaTypeCodesOfConductPreview) + + coc := new(CodeOfConduct) + resp, err := s.client.Do(ctx, req, coc) + if err != nil { + return nil, resp, err + } + + return coc, resp, nil +} + // GetByID fetches a repository. // // Note: GetByID uses the undocumented GitHub API endpoint /repositories/:id. @@ -338,9 +365,6 @@ func (s *RepositoriesService) Edit(ctx context.Context, owner, repo string, repo return nil, nil, err } - // TODO: Remove this preview header after API is fully vetted. - req.Header.Set("Accept", mediaTypeSquashPreview) - r := new(Repository) resp, err := s.client.Do(ctx, req, r) if err != nil { @@ -509,22 +533,22 @@ type Branch struct { // Protection represents a repository branch's protection. type Protection struct { - RequiredStatusChecks *RequiredStatusChecks `json:"required_status_checks"` - RequiredPullRequestReviews *RequiredPullRequestReviews `json:"required_pull_request_reviews"` - Restrictions *BranchRestrictions `json:"restrictions"` + RequiredStatusChecks *RequiredStatusChecks `json:"required_status_checks"` + RequiredPullRequestReviews *PullRequestReviewsEnforcement `json:"required_pull_request_reviews"` + EnforceAdmins *AdminEnforcement `json:"enforce_admins"` + Restrictions *BranchRestrictions `json:"restrictions"` } // ProtectionRequest represents a request to create/edit a branch's protection. type ProtectionRequest struct { - RequiredStatusChecks *RequiredStatusChecks `json:"required_status_checks"` - RequiredPullRequestReviews *RequiredPullRequestReviews `json:"required_pull_request_reviews"` - Restrictions *BranchRestrictionsRequest `json:"restrictions"` + RequiredStatusChecks *RequiredStatusChecks `json:"required_status_checks"` + RequiredPullRequestReviews *PullRequestReviewsEnforcementRequest `json:"required_pull_request_reviews"` + EnforceAdmins bool `json:"enforce_admins"` + Restrictions *BranchRestrictionsRequest `json:"restrictions"` } // RequiredStatusChecks represents the protection status of a individual branch. type RequiredStatusChecks struct { - // Enforce required status checks for repository administrators. (Required.) - IncludeAdmins bool `json:"include_admins"` // Require branches to be up to date before merging. (Required.) Strict bool `json:"strict"` // The list of status checks to require in order to merge into this @@ -532,10 +556,61 @@ type RequiredStatusChecks struct { Contexts []string `json:"contexts"` } -// RequiredPullRequestReviews represents the protection configuration for pull requests. -type RequiredPullRequestReviews struct { - // Enforce pull request reviews for repository administrators. (Required.) - IncludeAdmins bool `json:"include_admins"` +// PullRequestReviewsEnforcement represents the pull request reviews enforcement of a protected branch. +type PullRequestReviewsEnforcement struct { + // Specifies which users and teams can dismiss pull request reviews. + DismissalRestrictions DismissalRestrictions `json:"dismissal_restrictions"` + // Specifies if approved reviews are dismissed automatically, when a new commit is pushed. + DismissStaleReviews bool `json:"dismiss_stale_reviews"` +} + +// PullRequestReviewsEnforcementRequest represents request to set the pull request review +// enforcement of a protected branch. It is separate from PullRequestReviewsEnforcement above +// because the request structure is different from the response structure. +type PullRequestReviewsEnforcementRequest struct { + // Specifies which users and teams should be allowed to dismiss pull request reviews. Can be nil to disable the restrictions. + DismissalRestrictionsRequest *DismissalRestrictionsRequest `json:"dismissal_restrictions"` + // Specifies if approved reviews can be dismissed automatically, when a new commit is pushed. (Required) + DismissStaleReviews bool `json:"dismiss_stale_reviews"` +} + +// MarshalJSON implements the json.Marshaler interface. +// Converts nil value of PullRequestReviewsEnforcementRequest.DismissalRestrictionsRequest to empty array +func (req PullRequestReviewsEnforcementRequest) MarshalJSON() ([]byte, error) { + if req.DismissalRestrictionsRequest == nil { + newReq := struct { + R []interface{} `json:"dismissal_restrictions"` + D bool `json:"dismiss_stale_reviews"` + }{ + R: []interface{}{}, + D: req.DismissStaleReviews, + } + return json.Marshal(newReq) + } + newReq := struct { + R *DismissalRestrictionsRequest `json:"dismissal_restrictions"` + D bool `json:"dismiss_stale_reviews"` + }{ + R: req.DismissalRestrictionsRequest, + D: req.DismissStaleReviews, + } + return json.Marshal(newReq) +} + +// PullRequestReviewsEnforcementUpdate represents request to patch the pull request review +// enforcement of a protected branch. It is separate from PullRequestReviewsEnforcementRequest above +// because the patch request does not require all fields to be initialized. +type PullRequestReviewsEnforcementUpdate struct { + // Specifies which users and teams can dismiss pull request reviews. Can be omitted. + DismissalRestrictionsRequest *DismissalRestrictionsRequest `json:"dismissal_restrictions,omitempty"` + // Specifies if approved reviews can be dismissed automatically, when a new commit is pushed. Can be omitted. + DismissStaleReviews *bool `json:"dismiss_stale_reviews,omitempty"` +} + +// AdminEnforcement represents the configuration to enforce required status checks for repository administrators. +type AdminEnforcement struct { + URL *string `json:"url,omitempty"` + Enabled bool `json:"enabled"` } // BranchRestrictions represents the restriction that only certain users or @@ -558,6 +633,25 @@ type BranchRestrictionsRequest struct { Teams []string `json:"teams"` } +// DismissalRestrictions specifies which users and teams can dismiss pull request reviews. +type DismissalRestrictions struct { + // The list of users who can dimiss pull request reviews. + Users []*User `json:"users"` + // The list of teams which can dismiss pull request reviews. + Teams []*Team `json:"teams"` +} + +// DismissalRestrictionsRequest represents the request to create/edit the +// restriction to allows only specific users or teams to dimiss pull request reviews. It is +// separate from DismissalRestrictions above because the request structure is +// different from the response structure. +type DismissalRestrictionsRequest struct { + // The list of user logins who can dismiss pull request reviews. (Required; use []string{} instead of nil for empty list.) + Users []string `json:"users"` + // The list of team slugs which can dismiss pull request reviews. (Required; use []string{} instead of nil for empty list.) + Teams []string `json:"teams"` +} + // ListBranches lists branches for the specified repository. // // GitHub API docs: https://developer.github.com/v3/repos/#list-branches @@ -728,3 +822,202 @@ func (s *RepositoriesService) License(ctx context.Context, owner, repo string) ( return r, resp, nil } + +// GetPullRequestReviewEnforcement gets pull request review enforcement of a protected branch. +// +// GitHub API docs: https://developer.github.com/v3/repos/branches/#get-pull-request-review-enforcement-of-protected-branch +func (s *RepositoriesService) GetPullRequestReviewEnforcement(ctx context.Context, owner, repo, branch string) (*PullRequestReviewsEnforcement, *Response, error) { + u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/required_pull_request_reviews", owner, repo, branch) + req, err := s.client.NewRequest("GET", u, nil) + if err != nil { + return nil, nil, err + } + + // TODO: remove custom Accept header when this API fully launches + req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) + + r := new(PullRequestReviewsEnforcement) + resp, err := s.client.Do(ctx, req, r) + if err != nil { + return nil, resp, err + } + + return r, resp, nil +} + +// UpdatePullRequestReviewEnforcement patches pull request review enforcement of a protected branch. +// It requires admin access and branch protection to be enabled. +// +// GitHub API docs: https://developer.github.com/v3/repos/branches/#update-pull-request-review-enforcement-of-protected-branch +func (s *RepositoriesService) UpdatePullRequestReviewEnforcement(ctx context.Context, owner, repo, branch string, patch *PullRequestReviewsEnforcementUpdate) (*PullRequestReviewsEnforcement, *Response, error) { + u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/required_pull_request_reviews", owner, repo, branch) + req, err := s.client.NewRequest("PATCH", u, patch) + if err != nil { + return nil, nil, err + } + + // TODO: remove custom Accept header when this API fully launches + req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) + + r := new(PullRequestReviewsEnforcement) + resp, err := s.client.Do(ctx, req, r) + if err != nil { + return nil, resp, err + } + + return r, resp, err +} + +// DisableDismissalRestrictions disables dismissal restrictions of a protected branch. +// It requires admin access and branch protection to be enabled. +// +// GitHub API docs: https://developer.github.com/v3/repos/branches/#update-pull-request-review-enforcement-of-protected-branch +func (s *RepositoriesService) DisableDismissalRestrictions(ctx context.Context, owner, repo, branch string) (*PullRequestReviewsEnforcement, *Response, error) { + u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/required_pull_request_reviews", owner, repo, branch) + + data := struct { + R []interface{} `json:"dismissal_restrictions"` + }{[]interface{}{}} + + req, err := s.client.NewRequest("PATCH", u, data) + if err != nil { + return nil, nil, err + } + + // TODO: remove custom Accept header when this API fully launches + req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) + + r := new(PullRequestReviewsEnforcement) + resp, err := s.client.Do(ctx, req, r) + if err != nil { + return nil, resp, err + } + + return r, resp, err +} + +// RemovePullRequestReviewEnforcement removes pull request enforcement of a protected branch. +// +// GitHub API docs: https://developer.github.com/v3/repos/branches/#remove-pull-request-review-enforcement-of-protected-branch +func (s *RepositoriesService) RemovePullRequestReviewEnforcement(ctx context.Context, owner, repo, branch string) (*Response, error) { + u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/required_pull_request_reviews", owner, repo, branch) + req, err := s.client.NewRequest("DELETE", u, nil) + if err != nil { + return nil, err + } + + // TODO: remove custom Accept header when this API fully launches + req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) + + return s.client.Do(ctx, req, nil) +} + +// GetAdminEnforcement gets admin enforcement information of a protected branch. +// +// GitHub API docs: https://developer.github.com/v3/repos/branches/#get-admin-enforcement-of-protected-branch +func (s *RepositoriesService) GetAdminEnforcement(ctx context.Context, owner, repo, branch string) (*AdminEnforcement, *Response, error) { + u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/enforce_admins", owner, repo, branch) + req, err := s.client.NewRequest("GET", u, nil) + if err != nil { + return nil, nil, err + } + + // TODO: remove custom Accept header when this API fully launches + req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) + + r := new(AdminEnforcement) + resp, err := s.client.Do(ctx, req, r) + if err != nil { + return nil, resp, err + } + + return r, resp, nil +} + +// AddAdminEnforcement adds admin enforcement to a protected branch. +// It requires admin access and branch protection to be enabled. +// +// GitHub API docs: https://developer.github.com/v3/repos/branches/#add-admin-enforcement-of-protected-branch +func (s *RepositoriesService) AddAdminEnforcement(ctx context.Context, owner, repo, branch string) (*AdminEnforcement, *Response, error) { + u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/enforce_admins", owner, repo, branch) + req, err := s.client.NewRequest("POST", u, nil) + if err != nil { + return nil, nil, err + } + + // TODO: remove custom Accept header when this API fully launches + req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) + + r := new(AdminEnforcement) + resp, err := s.client.Do(ctx, req, r) + if err != nil { + return nil, resp, err + } + + return r, resp, err +} + +// RemoveAdminEnforcement removes admin enforcement from a protected branch. +// +// GitHub API docs: https://developer.github.com/v3/repos/branches/#remove-admin-enforcement-of-protected-branch +func (s *RepositoriesService) RemoveAdminEnforcement(ctx context.Context, owner, repo, branch string) (*Response, error) { + u := fmt.Sprintf("repos/%v/%v/branches/%v/protection/enforce_admins", owner, repo, branch) + req, err := s.client.NewRequest("DELETE", u, nil) + if err != nil { + return nil, err + } + + // TODO: remove custom Accept header when this API fully launches + req.Header.Set("Accept", mediaTypeProtectedBranchesPreview) + + return s.client.Do(ctx, req, nil) +} + +// Topics represents a collection of repository topics. +type Topics struct { + Names []string `json:"names,omitempty"` +} + +// ListAllTopics lists topics for a repository. +// +// GitHub API docs: https://developer.github.com/v3/repos/#list-all-topics-for-a-repository +func (s *RepositoriesService) ListAllTopics(ctx context.Context, owner, repo string) (*Topics, *Response, error) { + u := fmt.Sprintf("repos/%v/%v/topics", owner, repo) + req, err := s.client.NewRequest("GET", u, nil) + if err != nil { + return nil, nil, err + } + + // TODO: remove custom Accept header when this API fully launches. + req.Header.Set("Accept", mediaTypeTopicsPreview) + + topics := new(Topics) + resp, err := s.client.Do(ctx, req, topics) + if err != nil { + return nil, resp, err + } + + return topics, resp, nil +} + +// ReplaceAllTopics replaces topics for a repository. +// +// GitHub API docs: https://developer.github.com/v3/repos/#replace-all-topics-for-a-repository +func (s *RepositoriesService) ReplaceAllTopics(ctx context.Context, owner, repo string, topics *Topics) (*Topics, *Response, error) { + u := fmt.Sprintf("repos/%v/%v/topics", owner, repo) + req, err := s.client.NewRequest("PUT", u, topics) + if err != nil { + return nil, nil, err + } + + // TODO: remove custom Accept header when this API fully launches. + req.Header.Set("Accept", mediaTypeTopicsPreview) + + t := new(Topics) + resp, err := s.client.Do(ctx, req, t) + if err != nil { + return nil, resp, err + } + + return t, resp, nil +} diff --git a/vendor/github.com/google/go-github/github/repos_collaborators.go b/vendor/github.com/google/go-github/github/repos_collaborators.go index 76e8a1f0a..100a92572 100644 --- a/vendor/github.com/google/go-github/github/repos_collaborators.go +++ b/vendor/github.com/google/go-github/github/repos_collaborators.go @@ -10,10 +10,26 @@ import ( "fmt" ) +// ListCollaboratorsOptions specifies the optional parameters to the +// RepositoriesService.ListCollaborators method. +type ListCollaboratorsOptions struct { + // Affiliation specifies how collaborators should be filtered by their affiliation. + // Possible values are: + // outside - All outside collaborators of an organization-owned repository + // direct - All collaborators with permissions to an organization-owned repository, + // regardless of organization membership status + // all - All collaborators the authenticated user can see + // + // Default value is "all". + Affiliation string `url:"affiliation,omitempty"` + + ListOptions +} + // ListCollaborators lists the GitHub users that have access to the repository. // -// GitHub API docs: https://developer.github.com/v3/repos/collaborators/#list -func (s *RepositoriesService) ListCollaborators(ctx context.Context, owner, repo string, opt *ListOptions) ([]*User, *Response, error) { +// GitHub API docs: https://developer.github.com/v3/repos/collaborators/#list-collaborators +func (s *RepositoriesService) ListCollaborators(ctx context.Context, owner, repo string, opt *ListCollaboratorsOptions) ([]*User, *Response, error) { u := fmt.Sprintf("repos/%v/%v/collaborators", owner, repo) u, err := addOptions(u, opt) if err != nil { @@ -91,7 +107,8 @@ type RepositoryAddCollaboratorOptions struct { Permission string `json:"permission,omitempty"` } -// AddCollaborator adds the specified GitHub user as collaborator to the given repo. +// AddCollaborator sends an invitation to the specified GitHub user +// to become a collaborator to the given repo. // // GitHub API docs: https://developer.github.com/v3/repos/collaborators/#add-user-as-a-collaborator func (s *RepositoriesService) AddCollaborator(ctx context.Context, owner, repo, user string, opt *RepositoryAddCollaboratorOptions) (*Response, error) { diff --git a/vendor/github.com/google/go-github/github/repos_commits.go b/vendor/github.com/google/go-github/github/repos_commits.go index e516f1afd..4451b6bb4 100644 --- a/vendor/github.com/google/go-github/github/repos_commits.go +++ b/vendor/github.com/google/go-github/github/repos_commits.go @@ -79,6 +79,12 @@ type CommitsComparison struct { Commits []RepositoryCommit `json:"commits,omitempty"` Files []CommitFile `json:"files,omitempty"` + + HTMLURL *string `json:"html_url,omitempty"` + PermalinkURL *string `json:"permalink_url,omitempty"` + DiffURL *string `json:"diff_url,omitempty"` + PatchURL *string `json:"patch_url,omitempty"` + URL *string `json:"url,omitempty"` // API URL. } func (c CommitsComparison) String() string { @@ -121,6 +127,9 @@ func (s *RepositoriesService) ListCommits(ctx context.Context, owner, repo strin return nil, nil, err } + // TODO: remove custom Accept header when this API fully launches. + req.Header.Set("Accept", mediaTypeGitSigningPreview) + var commits []*RepositoryCommit resp, err := s.client.Do(ctx, req, &commits) if err != nil { diff --git a/vendor/github.com/google/go-github/github/repos_community_health.go b/vendor/github.com/google/go-github/github/repos_community_health.go new file mode 100644 index 000000000..b5c75d6f5 --- /dev/null +++ b/vendor/github.com/google/go-github/github/repos_community_health.go @@ -0,0 +1,57 @@ +// Copyright 2017 The go-github AUTHORS. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package github + +import ( + "context" + "fmt" + "time" +) + +// Metric represents the different fields for one file in community health files. +type Metric struct { + Name *string `json:"name"` + Key *string `json:"key"` + URL *string `json:"url"` + HTMLURL *string `json:"html_url"` +} + +// CommunityHealthFiles represents the different files in the community health metrics response. +type CommunityHealthFiles struct { + CodeOfConduct *Metric `json:"code_of_conduct"` + Contributing *Metric `json:"contributing"` + License *Metric `json:"license"` + Readme *Metric `json:"readme"` +} + +// CommunityHealthMetrics represents a response containing the community metrics of a repository. +type CommunityHealthMetrics struct { + HealthPercentage *int `json:"health_percentage"` + Files *CommunityHealthFiles `json:"files"` + UpdatedAt *time.Time `json:"updated_at"` +} + +// GetCommunityHealthMetrics retrieves all the community health metrics for a repository. +// +// GitHub API docs: https://developer.github.com/v3/repos/community/#retrieve-community-health-metrics +func (s *RepositoriesService) GetCommunityHealthMetrics(ctx context.Context, owner, repo string) (*CommunityHealthMetrics, *Response, error) { + u := fmt.Sprintf("repos/%v/%v/community/profile", owner, repo) + req, err := s.client.NewRequest("GET", u, nil) + if err != nil { + return nil, nil, err + } + + // TODO: remove custom Accept header when this API fully launches. + req.Header.Set("Accept", mediaTypeRepositoryCommunityHealthMetricsPreview) + + metrics := &CommunityHealthMetrics{} + resp, err := s.client.Do(ctx, req, metrics) + if err != nil { + return nil, resp, err + } + + return metrics, resp, nil +} diff --git a/vendor/github.com/google/go-github/github/repos_contents.go b/vendor/github.com/google/go-github/github/repos_contents.go index dfcbe33d2..ffb56b90d 100644 --- a/vendor/github.com/google/go-github/github/repos_contents.go +++ b/vendor/github.com/google/go-github/github/repos_contents.go @@ -164,7 +164,7 @@ func (s *RepositoriesService) GetContents(ctx context.Context, owner, repo, path if directoryUnmarshalError == nil { return nil, directoryContent, resp, nil } - return nil, nil, resp, fmt.Errorf("unmarshalling failed for both file and directory content: %s and %s ", fileUnmarshalError, directoryUnmarshalError) + return nil, nil, resp, fmt.Errorf("unmarshalling failed for both file and directory content: %s and %s", fileUnmarshalError, directoryUnmarshalError) } // CreateFile creates a new file in a repository at the given path and returns @@ -248,7 +248,7 @@ func (s *RepositoriesService) GetArchiveLink(ctx context.Context, owner, repo st } var resp *http.Response // Use http.DefaultTransport if no custom Transport is configured - ctx, req = withContext(ctx, req) + req = withContext(ctx, req) if s.client.client.Transport == nil { resp, err = http.DefaultTransport.RoundTrip(req) } else { diff --git a/vendor/github.com/google/go-github/github/repos_deployments.go b/vendor/github.com/google/go-github/github/repos_deployments.go index 9054ca947..ec0e84215 100644 --- a/vendor/github.com/google/go-github/github/repos_deployments.go +++ b/vendor/github.com/google/go-github/github/repos_deployments.go @@ -23,7 +23,7 @@ type Deployment struct { Description *string `json:"description,omitempty"` Creator *User `json:"creator,omitempty"` CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"pushed_at,omitempty"` + UpdatedAt *Timestamp `json:"updated_at,omitempty"` StatusesURL *string `json:"statuses_url,omitempty"` RepositoryURL *string `json:"repository_url,omitempty"` } @@ -137,7 +137,7 @@ type DeploymentStatus struct { Description *string `json:"description,omitempty"` TargetURL *string `json:"target_url,omitempty"` CreatedAt *Timestamp `json:"created_at,omitempty"` - UpdatedAt *Timestamp `json:"pushed_at,omitempty"` + UpdatedAt *Timestamp `json:"updated_at,omitempty"` DeploymentURL *string `json:"deployment_url,omitempty"` RepositoryURL *string `json:"repository_url,omitempty"` } diff --git a/vendor/github.com/google/go-github/github/repos_forks.go b/vendor/github.com/google/go-github/github/repos_forks.go index 6b5e4eabb..4ca19a42d 100644 --- a/vendor/github.com/google/go-github/github/repos_forks.go +++ b/vendor/github.com/google/go-github/github/repos_forks.go @@ -35,6 +35,9 @@ func (s *RepositoriesService) ListForks(ctx context.Context, owner, repo string, return nil, nil, err } + // TODO: remove custom Accept header when topics API fully launches. + req.Header.Set("Accept", mediaTypeTopicsPreview) + var repos []*Repository resp, err := s.client.Do(ctx, req, &repos) if err != nil { diff --git a/vendor/github.com/google/go-github/github/repos_invitations.go b/vendor/github.com/google/go-github/github/repos_invitations.go index a803a12da..0a2b7c198 100644 --- a/vendor/github.com/google/go-github/github/repos_invitations.go +++ b/vendor/github.com/google/go-github/github/repos_invitations.go @@ -90,5 +90,9 @@ func (s *RepositoriesService) UpdateInvitation(ctx context.Context, owner, repo invite := &RepositoryInvitation{} resp, err := s.client.Do(ctx, req, invite) - return invite, resp, err + if err != nil { + return nil, resp, err + } + + return invite, resp, nil } diff --git a/vendor/github.com/google/go-github/github/repos_pages.go b/vendor/github.com/google/go-github/github/repos_pages.go index 3d19b43db..075f5742d 100644 --- a/vendor/github.com/google/go-github/github/repos_pages.go +++ b/vendor/github.com/google/go-github/github/repos_pages.go @@ -61,8 +61,13 @@ func (s *RepositoriesService) GetPagesInfo(ctx context.Context, owner, repo stri // ListPagesBuilds lists the builds for a GitHub Pages site. // // GitHub API docs: https://developer.github.com/v3/repos/pages/#list-pages-builds -func (s *RepositoriesService) ListPagesBuilds(ctx context.Context, owner, repo string) ([]*PagesBuild, *Response, error) { +func (s *RepositoriesService) ListPagesBuilds(ctx context.Context, owner, repo string, opt *ListOptions) ([]*PagesBuild, *Response, error) { u := fmt.Sprintf("repos/%v/%v/pages/builds", owner, repo) + u, err := addOptions(u, opt) + if err != nil { + return nil, nil, err + } + req, err := s.client.NewRequest("GET", u, nil) if err != nil { return nil, nil, err diff --git a/vendor/github.com/google/go-github/github/repos_releases.go b/vendor/github.com/google/go-github/github/repos_releases.go index 5c2756551..1ee7ecf99 100644 --- a/vendor/github.com/google/go-github/github/repos_releases.go +++ b/vendor/github.com/google/go-github/github/repos_releases.go @@ -244,7 +244,7 @@ func (s *RepositoriesService) DownloadReleaseAsset(ctx context.Context, owner, r } defer func() { s.client.client.CheckRedirect = saveRedirect }() - ctx, req = withContext(ctx, req) + req = withContext(ctx, req) resp, err := s.client.client.Do(req) if err != nil { if !strings.Contains(err.Error(), "disable redirect") { diff --git a/vendor/github.com/google/go-github/github/search.go b/vendor/github.com/google/go-github/github/search.go index 7668b8b62..a59735202 100644 --- a/vendor/github.com/google/go-github/github/search.go +++ b/vendor/github.com/google/go-github/github/search.go @@ -15,6 +15,14 @@ import ( // SearchService provides access to the search related functions // in the GitHub API. // +// Each method takes a query string defining the search keywords and any search qualifiers. +// For example, when searching issues, the query "gopher is:issue language:go" will search +// for issues containing the word "gopher" in Go repositories. The method call +// opts := &github.SearchOptions{Sort: "created", Order: "asc"} +// cl.Search.Issues(ctx, "gopher is:issue language:go", opts) +// will search for such issues, sorting by creation date in ascending order +// (i.e., oldest first). +// // GitHub API docs: https://developer.github.com/v3/search/ type SearchService service @@ -188,6 +196,10 @@ func (s *SearchService) search(ctx context.Context, searchType string, query str // Accept header for search commits preview endpoint // TODO: remove custom Accept header when this API fully launches. req.Header.Set("Accept", mediaTypeCommitSearchPreview) + case searchType == "repositories": + // Accept header for search repositories based on topics preview endpoint + // TODO: remove custom Accept header when this API fully launches. + req.Header.Set("Accept", mediaTypeTopicsPreview) case opt != nil && opt.TextMatch: // Accept header defaults to "application/vnd.github.v3+json" // We change it here to fetch back text-match metadata diff --git a/vendor/github.com/google/go-github/github/users.go b/vendor/github.com/google/go-github/github/users.go index d74439c7b..83cfb45b5 100644 --- a/vendor/github.com/google/go-github/github/users.go +++ b/vendor/github.com/google/go-github/github/users.go @@ -172,8 +172,13 @@ func (s *UsersService) ListAll(ctx context.Context, opt *UserListOptions) ([]*Us // authenticated user. // // GitHub API docs: https://developer.github.com/v3/repos/invitations/#list-a-users-repository-invitations -func (s *UsersService) ListInvitations(ctx context.Context) ([]*RepositoryInvitation, *Response, error) { - req, err := s.client.NewRequest("GET", "user/repository_invitations", nil) +func (s *UsersService) ListInvitations(ctx context.Context, opt *ListOptions) ([]*RepositoryInvitation, *Response, error) { + u, err := addOptions("user/repository_invitations", opt) + if err != nil { + return nil, nil, err + } + + req, err := s.client.NewRequest("GET", u, nil) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/github/users_gpg_keys.go b/vendor/github.com/google/go-github/github/users_gpg_keys.go index be88c042a..3e95fb446 100644 --- a/vendor/github.com/google/go-github/github/users_gpg_keys.go +++ b/vendor/github.com/google/go-github/github/users_gpg_keys.go @@ -43,7 +43,7 @@ type GPGEmail struct { // ListGPGKeys lists the public GPG keys for a user. Passing the empty // string will fetch keys for the authenticated user. It requires authentication // via Basic Auth or via OAuth with at least read:gpg_key scope. - +// // GitHub API docs: https://developer.github.com/v3/users/gpg_keys/#list-gpg-keys-for-a-user func (s *UsersService) ListGPGKeys(ctx context.Context, user string, opt *ListOptions) ([]*GPGKey, *Response, error) { var u string diff --git a/vendor/github.com/google/go-github/github/with_appengine.go b/vendor/github.com/google/go-github/github/with_appengine.go index 957c4d307..87a228ad7 100644 --- a/vendor/github.com/google/go-github/github/with_appengine.go +++ b/vendor/github.com/google/go-github/github/with_appengine.go @@ -17,10 +17,9 @@ package github import ( "context" "net/http" - - "google.golang.org/appengine" ) -func withContext(ctx context.Context, req *http.Request) (context.Context, *http.Request) { - return appengine.WithContext(ctx, req), req +func withContext(ctx context.Context, req *http.Request) *http.Request { + // No-op because App Engine adds context to a request differently. + return req } diff --git a/vendor/github.com/google/go-github/github/without_appengine.go b/vendor/github.com/google/go-github/github/without_appengine.go index b0edc04db..6f8fdac56 100644 --- a/vendor/github.com/google/go-github/github/without_appengine.go +++ b/vendor/github.com/google/go-github/github/without_appengine.go @@ -14,6 +14,6 @@ import ( "net/http" ) -func withContext(ctx context.Context, req *http.Request) (context.Context, *http.Request) { - return ctx, req.WithContext(ctx) +func withContext(ctx context.Context, req *http.Request) *http.Request { + return req.WithContext(ctx) } diff --git a/vendor/github.com/google/go-querystring/query/encode.go b/vendor/github.com/google/go-querystring/query/encode.go index 19437b34f..37080b19b 100644 --- a/vendor/github.com/google/go-querystring/query/encode.go +++ b/vendor/github.com/google/go-querystring/query/encode.go @@ -217,11 +217,6 @@ func reflectValue(values url.Values, val reflect.Value, scope string) error { continue } - if sv.Type() == timeType { - values.Add(name, valueString(sv, opts)) - continue - } - for sv.Kind() == reflect.Ptr { if sv.IsNil() { break @@ -229,6 +224,11 @@ func reflectValue(values url.Values, val reflect.Value, scope string) error { sv = sv.Elem() } + if sv.Type() == timeType { + values.Add(name, valueString(sv, opts)) + continue + } + if sv.Kind() == reflect.Struct { reflectValue(values, sv, name) continue diff --git a/vendor/github.com/miekg/dns/README.md b/vendor/github.com/miekg/dns/README.md index 2acc7f1ff..32a49cbf5 100644 --- a/vendor/github.com/miekg/dns/README.md +++ b/vendor/github.com/miekg/dns/README.md @@ -13,13 +13,13 @@ can build servers and resolvers with it. We try to keep the "master" branch as sane as possible and at the bleeding edge of standards, avoiding breaking changes wherever reasonable. We support the last -two versions of Go, currently: 1.6 and 1.7. +two versions of Go, currently: 1.7 and 1.8. # Goals * KISS; * Fast; -* Small API, if its easy to code in Go, don't make a function for it. +* Small API. If it's easy to code in Go, don't make a function for it. # Users @@ -57,6 +57,9 @@ A not-so-up-to-date-list-that-may-be-actually-current: * https://github.com/fffaraz/microdns * http://quilt.io * https://github.com/ipdcode/hades (JD.COM) +* https://github.com/StackExchange/dnscontrol/ +* https://www.dnsperf.com/ +* https://dnssectest.net/ Send pull request if you want to be listed here. diff --git a/vendor/github.com/miekg/dns/client.go b/vendor/github.com/miekg/dns/client.go index 301dab9c1..1c14a19d8 100644 --- a/vendor/github.com/miekg/dns/client.go +++ b/vendor/github.com/miekg/dns/client.go @@ -4,6 +4,7 @@ package dns import ( "bytes" + "context" "crypto/tls" "encoding/binary" "io" @@ -70,6 +71,43 @@ func Exchange(m *Msg, a string) (r *Msg, err error) { return r, err } +// ExchangeContext performs a synchronous UDP query, like Exchange. It +// additionally obeys deadlines from the passed Context. +func ExchangeContext(ctx context.Context, m *Msg, a string) (r *Msg, err error) { + // Combine context deadline with built-in timeout. Context chooses whichever + // is sooner. + timeoutCtx, cancel := context.WithTimeout(ctx, dnsTimeout) + defer cancel() + deadline, _ := timeoutCtx.Deadline() + + co := new(Conn) + dialer := net.Dialer{} + co.Conn, err = dialer.DialContext(timeoutCtx, "udp", a) + if err != nil { + return nil, err + } + + defer co.Conn.Close() + + opt := m.IsEdns0() + // If EDNS0 is used use that for size. + if opt != nil && opt.UDPSize() >= MinMsgSize { + co.UDPSize = opt.UDPSize() + } + + co.SetWriteDeadline(deadline) + if err = co.WriteMsg(m); err != nil { + return nil, err + } + + co.SetReadDeadline(deadline) + r, err = co.ReadMsg() + if err == nil && r.Id != m.Id { + err = ErrId + } + return r, err +} + // ExchangeConn performs a synchronous query. It sends the message m via the connection // c and waits for a reply. The connection c is not closed by ExchangeConn. // This function is going away, but can easily be mimicked: @@ -106,8 +144,18 @@ func ExchangeConn(c net.Conn, m *Msg) (r *Msg, err error) { // buffer, see SetEdns0. Messages without an OPT RR will fallback to the historic limit // of 512 bytes. func (c *Client) Exchange(m *Msg, a string) (r *Msg, rtt time.Duration, err error) { + return c.ExchangeContext(context.Background(), m, a) +} + +// ExchangeContext acts like Exchange, but honors the deadline on the provided +// context, if present. If there is both a context deadline and a configured +// timeout on the client, the earliest of the two takes effect. +func (c *Client) ExchangeContext(ctx context.Context, m *Msg, a string) ( + r *Msg, + rtt time.Duration, + err error) { if !c.SingleInflight { - return c.exchange(m, a) + return c.exchange(ctx, m, a) } // This adds a bunch of garbage, TODO(miek). t := "nop" @@ -119,7 +167,7 @@ func (c *Client) Exchange(m *Msg, a string) (r *Msg, rtt time.Duration, err erro cl = cl1 } r, rtt, err, shared := c.group.Do(m.Question[0].Name+t+cl, func() (*Msg, time.Duration, error) { - return c.exchange(m, a) + return c.exchange(ctx, m, a) }) if r != nil && shared { r = r.Copy() @@ -154,7 +202,7 @@ func (c *Client) writeTimeout() time.Duration { return dnsTimeout } -func (c *Client) exchange(m *Msg, a string) (r *Msg, rtt time.Duration, err error) { +func (c *Client) exchange(ctx context.Context, m *Msg, a string) (r *Msg, rtt time.Duration, err error) { var co *Conn network := "udp" tls := false @@ -180,10 +228,13 @@ func (c *Client) exchange(m *Msg, a string) (r *Msg, rtt time.Duration, err erro deadline = time.Now().Add(c.Timeout) } + dialDeadline := deadlineOrTimeoutOrCtx(ctx, deadline, c.dialTimeout()) + dialTimeout := dialDeadline.Sub(time.Now()) + if tls { - co, err = DialTimeoutWithTLS(network, a, c.TLSConfig, c.dialTimeout()) + co, err = DialTimeoutWithTLS(network, a, c.TLSConfig, dialTimeout) } else { - co, err = DialTimeout(network, a, c.dialTimeout()) + co, err = DialTimeout(network, a, dialTimeout) } if err != nil { @@ -202,12 +253,12 @@ func (c *Client) exchange(m *Msg, a string) (r *Msg, rtt time.Duration, err erro } co.TsigSecret = c.TsigSecret - co.SetWriteDeadline(deadlineOrTimeout(deadline, c.writeTimeout())) + co.SetWriteDeadline(deadlineOrTimeoutOrCtx(ctx, deadline, c.writeTimeout())) if err = co.WriteMsg(m); err != nil { return nil, 0, err } - co.SetReadDeadline(deadlineOrTimeout(deadline, c.readTimeout())) + co.SetReadDeadline(deadlineOrTimeoutOrCtx(ctx, deadline, c.readTimeout())) r, err = co.ReadMsg() if err == nil && r.Id != m.Id { err = ErrId @@ -459,9 +510,22 @@ func DialTimeoutWithTLS(network, address string, tlsConfig *tls.Config, timeout return conn, nil } +// deadlineOrTimeout chooses between the provided deadline and timeout +// by always preferring the deadline so long as it's non-zero (regardless +// of which is bigger), and returns the equivalent deadline value. func deadlineOrTimeout(deadline time.Time, timeout time.Duration) time.Time { if deadline.IsZero() { return time.Now().Add(timeout) } return deadline } + +// deadlineOrTimeoutOrCtx returns the earliest of: a context deadline, or the +// output of deadlineOrtimeout. +func deadlineOrTimeoutOrCtx(ctx context.Context, deadline time.Time, timeout time.Duration) time.Time { + result := deadlineOrTimeout(deadline, timeout) + if ctxDeadline, ok := ctx.Deadline(); ok && ctxDeadline.Before(result) { + result = ctxDeadline + } + return result +} diff --git a/vendor/github.com/miekg/dns/defaults.go b/vendor/github.com/miekg/dns/defaults.go index 3308ec838..c34890eec 100644 --- a/vendor/github.com/miekg/dns/defaults.go +++ b/vendor/github.com/miekg/dns/defaults.go @@ -13,9 +13,12 @@ const hexDigit = "0123456789abcdef" // SetReply creates a reply message from a request message. func (dns *Msg) SetReply(request *Msg) *Msg { dns.Id = request.Id - dns.RecursionDesired = request.RecursionDesired // Copy rd bit dns.Response = true - dns.Opcode = OpcodeQuery + dns.Opcode = request.Opcode + if dns.Opcode == OpcodeQuery { + dns.RecursionDesired = request.RecursionDesired // Copy rd bit + dns.CheckingDisabled = request.CheckingDisabled // Copy cd bit + } dns.Rcode = RcodeSuccess if len(request.Question) > 0 { dns.Question = make([]Question, 1) diff --git a/vendor/github.com/miekg/dns/dnssec.go b/vendor/github.com/miekg/dns/dnssec.go index 07262011e..3bd55388d 100644 --- a/vendor/github.com/miekg/dns/dnssec.go +++ b/vendor/github.com/miekg/dns/dnssec.go @@ -515,7 +515,7 @@ func (k *DNSKEY) publicKeyRSA() *rsa.PublicKey { } // Remainder expo += uint64(keybuf[keyoff]) - if expo > 2<<31 { + if expo > (2<<31)+1 { // Larger expo than supported. // println("dns: F5 primes (or larger) are not supported") return nil diff --git a/vendor/github.com/miekg/dns/labels.go b/vendor/github.com/miekg/dns/labels.go index fca5c7dd2..9538d9c3a 100644 --- a/vendor/github.com/miekg/dns/labels.go +++ b/vendor/github.com/miekg/dns/labels.go @@ -1,5 +1,7 @@ package dns +import "strings" + // Holds a bunch of helper functions for dealing with labels. // SplitDomainName splits a name string into it's labels. @@ -50,6 +52,7 @@ func SplitDomainName(s string) (labels []string) { // // s1 and s2 must be syntactically valid domain names. func CompareDomainName(s1, s2 string) (n int) { + s1, s2 = strings.ToLower(s1), strings.ToLower(s2) s1 = Fqdn(s1) s2 = Fqdn(s2) l1 := Split(s1) diff --git a/vendor/github.com/miekg/dns/msg.go b/vendor/github.com/miekg/dns/msg.go index 57262a10c..605fe6c5c 100644 --- a/vendor/github.com/miekg/dns/msg.go +++ b/vendor/github.com/miekg/dns/msg.go @@ -14,25 +14,30 @@ package dns import ( crand "crypto/rand" "encoding/binary" + "fmt" "math/big" "math/rand" "strconv" "sync" ) -const maxCompressionOffset = 2 << 13 // We have 14 bits for the compression pointer +const ( + maxCompressionOffset = 2 << 13 // We have 14 bits for the compression pointer + maxDomainNameWireOctets = 255 // See RFC 1035 section 2.3.4 +) var ( ErrAlg error = &Error{err: "bad algorithm"} // ErrAlg indicates an error with the (DNSSEC) algorithm. ErrAuth error = &Error{err: "bad authentication"} // ErrAuth indicates an error in the TSIG authentication. - ErrBuf error = &Error{err: "buffer size too small"} // ErrBuf indicates that the buffer used it too small for the message. - ErrConnEmpty error = &Error{err: "conn has no connection"} // ErrConnEmpty indicates a connection is being uses before it is initialized. + ErrBuf error = &Error{err: "buffer size too small"} // ErrBuf indicates that the buffer used is too small for the message. + ErrConnEmpty error = &Error{err: "conn has no connection"} // ErrConnEmpty indicates a connection is being used before it is initialized. ErrExtendedRcode error = &Error{err: "bad extended rcode"} // ErrExtendedRcode ... ErrFqdn error = &Error{err: "domain must be fully qualified"} // ErrFqdn indicates that a domain name does not have a closing dot. ErrId error = &Error{err: "id mismatch"} // ErrId indicates there is a mismatch with the message's ID. ErrKeyAlg error = &Error{err: "bad key algorithm"} // ErrKeyAlg indicates that the algorithm in the key is not valid. ErrKey error = &Error{err: "bad key"} ErrKeySize error = &Error{err: "bad key size"} + ErrLongDomain error = &Error{err: fmt.Sprintf("domain name exceeded %d wire-format octets", maxDomainNameWireOctets)} ErrNoSig error = &Error{err: "no signature found"} ErrPrivKey error = &Error{err: "bad private key"} ErrRcode error = &Error{err: "bad rcode"} @@ -329,6 +334,7 @@ func UnpackDomainName(msg []byte, off int) (string, int, error) { s := make([]byte, 0, 64) off1 := 0 lenmsg := len(msg) + maxLen := maxDomainNameWireOctets ptr := 0 // number of pointers followed Loop: for { @@ -353,8 +359,10 @@ Loop: fallthrough case '"', '\\': s = append(s, '\\', b) + // presentation-format \X escapes add an extra byte + maxLen += 1 default: - if b < 32 || b >= 127 { // unprintable use \DDD + if b < 32 || b >= 127 { // unprintable, use \DDD var buf [3]byte bufs := strconv.AppendInt(buf[:0], int64(b), 10) s = append(s, '\\') @@ -364,6 +372,8 @@ Loop: for _, r := range bufs { s = append(s, r) } + // presentation-format \DDD escapes add 3 extra bytes + maxLen += 3 } else { s = append(s, b) } @@ -388,6 +398,9 @@ Loop: if ptr++; ptr > 10 { return "", lenmsg, &Error{err: "too many compression pointers"} } + // pointer should guarantee that it advances and points forwards at least + // but the condition on previous three lines guarantees that it's + // at least loop-free off = (c^0xC0)<<8 | int(c1) default: // 0x80 and 0x40 are reserved @@ -399,6 +412,9 @@ Loop: } if len(s) == 0 { s = []byte(".") + } else if len(s) >= maxLen { + // error if the name is too long, but don't throw it away + return string(s), lenmsg, ErrLongDomain } return string(s), off1, nil } diff --git a/vendor/github.com/miekg/dns/msg_helpers.go b/vendor/github.com/miekg/dns/msg_helpers.go index 615274ab0..8d415c92a 100644 --- a/vendor/github.com/miekg/dns/msg_helpers.go +++ b/vendor/github.com/miekg/dns/msg_helpers.go @@ -96,7 +96,7 @@ func unpackHeader(msg []byte, off int) (rr RR_Header, off1 int, truncmsg []byte, return hdr, len(msg), msg, err } msg, err = truncateMsgFromRdlength(msg, off, hdr.Rdlength) - return hdr, off, msg, nil + return hdr, off, msg, err } // pack packs an RR header, returning the offset to the end of the header. diff --git a/vendor/github.com/miekg/dns/nsecx.go b/vendor/github.com/miekg/dns/nsecx.go index 51ce7f8b1..9b908c447 100644 --- a/vendor/github.com/miekg/dns/nsecx.go +++ b/vendor/github.com/miekg/dns/nsecx.go @@ -48,62 +48,50 @@ func HashName(label string, ha uint8, iter uint16, salt string) string { return toBase32(nsec3) } -// Denialer is an interface that should be implemented by types that are used to denial -// answers in DNSSEC. -type Denialer interface { - // Cover will check if the (unhashed) name is being covered by this NSEC or NSEC3. - Cover(name string) bool - // Match will check if the ownername matches the (unhashed) name for this NSEC3 or NSEC3. - Match(name string) bool -} - -// Cover implements the Denialer interface. -func (rr *NSEC) Cover(name string) bool { - return true -} - -// Match implements the Denialer interface. -func (rr *NSEC) Match(name string) bool { - return true -} - -// Cover implements the Denialer interface. +// Cover returns true if a name is covered by the NSEC3 record func (rr *NSEC3) Cover(name string) bool { - // FIXME(miek): check if the zones match - // FIXME(miek): check if we're not dealing with parent nsec3 - hname := HashName(name, rr.Hash, rr.Iterations, rr.Salt) - labels := Split(rr.Hdr.Name) - if len(labels) < 2 { + nameHash := HashName(name, rr.Hash, rr.Iterations, rr.Salt) + owner := strings.ToUpper(rr.Hdr.Name) + labelIndices := Split(owner) + if len(labelIndices) < 2 { return false } - hash := strings.ToUpper(rr.Hdr.Name[labels[0] : labels[1]-1]) // -1 to remove the dot - if hash == rr.NextDomain { - return false // empty interval - } - if hash > rr.NextDomain { // last name, points to apex - // hname > hash - // hname > rr.NextDomain - // TODO(miek) - } - if hname <= hash { + ownerHash := owner[:labelIndices[1]-1] + ownerZone := owner[labelIndices[1]:] + if !IsSubDomain(ownerZone, strings.ToUpper(name)) { // name is outside owner zone return false } - if hname >= rr.NextDomain { + + nextHash := rr.NextDomain + if ownerHash == nextHash { // empty interval return false } - return true + if ownerHash > nextHash { // end of zone + if nameHash > ownerHash { // covered since there is nothing after ownerHash + return true + } + return nameHash < nextHash // if nameHash is before beginning of zone it is covered + } + if nameHash < ownerHash { // nameHash is before ownerHash, not covered + return false + } + return nameHash < nextHash // if nameHash is before nextHash is it covered (between ownerHash and nextHash) } -// Match implements the Denialer interface. +// Match returns true if a name matches the NSEC3 record func (rr *NSEC3) Match(name string) bool { - // FIXME(miek): Check if we are in the same zone - hname := HashName(name, rr.Hash, rr.Iterations, rr.Salt) - labels := Split(rr.Hdr.Name) - if len(labels) < 2 { + nameHash := HashName(name, rr.Hash, rr.Iterations, rr.Salt) + owner := strings.ToUpper(rr.Hdr.Name) + labelIndices := Split(owner) + if len(labelIndices) < 2 { return false } - hash := strings.ToUpper(rr.Hdr.Name[labels[0] : labels[1]-1]) // -1 to remove the . - if hash == hname { + ownerHash := owner[:labelIndices[1]-1] + ownerZone := owner[labelIndices[1]:] + if !IsSubDomain(ownerZone, strings.ToUpper(name)) { // name is outside owner zone + return false + } + if ownerHash == nameHash { return true } return false diff --git a/vendor/github.com/miekg/dns/scan.go b/vendor/github.com/miekg/dns/scan.go index de0db32f8..a76f1d83f 100644 --- a/vendor/github.com/miekg/dns/scan.go +++ b/vendor/github.com/miekg/dns/scan.go @@ -278,8 +278,7 @@ func parseZone(r io.Reader, origin, f string, t chan *Token, include int) { return } neworigin := origin // There may be optionally a new origin set after the filename, if not use current one - l := <-c - switch l.value { + switch l := <-c; l.value { case zBlank: l := <-c if l.value == zString { @@ -314,7 +313,7 @@ func parseZone(r io.Reader, origin, f string, t chan *Token, include int) { t <- &Token{Error: &ParseError{f, "too deeply nested $INCLUDE", l}} return } - parseZone(r1, l.token, neworigin, t, include+1) + parseZone(r1, neworigin, l.token, t, include+1) st = zExpectOwnerDir case zExpectDirTtlBl: if l.value != zBlank { @@ -811,6 +810,12 @@ func zlexer(s *scan, c chan lex) { debug.Printf("[%+v]", l.token) c <- l } + if brace != 0 { + l.token = "unbalanced brace" + l.tokenUpper = l.token + l.err = true + c <- l + } } // Extract the class number from CLASSxx diff --git a/vendor/github.com/miekg/dns/scan_rr.go b/vendor/github.com/miekg/dns/scan_rr.go index f4c0d3767..b8b18fd77 100644 --- a/vendor/github.com/miekg/dns/scan_rr.go +++ b/vendor/github.com/miekg/dns/scan_rr.go @@ -1807,6 +1807,18 @@ func setSPF(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) { return rr, nil, c1 } +func setAVC(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) { + rr := new(AVC) + rr.Hdr = h + + s, e, c1 := endingToTxtSlice(c, "bad AVC Txt", f) + if e != nil { + return nil, e, "" + } + rr.Txt = s + return rr, nil, c1 +} + func setTXT(h RR_Header, c chan lex, o, f string) (RR, *ParseError, string) { rr := new(TXT) rr.Hdr = h @@ -2158,6 +2170,7 @@ var typeToparserFunc = map[uint16]parserFunc{ TypeSMIMEA: {setSMIMEA, true}, TypeSOA: {setSOA, false}, TypeSPF: {setSPF, true}, + TypeAVC: {setAVC, true}, TypeSRV: {setSRV, false}, TypeSSHFP: {setSSHFP, true}, TypeTALINK: {setTALINK, false}, diff --git a/vendor/github.com/miekg/dns/tsig.go b/vendor/github.com/miekg/dns/tsig.go index 24013096b..4837b4ab1 100644 --- a/vendor/github.com/miekg/dns/tsig.go +++ b/vendor/github.com/miekg/dns/tsig.go @@ -208,6 +208,9 @@ func tsigBuffer(msgbuf []byte, rr *TSIG, requestMAC string, timersOnly bool) []b rr.Fudge = 300 // Standard (RFC) default. } + // Replace message ID in header with original ID from TSIG + binary.BigEndian.PutUint16(msgbuf[0:2], rr.OrigId) + if requestMAC != "" { m := new(macWireFmt) m.MACSize = uint16(len(requestMAC) / 2) diff --git a/vendor/github.com/miekg/dns/types.go b/vendor/github.com/miekg/dns/types.go index c17251cb6..57f065bc8 100644 --- a/vendor/github.com/miekg/dns/types.go +++ b/vendor/github.com/miekg/dns/types.go @@ -91,6 +91,7 @@ const ( TypeEUI64 uint16 = 109 TypeURI uint16 = 256 TypeCAA uint16 = 257 + TypeAVC uint16 = 258 TypeTKEY uint16 = 249 TypeTSIG uint16 = 250 @@ -114,27 +115,27 @@ const ( ClassNONE = 254 ClassANY = 255 - // Message Response Codes. - RcodeSuccess = 0 - RcodeFormatError = 1 - RcodeServerFailure = 2 - RcodeNameError = 3 - RcodeNotImplemented = 4 - RcodeRefused = 5 - RcodeYXDomain = 6 - RcodeYXRrset = 7 - RcodeNXRrset = 8 - RcodeNotAuth = 9 - RcodeNotZone = 10 - RcodeBadSig = 16 // TSIG - RcodeBadVers = 16 // EDNS0 - RcodeBadKey = 17 - RcodeBadTime = 18 - RcodeBadMode = 19 // TKEY - RcodeBadName = 20 - RcodeBadAlg = 21 - RcodeBadTrunc = 22 // TSIG - RcodeBadCookie = 23 // DNS Cookies + // Message Response Codes, see https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml + RcodeSuccess = 0 // NoError - No Error [DNS] + RcodeFormatError = 1 // FormErr - Format Error [DNS] + RcodeServerFailure = 2 // ServFail - Server Failure [DNS] + RcodeNameError = 3 // NXDomain - Non-Existent Domain [DNS] + RcodeNotImplemented = 4 // NotImp - Not Implemented [DNS] + RcodeRefused = 5 // Refused - Query Refused [DNS] + RcodeYXDomain = 6 // YXDomain - Name Exists when it should not [DNS Update] + RcodeYXRrset = 7 // YXRRSet - RR Set Exists when it should not [DNS Update] + RcodeNXRrset = 8 // NXRRSet - RR Set that should exist does not [DNS Update] + RcodeNotAuth = 9 // NotAuth - Server Not Authoritative for zone [DNS Update] + RcodeNotZone = 10 // NotZone - Name not contained in zone [DNS Update/TSIG] + RcodeBadSig = 16 // BADSIG - TSIG Signature Failure [TSIG] + RcodeBadVers = 16 // BADVERS - Bad OPT Version [EDNS0] + RcodeBadKey = 17 // BADKEY - Key not recognized [TSIG] + RcodeBadTime = 18 // BADTIME - Signature out of time window [TSIG] + RcodeBadMode = 19 // BADMODE - Bad TKEY Mode [TKEY] + RcodeBadName = 20 // BADNAME - Duplicate key name [TKEY] + RcodeBadAlg = 21 // BADALG - Algorithm not supported [TKEY] + RcodeBadTrunc = 22 // BADTRUNC - Bad Truncation [TSIG] + RcodeBadCookie = 23 // BADCOOKIE - Bad/missing Server Cookie [DNS Cookies] // Message Opcodes. There is no 3. OpcodeQuery = 0 @@ -530,6 +531,13 @@ type SPF struct { func (rr *SPF) String() string { return rr.Hdr.String() + sprintTxt(rr.Txt) } +type AVC struct { + Hdr RR_Header + Txt []string `dns:"txt"` +} + +func (rr *AVC) String() string { return rr.Hdr.String() + sprintTxt(rr.Txt) } + type SRV struct { Hdr RR_Header Priority uint16 diff --git a/vendor/github.com/miekg/dns/xfr.go b/vendor/github.com/miekg/dns/xfr.go index 7346deffb..576c5590a 100644 --- a/vendor/github.com/miekg/dns/xfr.go +++ b/vendor/github.com/miekg/dns/xfr.go @@ -1,6 +1,7 @@ package dns import ( + "fmt" "time" ) @@ -81,6 +82,10 @@ func (t *Transfer) inAxfr(id uint16, c chan *Envelope) { return } if first { + if in.Rcode != RcodeSuccess { + c <- &Envelope{in.Answer, &Error{err: fmt.Sprintf(errXFR, in.Rcode)}} + return + } if !isSOAFirst(in) { c <- &Envelope{in.Answer, ErrSoa} return @@ -126,6 +131,10 @@ func (t *Transfer) inIxfr(id uint16, c chan *Envelope) { return } if first { + if in.Rcode != RcodeSuccess { + c <- &Envelope{in.Answer, &Error{err: fmt.Sprintf(errXFR, in.Rcode)}} + return + } // A single SOA RR signals "no changes" if len(in.Answer) == 1 && isSOAFirst(in) { c <- &Envelope{in.Answer, nil} @@ -242,3 +251,5 @@ func isSOALast(in *Msg) bool { } return false } + +const errXFR = "bad xfr rcode: %d" diff --git a/vendor/github.com/miekg/dns/zcompress.go b/vendor/github.com/miekg/dns/zcompress.go index 86a31a916..b277978b9 100644 --- a/vendor/github.com/miekg/dns/zcompress.go +++ b/vendor/github.com/miekg/dns/zcompress.go @@ -5,99 +5,95 @@ package dns func compressionLenHelperType(c map[string]int, r RR) { switch x := r.(type) { - case *KX: - compressionLenHelper(c, x.Exchanger) - case *MX: - compressionLenHelper(c, x.Mx) - case *NSEC: - compressionLenHelper(c, x.NextDomain) - case *DNAME: - compressionLenHelper(c, x.Target) - case *HIP: - for i := range x.RendezvousServers { - compressionLenHelper(c, x.RendezvousServers[i]) - } - case *CNAME: - compressionLenHelper(c, x.Target) - case *MR: - compressionLenHelper(c, x.Mr) - case *PX: - compressionLenHelper(c, x.Map822) - compressionLenHelper(c, x.Mapx400) - case *SIG: - compressionLenHelper(c, x.SignerName) - case *SRV: - compressionLenHelper(c, x.Target) - case *TALINK: - compressionLenHelper(c, x.PreviousName) - compressionLenHelper(c, x.NextName) - case *LP: - compressionLenHelper(c, x.Fqdn) - case *NAPTR: - compressionLenHelper(c, x.Replacement) - case *NS: - compressionLenHelper(c, x.Ns) - case *RP: - compressionLenHelper(c, x.Mbox) - compressionLenHelper(c, x.Txt) - case *RRSIG: - compressionLenHelper(c, x.SignerName) - case *TKEY: - compressionLenHelper(c, x.Algorithm) - case *TSIG: - compressionLenHelper(c, x.Algorithm) - case *AFSDB: - compressionLenHelper(c, x.Hostname) - case *MF: - compressionLenHelper(c, x.Mf) - case *RT: - compressionLenHelper(c, x.Host) - case *MINFO: - compressionLenHelper(c, x.Rmail) - compressionLenHelper(c, x.Email) case *PTR: compressionLenHelper(c, x.Ptr) case *SOA: compressionLenHelper(c, x.Ns) compressionLenHelper(c, x.Mbox) - case *MD: - compressionLenHelper(c, x.Md) - case *NSAPPTR: - compressionLenHelper(c, x.Ptr) - case *MG: - compressionLenHelper(c, x.Mg) + case *AFSDB: + compressionLenHelper(c, x.Hostname) + case *HIP: + for i := range x.RendezvousServers { + compressionLenHelper(c, x.RendezvousServers[i]) + } + case *LP: + compressionLenHelper(c, x.Fqdn) + case *CNAME: + compressionLenHelper(c, x.Target) case *MB: compressionLenHelper(c, x.Mb) + case *RP: + compressionLenHelper(c, x.Mbox) + compressionLenHelper(c, x.Txt) + case *RRSIG: + compressionLenHelper(c, x.SignerName) + case *MF: + compressionLenHelper(c, x.Mf) + case *MINFO: + compressionLenHelper(c, x.Rmail) + compressionLenHelper(c, x.Email) + case *SIG: + compressionLenHelper(c, x.SignerName) + case *SRV: + compressionLenHelper(c, x.Target) + case *TSIG: + compressionLenHelper(c, x.Algorithm) + case *KX: + compressionLenHelper(c, x.Exchanger) + case *MG: + compressionLenHelper(c, x.Mg) + case *NSAPPTR: + compressionLenHelper(c, x.Ptr) + case *PX: + compressionLenHelper(c, x.Map822) + compressionLenHelper(c, x.Mapx400) + case *DNAME: + compressionLenHelper(c, x.Target) + case *MR: + compressionLenHelper(c, x.Mr) + case *MX: + compressionLenHelper(c, x.Mx) + case *TKEY: + compressionLenHelper(c, x.Algorithm) + case *NSEC: + compressionLenHelper(c, x.NextDomain) + case *TALINK: + compressionLenHelper(c, x.PreviousName) + compressionLenHelper(c, x.NextName) + case *MD: + compressionLenHelper(c, x.Md) + case *NAPTR: + compressionLenHelper(c, x.Replacement) + case *NS: + compressionLenHelper(c, x.Ns) + case *RT: + compressionLenHelper(c, x.Host) } } func compressionLenSearchType(c map[string]int, r RR) (int, bool) { switch x := r.(type) { - case *MF: - k1, ok1 := compressionLenSearch(c, x.Mf) - return k1, ok1 case *MG: k1, ok1 := compressionLenSearch(c, x.Mg) return k1, ok1 - case *MINFO: - k1, ok1 := compressionLenSearch(c, x.Rmail) - k2, ok2 := compressionLenSearch(c, x.Email) - return k1 + k2, ok1 && ok2 - case *MR: - k1, ok1 := compressionLenSearch(c, x.Mr) - return k1, ok1 case *PTR: k1, ok1 := compressionLenSearch(c, x.Ptr) return k1, ok1 case *AFSDB: k1, ok1 := compressionLenSearch(c, x.Hostname) return k1, ok1 - case *CNAME: - k1, ok1 := compressionLenSearch(c, x.Target) + case *MB: + k1, ok1 := compressionLenSearch(c, x.Mb) return k1, ok1 case *MD: k1, ok1 := compressionLenSearch(c, x.Md) return k1, ok1 + case *MF: + k1, ok1 := compressionLenSearch(c, x.Mf) + return k1, ok1 + case *NS: + k1, ok1 := compressionLenSearch(c, x.Ns) + return k1, ok1 case *RT: k1, ok1 := compressionLenSearch(c, x.Host) return k1, ok1 @@ -105,15 +101,19 @@ func compressionLenSearchType(c map[string]int, r RR) (int, bool) { k1, ok1 := compressionLenSearch(c, x.Ns) k2, ok2 := compressionLenSearch(c, x.Mbox) return k1 + k2, ok1 && ok2 - case *MB: - k1, ok1 := compressionLenSearch(c, x.Mb) + case *CNAME: + k1, ok1 := compressionLenSearch(c, x.Target) + return k1, ok1 + case *MINFO: + k1, ok1 := compressionLenSearch(c, x.Rmail) + k2, ok2 := compressionLenSearch(c, x.Email) + return k1 + k2, ok1 && ok2 + case *MR: + k1, ok1 := compressionLenSearch(c, x.Mr) return k1, ok1 case *MX: k1, ok1 := compressionLenSearch(c, x.Mx) return k1, ok1 - case *NS: - k1, ok1 := compressionLenSearch(c, x.Ns) - return k1, ok1 } return 0, false } diff --git a/vendor/github.com/miekg/dns/zmsg.go b/vendor/github.com/miekg/dns/zmsg.go index 9b98e1bb2..418fb1fe3 100644 --- a/vendor/github.com/miekg/dns/zmsg.go +++ b/vendor/github.com/miekg/dns/zmsg.go @@ -61,6 +61,20 @@ func (rr *ANY) pack(msg []byte, off int, compression map[string]int, compress bo return off, nil } +func (rr *AVC) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { + off, err := rr.Hdr.pack(msg, off, compression, compress) + if err != nil { + return off, err + } + headerEnd := off + off, err = packStringTxt(rr.Txt, msg, off) + if err != nil { + return off, err + } + rr.Header().Rdlength = uint16(off - headerEnd) + return off, nil +} + func (rr *CAA) pack(msg []byte, off int, compression map[string]int, compress bool) (int, error) { off, err := rr.Hdr.pack(msg, off, compression, compress) if err != nil { @@ -1528,6 +1542,23 @@ func unpackANY(h RR_Header, msg []byte, off int) (RR, int, error) { return rr, off, err } +func unpackAVC(h RR_Header, msg []byte, off int) (RR, int, error) { + rr := new(AVC) + rr.Hdr = h + if noRdata(h) { + return rr, off, nil + } + var err error + rdStart := off + _ = rdStart + + rr.Txt, off, err = unpackStringTxt(msg, off) + if err != nil { + return rr, off, err + } + return rr, off, err +} + func unpackCAA(h RR_Header, msg []byte, off int) (RR, int, error) { rr := new(CAA) rr.Hdr = h @@ -3467,6 +3498,7 @@ var typeToUnpack = map[uint16]func(RR_Header, []byte, int) (RR, int, error){ TypeAAAA: unpackAAAA, TypeAFSDB: unpackAFSDB, TypeANY: unpackANY, + TypeAVC: unpackAVC, TypeCAA: unpackCAA, TypeCDNSKEY: unpackCDNSKEY, TypeCDS: unpackCDS, diff --git a/vendor/github.com/miekg/dns/ztypes.go b/vendor/github.com/miekg/dns/ztypes.go index 311b8243b..3e534f12e 100644 --- a/vendor/github.com/miekg/dns/ztypes.go +++ b/vendor/github.com/miekg/dns/ztypes.go @@ -14,6 +14,7 @@ var TypeToRR = map[uint16]func() RR{ TypeAAAA: func() RR { return new(AAAA) }, TypeAFSDB: func() RR { return new(AFSDB) }, TypeANY: func() RR { return new(ANY) }, + TypeAVC: func() RR { return new(AVC) }, TypeCAA: func() RR { return new(CAA) }, TypeCDNSKEY: func() RR { return new(CDNSKEY) }, TypeCDS: func() RR { return new(CDS) }, @@ -86,6 +87,7 @@ var TypeToString = map[uint16]string{ TypeAFSDB: "AFSDB", TypeANY: "ANY", TypeATMA: "ATMA", + TypeAVC: "AVC", TypeAXFR: "AXFR", TypeCAA: "CAA", TypeCDNSKEY: "CDNSKEY", @@ -166,6 +168,7 @@ func (rr *A) Header() *RR_Header { return &rr.Hdr } func (rr *AAAA) Header() *RR_Header { return &rr.Hdr } func (rr *AFSDB) Header() *RR_Header { return &rr.Hdr } func (rr *ANY) Header() *RR_Header { return &rr.Hdr } +func (rr *AVC) Header() *RR_Header { return &rr.Hdr } func (rr *CAA) Header() *RR_Header { return &rr.Hdr } func (rr *CDNSKEY) Header() *RR_Header { return &rr.Hdr } func (rr *CDS) Header() *RR_Header { return &rr.Hdr } @@ -252,6 +255,13 @@ func (rr *ANY) len() int { l := rr.Hdr.len() return l } +func (rr *AVC) len() int { + l := rr.Hdr.len() + for _, x := range rr.Txt { + l += len(x) + 1 + } + return l +} func (rr *CAA) len() int { l := rr.Hdr.len() l++ // Flag @@ -649,6 +659,11 @@ func (rr *AFSDB) copy() RR { func (rr *ANY) copy() RR { return &ANY{*rr.Hdr.copyHeader()} } +func (rr *AVC) copy() RR { + Txt := make([]string, len(rr.Txt)) + copy(Txt, rr.Txt) + return &AVC{*rr.Hdr.copyHeader(), Txt} +} func (rr *CAA) copy() RR { return &CAA{*rr.Hdr.copyHeader(), rr.Flag, rr.Tag, rr.Value} } diff --git a/vendor/github.com/mjibson/esc/embed/embed.go b/vendor/github.com/mjibson/esc/embed/embed.go index 03db538f1..4c9b21a2a 100644 --- a/vendor/github.com/mjibson/esc/embed/embed.go +++ b/vendor/github.com/mjibson/esc/embed/embed.go @@ -1,4 +1,4 @@ -//Package embed implements all file embedding logic for github.com/mjibson/esc +// Package embed implements all file embedding logic for github.com/mjibson/esc. package embed import ( @@ -7,7 +7,6 @@ import ( "encoding/base64" "fmt" "io/ioutil" - "log" "os" "path" "path/filepath" @@ -18,30 +17,34 @@ import ( "text/template" ) -//Config contains all information needed to run esc +// Config contains all information needed to run esc. type Config struct { - //Output file, else stdout + // OutputFile is the file name to write output, else stdout. OutputFile string - //Package declaration for generated file + // Package name for the generated file. Package string - //Prefix to strip from filenames + // Prefix is stripped from filenames. Prefix string - //Regexp for files we should ignore (for example \\\\.DS_Store) + // Ignore is the regexp for files we should ignore (for example `\.DS_Store`). Ignore string - //Regexp for files to include. If provided, only files that match will be included + // Include is the regexp for files to include. If provided, only files that + // match will be included. Include string - //Unix timestamp to override as modification time for all files + // ModTime is the Unix timestamp to override as modification time for all files. ModTime string - //If true, do not export autogenerated functions + // Private, if true, causes autogenerated functions to be unexported. Private bool + // NoCompression, if true, stores the files without compression. + NoCompression bool - //List of files or directories to embed + // Files is the list of files or directories to embed. Files []string } var modTime *int64 type headerTemplateParams struct { + Invocation string PackageName string FunctionPrefix string } @@ -52,12 +55,13 @@ type _escFile struct { fileinfo os.FileInfo } -func Run(conf *Config) { +// Run executes a Config. +func Run(conf *Config) error { var err error if conf.ModTime != "" { i, err := strconv.ParseInt(conf.ModTime, 10, 64) if err != nil { - log.Fatalf("modtime must be an integer: %v", err) + return fmt.Errorf("modtime must be an integer: %v", err) } modTime = &i } @@ -68,14 +72,14 @@ func Run(conf *Config) { if conf.Ignore != "" { ignoreRegexp, err = regexp.Compile(conf.Ignore) if err != nil { - log.Fatal(err) + return err } } var includeRegexp *regexp.Regexp if conf.Include != "" { includeRegexp, err = regexp.Compile(conf.Include) if err != nil { - log.Fatal(err) + return err } } for _, base := range conf.Files { @@ -88,16 +92,16 @@ func Run(conf *Config) { } f, err := os.Open(fname) if err != nil { - log.Fatal(err) + return err } fi, err := f.Stat() if err != nil { - log.Fatal(err) + return err } if fi.IsDir() { fis, err := f.Readdir(0) if err != nil { - log.Fatal(err) + return err } for _, fi := range fis { files = append(files, filepath.Join(fname, fi.Name())) @@ -105,11 +109,14 @@ func Run(conf *Config) { } else if includeRegexp == nil || includeRegexp.MatchString(fname) { b, err := ioutil.ReadAll(f) if err != nil { - log.Fatal(err) + return err } fpath := filepath.ToSlash(fname) n := strings.TrimPrefix(fpath, prefix) n = path.Join("/", n) + if _, ok := content[n]; ok { + return fmt.Errorf("%s, %s: duplicate name after prefix removal", n, fpath) + } content[n] = _escFile{data: b, local: fpath, fileinfo: fi} fnames = append(fnames, n) } @@ -117,33 +124,34 @@ func Run(conf *Config) { } } sort.Strings(fnames) - w := os.Stdout - if conf.OutputFile != "" { - if w, err = os.Create(conf.OutputFile); err != nil { - log.Fatal(err) - } - defer w.Close() - } + w := new(bytes.Buffer) headerText, err := header(conf.Package, !(conf.Private)) if nil != err { - log.Fatalf("failed to expand autogenerated code: %s", err) + return fmt.Errorf("failed to expand autogenerated code: %s", err) } if _, err := w.Write(headerText); err != nil { - log.Fatalf("failed to write output: %s", err) + return fmt.Errorf("failed to write output: %s", err) } dirs := map[string]bool{"/": true} + gzipLevel := gzip.BestCompression + if conf.NoCompression { + gzipLevel = gzip.NoCompression + } for _, fname := range fnames { f := content[fname] for b := path.Dir(fname); b != "/"; b = path.Dir(b) { dirs[b] = true } var buf bytes.Buffer - gw := gzip.NewWriter(&buf) + gw, err := gzip.NewWriterLevel(&buf, gzipLevel) + if err != nil { + return err + } if _, err := gw.Write(f.data); err != nil { - log.Fatal(err) + return err } if err := gw.Close(); err != nil { - log.Fatal(err) + return err } t := f.fileinfo.ModTime().Unix() if modTime != nil { @@ -166,13 +174,31 @@ func Run(conf *Config) { if len(local) == 0 { local = "." } + if local[0] == '/' { + // Read dirs relative to the go proc's cwd vs system's + // fs root. + local = local[1:] + } fmt.Fprintf(w, ` %q: { isDir: true, local: %q, },%s`, dir, local, "\n") } - fmt.Fprint(w, footer) + w.WriteString(footer) + out := os.Stdout + if conf.OutputFile != "" { + if out, err = os.Create(conf.OutputFile); err != nil { + return err + } + } + if _, err := w.WriteTo(out); err != nil { + return err + } + if conf.OutputFile != "" { + return out.Close() + } + return nil } func segment(s *bytes.Buffer) string { @@ -194,6 +220,7 @@ func header(packageName string, enableExports bool) ([]byte, error) { functionPrefix = "_esc" } headerParams := headerTemplateParams{ + Invocation: strings.Join(os.Args[1:], " "), PackageName: packageName, FunctionPrefix: functionPrefix, } @@ -210,7 +237,9 @@ func header(packageName string, enableExports bool) ([]byte, error) { } const ( - headerTemplate = `package {{.PackageName}} + headerTemplate = `// Code generated by "esc {{.Invocation}}"; DO NOT EDIT. + +package {{.PackageName}} import ( "bytes" @@ -368,7 +397,7 @@ func {{.FunctionPrefix}}FSByte(useLocal bool, name string) ([]byte, error) { return nil, err } b, err := ioutil.ReadAll(f) - f.Close() + _ = f.Close() return b, err } f, err := _escStatic.prepare(name) diff --git a/vendor/github.com/pkg/errors/stack.go b/vendor/github.com/pkg/errors/stack.go index 6b1f2891a..cbe3f3e38 100644 --- a/vendor/github.com/pkg/errors/stack.go +++ b/vendor/github.com/pkg/errors/stack.go @@ -79,6 +79,14 @@ func (f Frame) Format(s fmt.State, verb rune) { // StackTrace is stack of Frames from innermost (newest) to outermost (oldest). type StackTrace []Frame +// Format formats the stack of Frames according to the fmt.Formatter interface. +// +// %s lists source files for each Frame in the stack +// %v lists the source file and line number for each Frame in the stack +// +// Format accepts flags that alter the printing of some verbs, as follows: +// +// %+v Prints filename, function, and line number for each Frame in the stack. func (st StackTrace) Format(s fmt.State, verb rune) { switch verb { case 'v': diff --git a/vendor/github.com/prasmussen/gandi-api/contact/contact.go b/vendor/github.com/prasmussen/gandi-api/contact/contact.go deleted file mode 100644 index c4b6cf5d0..000000000 --- a/vendor/github.com/prasmussen/gandi-api/contact/contact.go +++ /dev/null @@ -1,76 +0,0 @@ -package contact - -import "github.com/prasmussen/gandi-api/client" - -type Contact struct { - *client.Client -} - -func New(c *client.Client) *Contact { - return &Contact{c} -} - -// Get contact financial balance -func (self *Contact) Balance() (*BalanceInformation, error) { - var res map[string]interface{} - params := []interface{}{self.Key} - if err := self.Call("contact.balance", params, &res); err != nil { - return nil, err - } - return toBalanceInformation(res), nil -} - -// Get contact information -func (self *Contact) Info(handle string) (*ContactInformation, error) { - var res map[string]interface{} - - var params []interface{} - if handle == "" { - params = []interface{}{self.Key} - } else { - params = []interface{}{self.Key, handle} - } - if err := self.Call("contact.info", params, &res); err != nil { - return nil, err - } - return toContactInformation(res), nil -} - -// Create a contact -func (self *Contact) Create(opts ContactCreate) (*ContactInformation, error) { - var res map[string]interface{} - createArgs := map[string]interface{}{ - "given": opts.Firstname, - "family": opts.Lastname, - "email": opts.Email, - "password": opts.Password, - "streetaddr": opts.Address, - "zip": opts.Zipcode, - "city": opts.City, - "country": opts.Country, - "phone": opts.Phone, - "type": opts.ContactType(), - } - - params := []interface{}{self.Key, createArgs} - if err := self.Call("contact.create", params, &res); err != nil { - return nil, err - } - return toContactInformation(res), nil -} - -// Delete a contact -func (self *Contact) Delete(handle string) (bool, error) { - var res bool - - var params []interface{} - if handle == "" { - params = []interface{}{self.Key} - } else { - params = []interface{}{self.Key, handle} - } - if err := self.Call("contact.delete", params, &res); err != nil { - return false, err - } - return res, nil -} diff --git a/vendor/github.com/prasmussen/gandi-api/contact/structs.go b/vendor/github.com/prasmussen/gandi-api/contact/structs.go deleted file mode 100644 index 285463035..000000000 --- a/vendor/github.com/prasmussen/gandi-api/contact/structs.go +++ /dev/null @@ -1,80 +0,0 @@ -package contact - -import ( - "time" -) - -type PrepaidInformation struct { - Id int64 - Amount string - Currency string - DateCreated time.Time - DateUpdated time.Time -} - -type BalanceInformation struct { - AnnualBalance string - Grid string - OutstandingAmount float64 - Prepaid *PrepaidInformation -} - -type ContactInformation struct { - Firstname string - Lastname string - Email string - Address string - Zipcode string - City string - Country string - Phone string - ContactType int64 - Handle string -} - -func (self ContactInformation) ContactTypeString() string { - switch self.ContactType { - case 0: - return "Person" - case 1: - return "Company" - case 2: - return "Association" - case 3: - return "Public Body" - case 4: - return "Reseller" - } - return "" -} - -type ContactCreate struct { - Firstname string `goptions:"--firstname, obligatory, description='First name'"` - Lastname string `goptions:"--lastname, obligatory, description='Last name'"` - Email string `goptions:"--email, obligatory, description='Email address'"` - Password string `goptions:"--password, obligatory, description='Password'"` - Address string `goptions:"--address, obligatory, description='Street address'"` - Zipcode string `goptions:"--zipcode, obligatory, description='Zip code'"` - City string `goptions:"--city, obligatory, description='City'"` - Country string `goptions:"--country, obligatory, description='Country'"` - Phone string `goptions:"--phone, obligatory, description='Phone number'"` - - // Contact types - IsPerson bool `goptions:"--person, obligatory, mutexgroup='type', description='Contact type person'"` - IsCompany bool `goptions:"--company, obligatory, mutexgroup='type', description='Contact type company'"` - IsAssociation bool `goptions:"--association, obligatory, mutexgroup='type', description='Contact type association'"` - IsPublicBody bool `goptions:"--publicbody, obligatory, mutexgroup='type', description='Contact type public body'"` - IsReseller bool `goptions:"--reseller, obligatory, mutexgroup='type', description='Contact type reseller'"` -} - -func (self ContactCreate) ContactType() int { - if self.IsPerson { return 0 } - if self.IsCompany { return 1 } - if self.IsAssociation { return 2 } - if self.IsPublicBody { return 3 } - if self.IsReseller { return 4 } - - // Default to person - return 0 -} - diff --git a/vendor/github.com/prasmussen/gandi-api/contact/util.go b/vendor/github.com/prasmussen/gandi-api/contact/util.go deleted file mode 100644 index f267dd910..000000000 --- a/vendor/github.com/prasmussen/gandi-api/contact/util.go +++ /dev/null @@ -1,39 +0,0 @@ -package contact - -import ( - "github.com/prasmussen/gandi-api/util" -) - -func toBalanceInformation(res map[string]interface{}) *BalanceInformation { - return &BalanceInformation{ - AnnualBalance: util.ToString(res["annual_balance"]), - Grid: util.ToString(res["grid"]), - OutstandingAmount: util.ToFloat64(res["outstanding_amount"]), - Prepaid: toPrepaidInformation(util.ToXmlrpcStruct(res["prepaid"])), - } -} - -func toPrepaidInformation(res map[string]interface{}) *PrepaidInformation { - return &PrepaidInformation{ - Id: util.ToInt64(res["id"]), - Amount: util.ToString(res["amount"]), - Currency: util.ToString(res["currency"]), - DateCreated: util.ToTime(res["date_created"]), - DateUpdated: util.ToTime(res["date_updated"]), - } -} - -func toContactInformation(res map[string]interface{}) *ContactInformation { - return &ContactInformation{ - Firstname: util.ToString(res["given"]), - Lastname: util.ToString(res["family"]), - Email: util.ToString(res["email"]), - Address: util.ToString(res["streetaddr"]), - Zipcode: util.ToString(res["zip"]), - City: util.ToString(res["city"]), - Country: util.ToString(res["country"]), - Phone: util.ToString(res["phone"]), - ContactType: util.ToInt64(res["type"]), - Handle: util.ToString(res["handle"]), - } -} diff --git a/vendor/github.com/robertkrimen/otto/ast/node.go b/vendor/github.com/robertkrimen/otto/ast/node.go index 49ae375d1..7e45abe97 100644 --- a/vendor/github.com/robertkrimen/otto/ast/node.go +++ b/vendor/github.com/robertkrimen/otto/ast/node.go @@ -472,7 +472,7 @@ func (self *ObjectLiteral) Idx1() file.Idx { return self.RightBrace } func (self *RegExpLiteral) Idx1() file.Idx { return file.Idx(int(self.Idx) + len(self.Literal)) } func (self *SequenceExpression) Idx1() file.Idx { return self.Sequence[0].Idx1() } func (self *StringLiteral) Idx1() file.Idx { return file.Idx(int(self.Idx) + len(self.Literal)) } -func (self *ThisExpression) Idx1() file.Idx { return self.Idx } +func (self *ThisExpression) Idx1() file.Idx { return self.Idx + 4 } func (self *UnaryExpression) Idx1() file.Idx { if self.Postfix { return self.Operand.Idx1() + 2 // ++ -- diff --git a/vendor/github.com/robertkrimen/otto/ast/walk.go b/vendor/github.com/robertkrimen/otto/ast/walk.go new file mode 100644 index 000000000..7580a82b5 --- /dev/null +++ b/vendor/github.com/robertkrimen/otto/ast/walk.go @@ -0,0 +1,217 @@ +package ast + +import "fmt" + +// Visitor Enter method is invoked for each node encountered by Walk. +// If the result visitor w is not nil, Walk visits each of the children +// of node with the visitor v, followed by a call of the Exit method. +type Visitor interface { + Enter(n Node) (v Visitor) + Exit(n Node) +} + +// Walk traverses an AST in depth-first order: It starts by calling +// v.Enter(node); node must not be nil. If the visitor v returned by +// v.Enter(node) is not nil, Walk is invoked recursively with visitor +// v for each of the non-nil children of node, followed by a call +// of v.Exit(node). +func Walk(v Visitor, n Node) { + if n == nil { + return + } + if v = v.Enter(n); v == nil { + return + } + + defer v.Exit(n) + + switch n := n.(type) { + case *ArrayLiteral: + if n != nil { + for _, ex := range n.Value { + Walk(v, ex) + } + } + case *AssignExpression: + if n != nil { + Walk(v, n.Left) + Walk(v, n.Right) + } + case *BadExpression: + case *BinaryExpression: + if n != nil { + Walk(v, n.Left) + Walk(v, n.Right) + } + case *BlockStatement: + if n != nil { + for _, s := range n.List { + Walk(v, s) + } + } + case *BooleanLiteral: + case *BracketExpression: + if n != nil { + Walk(v, n.Left) + Walk(v, n.Member) + } + case *BranchStatement: + if n != nil { + Walk(v, n.Label) + } + case *CallExpression: + if n != nil { + Walk(v, n.Callee) + for _, a := range n.ArgumentList { + Walk(v, a) + } + } + case *CaseStatement: + if n != nil { + Walk(v, n.Test) + for _, c := range n.Consequent { + Walk(v, c) + } + } + case *CatchStatement: + if n != nil { + Walk(v, n.Parameter) + Walk(v, n.Body) + } + case *ConditionalExpression: + if n != nil { + Walk(v, n.Test) + Walk(v, n.Consequent) + Walk(v, n.Alternate) + } + case *DebuggerStatement: + case *DoWhileStatement: + if n != nil { + Walk(v, n.Test) + Walk(v, n.Body) + } + case *DotExpression: + if n != nil { + Walk(v, n.Left) + } + case *EmptyExpression: + case *EmptyStatement: + case *ExpressionStatement: + if n != nil { + Walk(v, n.Expression) + } + case *ForInStatement: + if n != nil { + Walk(v, n.Into) + Walk(v, n.Source) + Walk(v, n.Body) + } + case *ForStatement: + if n != nil { + Walk(v, n.Initializer) + Walk(v, n.Update) + Walk(v, n.Test) + Walk(v, n.Body) + } + case *FunctionLiteral: + if n != nil { + Walk(v, n.Name) + for _, p := range n.ParameterList.List { + Walk(v, p) + } + Walk(v, n.Body) + } + case *FunctionStatement: + if n != nil { + Walk(v, n.Function) + } + case *Identifier: + case *IfStatement: + if n != nil { + Walk(v, n.Test) + Walk(v, n.Consequent) + Walk(v, n.Alternate) + } + case *LabelledStatement: + if n != nil { + Walk(v, n.Statement) + } + case *NewExpression: + if n != nil { + Walk(v, n.Callee) + for _, a := range n.ArgumentList { + Walk(v, a) + } + } + case *NullLiteral: + case *NumberLiteral: + case *ObjectLiteral: + if n != nil { + for _, p := range n.Value { + Walk(v, p.Value) + } + } + case *Program: + if n != nil { + for _, b := range n.Body { + Walk(v, b) + } + } + case *RegExpLiteral: + case *ReturnStatement: + if n != nil { + Walk(v, n.Argument) + } + case *SequenceExpression: + if n != nil { + for _, e := range n.Sequence { + Walk(v, e) + } + } + case *StringLiteral: + case *SwitchStatement: + if n != nil { + Walk(v, n.Discriminant) + for _, c := range n.Body { + Walk(v, c) + } + } + case *ThisExpression: + case *ThrowStatement: + if n != nil { + Walk(v, n.Argument) + } + case *TryStatement: + if n != nil { + Walk(v, n.Body) + Walk(v, n.Catch) + Walk(v, n.Finally) + } + case *UnaryExpression: + if n != nil { + Walk(v, n.Operand) + } + case *VariableExpression: + if n != nil { + Walk(v, n.Initializer) + } + case *VariableStatement: + if n != nil { + for _, e := range n.List { + Walk(v, e) + } + } + case *WhileStatement: + if n != nil { + Walk(v, n.Test) + Walk(v, n.Body) + } + case *WithStatement: + if n != nil { + Walk(v, n.Object) + Walk(v, n.Body) + } + default: + panic(fmt.Sprintf("Walk: unexpected node type %T", n)) + } +} diff --git a/vendor/github.com/robertkrimen/otto/builtin_array.go b/vendor/github.com/robertkrimen/otto/builtin_array.go index 557ffc024..56dd95ab6 100644 --- a/vendor/github.com/robertkrimen/otto/builtin_array.go +++ b/vendor/github.com/robertkrimen/otto/builtin_array.go @@ -170,7 +170,10 @@ func builtinArray_splice(call FunctionCall) Value { length := int64(toUint32(thisObject.get("length"))) start := valueToRangeIndex(call.Argument(0), length, false) - deleteCount := valueToRangeIndex(call.Argument(1), int64(length)-start, true) + deleteCount := length - start + if arg, ok := call.getArgument(1); ok { + deleteCount = valueToRangeIndex(arg, length-start, true) + } valueArray := make([]Value, deleteCount) for index := int64(0); index < deleteCount; index++ { diff --git a/vendor/github.com/robertkrimen/otto/type_go_map.go b/vendor/github.com/robertkrimen/otto/type_go_map.go index 3e204a028..41b9ac0de 100644 --- a/vendor/github.com/robertkrimen/otto/type_go_map.go +++ b/vendor/github.com/robertkrimen/otto/type_go_map.go @@ -53,6 +53,14 @@ func goMapGetOwnProperty(self *_object, name string) *_property { return &_property{self.runtime.toValue(value.Interface()), 0111} } + // Other methods + if method := self.value.(*_goMapObject).value.MethodByName(name); (method != reflect.Value{}) { + return &_property{ + value: self.runtime.toValue(method.Interface()), + mode: 0110, + } + } + return nil } diff --git a/vendor/github.com/tdewolff/buffer/README.md b/vendor/github.com/tdewolff/buffer/README.md index 3c71a95bc..8f5060736 100644 --- a/vendor/github.com/tdewolff/buffer/README.md +++ b/vendor/github.com/tdewolff/buffer/README.md @@ -32,7 +32,7 @@ Moving the end position can go through `Move(int)` which also accepts negative i When the internal `io.Reader` returned an error, `Err() error` will return that error (even if subsequent peeks are still possible). If `Peek(int) byte` returns `0` when an error occurred. `IsEOF() bool` is a faster alternative than `Err() == io.EOF`, if it returns true it means the internal buffer will not be reallocated/overwritten. So returned byte slices need not be copied for use after subsequent `Peek(int) byte` calls. When the `io.Reader` provides the `Bytes() []byte` function (which `Reader` does in this package), it will use that buffer instead and thus `IsEOF()` returns always `true` (ie. copying returned slices is not needed). ## Lexer -Lexer is an improvement over Shifter in that it does not need the returned byte slices to be copied. Instead you can call `ShiftLen() int`, which returns the number of bytes that have been shifted since the previous call to `ShiftLen`, and use that to specify how many bytes need to be freed up from the buffer. Calling `Free(n int)` frees up `n` bytes from the internal buffer(s). It holds an array of buffers to accomodate for keeping everything in-memory. If you don't need to keep returned byte slices around, call `Free(ShiftLen())` after every `Shift` call. +Lexer is an improvement over Shifter in that it does not need the returned byte slices to be copied. Instead you can call `ShiftLen() int`, which returns the number of bytes that have been shifted since the previous call to `ShiftLen`, and use that to specify how many bytes need to be freed up from the buffer. Calling `Free(n int)` frees up `n` bytes from the internal buffer(s). It holds an array of buffers to accommodate for keeping everything in-memory. If you don't need to keep returned byte slices around, call `Free(ShiftLen())` after every `Shift` call. The `MoveTo(int)` function has been renamed to `Rewind(int)` to fit its meaning better. Also `Bytes() []byte` has been renamed to `Lexeme() []byte` for the same reason. diff --git a/vendor/github.com/tdewolff/minify/README.md b/vendor/github.com/tdewolff/minify/README.md index b8370ff8c..98e9408d6 100644 --- a/vendor/github.com/tdewolff/minify/README.md +++ b/vendor/github.com/tdewolff/minify/README.md @@ -35,6 +35,9 @@ The core functionality associates mimetypes with minification functions, allowin - [From reader](#from-reader) - [From bytes](#from-bytes) - [From string](#from-string) + - [To reader](#to-reader) + - [To writer](#to-writer) + - [Middleware](#middleware) - [Custom minifier](#custom-minifier) - [Mediatypes](#mediatypes) - [Examples](#examples) @@ -309,7 +312,7 @@ if err != nil { } ``` -### From reader +### To reader Get a minifying reader for a specific mediatype. ``` go mr := m.Reader(mediatype, r) @@ -318,7 +321,7 @@ if _, err := mr.Read(b); err != nil { } ``` -### From writer +### To writer Get a minifying writer for a specific mediatype. Must be explicitly closed because it uses an `io.Pipe` underneath. ``` go mw := m.Writer(mediatype, w) @@ -330,6 +333,13 @@ if err := mw.Close(); err != nil { } ``` +### Middleware +Minify resources on the fly using middleware. It passes a wrapped response writer to the handler that removes the Content-Length header. The minifier is chosen based on the Content-Type header or, if the header is empty, by the request URI file extension. This is on-the-fly processing, you should preferably cache the results though! +``` go +fs := http.FileServer(http.Dir("www/")) +http.Handle("/", m.Middleware(fs)) +``` + ### Custom minifier Add a minifier for a specific mimetype. ``` go @@ -465,9 +475,8 @@ func main() { m.AddFuncRegexp(regexp.MustCompile("[/+]json$"), json.Minify) m.AddFuncRegexp(regexp.MustCompile("[/+]xml$"), xml.Minify) - http.Handle("/", m.Middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - http.ServeFile(w, r, path.Join("www", r.URL.Path)) - }))) + fs := http.FileServer(http.Dir("www/")) + http.Handle("/", m.Middleware(fs)) } ``` diff --git a/vendor/github.com/tdewolff/minify/json/json.go b/vendor/github.com/tdewolff/minify/json/json.go index 85229b1ff..e9e29f8fd 100644 --- a/vendor/github.com/tdewolff/minify/json/json.go +++ b/vendor/github.com/tdewolff/minify/json/json.go @@ -15,12 +15,15 @@ var ( //////////////////////////////////////////////////////////////// +// DefaultMinifier is the default minifier. +var DefaultMinifier = &Minifier{} + // Minifier is a JSON minifier. type Minifier struct{} // Minify minifies JSON data, it reads from r and writes to w. func Minify(m *minify.M, w io.Writer, r io.Reader, params map[string]string) error { - return (&Minifier{}).Minify(m, w, r, params) + return DefaultMinifier.Minify(m, w, r, params) } // Minify minifies JSON data, it reads from r and writes to w. diff --git a/vendor/github.com/tdewolff/minify/minify.go b/vendor/github.com/tdewolff/minify/minify.go index 7ff88b47f..a654603f5 100644 --- a/vendor/github.com/tdewolff/minify/minify.go +++ b/vendor/github.com/tdewolff/minify/minify.go @@ -231,6 +231,12 @@ type minifyResponseWriter struct { mediatype string } +// WriteHeader intercepts any header writes and removes the Content-Length header. +func (w *minifyResponseWriter) WriteHeader(status int) { + w.ResponseWriter.Header().Del("Content-Length") + w.ResponseWriter.WriteHeader(status) +} + // Write intercepts any writes to the response writer. // The first write will extract the Content-Type as the mediatype. Otherwise it falls back to the RequestURI extension. func (w *minifyResponseWriter) Write(b []byte) (int, error) { @@ -266,7 +272,8 @@ func (m *M) ResponseWriter(w http.ResponseWriter, r *http.Request) *minifyRespon func (m *M) Middleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { mw := m.ResponseWriter(w, r) + defer mw.Close() + next.ServeHTTP(mw, r) - mw.Close() }) } diff --git a/vendor/github.com/urfave/cli/CHANGELOG.md b/vendor/github.com/urfave/cli/CHANGELOG.md index 07f75464b..401eae5a2 100644 --- a/vendor/github.com/urfave/cli/CHANGELOG.md +++ b/vendor/github.com/urfave/cli/CHANGELOG.md @@ -4,6 +4,49 @@ ## [Unreleased] +## 1.20.0 - 2017-08-10 + +### Fixed + +* `HandleExitCoder` is now correctly iterates over all errors in + a `MultiError`. The exit code is the exit code of the last error or `1` if + there are no `ExitCoder`s in the `MultiError`. +* Fixed YAML file loading on Windows (previously would fail validate the file path) +* Subcommand `Usage`, `Description`, `ArgsUsage`, `OnUsageError` correctly + propogated +* `ErrWriter` is now passed downwards through command structure to avoid the + need to redefine it +* Pass `Command` context into `OnUsageError` rather than parent context so that + all fields are avaiable +* Errors occuring in `Before` funcs are no longer double printed +* Use `UsageText` in the help templates for commands and subcommands if + defined; otherwise build the usage as before (was previously ignoring this + field) +* `IsSet` and `GlobalIsSet` now correctly return whether a flag is set if + a program calls `Set` or `GlobalSet` directly after flag parsing (would + previously only return `true` if the flag was set during parsing) + +### Changed + +* No longer exit the program on command/subcommand error if the error raised is + not an `OsExiter`. This exiting behavior was introduced in 1.19.0, but was + determined to be a regression in functionality. See [the + PR](https://github.com/urfave/cli/pull/595) for discussion. + +### Added + +* `CommandsByName` type was added to make it easy to sort `Command`s by name, + alphabetically +* `altsrc` now handles loading of string and int arrays from TOML +* Support for definition of custom help templates for `App` via + `CustomAppHelpTemplate` +* Support for arbitrary key/value fields on `App` to be used with + `CustomAppHelpTemplate` via `ExtraInfo` +* `HelpFlag`, `VersionFlag`, and `BashCompletionFlag` changed to explictly be + `cli.Flag`s allowing for the use of custom flags satisfying the `cli.Flag` + interface to be used. + + ## [1.19.1] - 2016-11-21 ### Fixed diff --git a/vendor/github.com/urfave/cli/README.md b/vendor/github.com/urfave/cli/README.md index 2bbbd8ea9..34055fe74 100644 --- a/vendor/github.com/urfave/cli/README.md +++ b/vendor/github.com/urfave/cli/README.md @@ -33,6 +33,7 @@ applications in an expressive way. + [Ordering](#ordering) + [Values from the Environment](#values-from-the-environment) + [Values from alternate input sources (YAML, TOML, and others)](#values-from-alternate-input-sources-yaml-toml-and-others) + + [Precedence](#precedence) * [Subcommands](#subcommands) * [Subcommands categories](#subcommands-categories) * [Exit code](#exit-code) @@ -656,6 +657,15 @@ func main() { } ``` +#### Precedence + +The precedence for flag value sources is as follows (highest to lowest): + +0. Command line flag value from user +0. Environment variable (if specified) +0. Configuration file (if specified) +0. Default defined on the flag + ### Subcommands Subcommands can be defined for a more git-like command line app. @@ -751,11 +761,11 @@ func main() { }, { Name: "add", - Category: "template", + Category: "Template actions", }, { Name: "remove", - Category: "template", + Category: "Template actions", }, } diff --git a/vendor/github.com/urfave/cli/appveyor.yml b/vendor/github.com/urfave/cli/appveyor.yml index 698b188e1..1e1489c36 100644 --- a/vendor/github.com/urfave/cli/appveyor.yml +++ b/vendor/github.com/urfave/cli/appveyor.yml @@ -1,14 +1,16 @@ version: "{build}" -os: Windows Server 2012 R2 +os: Windows Server 2016 + +image: Visual Studio 2017 clone_folder: c:\gopath\src\github.com\urfave\cli environment: GOPATH: C:\gopath - GOVERSION: 1.6 - PYTHON: C:\Python27-x64 - PYTHON_VERSION: 2.7.x + GOVERSION: 1.8.x + PYTHON: C:\Python36-x64 + PYTHON_VERSION: 3.6.x PYTHON_ARCH: 64 install: diff --git a/vendor/github.com/urfave/cli/help.go b/vendor/github.com/urfave/cli/help.go index 57ec98d58..ed084fc1d 100644 --- a/vendor/github.com/urfave/cli/help.go +++ b/vendor/github.com/urfave/cli/help.go @@ -29,6 +29,7 @@ AUTHOR{{with $length := len .Authors}}{{if ne 1 $length}}S{{end}}{{end}}: {{end}}{{$author}}{{end}}{{end}}{{if .VisibleCommands}} COMMANDS:{{range .VisibleCategories}}{{if .Name}} + {{.Name}}:{{end}}{{range .VisibleCommands}} {{join .Names ", "}}{{"\t"}}{{.Usage}}{{end}}{{end}}{{end}}{{if .VisibleFlags}} diff --git a/vendor/golang.org/x/net/publicsuffix/gen.go b/vendor/golang.org/x/net/publicsuffix/gen.go deleted file mode 100644 index a2d499529..000000000 --- a/vendor/golang.org/x/net/publicsuffix/gen.go +++ /dev/null @@ -1,713 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -package main - -// This program generates table.go and table_test.go based on the authoritative -// public suffix list at https://publicsuffix.org/list/effective_tld_names.dat -// -// The version is derived from -// https://api.github.com/repos/publicsuffix/list/commits?path=public_suffix_list.dat -// and a human-readable form is at -// https://github.com/publicsuffix/list/commits/master/public_suffix_list.dat -// -// To fetch a particular git revision, such as 5c70ccd250, pass -// -url "https://raw.githubusercontent.com/publicsuffix/list/5c70ccd250/public_suffix_list.dat" -// and -version "an explicit version string". - -import ( - "bufio" - "bytes" - "flag" - "fmt" - "go/format" - "io" - "io/ioutil" - "net/http" - "os" - "regexp" - "sort" - "strings" - - "golang.org/x/net/idna" -) - -const ( - // These sum of these four values must be no greater than 32. - nodesBitsChildren = 9 - nodesBitsICANN = 1 - nodesBitsTextOffset = 15 - nodesBitsTextLength = 6 - - // These sum of these four values must be no greater than 32. - childrenBitsWildcard = 1 - childrenBitsNodeType = 2 - childrenBitsHi = 14 - childrenBitsLo = 14 -) - -var ( - maxChildren int - maxTextOffset int - maxTextLength int - maxHi uint32 - maxLo uint32 -) - -func max(a, b int) int { - if a < b { - return b - } - return a -} - -func u32max(a, b uint32) uint32 { - if a < b { - return b - } - return a -} - -const ( - nodeTypeNormal = 0 - nodeTypeException = 1 - nodeTypeParentOnly = 2 - numNodeType = 3 -) - -func nodeTypeStr(n int) string { - switch n { - case nodeTypeNormal: - return "+" - case nodeTypeException: - return "!" - case nodeTypeParentOnly: - return "o" - } - panic("unreachable") -} - -const ( - defaultURL = "https://publicsuffix.org/list/effective_tld_names.dat" - gitCommitURL = "https://api.github.com/repos/publicsuffix/list/commits?path=public_suffix_list.dat" -) - -var ( - labelEncoding = map[string]uint32{} - labelsList = []string{} - labelsMap = map[string]bool{} - rules = []string{} - - // validSuffixRE is used to check that the entries in the public suffix - // list are in canonical form (after Punycode encoding). Specifically, - // capital letters are not allowed. - validSuffixRE = regexp.MustCompile(`^[a-z0-9_\!\*\-\.]+$`) - - shaRE = regexp.MustCompile(`"sha":"([^"]+)"`) - dateRE = regexp.MustCompile(`"committer":{[^{]+"date":"([^"]+)"`) - - comments = flag.Bool("comments", false, "generate table.go comments, for debugging") - subset = flag.Bool("subset", false, "generate only a subset of the full table, for debugging") - url = flag.String("url", defaultURL, "URL of the publicsuffix.org list. If empty, stdin is read instead") - v = flag.Bool("v", false, "verbose output (to stderr)") - version = flag.String("version", "", "the effective_tld_names.dat version") -) - -func main() { - if err := main1(); err != nil { - fmt.Fprintln(os.Stderr, err) - os.Exit(1) - } -} - -func main1() error { - flag.Parse() - if nodesBitsTextLength+nodesBitsTextOffset+nodesBitsICANN+nodesBitsChildren > 32 { - return fmt.Errorf("not enough bits to encode the nodes table") - } - if childrenBitsLo+childrenBitsHi+childrenBitsNodeType+childrenBitsWildcard > 32 { - return fmt.Errorf("not enough bits to encode the children table") - } - if *version == "" { - if *url != defaultURL { - return fmt.Errorf("-version was not specified, and the -url is not the default one") - } - sha, date, err := gitCommit() - if err != nil { - return err - } - *version = fmt.Sprintf("publicsuffix.org's public_suffix_list.dat, git revision %s (%s)", sha, date) - } - var r io.Reader = os.Stdin - if *url != "" { - res, err := http.Get(*url) - if err != nil { - return err - } - if res.StatusCode != http.StatusOK { - return fmt.Errorf("bad GET status for %s: %d", *url, res.Status) - } - r = res.Body - defer res.Body.Close() - } - - var root node - icann := false - br := bufio.NewReader(r) - for { - s, err := br.ReadString('\n') - if err != nil { - if err == io.EOF { - break - } - return err - } - s = strings.TrimSpace(s) - if strings.Contains(s, "BEGIN ICANN DOMAINS") { - icann = true - continue - } - if strings.Contains(s, "END ICANN DOMAINS") { - icann = false - continue - } - if s == "" || strings.HasPrefix(s, "//") { - continue - } - s, err = idna.ToASCII(s) - if err != nil { - return err - } - if !validSuffixRE.MatchString(s) { - return fmt.Errorf("bad publicsuffix.org list data: %q", s) - } - - if *subset { - switch { - case s == "ac.jp" || strings.HasSuffix(s, ".ac.jp"): - case s == "ak.us" || strings.HasSuffix(s, ".ak.us"): - case s == "ao" || strings.HasSuffix(s, ".ao"): - case s == "ar" || strings.HasSuffix(s, ".ar"): - case s == "arpa" || strings.HasSuffix(s, ".arpa"): - case s == "cy" || strings.HasSuffix(s, ".cy"): - case s == "dyndns.org" || strings.HasSuffix(s, ".dyndns.org"): - case s == "jp": - case s == "kobe.jp" || strings.HasSuffix(s, ".kobe.jp"): - case s == "kyoto.jp" || strings.HasSuffix(s, ".kyoto.jp"): - case s == "om" || strings.HasSuffix(s, ".om"): - case s == "uk" || strings.HasSuffix(s, ".uk"): - case s == "uk.com" || strings.HasSuffix(s, ".uk.com"): - case s == "tw" || strings.HasSuffix(s, ".tw"): - case s == "zw" || strings.HasSuffix(s, ".zw"): - case s == "xn--p1ai" || strings.HasSuffix(s, ".xn--p1ai"): - // xn--p1ai is Russian-Cyrillic "рф". - default: - continue - } - } - - rules = append(rules, s) - - nt, wildcard := nodeTypeNormal, false - switch { - case strings.HasPrefix(s, "*."): - s, nt = s[2:], nodeTypeParentOnly - wildcard = true - case strings.HasPrefix(s, "!"): - s, nt = s[1:], nodeTypeException - } - labels := strings.Split(s, ".") - for n, i := &root, len(labels)-1; i >= 0; i-- { - label := labels[i] - n = n.child(label) - if i == 0 { - if nt != nodeTypeParentOnly && n.nodeType == nodeTypeParentOnly { - n.nodeType = nt - } - n.icann = n.icann && icann - n.wildcard = n.wildcard || wildcard - } - labelsMap[label] = true - } - } - labelsList = make([]string, 0, len(labelsMap)) - for label := range labelsMap { - labelsList = append(labelsList, label) - } - sort.Strings(labelsList) - - if err := generate(printReal, &root, "table.go"); err != nil { - return err - } - if err := generate(printTest, &root, "table_test.go"); err != nil { - return err - } - return nil -} - -func generate(p func(io.Writer, *node) error, root *node, filename string) error { - buf := new(bytes.Buffer) - if err := p(buf, root); err != nil { - return err - } - b, err := format.Source(buf.Bytes()) - if err != nil { - return err - } - return ioutil.WriteFile(filename, b, 0644) -} - -func gitCommit() (sha, date string, retErr error) { - res, err := http.Get(gitCommitURL) - if err != nil { - return "", "", err - } - if res.StatusCode != http.StatusOK { - return "", "", fmt.Errorf("bad GET status for %s: %d", gitCommitURL, res.Status) - } - defer res.Body.Close() - b, err := ioutil.ReadAll(res.Body) - if err != nil { - return "", "", err - } - if m := shaRE.FindSubmatch(b); m != nil { - sha = string(m[1]) - } - if m := dateRE.FindSubmatch(b); m != nil { - date = string(m[1]) - } - if sha == "" || date == "" { - retErr = fmt.Errorf("could not find commit SHA and date in %s", gitCommitURL) - } - return sha, date, retErr -} - -func printTest(w io.Writer, n *node) error { - fmt.Fprintf(w, "// generated by go run gen.go; DO NOT EDIT\n\n") - fmt.Fprintf(w, "package publicsuffix\n\nvar rules = [...]string{\n") - for _, rule := range rules { - fmt.Fprintf(w, "%q,\n", rule) - } - fmt.Fprintf(w, "}\n\nvar nodeLabels = [...]string{\n") - if err := n.walk(w, printNodeLabel); err != nil { - return err - } - fmt.Fprintf(w, "}\n") - return nil -} - -func printReal(w io.Writer, n *node) error { - const header = `// generated by go run gen.go; DO NOT EDIT - -package publicsuffix - -const version = %q - -const ( - nodesBitsChildren = %d - nodesBitsICANN = %d - nodesBitsTextOffset = %d - nodesBitsTextLength = %d - - childrenBitsWildcard = %d - childrenBitsNodeType = %d - childrenBitsHi = %d - childrenBitsLo = %d -) - -const ( - nodeTypeNormal = %d - nodeTypeException = %d - nodeTypeParentOnly = %d -) - -// numTLD is the number of top level domains. -const numTLD = %d - -` - fmt.Fprintf(w, header, *version, - nodesBitsChildren, nodesBitsICANN, nodesBitsTextOffset, nodesBitsTextLength, - childrenBitsWildcard, childrenBitsNodeType, childrenBitsHi, childrenBitsLo, - nodeTypeNormal, nodeTypeException, nodeTypeParentOnly, len(n.children)) - - text := combineText(labelsList) - if text == "" { - return fmt.Errorf("internal error: makeText returned no text") - } - for _, label := range labelsList { - offset, length := strings.Index(text, label), len(label) - if offset < 0 { - return fmt.Errorf("internal error: could not find %q in text %q", label, text) - } - maxTextOffset, maxTextLength = max(maxTextOffset, offset), max(maxTextLength, length) - if offset >= 1<= 1< 64 { - n, plus = 64, " +" - } - fmt.Fprintf(w, "%q%s\n", text[:n], plus) - text = text[n:] - } - - if err := n.walk(w, assignIndexes); err != nil { - return err - } - - fmt.Fprintf(w, ` - -// nodes is the list of nodes. Each node is represented as a uint32, which -// encodes the node's children, wildcard bit and node type (as an index into -// the children array), ICANN bit and text. -// -// If the table was generated with the -comments flag, there is a //-comment -// after each node's data. In it is the nodes-array indexes of the children, -// formatted as (n0x1234-n0x1256), with * denoting the wildcard bit. The -// nodeType is printed as + for normal, ! for exception, and o for parent-only -// nodes that have children but don't match a domain label in their own right. -// An I denotes an ICANN domain. -// -// The layout within the uint32, from MSB to LSB, is: -// [%2d bits] unused -// [%2d bits] children index -// [%2d bits] ICANN bit -// [%2d bits] text index -// [%2d bits] text length -var nodes = [...]uint32{ -`, - 32-nodesBitsChildren-nodesBitsICANN-nodesBitsTextOffset-nodesBitsTextLength, - nodesBitsChildren, nodesBitsICANN, nodesBitsTextOffset, nodesBitsTextLength) - if err := n.walk(w, printNode); err != nil { - return err - } - fmt.Fprintf(w, `} - -// children is the list of nodes' children, the parent's wildcard bit and the -// parent's node type. If a node has no children then their children index -// will be in the range [0, 6), depending on the wildcard bit and node type. -// -// The layout within the uint32, from MSB to LSB, is: -// [%2d bits] unused -// [%2d bits] wildcard bit -// [%2d bits] node type -// [%2d bits] high nodes index (exclusive) of children -// [%2d bits] low nodes index (inclusive) of children -var children=[...]uint32{ -`, - 32-childrenBitsWildcard-childrenBitsNodeType-childrenBitsHi-childrenBitsLo, - childrenBitsWildcard, childrenBitsNodeType, childrenBitsHi, childrenBitsLo) - for i, c := range childrenEncoding { - s := "---------------" - lo := c & (1<> childrenBitsLo) & (1<>(childrenBitsLo+childrenBitsHi)) & (1<>(childrenBitsLo+childrenBitsHi+childrenBitsNodeType) != 0 - if *comments { - fmt.Fprintf(w, "0x%08x, // c0x%04x (%s)%s %s\n", - c, i, s, wildcardStr(wildcard), nodeTypeStr(nodeType)) - } else { - fmt.Fprintf(w, "0x%x,\n", c) - } - } - fmt.Fprintf(w, "}\n\n") - fmt.Fprintf(w, "// max children %d (capacity %d)\n", maxChildren, 1<= 1<= 1<= 1< 0 && ss[0] == "" { - ss = ss[1:] - } - return ss -} - -// crush combines a list of strings, taking advantage of overlaps. It returns a -// single string that contains each input string as a substring. -func crush(ss []string) string { - maxLabelLen := 0 - for _, s := range ss { - if maxLabelLen < len(s) { - maxLabelLen = len(s) - } - } - - for prefixLen := maxLabelLen; prefixLen > 0; prefixLen-- { - prefixes := makePrefixMap(ss, prefixLen) - for i, s := range ss { - if len(s) <= prefixLen { - continue - } - mergeLabel(ss, i, prefixLen, prefixes) - } - } - - return strings.Join(ss, "") -} - -// mergeLabel merges the label at ss[i] with the first available matching label -// in prefixMap, where the last "prefixLen" characters in ss[i] match the first -// "prefixLen" characters in the matching label. -// It will merge ss[i] repeatedly until no more matches are available. -// All matching labels merged into ss[i] are replaced by "". -func mergeLabel(ss []string, i, prefixLen int, prefixes prefixMap) { - s := ss[i] - suffix := s[len(s)-prefixLen:] - for _, j := range prefixes[suffix] { - // Empty strings mean "already used." Also avoid merging with self. - if ss[j] == "" || i == j { - continue - } - if *v { - fmt.Fprintf(os.Stderr, "%d-length overlap at (%4d,%4d): %q and %q share %q\n", - prefixLen, i, j, ss[i], ss[j], suffix) - } - ss[i] += ss[j][prefixLen:] - ss[j] = "" - // ss[i] has a new suffix, so merge again if possible. - // Note: we only have to merge again at the same prefix length. Shorter - // prefix lengths will be handled in the next iteration of crush's for loop. - // Can there be matches for longer prefix lengths, introduced by the merge? - // I believe that any such matches would by necessity have been eliminated - // during substring removal or merged at a higher prefix length. For - // instance, in crush("abc", "cde", "bcdef"), combining "abc" and "cde" - // would yield "abcde", which could be merged with "bcdef." However, in - // practice "cde" would already have been elimintated by removeSubstrings. - mergeLabel(ss, i, prefixLen, prefixes) - return - } -} - -// prefixMap maps from a prefix to a list of strings containing that prefix. The -// list of strings is represented as indexes into a slice of strings stored -// elsewhere. -type prefixMap map[string][]int - -// makePrefixMap constructs a prefixMap from a slice of strings. -func makePrefixMap(ss []string, prefixLen int) prefixMap { - prefixes := make(prefixMap) - for i, s := range ss { - // We use < rather than <= because if a label matches on a prefix equal to - // its full length, that's actually a substring match handled by - // removeSubstrings. - if prefixLen < len(s) { - prefix := s[:prefixLen] - prefixes[prefix] = append(prefixes[prefix], i) - } - } - - return prefixes -} diff --git a/vendor/golang.org/x/net/publicsuffix/list.go b/vendor/golang.org/x/net/publicsuffix/list.go deleted file mode 100644 index 8bbf3bcd7..000000000 --- a/vendor/golang.org/x/net/publicsuffix/list.go +++ /dev/null @@ -1,135 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:generate go run gen.go - -// Package publicsuffix provides a public suffix list based on data from -// http://publicsuffix.org/. A public suffix is one under which Internet users -// can directly register names. -package publicsuffix // import "golang.org/x/net/publicsuffix" - -// TODO: specify case sensitivity and leading/trailing dot behavior for -// func PublicSuffix and func EffectiveTLDPlusOne. - -import ( - "fmt" - "net/http/cookiejar" - "strings" -) - -// List implements the cookiejar.PublicSuffixList interface by calling the -// PublicSuffix function. -var List cookiejar.PublicSuffixList = list{} - -type list struct{} - -func (list) PublicSuffix(domain string) string { - ps, _ := PublicSuffix(domain) - return ps -} - -func (list) String() string { - return version -} - -// PublicSuffix returns the public suffix of the domain using a copy of the -// publicsuffix.org database compiled into the library. -// -// icann is whether the public suffix is managed by the Internet Corporation -// for Assigned Names and Numbers. If not, the public suffix is privately -// managed. For example, foo.org and foo.co.uk are ICANN domains, -// foo.dyndns.org and foo.blogspot.co.uk are private domains. -// -// Use cases for distinguishing ICANN domains like foo.com from private -// domains like foo.appspot.com can be found at -// https://wiki.mozilla.org/Public_Suffix_List/Use_Cases -func PublicSuffix(domain string) (publicSuffix string, icann bool) { - lo, hi := uint32(0), uint32(numTLD) - s, suffix, wildcard := domain, len(domain), false -loop: - for { - dot := strings.LastIndex(s, ".") - if wildcard { - suffix = 1 + dot - } - if lo == hi { - break - } - f := find(s[1+dot:], lo, hi) - if f == notFound { - break - } - - u := nodes[f] >> (nodesBitsTextOffset + nodesBitsTextLength) - icann = u&(1<>= nodesBitsICANN - u = children[u&(1<>= childrenBitsLo - hi = u & (1<>= childrenBitsHi - switch u & (1<>= childrenBitsNodeType - wildcard = u&(1<>= nodesBitsTextLength - offset := x & (1< 0 { claimSet.Exp = time.Now().Add(t).Unix() } - payload, err := jws.Encode(defaultHeader, claimSet, pk) + h := *defaultHeader + h.KeyID = js.conf.PrivateKeyID + payload, err := jws.Encode(&h, claimSet, pk) if err != nil { return nil, err } diff --git a/vendor/golang.org/x/oauth2/oauth2.go b/vendor/golang.org/x/oauth2/oauth2.go index 7b06bfe1e..4bafe873d 100644 --- a/vendor/golang.org/x/oauth2/oauth2.go +++ b/vendor/golang.org/x/oauth2/oauth2.go @@ -180,7 +180,6 @@ func (c *Config) Exchange(ctx context.Context, code string) (*Token, error) { "grant_type": {"authorization_code"}, "code": {code}, "redirect_uri": internal.CondVal(c.RedirectURL), - "scope": internal.CondVal(strings.Join(c.Scopes, " ")), }) } @@ -292,6 +291,10 @@ var HTTPClient internal.ContextKey // NewClient creates an *http.Client from a Context and TokenSource. // The returned client is not valid beyond the lifetime of the context. // +// Note that if a custom *http.Client is provided via the Context it +// is used only for token acquisition and is not used to configure the +// *http.Client returned from NewClient. +// // As a special case, if src is nil, a non-OAuth2 client is returned // using the provided context. This exists to support related OAuth2 // packages. diff --git a/vendor/golang.org/x/text/internal/gen/code.go b/vendor/golang.org/x/text/internal/gen/code.go deleted file mode 100644 index ca917d281..000000000 --- a/vendor/golang.org/x/text/internal/gen/code.go +++ /dev/null @@ -1,338 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gen - -import ( - "bytes" - "encoding/gob" - "fmt" - "hash" - "hash/fnv" - "io" - "log" - "os" - "reflect" - "strings" - "unicode" - "unicode/utf8" -) - -// This file contains utilities for generating code. - -// TODO: other write methods like: -// - slices, maps, types, etc. - -// CodeWriter is a utility for writing structured code. It computes the content -// hash and size of written content. It ensures there are newlines between -// written code blocks. -type CodeWriter struct { - buf bytes.Buffer - Size int - Hash hash.Hash32 // content hash - gob *gob.Encoder - // For comments we skip the usual one-line separator if they are followed by - // a code block. - skipSep bool -} - -func (w *CodeWriter) Write(p []byte) (n int, err error) { - return w.buf.Write(p) -} - -// NewCodeWriter returns a new CodeWriter. -func NewCodeWriter() *CodeWriter { - h := fnv.New32() - return &CodeWriter{Hash: h, gob: gob.NewEncoder(h)} -} - -// WriteGoFile appends the buffer with the total size of all created structures -// and writes it as a Go file to the the given file with the given package name. -func (w *CodeWriter) WriteGoFile(filename, pkg string) { - f, err := os.Create(filename) - if err != nil { - log.Fatalf("Could not create file %s: %v", filename, err) - } - defer f.Close() - if _, err = w.WriteGo(f, pkg); err != nil { - log.Fatalf("Error writing file %s: %v", filename, err) - } -} - -// WriteGo appends the buffer with the total size of all created structures and -// writes it as a Go file to the the given writer with the given package name. -func (w *CodeWriter) WriteGo(out io.Writer, pkg string) (n int, err error) { - sz := w.Size - w.WriteComment("Total table size %d bytes (%dKiB); checksum: %X\n", sz, sz/1024, w.Hash.Sum32()) - defer w.buf.Reset() - return WriteGo(out, pkg, w.buf.Bytes()) -} - -func (w *CodeWriter) printf(f string, x ...interface{}) { - fmt.Fprintf(w, f, x...) -} - -func (w *CodeWriter) insertSep() { - if w.skipSep { - w.skipSep = false - return - } - // Use at least two newlines to ensure a blank space between the previous - // block. WriteGoFile will remove extraneous newlines. - w.printf("\n\n") -} - -// WriteComment writes a comment block. All line starts are prefixed with "//". -// Initial empty lines are gobbled. The indentation for the first line is -// stripped from consecutive lines. -func (w *CodeWriter) WriteComment(comment string, args ...interface{}) { - s := fmt.Sprintf(comment, args...) - s = strings.Trim(s, "\n") - - // Use at least two newlines to ensure a blank space between the previous - // block. WriteGoFile will remove extraneous newlines. - w.printf("\n\n// ") - w.skipSep = true - - // strip first indent level. - sep := "\n" - for ; len(s) > 0 && (s[0] == '\t' || s[0] == ' '); s = s[1:] { - sep += s[:1] - } - - strings.NewReplacer(sep, "\n// ", "\n", "\n// ").WriteString(w, s) - - w.printf("\n") -} - -func (w *CodeWriter) writeSizeInfo(size int) { - w.printf("// Size: %d bytes\n", size) -} - -// WriteConst writes a constant of the given name and value. -func (w *CodeWriter) WriteConst(name string, x interface{}) { - w.insertSep() - v := reflect.ValueOf(x) - - switch v.Type().Kind() { - case reflect.String: - // See golang.org/issue/13145. - const arbitraryCutoff = 16 - if v.Len() > arbitraryCutoff { - w.printf("var %s %s = ", name, typeName(x)) - } else { - w.printf("const %s %s = ", name, typeName(x)) - } - w.WriteString(v.String()) - w.printf("\n") - default: - w.printf("const %s = %#v\n", name, x) - } -} - -// WriteVar writes a variable of the given name and value. -func (w *CodeWriter) WriteVar(name string, x interface{}) { - w.insertSep() - v := reflect.ValueOf(x) - oldSize := w.Size - sz := int(v.Type().Size()) - w.Size += sz - - switch v.Type().Kind() { - case reflect.String: - w.printf("var %s %s = ", name, typeName(x)) - w.WriteString(v.String()) - case reflect.Struct: - w.gob.Encode(x) - fallthrough - case reflect.Slice, reflect.Array: - w.printf("var %s = ", name) - w.writeValue(v) - w.writeSizeInfo(w.Size - oldSize) - default: - w.printf("var %s %s = ", name, typeName(x)) - w.gob.Encode(x) - w.writeValue(v) - w.writeSizeInfo(w.Size - oldSize) - } - w.printf("\n") -} - -func (w *CodeWriter) writeValue(v reflect.Value) { - x := v.Interface() - switch v.Kind() { - case reflect.String: - w.WriteString(v.String()) - case reflect.Array: - // Don't double count: callers of WriteArray count on the size being - // added, so we need to discount it here. - w.Size -= int(v.Type().Size()) - w.writeSlice(x, true) - case reflect.Slice: - w.writeSlice(x, false) - case reflect.Struct: - w.printf("%s{\n", typeName(v.Interface())) - t := v.Type() - for i := 0; i < v.NumField(); i++ { - w.printf("%s: ", t.Field(i).Name) - w.writeValue(v.Field(i)) - w.printf(",\n") - } - w.printf("}") - default: - w.printf("%#v", x) - } -} - -// WriteString writes a string literal. -func (w *CodeWriter) WriteString(s string) { - io.WriteString(w.Hash, s) // content hash - w.Size += len(s) - - const maxInline = 40 - if len(s) <= maxInline { - w.printf("%q", s) - return - } - - // We will render the string as a multi-line string. - const maxWidth = 80 - 4 - len(`"`) - len(`" +`) - - // When starting on its own line, go fmt indents line 2+ an extra level. - n, max := maxWidth, maxWidth-4 - - // Print "" +\n, if a string does not start on its own line. - b := w.buf.Bytes() - if p := len(bytes.TrimRight(b, " \t")); p > 0 && b[p-1] != '\n' { - w.printf("\"\" + // Size: %d bytes\n", len(s)) - n, max = maxWidth, maxWidth - } - - w.printf(`"`) - - for sz, p := 0, 0; p < len(s); { - var r rune - r, sz = utf8.DecodeRuneInString(s[p:]) - out := s[p : p+sz] - chars := 1 - if !unicode.IsPrint(r) || r == utf8.RuneError || r == '"' { - switch sz { - case 1: - out = fmt.Sprintf("\\x%02x", s[p]) - case 2, 3: - out = fmt.Sprintf("\\u%04x", r) - case 4: - out = fmt.Sprintf("\\U%08x", r) - } - chars = len(out) - } - if n -= chars; n < 0 { - w.printf("\" +\n\"") - n = max - len(out) - } - w.printf("%s", out) - p += sz - } - w.printf(`"`) -} - -// WriteSlice writes a slice value. -func (w *CodeWriter) WriteSlice(x interface{}) { - w.writeSlice(x, false) -} - -// WriteArray writes an array value. -func (w *CodeWriter) WriteArray(x interface{}) { - w.writeSlice(x, true) -} - -func (w *CodeWriter) writeSlice(x interface{}, isArray bool) { - v := reflect.ValueOf(x) - w.gob.Encode(v.Len()) - w.Size += v.Len() * int(v.Type().Elem().Size()) - name := typeName(x) - if isArray { - name = fmt.Sprintf("[%d]%s", v.Len(), name[strings.Index(name, "]")+1:]) - } - if isArray { - w.printf("%s{\n", name) - } else { - w.printf("%s{ // %d elements\n", name, v.Len()) - } - - switch kind := v.Type().Elem().Kind(); kind { - case reflect.String: - for _, s := range x.([]string) { - w.WriteString(s) - w.printf(",\n") - } - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, - reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - // nLine and nBlock are the number of elements per line and block. - nLine, nBlock, format := 8, 64, "%d," - switch kind { - case reflect.Uint8: - format = "%#02x," - case reflect.Uint16: - format = "%#04x," - case reflect.Uint32: - nLine, nBlock, format = 4, 32, "%#08x," - case reflect.Uint, reflect.Uint64: - nLine, nBlock, format = 4, 32, "%#016x," - case reflect.Int8: - nLine = 16 - } - n := nLine - for i := 0; i < v.Len(); i++ { - if i%nBlock == 0 && v.Len() > nBlock { - w.printf("// Entry %X - %X\n", i, i+nBlock-1) - } - x := v.Index(i).Interface() - w.gob.Encode(x) - w.printf(format, x) - if n--; n == 0 { - n = nLine - w.printf("\n") - } - } - w.printf("\n") - case reflect.Struct: - zero := reflect.Zero(v.Type().Elem()).Interface() - for i := 0; i < v.Len(); i++ { - x := v.Index(i).Interface() - w.gob.EncodeValue(v) - if !reflect.DeepEqual(zero, x) { - line := fmt.Sprintf("%#v,\n", x) - line = line[strings.IndexByte(line, '{'):] - w.printf("%d: ", i) - w.printf(line) - } - } - case reflect.Array: - for i := 0; i < v.Len(); i++ { - w.printf("%d: %#v,\n", i, v.Index(i).Interface()) - } - default: - panic("gen: slice elem type not supported") - } - w.printf("}") -} - -// WriteType writes a definition of the type of the given value and returns the -// type name. -func (w *CodeWriter) WriteType(x interface{}) string { - t := reflect.TypeOf(x) - w.printf("type %s struct {\n", t.Name()) - for i := 0; i < t.NumField(); i++ { - w.printf("\t%s %s\n", t.Field(i).Name, t.Field(i).Type) - } - w.printf("}\n") - return t.Name() -} - -// typeName returns the name of the go type of x. -func typeName(x interface{}) string { - t := reflect.ValueOf(x).Type() - return strings.Replace(fmt.Sprint(t), "main.", "", 1) -} diff --git a/vendor/golang.org/x/text/internal/gen/gen.go b/vendor/golang.org/x/text/internal/gen/gen.go deleted file mode 100644 index dfaa278a1..000000000 --- a/vendor/golang.org/x/text/internal/gen/gen.go +++ /dev/null @@ -1,226 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package gen contains common code for the various code generation tools in the -// text repository. Its usage ensures consistency between tools. -// -// This package defines command line flags that are common to most generation -// tools. The flags allow for specifying specific Unicode and CLDR versions -// in the public Unicode data repository (http://www.unicode.org/Public). -// -// A local Unicode data mirror can be set through the flag -local or the -// environment variable UNICODE_DIR. The former takes precedence. The local -// directory should follow the same structure as the public repository. -// -// IANA data can also optionally be mirrored by putting it in the iana directory -// rooted at the top of the local mirror. Beware, though, that IANA data is not -// versioned. So it is up to the developer to use the right version. -package gen // import "golang.org/x/text/internal/gen" - -import ( - "bytes" - "flag" - "fmt" - "go/format" - "io" - "io/ioutil" - "log" - "net/http" - "os" - "path" - "path/filepath" - "unicode" - - "golang.org/x/text/unicode/cldr" -) - -var ( - url = flag.String("url", - "http://www.unicode.org/Public", - "URL of Unicode database directory") - iana = flag.String("iana", - "http://www.iana.org", - "URL of the IANA repository") - unicodeVersion = flag.String("unicode", - getEnv("UNICODE_VERSION", unicode.Version), - "unicode version to use") - cldrVersion = flag.String("cldr", - getEnv("CLDR_VERSION", cldr.Version), - "cldr version to use") - // Allow an environment variable to specify the local directory. - // go generate doesn't allow specifying arguments; this is a useful - // alternative to specifying a local mirror. - localDir = flag.String("local", - os.Getenv("UNICODE_DIR"), - "directory containing local data files; for debugging only.") -) - -func getEnv(name, def string) string { - if v := os.Getenv(name); v != "" { - return v - } - return def -} - -// Init performs common initialization for a gen command. It parses the flags -// and sets up the standard logging parameters. -func Init() { - log.SetPrefix("") - log.SetFlags(log.Lshortfile) - flag.Parse() -} - -const header = `// This file was generated by go generate; DO NOT EDIT - -package %s - -` - -// UnicodeVersion reports the requested Unicode version. -func UnicodeVersion() string { - return *unicodeVersion -} - -// UnicodeVersion reports the requested CLDR version. -func CLDRVersion() string { - return *cldrVersion -} - -// IsLocal reports whether the user specified a local directory. -func IsLocal() bool { - return *localDir != "" -} - -// OpenUCDFile opens the requested UCD file. The file is specified relative to -// the public Unicode root directory. It will call log.Fatal if there are any -// errors. -func OpenUCDFile(file string) io.ReadCloser { - return openUnicode(path.Join(*unicodeVersion, "ucd", file)) -} - -// OpenCLDRCoreZip opens the CLDR core zip file. It will call log.Fatal if there -// are any errors. -func OpenCLDRCoreZip() io.ReadCloser { - return OpenUnicodeFile("cldr", *cldrVersion, "core.zip") -} - -// OpenUnicodeFile opens the requested file of the requested category from the -// root of the Unicode data archive. The file is specified relative to the -// public Unicode root directory. If version is "", it will use the default -// Unicode version. It will call log.Fatal if there are any errors. -func OpenUnicodeFile(category, version, file string) io.ReadCloser { - if version == "" { - version = UnicodeVersion() - } - return openUnicode(path.Join(category, version, file)) -} - -// OpenIANAFile opens the requested IANA file. The file is specified relative -// to the IANA root, which is typically either http://www.iana.org or the -// iana directory in the local mirror. It will call log.Fatal if there are any -// errors. -func OpenIANAFile(path string) io.ReadCloser { - return Open(*iana, "iana", path) -} - -// Open opens subdir/path if a local directory is specified and the file exists, -// where subdir is a directory relative to the local root, or fetches it from -// urlRoot/path otherwise. It will call log.Fatal if there are any errors. -func Open(urlRoot, subdir, path string) io.ReadCloser { - if *localDir != "" { - path = filepath.FromSlash(path) - if f, err := os.Open(filepath.Join(*localDir, subdir, path)); err == nil { - return f - } - } - return get(urlRoot, path) -} - -func openUnicode(path string) io.ReadCloser { - if *localDir != "" { - path = filepath.FromSlash(path) - f, err := os.Open(filepath.Join(*localDir, path)) - if err != nil { - log.Fatal(err) - } - return f - } - return get(*url, path) -} - -func get(root, path string) io.ReadCloser { - url := root + "/" + path - fmt.Printf("Fetching %s...", url) - defer fmt.Println(" done.") - resp, err := http.Get(url) - if err != nil { - log.Fatalf("HTTP GET: %v", err) - } - if resp.StatusCode != 200 { - log.Fatalf("Bad GET status for %q: %q", url, resp.Status) - } - return resp.Body -} - -// TODO: use Write*Version in all applicable packages. - -// WriteUnicodeVersion writes a constant for the Unicode version from which the -// tables are generated. -func WriteUnicodeVersion(w io.Writer) { - fmt.Fprintf(w, "// UnicodeVersion is the Unicode version from which the tables in this package are derived.\n") - fmt.Fprintf(w, "const UnicodeVersion = %q\n\n", UnicodeVersion()) -} - -// WriteCLDRVersion writes a constant for the CLDR version from which the -// tables are generated. -func WriteCLDRVersion(w io.Writer) { - fmt.Fprintf(w, "// CLDRVersion is the CLDR version from which the tables in this package are derived.\n") - fmt.Fprintf(w, "const CLDRVersion = %q\n\n", CLDRVersion()) -} - -// WriteGoFile prepends a standard file comment and package statement to the -// given bytes, applies gofmt, and writes them to a file with the given name. -// It will call log.Fatal if there are any errors. -func WriteGoFile(filename, pkg string, b []byte) { - w, err := os.Create(filename) - if err != nil { - log.Fatalf("Could not create file %s: %v", filename, err) - } - defer w.Close() - if _, err = WriteGo(w, pkg, b); err != nil { - log.Fatalf("Error writing file %s: %v", filename, err) - } -} - -// WriteGo prepends a standard file comment and package statement to the given -// bytes, applies gofmt, and writes them to w. -func WriteGo(w io.Writer, pkg string, b []byte) (n int, err error) { - src := []byte(fmt.Sprintf(header, pkg)) - src = append(src, b...) - formatted, err := format.Source(src) - if err != nil { - // Print the generated code even in case of an error so that the - // returned error can be meaningfully interpreted. - n, _ = w.Write(src) - return n, err - } - return w.Write(formatted) -} - -// Repackage rewrites a Go file from belonging to package main to belonging to -// the given package. -func Repackage(inFile, outFile, pkg string) { - src, err := ioutil.ReadFile(inFile) - if err != nil { - log.Fatalf("reading %s: %v", inFile, err) - } - const toDelete = "package main\n\n" - i := bytes.Index(src, []byte(toDelete)) - if i < 0 { - log.Fatalf("Could not find %q in %s.", toDelete, inFile) - } - w := &bytes.Buffer{} - w.Write(src[i+len(toDelete):]) - WriteGoFile(outFile, pkg, w.Bytes()) -} diff --git a/vendor/golang.org/x/text/unicode/cldr/base.go b/vendor/golang.org/x/text/unicode/cldr/base.go deleted file mode 100644 index 21821791e..000000000 --- a/vendor/golang.org/x/text/unicode/cldr/base.go +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package cldr provides a parser for LDML and related XML formats. -// This package is inteded to be used by the table generation tools -// for the various internationalization-related packages. -// As the XML types are generated from the CLDR DTD, and as the CLDR standard -// is periodically amended, this package may change considerably over time. -// This mostly means that data may appear and disappear between versions. -// That is, old code should keep compiling for newer versions, but data -// may have moved or changed. -// CLDR version 22 is the first version supported by this package. -// Older versions may not work. -package cldr - -import ( - "encoding/xml" - "regexp" - "strconv" -) - -// Elem is implemented by every XML element. -type Elem interface { - setEnclosing(Elem) - setName(string) - enclosing() Elem - - GetCommon() *Common -} - -type hidden struct { - CharData string `xml:",chardata"` - Alias *struct { - Common - Source string `xml:"source,attr"` - Path string `xml:"path,attr"` - } `xml:"alias"` - Def *struct { - Common - Choice string `xml:"choice,attr,omitempty"` - Type string `xml:"type,attr,omitempty"` - } `xml:"default"` -} - -// Common holds several of the most common attributes and sub elements -// of an XML element. -type Common struct { - XMLName xml.Name - name string - enclElem Elem - Type string `xml:"type,attr,omitempty"` - Reference string `xml:"reference,attr,omitempty"` - Alt string `xml:"alt,attr,omitempty"` - ValidSubLocales string `xml:"validSubLocales,attr,omitempty"` - Draft string `xml:"draft,attr,omitempty"` - hidden -} - -// Default returns the default type to select from the enclosed list -// or "" if no default value is specified. -func (e *Common) Default() string { - if e.Def == nil { - return "" - } - if e.Def.Choice != "" { - return e.Def.Choice - } else if e.Def.Type != "" { - // Type is still used by the default element in collation. - return e.Def.Type - } - return "" -} - -// GetCommon returns e. It is provided such that Common implements Elem. -func (e *Common) GetCommon() *Common { - return e -} - -// Data returns the character data accumulated for this element. -func (e *Common) Data() string { - e.CharData = charRe.ReplaceAllStringFunc(e.CharData, replaceUnicode) - return e.CharData -} - -func (e *Common) setName(s string) { - e.name = s -} - -func (e *Common) enclosing() Elem { - return e.enclElem -} - -func (e *Common) setEnclosing(en Elem) { - e.enclElem = en -} - -// Escape characters that can be escaped without further escaping the string. -var charRe = regexp.MustCompile(`&#x[0-9a-fA-F]*;|\\u[0-9a-fA-F]{4}|\\U[0-9a-fA-F]{8}|\\x[0-9a-fA-F]{2}|\\[0-7]{3}|\\[abtnvfr]`) - -// replaceUnicode converts hexadecimal Unicode codepoint notations to a one-rune string. -// It assumes the input string is correctly formatted. -func replaceUnicode(s string) string { - if s[1] == '#' { - r, _ := strconv.ParseInt(s[3:len(s)-1], 16, 32) - return string(r) - } - r, _, _, _ := strconv.UnquoteChar(s, 0) - return string(r) -} diff --git a/vendor/golang.org/x/text/unicode/cldr/cldr.go b/vendor/golang.org/x/text/unicode/cldr/cldr.go deleted file mode 100644 index ea3fe139e..000000000 --- a/vendor/golang.org/x/text/unicode/cldr/cldr.go +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:generate go run makexml.go -output xml.go - -// Package cldr provides a parser for LDML and related XML formats. -// This package is inteded to be used by the table generation tools -// for the various internationalization-related packages. -// As the XML types are generated from the CLDR DTD, and as the CLDR standard -// is periodically amended, this package may change considerably over time. -// This mostly means that data may appear and disappear between versions. -// That is, old code should keep compiling for newer versions, but data -// may have moved or changed. -// CLDR version 22 is the first version supported by this package. -// Older versions may not work. -package cldr // import "golang.org/x/text/unicode/cldr" - -import ( - "fmt" - "sort" -) - -// CLDR provides access to parsed data of the Unicode Common Locale Data Repository. -type CLDR struct { - parent map[string][]string - locale map[string]*LDML - resolved map[string]*LDML - bcp47 *LDMLBCP47 - supp *SupplementalData -} - -func makeCLDR() *CLDR { - return &CLDR{ - parent: make(map[string][]string), - locale: make(map[string]*LDML), - resolved: make(map[string]*LDML), - bcp47: &LDMLBCP47{}, - supp: &SupplementalData{}, - } -} - -// BCP47 returns the parsed BCP47 LDML data. If no such data was parsed, nil is returned. -func (cldr *CLDR) BCP47() *LDMLBCP47 { - return nil -} - -// Draft indicates the draft level of an element. -type Draft int - -const ( - Approved Draft = iota - Contributed - Provisional - Unconfirmed -) - -var drafts = []string{"unconfirmed", "provisional", "contributed", "approved", ""} - -// ParseDraft returns the Draft value corresponding to the given string. The -// empty string corresponds to Approved. -func ParseDraft(level string) (Draft, error) { - if level == "" { - return Approved, nil - } - for i, s := range drafts { - if level == s { - return Unconfirmed - Draft(i), nil - } - } - return Approved, fmt.Errorf("cldr: unknown draft level %q", level) -} - -func (d Draft) String() string { - return drafts[len(drafts)-1-int(d)] -} - -// SetDraftLevel sets which draft levels to include in the evaluated LDML. -// Any draft element for which the draft level is higher than lev will be excluded. -// If multiple draft levels are available for a single element, the one with the -// lowest draft level will be selected, unless preferDraft is true, in which case -// the highest draft will be chosen. -// It is assumed that the underlying LDML is canonicalized. -func (cldr *CLDR) SetDraftLevel(lev Draft, preferDraft bool) { - // TODO: implement - cldr.resolved = make(map[string]*LDML) -} - -// RawLDML returns the LDML XML for id in unresolved form. -// id must be one of the strings returned by Locales. -func (cldr *CLDR) RawLDML(loc string) *LDML { - return cldr.locale[loc] -} - -// LDML returns the fully resolved LDML XML for loc, which must be one of -// the strings returned by Locales. -func (cldr *CLDR) LDML(loc string) (*LDML, error) { - return cldr.resolve(loc) -} - -// Supplemental returns the parsed supplemental data. If no such data was parsed, -// nil is returned. -func (cldr *CLDR) Supplemental() *SupplementalData { - return cldr.supp -} - -// Locales returns the locales for which there exist files. -// Valid sublocales for which there is no file are not included. -// The root locale is always sorted first. -func (cldr *CLDR) Locales() []string { - loc := []string{"root"} - hasRoot := false - for l, _ := range cldr.locale { - if l == "root" { - hasRoot = true - continue - } - loc = append(loc, l) - } - sort.Strings(loc[1:]) - if !hasRoot { - return loc[1:] - } - return loc -} - -// Get fills in the fields of x based on the XPath path. -func Get(e Elem, path string) (res Elem, err error) { - return walkXPath(e, path) -} diff --git a/vendor/golang.org/x/text/unicode/cldr/collate.go b/vendor/golang.org/x/text/unicode/cldr/collate.go deleted file mode 100644 index 80ee28d79..000000000 --- a/vendor/golang.org/x/text/unicode/cldr/collate.go +++ /dev/null @@ -1,359 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package cldr - -import ( - "bufio" - "encoding/xml" - "errors" - "fmt" - "strconv" - "strings" - "unicode" - "unicode/utf8" -) - -// RuleProcessor can be passed to Collator's Process method, which -// parses the rules and calls the respective method for each rule found. -type RuleProcessor interface { - Reset(anchor string, before int) error - Insert(level int, str, context, extend string) error - Index(id string) -} - -const ( - // cldrIndex is a Unicode-reserved sentinel value used to mark the start - // of a grouping within an index. - // We ignore any rule that starts with this rune. - // See http://unicode.org/reports/tr35/#Collation_Elements for details. - cldrIndex = "\uFDD0" - - // specialAnchor is the format in which to represent logical reset positions, - // such as "first tertiary ignorable". - specialAnchor = "<%s/>" -) - -// Process parses the rules for the tailorings of this collation -// and calls the respective methods of p for each rule found. -func (c Collation) Process(p RuleProcessor) (err error) { - if len(c.Cr) > 0 { - if len(c.Cr) > 1 { - return fmt.Errorf("multiple cr elements, want 0 or 1") - } - return processRules(p, c.Cr[0].Data()) - } - if c.Rules.Any != nil { - return c.processXML(p) - } - return errors.New("no tailoring data") -} - -// processRules parses rules in the Collation Rule Syntax defined in -// http://www.unicode.org/reports/tr35/tr35-collation.html#Collation_Tailorings. -func processRules(p RuleProcessor, s string) (err error) { - chk := func(s string, e error) string { - if err == nil { - err = e - } - return s - } - i := 0 // Save the line number for use after the loop. - scanner := bufio.NewScanner(strings.NewReader(s)) - for ; scanner.Scan() && err == nil; i++ { - for s := skipSpace(scanner.Text()); s != "" && s[0] != '#'; s = skipSpace(s) { - level := 5 - var ch byte - switch ch, s = s[0], s[1:]; ch { - case '&': // followed by or '[' ']' - if s = skipSpace(s); consume(&s, '[') { - s = chk(parseSpecialAnchor(p, s)) - } else { - s = chk(parseAnchor(p, 0, s)) - } - case '<': // sort relation '<'{1,4}, optionally followed by '*'. - for level = 1; consume(&s, '<'); level++ { - } - if level > 4 { - err = fmt.Errorf("level %d > 4", level) - } - fallthrough - case '=': // identity relation, optionally followed by *. - if consume(&s, '*') { - s = chk(parseSequence(p, level, s)) - } else { - s = chk(parseOrder(p, level, s)) - } - default: - chk("", fmt.Errorf("illegal operator %q", ch)) - break - } - } - } - if chk("", scanner.Err()); err != nil { - return fmt.Errorf("%d: %v", i, err) - } - return nil -} - -// parseSpecialAnchor parses the anchor syntax which is either of the form -// ['before' ] -// or -// [