diff --git a/go.mod b/go.mod index 4a8e78d8..d609bcd3 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,6 @@ module github.com/gardener/docforge go 1.18 require ( - github.com/go-git/go-git/v5 v5.3.0 github.com/google/uuid v1.1.2 github.com/hashicorp/go-multierror v1.1.0 github.com/maxbrunsfeld/counterfeiter/v6 v6.4.1 @@ -12,10 +11,9 @@ require ( github.com/spf13/cobra v1.1.1 github.com/stretchr/testify v1.7.0 golang.org/x/oauth2 v0.0.0-20211104180415-d3ed0bb246c8 - golang.org/x/tools v0.1.7 // indirect + golang.org/x/tools v0.1.12 // indirect gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b k8s.io/klog/v2 v2.2.0 - k8s.io/utils v0.0.0-20201027101359-01387209bb0d ) require ( @@ -23,53 +21,43 @@ require ( github.com/gregjones/httpcache v0.0.0-20190611155906-901d90724c79 github.com/peterbourgon/diskv v2.0.1+incompatible github.com/spf13/viper v1.10.1 - github.com/yuin/goldmark v1.4.4 + github.com/yuin/goldmark v1.4.13 github.com/yuin/goldmark-meta v1.0.0 - golang.org/x/net v0.0.0-20210813160813-60bc85c4be6d + golang.org/x/net v0.7.0 + gopkg.in/yaml.v2 v2.4.0 ) require ( - github.com/Microsoft/go-winio v0.4.16 // indirect github.com/cpuguy83/go-md2man/v2 v2.0.0 // indirect github.com/davecgh/go-spew v1.1.1 // indirect - github.com/emirpasic/gods v1.12.0 // indirect github.com/fsnotify/fsnotify v1.5.1 // indirect - github.com/go-git/gcfg v1.5.0 // indirect - github.com/go-git/go-billy/v5 v5.1.0 // indirect github.com/go-logr/logr v0.2.0 // indirect github.com/golang/protobuf v1.5.2 // indirect github.com/google/btree v1.0.0 // indirect github.com/google/go-querystring v1.1.0 // indirect github.com/hashicorp/errwrap v1.0.0 // indirect github.com/hashicorp/hcl v1.0.0 // indirect - github.com/imdario/mergo v0.3.12 // indirect github.com/inconshreveable/mousetrap v1.0.0 // indirect - github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect - github.com/kevinburke/ssh_config v0.0.0-20201106050909-4977a11b4351 // indirect + github.com/kr/text v0.2.0 // indirect github.com/magiconair/properties v1.8.5 // indirect - github.com/mitchellh/go-homedir v1.1.0 // indirect github.com/mitchellh/mapstructure v1.4.3 // indirect github.com/nxadm/tail v1.4.8 // indirect github.com/pelletier/go-toml v1.9.4 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect github.com/russross/blackfriday/v2 v2.0.1 // indirect - github.com/sergi/go-diff v1.1.0 // indirect github.com/shurcooL/sanitized_anchor_name v1.0.0 // indirect github.com/spf13/afero v1.6.0 // indirect github.com/spf13/cast v1.4.1 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/subosito/gotenv v1.2.0 // indirect - github.com/xanzy/ssh-agent v0.3.0 // indirect - golang.org/x/crypto v0.0.0-20210817164053-32db794688a5 // indirect - golang.org/x/mod v0.5.0 // indirect - golang.org/x/sys v0.0.0-20211210111614-af8b64212486 // indirect - golang.org/x/text v0.3.7 // indirect - golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect + golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 // indirect + golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 // indirect + golang.org/x/sys v0.5.0 // indirect + golang.org/x/text v0.7.0 // indirect google.golang.org/appengine v1.6.7 // indirect google.golang.org/protobuf v1.27.1 // indirect + gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect gopkg.in/ini.v1 v1.66.2 // indirect gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect - gopkg.in/warnings.v0 v0.1.2 // indirect - gopkg.in/yaml.v2 v2.4.0 // indirect ) diff --git a/go.sum b/go.sum index d456a66d..146d63fa 100644 --- a/go.sum +++ b/go.sum @@ -34,21 +34,12 @@ cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9 dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= -github.com/Microsoft/go-winio v0.4.14/go.mod h1:qXqCSQ3Xa7+6tgxaGTIe4Kpcdsi+P8jBhyzoq1bpyYA= -github.com/Microsoft/go-winio v0.4.16 h1:FtSW/jqD+l4ba5iPBj9CODVtgfYAD8w2wS923g/cFDk= -github.com/Microsoft/go-winio v0.4.16/go.mod h1:XB6nPKklQyQ7GC9LdcBEcBl8PF76WugXOPRXwdLnMv0= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= -github.com/alcortesm/tgz v0.0.0-20161220082320-9c5fe88206d7 h1:uSoVVbwJiQipAclBbw+8quDsfcvFjOpI5iCf4p/cqCs= -github.com/alcortesm/tgz v0.0.0-20161220082320-9c5fe88206d7/go.mod h1:6zEj6s6u/ghQa61ZWa/C2Aw3RkjiTBOix7dkqa1VLIs= github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= -github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239 h1:kFOfPq6dUM1hTo4JG6LR5AXSUEsOjtdm0kw0FtQtMJA= -github.com/anmitsu/go-shlex v0.0.0-20161002113705-648efa622239/go.mod h1:2FmKhYUyUczH0OGQWaF5ceTx0UBShxjsH6f8oGKYe2c= github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o= github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY= github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= -github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= -github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= @@ -73,37 +64,22 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no= -github.com/emirpasic/gods v1.12.0 h1:QAUIPSaCu4G+POclxeqb3F+WPpdKqFGlw36+yOzGlrg= -github.com/emirpasic/gods v1.12.0/go.mod h1:YfzfFFoVP/catgzJb4IKIqXjX78Ha8FMSDh3ymbK86o= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= -github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= github.com/fsnotify/fsnotify v1.5.1 h1:mZcQUHVQUQWoPXXtuf9yuEXKudkV2sx1E06UadKWpgI= github.com/fsnotify/fsnotify v1.5.1/go.mod h1:T3375wBYaZdLLcVNkcVbzGHY7f1l/uK5T5Ai1i3InKU= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= -github.com/gliderlabs/ssh v0.2.2 h1:6zsha5zo/TWhRhwqCD3+EarCAgZ2yN28ipRnGPnwkI0= -github.com/gliderlabs/ssh v0.2.2/go.mod h1:U7qILu1NlMHj9FlMhZLlkCdDnU1DBEAqr0aevW3Awn0= -github.com/go-git/gcfg v1.5.0 h1:Q5ViNfGF8zFgyJWPqYwA7qGFoMTEiBmdlkcfRmpIMa4= -github.com/go-git/gcfg v1.5.0/go.mod h1:5m20vg6GwYabIxaOonVkTdrILxQMpEShl1xiMF4ua+E= -github.com/go-git/go-billy/v5 v5.0.0/go.mod h1:pmpqyWchKfYfrkb/UVH4otLvyi/5gJlGI4Hb3ZqZ3W0= -github.com/go-git/go-billy/v5 v5.1.0 h1:4pl5BV4o7ZG/lterP4S6WzJ6xr49Ba5ET9ygheTYahk= -github.com/go-git/go-billy/v5 v5.1.0/go.mod h1:pmpqyWchKfYfrkb/UVH4otLvyi/5gJlGI4Hb3ZqZ3W0= -github.com/go-git/go-git-fixtures/v4 v4.0.2-0.20200613231340-f56387b50c12 h1:PbKy9zOy4aAKrJ5pibIRpVO2BXnK1Tlcg+caKI7Ox5M= -github.com/go-git/go-git-fixtures/v4 v4.0.2-0.20200613231340-f56387b50c12/go.mod h1:m+ICp2rF3jDhFgEZ/8yziagdT1C+ZpZcrJjappBCDSw= -github.com/go-git/go-git/v5 v5.3.0 h1:8WKMtJR2j8RntEXR/uvTKagfEt4GYlwQ7mntE4+0GWc= -github.com/go-git/go-git/v5 v5.3.0/go.mod h1:xdX4bWJ48aOrdhnl2XqHYstHbbp6+LFS4r4X+lNVprw= github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= -github.com/go-logr/logr v0.1.0/go.mod h1:ixOQHD9gLJUVQQ2ZOR7zLEifBX6tGkNJF4QyIY7sIas= github.com/go-logr/logr v0.2.0 h1:QvGt2nLcHH0WK9orKa+ppBPAxREcH364nPUedEpK0TY= github.com/go-logr/logr v0.2.0/go.mod h1:z6/tIYblkpsD+a4lm/fGIIU9mZ+XfAiaFtq7xTgseGU= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= @@ -203,21 +179,14 @@ github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2p github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= -github.com/imdario/mergo v0.3.12 h1:b6R2BslTbIEToALKP7LxUvijTsNI9TAe80pLWN2g/HU= -github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA= github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= -github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 h1:BQSFePA1RWJOlocH6Fxy8MmwDt+yVQYULKfN0RoTN8A= -github.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99/go.mod h1:1lJo3i6rXxKeerYnT8Nvf0QmHCRC1n8sfWVwXF2Frvo= -github.com/jessevdk/go-flags v1.5.0/go.mod h1:Fw0T6WPc1dYxT4mKEZRfG5kJhaTDP9pj1c2EWnYs/m4= github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= -github.com/kevinburke/ssh_config v0.0.0-20201106050909-4977a11b4351 h1:DowS9hvgyYSX4TO5NpyC606/Z4SxnNYbT+WX27or6Ck= -github.com/kevinburke/ssh_config v0.0.0-20201106050909-4977a11b4351/go.mod h1:CT57kijsi8u/K/BOFA39wgDQJ9CxiF4nAY/ojJ6r6mM= github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q= github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= @@ -241,7 +210,6 @@ github.com/maxbrunsfeld/counterfeiter/v6 v6.4.1/go.mod h1:DK1Cjkc0E49ShgRVs5jy5A github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= -github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI= github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg= @@ -274,8 +242,6 @@ github.com/peterbourgon/diskv v2.0.1+incompatible h1:UBdAOUP5p4RWqPBg048CAvpKN+v github.com/peterbourgon/diskv v2.0.1+incompatible/go.mod h1:uqqh8zWWbv1HBMNONnaR/tNboyR3/BZd58JJSHlUSCU= github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= -github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= -github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/sftp v1.10.1/go.mod h1:lYOWFsE0bwd1+KfKJaKeuokY15vzFx25BLbzYYoAxZI= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= @@ -298,18 +264,14 @@ github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb github.com/sclevine/spec v1.4.0 h1:z/Q9idDcay5m5irkZ28M7PtQM4aOISzOpj4bUPkDee8= github.com/sclevine/spec v1.4.0/go.mod h1:LvpgJaFyvQzRvc1kaDs0bulYwzC70PbiYjC4QnFHkOM= github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc= -github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0= -github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM= github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo= github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= -github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM= github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ= -github.com/spf13/afero v1.2.2/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk= github.com/spf13/afero v1.6.0 h1:xoax2sJ2DT8S8xA2paPFjDCScCNeWsg75VG0DLRreiY= github.com/spf13/afero v1.6.0/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I= github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE= @@ -337,15 +299,13 @@ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s= github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw= github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= -github.com/xanzy/ssh-agent v0.3.0 h1:wUMzuKtKilRgBAD1sUb8gOwwRr2FGoBVumcjoOACClI= -github.com/xanzy/ssh-agent v0.3.0/go.mod h1:3s9xbODqPuuhK9JV1R321M/FlMZSBvE5aY6eAcqrDh0= github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU= github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= -github.com/yuin/goldmark v1.4.4 h1:zNWRjYUW32G9KirMXYHQHVNFkXvMI7LpgNW2AgYAoIs= -github.com/yuin/goldmark v1.4.4/go.mod h1:rmuwmfZ0+bvzB24eSC//bk1R1Zp3hM0OXYv/G2LIilg= +github.com/yuin/goldmark v1.4.13 h1:fVcFKWvrslecOb/tg+Cc05dkeYx540o0FuFt3nUVDoE= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= github.com/yuin/goldmark-meta v1.0.0 h1:ScsatUIT2gFS6azqzLGUjgOnELsBOxMXerM3ogdJhAM= github.com/yuin/goldmark-meta v1.0.0/go.mod h1:zsNNOrZ4nLuyHAJeLQEZcQat8dm70SmB2kHbls092Gc= go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= @@ -359,16 +319,14 @@ go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/ go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= -golang.org/x/crypto v0.0.0-20190219172222-a4c6cb3142f2/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20210322153248-0c34fe9e7dc2/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4= -golang.org/x/crypto v0.0.0-20210817164053-32db794688a5 h1:HWj/xjIHfjYU5nVXpTM0s39J9CbLn7Cc5a7IC5rwsMQ= -golang.org/x/crypto v0.0.0-20210817164053-32db794688a5/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 h1:7I4JAnoQBe7ZtJcBaYHi5UtiO8tQHbUSXxL+pnGRANg= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -399,8 +357,8 @@ golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzB golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= -golang.org/x/mod v0.5.0 h1:UG21uOlmZabA4fW5i7ZX6bjw1xELEGg/ZLgZq9auk/Q= -golang.org/x/mod v0.5.0/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 h1:6zppjxzCulZykYSLyVDYbneBfbaBIQPYMevg0bEwv2s= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -435,11 +393,9 @@ golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81R golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20201202161906-c7110b5ffcbb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= -golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/net v0.0.0-20210326060303-6b1517762897/go.mod h1:uSPa2vr4CLtc/ILN5odXGNXS6mhrKVzTaCXzk9m6W3k= golang.org/x/net v0.0.0-20210331212208-0fccb6fa2b5c/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= -golang.org/x/net v0.0.0-20210813160813-60bc85c4be6d h1:LO7XpTYMwTqxjLcGWPijK3vRXg1aWdlNOVOHRq45d7c= -golang.org/x/net v0.0.0-20210813160813-60bc85c4be6d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.7.0 h1:rJrUqqhjsgNp7KqAIc25s9pZnjU7TUcSY7HcVZjdn1g= +golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -472,7 +428,6 @@ golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -495,13 +450,10 @@ golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210324051608-47abb6519492/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211210111614-af8b64212486 h1:5hpz5aRr+W1erYCL5JRhSUBJRph7l9XkNveoExlrKYk= -golang.org/x/sys v0.0.0-20211210111614-af8b64212486/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 h1:v+OssWQX+hTHEmOBgwxdZxK4zHq3yOs8F9J7mk0PY8E= +golang.org/x/sys v0.5.0 h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -509,8 +461,8 @@ golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3 golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= -golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.7.0 h1:4BRB4x83lYWy72KwLD/qYDuTu7q9PjSagHvijDw7cLo= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= @@ -559,8 +511,8 @@ golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= -golang.org/x/tools v0.1.7 h1:6j8CgantCy3yc8JGBqkDLMKWqZ0RDU2g1HVgacojGWQ= -golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo= +golang.org/x/tools v0.1.12 h1:VveCTK38A2rkS8ZqFY25HIDFscX5X9OoEhJd3quQmXU= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -648,8 +600,6 @@ google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQ gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20200902074654-038fdea0a05b/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= @@ -661,8 +611,6 @@ gopkg.in/ini.v1 v1.66.2/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= -gopkg.in/warnings.v0 v0.1.2 h1:wFXVbFY8DY5/xOe1ECiWdKCzZlxgshcYVNkBHstARME= -gopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI= gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= @@ -681,11 +629,8 @@ honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWh honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= -k8s.io/klog/v2 v2.0.0/go.mod h1:PBfzABfn139FHAV07az/IF9Wp1bkk3vpT2XSJ76fSDE= k8s.io/klog/v2 v2.2.0 h1:XRvcwJozkgZ1UQJmfMGpvRthQHOvihEhYtDfAaxMz/A= k8s.io/klog/v2 v2.2.0/go.mod h1:Od+F08eJP+W3HUb4pSrPpgp9DGU4GzlpG/TmITuYh/Y= -k8s.io/utils v0.0.0-20201027101359-01387209bb0d h1:1qqs/6lQQGCeZhCu0tO7La4lAazDXic6BiCmpjWcWUo= -k8s.io/utils v0.0.0-20201027101359-01387209bb0d/go.mod h1:jPW/WVKK9YHAvNhRxK0md/EJ228hCsBRufyofKtW8HA= rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= diff --git a/vendor/github.com/Microsoft/go-winio/.gitignore b/vendor/github.com/Microsoft/go-winio/.gitignore deleted file mode 100644 index b883f1fd..00000000 --- a/vendor/github.com/Microsoft/go-winio/.gitignore +++ /dev/null @@ -1 +0,0 @@ -*.exe diff --git a/vendor/github.com/Microsoft/go-winio/LICENSE b/vendor/github.com/Microsoft/go-winio/LICENSE deleted file mode 100644 index b8b569d7..00000000 --- a/vendor/github.com/Microsoft/go-winio/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Microsoft - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - diff --git a/vendor/github.com/Microsoft/go-winio/README.md b/vendor/github.com/Microsoft/go-winio/README.md deleted file mode 100644 index 56800105..00000000 --- a/vendor/github.com/Microsoft/go-winio/README.md +++ /dev/null @@ -1,22 +0,0 @@ -# go-winio - -This repository contains utilities for efficiently performing Win32 IO operations in -Go. Currently, this is focused on accessing named pipes and other file handles, and -for using named pipes as a net transport. - -This code relies on IO completion ports to avoid blocking IO on system threads, allowing Go -to reuse the thread to schedule another goroutine. This limits support to Windows Vista and -newer operating systems. This is similar to the implementation of network sockets in Go's net -package. - -Please see the LICENSE file for licensing information. - -This project has adopted the [Microsoft Open Source Code of -Conduct](https://opensource.microsoft.com/codeofconduct/). For more information -see the [Code of Conduct -FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact -[opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional -questions or comments. - -Thanks to natefinch for the inspiration for this library. See https://github.com/natefinch/npipe -for another named pipe implementation. diff --git a/vendor/github.com/Microsoft/go-winio/backup.go b/vendor/github.com/Microsoft/go-winio/backup.go deleted file mode 100644 index 2be34af4..00000000 --- a/vendor/github.com/Microsoft/go-winio/backup.go +++ /dev/null @@ -1,280 +0,0 @@ -// +build windows - -package winio - -import ( - "encoding/binary" - "errors" - "fmt" - "io" - "io/ioutil" - "os" - "runtime" - "syscall" - "unicode/utf16" -) - -//sys backupRead(h syscall.Handle, b []byte, bytesRead *uint32, abort bool, processSecurity bool, context *uintptr) (err error) = BackupRead -//sys backupWrite(h syscall.Handle, b []byte, bytesWritten *uint32, abort bool, processSecurity bool, context *uintptr) (err error) = BackupWrite - -const ( - BackupData = uint32(iota + 1) - BackupEaData - BackupSecurity - BackupAlternateData - BackupLink - BackupPropertyData - BackupObjectId - BackupReparseData - BackupSparseBlock - BackupTxfsData -) - -const ( - StreamSparseAttributes = uint32(8) -) - -const ( - WRITE_DAC = 0x40000 - WRITE_OWNER = 0x80000 - ACCESS_SYSTEM_SECURITY = 0x1000000 -) - -// BackupHeader represents a backup stream of a file. -type BackupHeader struct { - Id uint32 // The backup stream ID - Attributes uint32 // Stream attributes - Size int64 // The size of the stream in bytes - Name string // The name of the stream (for BackupAlternateData only). - Offset int64 // The offset of the stream in the file (for BackupSparseBlock only). -} - -type win32StreamId struct { - StreamId uint32 - Attributes uint32 - Size uint64 - NameSize uint32 -} - -// BackupStreamReader reads from a stream produced by the BackupRead Win32 API and produces a series -// of BackupHeader values. -type BackupStreamReader struct { - r io.Reader - bytesLeft int64 -} - -// NewBackupStreamReader produces a BackupStreamReader from any io.Reader. -func NewBackupStreamReader(r io.Reader) *BackupStreamReader { - return &BackupStreamReader{r, 0} -} - -// Next returns the next backup stream and prepares for calls to Read(). It skips the remainder of the current stream if -// it was not completely read. -func (r *BackupStreamReader) Next() (*BackupHeader, error) { - if r.bytesLeft > 0 { - if s, ok := r.r.(io.Seeker); ok { - // Make sure Seek on io.SeekCurrent sometimes succeeds - // before trying the actual seek. - if _, err := s.Seek(0, io.SeekCurrent); err == nil { - if _, err = s.Seek(r.bytesLeft, io.SeekCurrent); err != nil { - return nil, err - } - r.bytesLeft = 0 - } - } - if _, err := io.Copy(ioutil.Discard, r); err != nil { - return nil, err - } - } - var wsi win32StreamId - if err := binary.Read(r.r, binary.LittleEndian, &wsi); err != nil { - return nil, err - } - hdr := &BackupHeader{ - Id: wsi.StreamId, - Attributes: wsi.Attributes, - Size: int64(wsi.Size), - } - if wsi.NameSize != 0 { - name := make([]uint16, int(wsi.NameSize/2)) - if err := binary.Read(r.r, binary.LittleEndian, name); err != nil { - return nil, err - } - hdr.Name = syscall.UTF16ToString(name) - } - if wsi.StreamId == BackupSparseBlock { - if err := binary.Read(r.r, binary.LittleEndian, &hdr.Offset); err != nil { - return nil, err - } - hdr.Size -= 8 - } - r.bytesLeft = hdr.Size - return hdr, nil -} - -// Read reads from the current backup stream. -func (r *BackupStreamReader) Read(b []byte) (int, error) { - if r.bytesLeft == 0 { - return 0, io.EOF - } - if int64(len(b)) > r.bytesLeft { - b = b[:r.bytesLeft] - } - n, err := r.r.Read(b) - r.bytesLeft -= int64(n) - if err == io.EOF { - err = io.ErrUnexpectedEOF - } else if r.bytesLeft == 0 && err == nil { - err = io.EOF - } - return n, err -} - -// BackupStreamWriter writes a stream compatible with the BackupWrite Win32 API. -type BackupStreamWriter struct { - w io.Writer - bytesLeft int64 -} - -// NewBackupStreamWriter produces a BackupStreamWriter on top of an io.Writer. -func NewBackupStreamWriter(w io.Writer) *BackupStreamWriter { - return &BackupStreamWriter{w, 0} -} - -// WriteHeader writes the next backup stream header and prepares for calls to Write(). -func (w *BackupStreamWriter) WriteHeader(hdr *BackupHeader) error { - if w.bytesLeft != 0 { - return fmt.Errorf("missing %d bytes", w.bytesLeft) - } - name := utf16.Encode([]rune(hdr.Name)) - wsi := win32StreamId{ - StreamId: hdr.Id, - Attributes: hdr.Attributes, - Size: uint64(hdr.Size), - NameSize: uint32(len(name) * 2), - } - if hdr.Id == BackupSparseBlock { - // Include space for the int64 block offset - wsi.Size += 8 - } - if err := binary.Write(w.w, binary.LittleEndian, &wsi); err != nil { - return err - } - if len(name) != 0 { - if err := binary.Write(w.w, binary.LittleEndian, name); err != nil { - return err - } - } - if hdr.Id == BackupSparseBlock { - if err := binary.Write(w.w, binary.LittleEndian, hdr.Offset); err != nil { - return err - } - } - w.bytesLeft = hdr.Size - return nil -} - -// Write writes to the current backup stream. -func (w *BackupStreamWriter) Write(b []byte) (int, error) { - if w.bytesLeft < int64(len(b)) { - return 0, fmt.Errorf("too many bytes by %d", int64(len(b))-w.bytesLeft) - } - n, err := w.w.Write(b) - w.bytesLeft -= int64(n) - return n, err -} - -// BackupFileReader provides an io.ReadCloser interface on top of the BackupRead Win32 API. -type BackupFileReader struct { - f *os.File - includeSecurity bool - ctx uintptr -} - -// NewBackupFileReader returns a new BackupFileReader from a file handle. If includeSecurity is true, -// Read will attempt to read the security descriptor of the file. -func NewBackupFileReader(f *os.File, includeSecurity bool) *BackupFileReader { - r := &BackupFileReader{f, includeSecurity, 0} - return r -} - -// Read reads a backup stream from the file by calling the Win32 API BackupRead(). -func (r *BackupFileReader) Read(b []byte) (int, error) { - var bytesRead uint32 - err := backupRead(syscall.Handle(r.f.Fd()), b, &bytesRead, false, r.includeSecurity, &r.ctx) - if err != nil { - return 0, &os.PathError{"BackupRead", r.f.Name(), err} - } - runtime.KeepAlive(r.f) - if bytesRead == 0 { - return 0, io.EOF - } - return int(bytesRead), nil -} - -// Close frees Win32 resources associated with the BackupFileReader. It does not close -// the underlying file. -func (r *BackupFileReader) Close() error { - if r.ctx != 0 { - backupRead(syscall.Handle(r.f.Fd()), nil, nil, true, false, &r.ctx) - runtime.KeepAlive(r.f) - r.ctx = 0 - } - return nil -} - -// BackupFileWriter provides an io.WriteCloser interface on top of the BackupWrite Win32 API. -type BackupFileWriter struct { - f *os.File - includeSecurity bool - ctx uintptr -} - -// NewBackupFileWriter returns a new BackupFileWriter from a file handle. If includeSecurity is true, -// Write() will attempt to restore the security descriptor from the stream. -func NewBackupFileWriter(f *os.File, includeSecurity bool) *BackupFileWriter { - w := &BackupFileWriter{f, includeSecurity, 0} - return w -} - -// Write restores a portion of the file using the provided backup stream. -func (w *BackupFileWriter) Write(b []byte) (int, error) { - var bytesWritten uint32 - err := backupWrite(syscall.Handle(w.f.Fd()), b, &bytesWritten, false, w.includeSecurity, &w.ctx) - if err != nil { - return 0, &os.PathError{"BackupWrite", w.f.Name(), err} - } - runtime.KeepAlive(w.f) - if int(bytesWritten) != len(b) { - return int(bytesWritten), errors.New("not all bytes could be written") - } - return len(b), nil -} - -// Close frees Win32 resources associated with the BackupFileWriter. It does not -// close the underlying file. -func (w *BackupFileWriter) Close() error { - if w.ctx != 0 { - backupWrite(syscall.Handle(w.f.Fd()), nil, nil, true, false, &w.ctx) - runtime.KeepAlive(w.f) - w.ctx = 0 - } - return nil -} - -// OpenForBackup opens a file or directory, potentially skipping access checks if the backup -// or restore privileges have been acquired. -// -// If the file opened was a directory, it cannot be used with Readdir(). -func OpenForBackup(path string, access uint32, share uint32, createmode uint32) (*os.File, error) { - winPath, err := syscall.UTF16FromString(path) - if err != nil { - return nil, err - } - h, err := syscall.CreateFile(&winPath[0], access, share, nil, createmode, syscall.FILE_FLAG_BACKUP_SEMANTICS|syscall.FILE_FLAG_OPEN_REPARSE_POINT, 0) - if err != nil { - err = &os.PathError{Op: "open", Path: path, Err: err} - return nil, err - } - return os.NewFile(uintptr(h), path), nil -} diff --git a/vendor/github.com/Microsoft/go-winio/ea.go b/vendor/github.com/Microsoft/go-winio/ea.go deleted file mode 100644 index 4051c1b3..00000000 --- a/vendor/github.com/Microsoft/go-winio/ea.go +++ /dev/null @@ -1,137 +0,0 @@ -package winio - -import ( - "bytes" - "encoding/binary" - "errors" -) - -type fileFullEaInformation struct { - NextEntryOffset uint32 - Flags uint8 - NameLength uint8 - ValueLength uint16 -} - -var ( - fileFullEaInformationSize = binary.Size(&fileFullEaInformation{}) - - errInvalidEaBuffer = errors.New("invalid extended attribute buffer") - errEaNameTooLarge = errors.New("extended attribute name too large") - errEaValueTooLarge = errors.New("extended attribute value too large") -) - -// ExtendedAttribute represents a single Windows EA. -type ExtendedAttribute struct { - Name string - Value []byte - Flags uint8 -} - -func parseEa(b []byte) (ea ExtendedAttribute, nb []byte, err error) { - var info fileFullEaInformation - err = binary.Read(bytes.NewReader(b), binary.LittleEndian, &info) - if err != nil { - err = errInvalidEaBuffer - return - } - - nameOffset := fileFullEaInformationSize - nameLen := int(info.NameLength) - valueOffset := nameOffset + int(info.NameLength) + 1 - valueLen := int(info.ValueLength) - nextOffset := int(info.NextEntryOffset) - if valueLen+valueOffset > len(b) || nextOffset < 0 || nextOffset > len(b) { - err = errInvalidEaBuffer - return - } - - ea.Name = string(b[nameOffset : nameOffset+nameLen]) - ea.Value = b[valueOffset : valueOffset+valueLen] - ea.Flags = info.Flags - if info.NextEntryOffset != 0 { - nb = b[info.NextEntryOffset:] - } - return -} - -// DecodeExtendedAttributes decodes a list of EAs from a FILE_FULL_EA_INFORMATION -// buffer retrieved from BackupRead, ZwQueryEaFile, etc. -func DecodeExtendedAttributes(b []byte) (eas []ExtendedAttribute, err error) { - for len(b) != 0 { - ea, nb, err := parseEa(b) - if err != nil { - return nil, err - } - - eas = append(eas, ea) - b = nb - } - return -} - -func writeEa(buf *bytes.Buffer, ea *ExtendedAttribute, last bool) error { - if int(uint8(len(ea.Name))) != len(ea.Name) { - return errEaNameTooLarge - } - if int(uint16(len(ea.Value))) != len(ea.Value) { - return errEaValueTooLarge - } - entrySize := uint32(fileFullEaInformationSize + len(ea.Name) + 1 + len(ea.Value)) - withPadding := (entrySize + 3) &^ 3 - nextOffset := uint32(0) - if !last { - nextOffset = withPadding - } - info := fileFullEaInformation{ - NextEntryOffset: nextOffset, - Flags: ea.Flags, - NameLength: uint8(len(ea.Name)), - ValueLength: uint16(len(ea.Value)), - } - - err := binary.Write(buf, binary.LittleEndian, &info) - if err != nil { - return err - } - - _, err = buf.Write([]byte(ea.Name)) - if err != nil { - return err - } - - err = buf.WriteByte(0) - if err != nil { - return err - } - - _, err = buf.Write(ea.Value) - if err != nil { - return err - } - - _, err = buf.Write([]byte{0, 0, 0}[0 : withPadding-entrySize]) - if err != nil { - return err - } - - return nil -} - -// EncodeExtendedAttributes encodes a list of EAs into a FILE_FULL_EA_INFORMATION -// buffer for use with BackupWrite, ZwSetEaFile, etc. -func EncodeExtendedAttributes(eas []ExtendedAttribute) ([]byte, error) { - var buf bytes.Buffer - for i := range eas { - last := false - if i == len(eas)-1 { - last = true - } - - err := writeEa(&buf, &eas[i], last) - if err != nil { - return nil, err - } - } - return buf.Bytes(), nil -} diff --git a/vendor/github.com/Microsoft/go-winio/file.go b/vendor/github.com/Microsoft/go-winio/file.go deleted file mode 100644 index 0385e410..00000000 --- a/vendor/github.com/Microsoft/go-winio/file.go +++ /dev/null @@ -1,323 +0,0 @@ -// +build windows - -package winio - -import ( - "errors" - "io" - "runtime" - "sync" - "sync/atomic" - "syscall" - "time" -) - -//sys cancelIoEx(file syscall.Handle, o *syscall.Overlapped) (err error) = CancelIoEx -//sys createIoCompletionPort(file syscall.Handle, port syscall.Handle, key uintptr, threadCount uint32) (newport syscall.Handle, err error) = CreateIoCompletionPort -//sys getQueuedCompletionStatus(port syscall.Handle, bytes *uint32, key *uintptr, o **ioOperation, timeout uint32) (err error) = GetQueuedCompletionStatus -//sys setFileCompletionNotificationModes(h syscall.Handle, flags uint8) (err error) = SetFileCompletionNotificationModes -//sys wsaGetOverlappedResult(h syscall.Handle, o *syscall.Overlapped, bytes *uint32, wait bool, flags *uint32) (err error) = ws2_32.WSAGetOverlappedResult - -type atomicBool int32 - -func (b *atomicBool) isSet() bool { return atomic.LoadInt32((*int32)(b)) != 0 } -func (b *atomicBool) setFalse() { atomic.StoreInt32((*int32)(b), 0) } -func (b *atomicBool) setTrue() { atomic.StoreInt32((*int32)(b), 1) } -func (b *atomicBool) swap(new bool) bool { - var newInt int32 - if new { - newInt = 1 - } - return atomic.SwapInt32((*int32)(b), newInt) == 1 -} - -const ( - cFILE_SKIP_COMPLETION_PORT_ON_SUCCESS = 1 - cFILE_SKIP_SET_EVENT_ON_HANDLE = 2 -) - -var ( - ErrFileClosed = errors.New("file has already been closed") - ErrTimeout = &timeoutError{} -) - -type timeoutError struct{} - -func (e *timeoutError) Error() string { return "i/o timeout" } -func (e *timeoutError) Timeout() bool { return true } -func (e *timeoutError) Temporary() bool { return true } - -type timeoutChan chan struct{} - -var ioInitOnce sync.Once -var ioCompletionPort syscall.Handle - -// ioResult contains the result of an asynchronous IO operation -type ioResult struct { - bytes uint32 - err error -} - -// ioOperation represents an outstanding asynchronous Win32 IO -type ioOperation struct { - o syscall.Overlapped - ch chan ioResult -} - -func initIo() { - h, err := createIoCompletionPort(syscall.InvalidHandle, 0, 0, 0xffffffff) - if err != nil { - panic(err) - } - ioCompletionPort = h - go ioCompletionProcessor(h) -} - -// win32File implements Reader, Writer, and Closer on a Win32 handle without blocking in a syscall. -// It takes ownership of this handle and will close it if it is garbage collected. -type win32File struct { - handle syscall.Handle - wg sync.WaitGroup - wgLock sync.RWMutex - closing atomicBool - socket bool - readDeadline deadlineHandler - writeDeadline deadlineHandler -} - -type deadlineHandler struct { - setLock sync.Mutex - channel timeoutChan - channelLock sync.RWMutex - timer *time.Timer - timedout atomicBool -} - -// makeWin32File makes a new win32File from an existing file handle -func makeWin32File(h syscall.Handle) (*win32File, error) { - f := &win32File{handle: h} - ioInitOnce.Do(initIo) - _, err := createIoCompletionPort(h, ioCompletionPort, 0, 0xffffffff) - if err != nil { - return nil, err - } - err = setFileCompletionNotificationModes(h, cFILE_SKIP_COMPLETION_PORT_ON_SUCCESS|cFILE_SKIP_SET_EVENT_ON_HANDLE) - if err != nil { - return nil, err - } - f.readDeadline.channel = make(timeoutChan) - f.writeDeadline.channel = make(timeoutChan) - return f, nil -} - -func MakeOpenFile(h syscall.Handle) (io.ReadWriteCloser, error) { - // If we return the result of makeWin32File directly, it can result in an - // interface-wrapped nil, rather than a nil interface value. - f, err := makeWin32File(h) - if err != nil { - return nil, err - } - return f, nil -} - -// closeHandle closes the resources associated with a Win32 handle -func (f *win32File) closeHandle() { - f.wgLock.Lock() - // Atomically set that we are closing, releasing the resources only once. - if !f.closing.swap(true) { - f.wgLock.Unlock() - // cancel all IO and wait for it to complete - cancelIoEx(f.handle, nil) - f.wg.Wait() - // at this point, no new IO can start - syscall.Close(f.handle) - f.handle = 0 - } else { - f.wgLock.Unlock() - } -} - -// Close closes a win32File. -func (f *win32File) Close() error { - f.closeHandle() - return nil -} - -// prepareIo prepares for a new IO operation. -// The caller must call f.wg.Done() when the IO is finished, prior to Close() returning. -func (f *win32File) prepareIo() (*ioOperation, error) { - f.wgLock.RLock() - if f.closing.isSet() { - f.wgLock.RUnlock() - return nil, ErrFileClosed - } - f.wg.Add(1) - f.wgLock.RUnlock() - c := &ioOperation{} - c.ch = make(chan ioResult) - return c, nil -} - -// ioCompletionProcessor processes completed async IOs forever -func ioCompletionProcessor(h syscall.Handle) { - for { - var bytes uint32 - var key uintptr - var op *ioOperation - err := getQueuedCompletionStatus(h, &bytes, &key, &op, syscall.INFINITE) - if op == nil { - panic(err) - } - op.ch <- ioResult{bytes, err} - } -} - -// asyncIo processes the return value from ReadFile or WriteFile, blocking until -// the operation has actually completed. -func (f *win32File) asyncIo(c *ioOperation, d *deadlineHandler, bytes uint32, err error) (int, error) { - if err != syscall.ERROR_IO_PENDING { - return int(bytes), err - } - - if f.closing.isSet() { - cancelIoEx(f.handle, &c.o) - } - - var timeout timeoutChan - if d != nil { - d.channelLock.Lock() - timeout = d.channel - d.channelLock.Unlock() - } - - var r ioResult - select { - case r = <-c.ch: - err = r.err - if err == syscall.ERROR_OPERATION_ABORTED { - if f.closing.isSet() { - err = ErrFileClosed - } - } else if err != nil && f.socket { - // err is from Win32. Query the overlapped structure to get the winsock error. - var bytes, flags uint32 - err = wsaGetOverlappedResult(f.handle, &c.o, &bytes, false, &flags) - } - case <-timeout: - cancelIoEx(f.handle, &c.o) - r = <-c.ch - err = r.err - if err == syscall.ERROR_OPERATION_ABORTED { - err = ErrTimeout - } - } - - // runtime.KeepAlive is needed, as c is passed via native - // code to ioCompletionProcessor, c must remain alive - // until the channel read is complete. - runtime.KeepAlive(c) - return int(r.bytes), err -} - -// Read reads from a file handle. -func (f *win32File) Read(b []byte) (int, error) { - c, err := f.prepareIo() - if err != nil { - return 0, err - } - defer f.wg.Done() - - if f.readDeadline.timedout.isSet() { - return 0, ErrTimeout - } - - var bytes uint32 - err = syscall.ReadFile(f.handle, b, &bytes, &c.o) - n, err := f.asyncIo(c, &f.readDeadline, bytes, err) - runtime.KeepAlive(b) - - // Handle EOF conditions. - if err == nil && n == 0 && len(b) != 0 { - return 0, io.EOF - } else if err == syscall.ERROR_BROKEN_PIPE { - return 0, io.EOF - } else { - return n, err - } -} - -// Write writes to a file handle. -func (f *win32File) Write(b []byte) (int, error) { - c, err := f.prepareIo() - if err != nil { - return 0, err - } - defer f.wg.Done() - - if f.writeDeadline.timedout.isSet() { - return 0, ErrTimeout - } - - var bytes uint32 - err = syscall.WriteFile(f.handle, b, &bytes, &c.o) - n, err := f.asyncIo(c, &f.writeDeadline, bytes, err) - runtime.KeepAlive(b) - return n, err -} - -func (f *win32File) SetReadDeadline(deadline time.Time) error { - return f.readDeadline.set(deadline) -} - -func (f *win32File) SetWriteDeadline(deadline time.Time) error { - return f.writeDeadline.set(deadline) -} - -func (f *win32File) Flush() error { - return syscall.FlushFileBuffers(f.handle) -} - -func (f *win32File) Fd() uintptr { - return uintptr(f.handle) -} - -func (d *deadlineHandler) set(deadline time.Time) error { - d.setLock.Lock() - defer d.setLock.Unlock() - - if d.timer != nil { - if !d.timer.Stop() { - <-d.channel - } - d.timer = nil - } - d.timedout.setFalse() - - select { - case <-d.channel: - d.channelLock.Lock() - d.channel = make(chan struct{}) - d.channelLock.Unlock() - default: - } - - if deadline.IsZero() { - return nil - } - - timeoutIO := func() { - d.timedout.setTrue() - close(d.channel) - } - - now := time.Now() - duration := deadline.Sub(now) - if deadline.After(now) { - // Deadline is in the future, set a timer to wait - d.timer = time.AfterFunc(duration, timeoutIO) - } else { - // Deadline is in the past. Cancel all pending IO now. - timeoutIO() - } - return nil -} diff --git a/vendor/github.com/Microsoft/go-winio/fileinfo.go b/vendor/github.com/Microsoft/go-winio/fileinfo.go deleted file mode 100644 index ada2fbab..00000000 --- a/vendor/github.com/Microsoft/go-winio/fileinfo.go +++ /dev/null @@ -1,61 +0,0 @@ -// +build windows - -package winio - -import ( - "os" - "runtime" - "syscall" - "unsafe" -) - -//sys getFileInformationByHandleEx(h syscall.Handle, class uint32, buffer *byte, size uint32) (err error) = GetFileInformationByHandleEx -//sys setFileInformationByHandle(h syscall.Handle, class uint32, buffer *byte, size uint32) (err error) = SetFileInformationByHandle - -const ( - fileBasicInfo = 0 - fileIDInfo = 0x12 -) - -// FileBasicInfo contains file access time and file attributes information. -type FileBasicInfo struct { - CreationTime, LastAccessTime, LastWriteTime, ChangeTime syscall.Filetime - FileAttributes uint32 - pad uint32 // padding -} - -// GetFileBasicInfo retrieves times and attributes for a file. -func GetFileBasicInfo(f *os.File) (*FileBasicInfo, error) { - bi := &FileBasicInfo{} - if err := getFileInformationByHandleEx(syscall.Handle(f.Fd()), fileBasicInfo, (*byte)(unsafe.Pointer(bi)), uint32(unsafe.Sizeof(*bi))); err != nil { - return nil, &os.PathError{Op: "GetFileInformationByHandleEx", Path: f.Name(), Err: err} - } - runtime.KeepAlive(f) - return bi, nil -} - -// SetFileBasicInfo sets times and attributes for a file. -func SetFileBasicInfo(f *os.File, bi *FileBasicInfo) error { - if err := setFileInformationByHandle(syscall.Handle(f.Fd()), fileBasicInfo, (*byte)(unsafe.Pointer(bi)), uint32(unsafe.Sizeof(*bi))); err != nil { - return &os.PathError{Op: "SetFileInformationByHandle", Path: f.Name(), Err: err} - } - runtime.KeepAlive(f) - return nil -} - -// FileIDInfo contains the volume serial number and file ID for a file. This pair should be -// unique on a system. -type FileIDInfo struct { - VolumeSerialNumber uint64 - FileID [16]byte -} - -// GetFileID retrieves the unique (volume, file ID) pair for a file. -func GetFileID(f *os.File) (*FileIDInfo, error) { - fileID := &FileIDInfo{} - if err := getFileInformationByHandleEx(syscall.Handle(f.Fd()), fileIDInfo, (*byte)(unsafe.Pointer(fileID)), uint32(unsafe.Sizeof(*fileID))); err != nil { - return nil, &os.PathError{Op: "GetFileInformationByHandleEx", Path: f.Name(), Err: err} - } - runtime.KeepAlive(f) - return fileID, nil -} diff --git a/vendor/github.com/Microsoft/go-winio/hvsock.go b/vendor/github.com/Microsoft/go-winio/hvsock.go deleted file mode 100644 index dbfe790e..00000000 --- a/vendor/github.com/Microsoft/go-winio/hvsock.go +++ /dev/null @@ -1,305 +0,0 @@ -package winio - -import ( - "fmt" - "io" - "net" - "os" - "syscall" - "time" - "unsafe" - - "github.com/Microsoft/go-winio/pkg/guid" -) - -//sys bind(s syscall.Handle, name unsafe.Pointer, namelen int32) (err error) [failretval==socketError] = ws2_32.bind - -const ( - afHvSock = 34 // AF_HYPERV - - socketError = ^uintptr(0) -) - -// An HvsockAddr is an address for a AF_HYPERV socket. -type HvsockAddr struct { - VMID guid.GUID - ServiceID guid.GUID -} - -type rawHvsockAddr struct { - Family uint16 - _ uint16 - VMID guid.GUID - ServiceID guid.GUID -} - -// Network returns the address's network name, "hvsock". -func (addr *HvsockAddr) Network() string { - return "hvsock" -} - -func (addr *HvsockAddr) String() string { - return fmt.Sprintf("%s:%s", &addr.VMID, &addr.ServiceID) -} - -// VsockServiceID returns an hvsock service ID corresponding to the specified AF_VSOCK port. -func VsockServiceID(port uint32) guid.GUID { - g, _ := guid.FromString("00000000-facb-11e6-bd58-64006a7986d3") - g.Data1 = port - return g -} - -func (addr *HvsockAddr) raw() rawHvsockAddr { - return rawHvsockAddr{ - Family: afHvSock, - VMID: addr.VMID, - ServiceID: addr.ServiceID, - } -} - -func (addr *HvsockAddr) fromRaw(raw *rawHvsockAddr) { - addr.VMID = raw.VMID - addr.ServiceID = raw.ServiceID -} - -// HvsockListener is a socket listener for the AF_HYPERV address family. -type HvsockListener struct { - sock *win32File - addr HvsockAddr -} - -// HvsockConn is a connected socket of the AF_HYPERV address family. -type HvsockConn struct { - sock *win32File - local, remote HvsockAddr -} - -func newHvSocket() (*win32File, error) { - fd, err := syscall.Socket(afHvSock, syscall.SOCK_STREAM, 1) - if err != nil { - return nil, os.NewSyscallError("socket", err) - } - f, err := makeWin32File(fd) - if err != nil { - syscall.Close(fd) - return nil, err - } - f.socket = true - return f, nil -} - -// ListenHvsock listens for connections on the specified hvsock address. -func ListenHvsock(addr *HvsockAddr) (_ *HvsockListener, err error) { - l := &HvsockListener{addr: *addr} - sock, err := newHvSocket() - if err != nil { - return nil, l.opErr("listen", err) - } - sa := addr.raw() - err = bind(sock.handle, unsafe.Pointer(&sa), int32(unsafe.Sizeof(sa))) - if err != nil { - return nil, l.opErr("listen", os.NewSyscallError("socket", err)) - } - err = syscall.Listen(sock.handle, 16) - if err != nil { - return nil, l.opErr("listen", os.NewSyscallError("listen", err)) - } - return &HvsockListener{sock: sock, addr: *addr}, nil -} - -func (l *HvsockListener) opErr(op string, err error) error { - return &net.OpError{Op: op, Net: "hvsock", Addr: &l.addr, Err: err} -} - -// Addr returns the listener's network address. -func (l *HvsockListener) Addr() net.Addr { - return &l.addr -} - -// Accept waits for the next connection and returns it. -func (l *HvsockListener) Accept() (_ net.Conn, err error) { - sock, err := newHvSocket() - if err != nil { - return nil, l.opErr("accept", err) - } - defer func() { - if sock != nil { - sock.Close() - } - }() - c, err := l.sock.prepareIo() - if err != nil { - return nil, l.opErr("accept", err) - } - defer l.sock.wg.Done() - - // AcceptEx, per documentation, requires an extra 16 bytes per address. - const addrlen = uint32(16 + unsafe.Sizeof(rawHvsockAddr{})) - var addrbuf [addrlen * 2]byte - - var bytes uint32 - err = syscall.AcceptEx(l.sock.handle, sock.handle, &addrbuf[0], 0, addrlen, addrlen, &bytes, &c.o) - _, err = l.sock.asyncIo(c, nil, bytes, err) - if err != nil { - return nil, l.opErr("accept", os.NewSyscallError("acceptex", err)) - } - conn := &HvsockConn{ - sock: sock, - } - conn.local.fromRaw((*rawHvsockAddr)(unsafe.Pointer(&addrbuf[0]))) - conn.remote.fromRaw((*rawHvsockAddr)(unsafe.Pointer(&addrbuf[addrlen]))) - sock = nil - return conn, nil -} - -// Close closes the listener, causing any pending Accept calls to fail. -func (l *HvsockListener) Close() error { - return l.sock.Close() -} - -/* Need to finish ConnectEx handling -func DialHvsock(ctx context.Context, addr *HvsockAddr) (*HvsockConn, error) { - sock, err := newHvSocket() - if err != nil { - return nil, err - } - defer func() { - if sock != nil { - sock.Close() - } - }() - c, err := sock.prepareIo() - if err != nil { - return nil, err - } - defer sock.wg.Done() - var bytes uint32 - err = windows.ConnectEx(windows.Handle(sock.handle), sa, nil, 0, &bytes, &c.o) - _, err = sock.asyncIo(ctx, c, nil, bytes, err) - if err != nil { - return nil, err - } - conn := &HvsockConn{ - sock: sock, - remote: *addr, - } - sock = nil - return conn, nil -} -*/ - -func (conn *HvsockConn) opErr(op string, err error) error { - return &net.OpError{Op: op, Net: "hvsock", Source: &conn.local, Addr: &conn.remote, Err: err} -} - -func (conn *HvsockConn) Read(b []byte) (int, error) { - c, err := conn.sock.prepareIo() - if err != nil { - return 0, conn.opErr("read", err) - } - defer conn.sock.wg.Done() - buf := syscall.WSABuf{Buf: &b[0], Len: uint32(len(b))} - var flags, bytes uint32 - err = syscall.WSARecv(conn.sock.handle, &buf, 1, &bytes, &flags, &c.o, nil) - n, err := conn.sock.asyncIo(c, &conn.sock.readDeadline, bytes, err) - if err != nil { - if _, ok := err.(syscall.Errno); ok { - err = os.NewSyscallError("wsarecv", err) - } - return 0, conn.opErr("read", err) - } else if n == 0 { - err = io.EOF - } - return n, err -} - -func (conn *HvsockConn) Write(b []byte) (int, error) { - t := 0 - for len(b) != 0 { - n, err := conn.write(b) - if err != nil { - return t + n, err - } - t += n - b = b[n:] - } - return t, nil -} - -func (conn *HvsockConn) write(b []byte) (int, error) { - c, err := conn.sock.prepareIo() - if err != nil { - return 0, conn.opErr("write", err) - } - defer conn.sock.wg.Done() - buf := syscall.WSABuf{Buf: &b[0], Len: uint32(len(b))} - var bytes uint32 - err = syscall.WSASend(conn.sock.handle, &buf, 1, &bytes, 0, &c.o, nil) - n, err := conn.sock.asyncIo(c, &conn.sock.writeDeadline, bytes, err) - if err != nil { - if _, ok := err.(syscall.Errno); ok { - err = os.NewSyscallError("wsasend", err) - } - return 0, conn.opErr("write", err) - } - return n, err -} - -// Close closes the socket connection, failing any pending read or write calls. -func (conn *HvsockConn) Close() error { - return conn.sock.Close() -} - -func (conn *HvsockConn) shutdown(how int) error { - err := syscall.Shutdown(conn.sock.handle, syscall.SHUT_RD) - if err != nil { - return os.NewSyscallError("shutdown", err) - } - return nil -} - -// CloseRead shuts down the read end of the socket. -func (conn *HvsockConn) CloseRead() error { - err := conn.shutdown(syscall.SHUT_RD) - if err != nil { - return conn.opErr("close", err) - } - return nil -} - -// CloseWrite shuts down the write end of the socket, notifying the other endpoint that -// no more data will be written. -func (conn *HvsockConn) CloseWrite() error { - err := conn.shutdown(syscall.SHUT_WR) - if err != nil { - return conn.opErr("close", err) - } - return nil -} - -// LocalAddr returns the local address of the connection. -func (conn *HvsockConn) LocalAddr() net.Addr { - return &conn.local -} - -// RemoteAddr returns the remote address of the connection. -func (conn *HvsockConn) RemoteAddr() net.Addr { - return &conn.remote -} - -// SetDeadline implements the net.Conn SetDeadline method. -func (conn *HvsockConn) SetDeadline(t time.Time) error { - conn.SetReadDeadline(t) - conn.SetWriteDeadline(t) - return nil -} - -// SetReadDeadline implements the net.Conn SetReadDeadline method. -func (conn *HvsockConn) SetReadDeadline(t time.Time) error { - return conn.sock.SetReadDeadline(t) -} - -// SetWriteDeadline implements the net.Conn SetWriteDeadline method. -func (conn *HvsockConn) SetWriteDeadline(t time.Time) error { - return conn.sock.SetWriteDeadline(t) -} diff --git a/vendor/github.com/Microsoft/go-winio/pipe.go b/vendor/github.com/Microsoft/go-winio/pipe.go deleted file mode 100644 index 96700a73..00000000 --- a/vendor/github.com/Microsoft/go-winio/pipe.go +++ /dev/null @@ -1,517 +0,0 @@ -// +build windows - -package winio - -import ( - "context" - "errors" - "fmt" - "io" - "net" - "os" - "runtime" - "syscall" - "time" - "unsafe" -) - -//sys connectNamedPipe(pipe syscall.Handle, o *syscall.Overlapped) (err error) = ConnectNamedPipe -//sys createNamedPipe(name string, flags uint32, pipeMode uint32, maxInstances uint32, outSize uint32, inSize uint32, defaultTimeout uint32, sa *syscall.SecurityAttributes) (handle syscall.Handle, err error) [failretval==syscall.InvalidHandle] = CreateNamedPipeW -//sys createFile(name string, access uint32, mode uint32, sa *syscall.SecurityAttributes, createmode uint32, attrs uint32, templatefile syscall.Handle) (handle syscall.Handle, err error) [failretval==syscall.InvalidHandle] = CreateFileW -//sys getNamedPipeInfo(pipe syscall.Handle, flags *uint32, outSize *uint32, inSize *uint32, maxInstances *uint32) (err error) = GetNamedPipeInfo -//sys getNamedPipeHandleState(pipe syscall.Handle, state *uint32, curInstances *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32, userName *uint16, maxUserNameSize uint32) (err error) = GetNamedPipeHandleStateW -//sys localAlloc(uFlags uint32, length uint32) (ptr uintptr) = LocalAlloc -//sys ntCreateNamedPipeFile(pipe *syscall.Handle, access uint32, oa *objectAttributes, iosb *ioStatusBlock, share uint32, disposition uint32, options uint32, typ uint32, readMode uint32, completionMode uint32, maxInstances uint32, inboundQuota uint32, outputQuota uint32, timeout *int64) (status ntstatus) = ntdll.NtCreateNamedPipeFile -//sys rtlNtStatusToDosError(status ntstatus) (winerr error) = ntdll.RtlNtStatusToDosErrorNoTeb -//sys rtlDosPathNameToNtPathName(name *uint16, ntName *unicodeString, filePart uintptr, reserved uintptr) (status ntstatus) = ntdll.RtlDosPathNameToNtPathName_U -//sys rtlDefaultNpAcl(dacl *uintptr) (status ntstatus) = ntdll.RtlDefaultNpAcl - -type ioStatusBlock struct { - Status, Information uintptr -} - -type objectAttributes struct { - Length uintptr - RootDirectory uintptr - ObjectName *unicodeString - Attributes uintptr - SecurityDescriptor *securityDescriptor - SecurityQoS uintptr -} - -type unicodeString struct { - Length uint16 - MaximumLength uint16 - Buffer uintptr -} - -type securityDescriptor struct { - Revision byte - Sbz1 byte - Control uint16 - Owner uintptr - Group uintptr - Sacl uintptr - Dacl uintptr -} - -type ntstatus int32 - -func (status ntstatus) Err() error { - if status >= 0 { - return nil - } - return rtlNtStatusToDosError(status) -} - -const ( - cERROR_PIPE_BUSY = syscall.Errno(231) - cERROR_NO_DATA = syscall.Errno(232) - cERROR_PIPE_CONNECTED = syscall.Errno(535) - cERROR_SEM_TIMEOUT = syscall.Errno(121) - - cSECURITY_SQOS_PRESENT = 0x100000 - cSECURITY_ANONYMOUS = 0 - - cPIPE_TYPE_MESSAGE = 4 - - cPIPE_READMODE_MESSAGE = 2 - - cFILE_OPEN = 1 - cFILE_CREATE = 2 - - cFILE_PIPE_MESSAGE_TYPE = 1 - cFILE_PIPE_REJECT_REMOTE_CLIENTS = 2 - - cSE_DACL_PRESENT = 4 -) - -var ( - // ErrPipeListenerClosed is returned for pipe operations on listeners that have been closed. - // This error should match net.errClosing since docker takes a dependency on its text. - ErrPipeListenerClosed = errors.New("use of closed network connection") - - errPipeWriteClosed = errors.New("pipe has been closed for write") -) - -type win32Pipe struct { - *win32File - path string -} - -type win32MessageBytePipe struct { - win32Pipe - writeClosed bool - readEOF bool -} - -type pipeAddress string - -func (f *win32Pipe) LocalAddr() net.Addr { - return pipeAddress(f.path) -} - -func (f *win32Pipe) RemoteAddr() net.Addr { - return pipeAddress(f.path) -} - -func (f *win32Pipe) SetDeadline(t time.Time) error { - f.SetReadDeadline(t) - f.SetWriteDeadline(t) - return nil -} - -// CloseWrite closes the write side of a message pipe in byte mode. -func (f *win32MessageBytePipe) CloseWrite() error { - if f.writeClosed { - return errPipeWriteClosed - } - err := f.win32File.Flush() - if err != nil { - return err - } - _, err = f.win32File.Write(nil) - if err != nil { - return err - } - f.writeClosed = true - return nil -} - -// Write writes bytes to a message pipe in byte mode. Zero-byte writes are ignored, since -// they are used to implement CloseWrite(). -func (f *win32MessageBytePipe) Write(b []byte) (int, error) { - if f.writeClosed { - return 0, errPipeWriteClosed - } - if len(b) == 0 { - return 0, nil - } - return f.win32File.Write(b) -} - -// Read reads bytes from a message pipe in byte mode. A read of a zero-byte message on a message -// mode pipe will return io.EOF, as will all subsequent reads. -func (f *win32MessageBytePipe) Read(b []byte) (int, error) { - if f.readEOF { - return 0, io.EOF - } - n, err := f.win32File.Read(b) - if err == io.EOF { - // If this was the result of a zero-byte read, then - // it is possible that the read was due to a zero-size - // message. Since we are simulating CloseWrite with a - // zero-byte message, ensure that all future Read() calls - // also return EOF. - f.readEOF = true - } else if err == syscall.ERROR_MORE_DATA { - // ERROR_MORE_DATA indicates that the pipe's read mode is message mode - // and the message still has more bytes. Treat this as a success, since - // this package presents all named pipes as byte streams. - err = nil - } - return n, err -} - -func (s pipeAddress) Network() string { - return "pipe" -} - -func (s pipeAddress) String() string { - return string(s) -} - -// tryDialPipe attempts to dial the pipe at `path` until `ctx` cancellation or timeout. -func tryDialPipe(ctx context.Context, path *string, access uint32) (syscall.Handle, error) { - for { - - select { - case <-ctx.Done(): - return syscall.Handle(0), ctx.Err() - default: - h, err := createFile(*path, access, 0, nil, syscall.OPEN_EXISTING, syscall.FILE_FLAG_OVERLAPPED|cSECURITY_SQOS_PRESENT|cSECURITY_ANONYMOUS, 0) - if err == nil { - return h, nil - } - if err != cERROR_PIPE_BUSY { - return h, &os.PathError{Err: err, Op: "open", Path: *path} - } - // Wait 10 msec and try again. This is a rather simplistic - // view, as we always try each 10 milliseconds. - time.Sleep(10 * time.Millisecond) - } - } -} - -// DialPipe connects to a named pipe by path, timing out if the connection -// takes longer than the specified duration. If timeout is nil, then we use -// a default timeout of 2 seconds. (We do not use WaitNamedPipe.) -func DialPipe(path string, timeout *time.Duration) (net.Conn, error) { - var absTimeout time.Time - if timeout != nil { - absTimeout = time.Now().Add(*timeout) - } else { - absTimeout = time.Now().Add(2 * time.Second) - } - ctx, _ := context.WithDeadline(context.Background(), absTimeout) - conn, err := DialPipeContext(ctx, path) - if err == context.DeadlineExceeded { - return nil, ErrTimeout - } - return conn, err -} - -// DialPipeContext attempts to connect to a named pipe by `path` until `ctx` -// cancellation or timeout. -func DialPipeContext(ctx context.Context, path string) (net.Conn, error) { - return DialPipeAccess(ctx, path, syscall.GENERIC_READ|syscall.GENERIC_WRITE) -} - -// DialPipeAccess attempts to connect to a named pipe by `path` with `access` until `ctx` -// cancellation or timeout. -func DialPipeAccess(ctx context.Context, path string, access uint32) (net.Conn, error) { - var err error - var h syscall.Handle - h, err = tryDialPipe(ctx, &path, access) - if err != nil { - return nil, err - } - - var flags uint32 - err = getNamedPipeInfo(h, &flags, nil, nil, nil) - if err != nil { - return nil, err - } - - f, err := makeWin32File(h) - if err != nil { - syscall.Close(h) - return nil, err - } - - // If the pipe is in message mode, return a message byte pipe, which - // supports CloseWrite(). - if flags&cPIPE_TYPE_MESSAGE != 0 { - return &win32MessageBytePipe{ - win32Pipe: win32Pipe{win32File: f, path: path}, - }, nil - } - return &win32Pipe{win32File: f, path: path}, nil -} - -type acceptResponse struct { - f *win32File - err error -} - -type win32PipeListener struct { - firstHandle syscall.Handle - path string - config PipeConfig - acceptCh chan (chan acceptResponse) - closeCh chan int - doneCh chan int -} - -func makeServerPipeHandle(path string, sd []byte, c *PipeConfig, first bool) (syscall.Handle, error) { - path16, err := syscall.UTF16FromString(path) - if err != nil { - return 0, &os.PathError{Op: "open", Path: path, Err: err} - } - - var oa objectAttributes - oa.Length = unsafe.Sizeof(oa) - - var ntPath unicodeString - if err := rtlDosPathNameToNtPathName(&path16[0], &ntPath, 0, 0).Err(); err != nil { - return 0, &os.PathError{Op: "open", Path: path, Err: err} - } - defer localFree(ntPath.Buffer) - oa.ObjectName = &ntPath - - // The security descriptor is only needed for the first pipe. - if first { - if sd != nil { - len := uint32(len(sd)) - sdb := localAlloc(0, len) - defer localFree(sdb) - copy((*[0xffff]byte)(unsafe.Pointer(sdb))[:], sd) - oa.SecurityDescriptor = (*securityDescriptor)(unsafe.Pointer(sdb)) - } else { - // Construct the default named pipe security descriptor. - var dacl uintptr - if err := rtlDefaultNpAcl(&dacl).Err(); err != nil { - return 0, fmt.Errorf("getting default named pipe ACL: %s", err) - } - defer localFree(dacl) - - sdb := &securityDescriptor{ - Revision: 1, - Control: cSE_DACL_PRESENT, - Dacl: dacl, - } - oa.SecurityDescriptor = sdb - } - } - - typ := uint32(cFILE_PIPE_REJECT_REMOTE_CLIENTS) - if c.MessageMode { - typ |= cFILE_PIPE_MESSAGE_TYPE - } - - disposition := uint32(cFILE_OPEN) - access := uint32(syscall.GENERIC_READ | syscall.GENERIC_WRITE | syscall.SYNCHRONIZE) - if first { - disposition = cFILE_CREATE - // By not asking for read or write access, the named pipe file system - // will put this pipe into an initially disconnected state, blocking - // client connections until the next call with first == false. - access = syscall.SYNCHRONIZE - } - - timeout := int64(-50 * 10000) // 50ms - - var ( - h syscall.Handle - iosb ioStatusBlock - ) - err = ntCreateNamedPipeFile(&h, access, &oa, &iosb, syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE, disposition, 0, typ, 0, 0, 0xffffffff, uint32(c.InputBufferSize), uint32(c.OutputBufferSize), &timeout).Err() - if err != nil { - return 0, &os.PathError{Op: "open", Path: path, Err: err} - } - - runtime.KeepAlive(ntPath) - return h, nil -} - -func (l *win32PipeListener) makeServerPipe() (*win32File, error) { - h, err := makeServerPipeHandle(l.path, nil, &l.config, false) - if err != nil { - return nil, err - } - f, err := makeWin32File(h) - if err != nil { - syscall.Close(h) - return nil, err - } - return f, nil -} - -func (l *win32PipeListener) makeConnectedServerPipe() (*win32File, error) { - p, err := l.makeServerPipe() - if err != nil { - return nil, err - } - - // Wait for the client to connect. - ch := make(chan error) - go func(p *win32File) { - ch <- connectPipe(p) - }(p) - - select { - case err = <-ch: - if err != nil { - p.Close() - p = nil - } - case <-l.closeCh: - // Abort the connect request by closing the handle. - p.Close() - p = nil - err = <-ch - if err == nil || err == ErrFileClosed { - err = ErrPipeListenerClosed - } - } - return p, err -} - -func (l *win32PipeListener) listenerRoutine() { - closed := false - for !closed { - select { - case <-l.closeCh: - closed = true - case responseCh := <-l.acceptCh: - var ( - p *win32File - err error - ) - for { - p, err = l.makeConnectedServerPipe() - // If the connection was immediately closed by the client, try - // again. - if err != cERROR_NO_DATA { - break - } - } - responseCh <- acceptResponse{p, err} - closed = err == ErrPipeListenerClosed - } - } - syscall.Close(l.firstHandle) - l.firstHandle = 0 - // Notify Close() and Accept() callers that the handle has been closed. - close(l.doneCh) -} - -// PipeConfig contain configuration for the pipe listener. -type PipeConfig struct { - // SecurityDescriptor contains a Windows security descriptor in SDDL format. - SecurityDescriptor string - - // MessageMode determines whether the pipe is in byte or message mode. In either - // case the pipe is read in byte mode by default. The only practical difference in - // this implementation is that CloseWrite() is only supported for message mode pipes; - // CloseWrite() is implemented as a zero-byte write, but zero-byte writes are only - // transferred to the reader (and returned as io.EOF in this implementation) - // when the pipe is in message mode. - MessageMode bool - - // InputBufferSize specifies the size of the input buffer, in bytes. - InputBufferSize int32 - - // OutputBufferSize specifies the size of the output buffer, in bytes. - OutputBufferSize int32 -} - -// ListenPipe creates a listener on a Windows named pipe path, e.g. \\.\pipe\mypipe. -// The pipe must not already exist. -func ListenPipe(path string, c *PipeConfig) (net.Listener, error) { - var ( - sd []byte - err error - ) - if c == nil { - c = &PipeConfig{} - } - if c.SecurityDescriptor != "" { - sd, err = SddlToSecurityDescriptor(c.SecurityDescriptor) - if err != nil { - return nil, err - } - } - h, err := makeServerPipeHandle(path, sd, c, true) - if err != nil { - return nil, err - } - l := &win32PipeListener{ - firstHandle: h, - path: path, - config: *c, - acceptCh: make(chan (chan acceptResponse)), - closeCh: make(chan int), - doneCh: make(chan int), - } - go l.listenerRoutine() - return l, nil -} - -func connectPipe(p *win32File) error { - c, err := p.prepareIo() - if err != nil { - return err - } - defer p.wg.Done() - - err = connectNamedPipe(p.handle, &c.o) - _, err = p.asyncIo(c, nil, 0, err) - if err != nil && err != cERROR_PIPE_CONNECTED { - return err - } - return nil -} - -func (l *win32PipeListener) Accept() (net.Conn, error) { - ch := make(chan acceptResponse) - select { - case l.acceptCh <- ch: - response := <-ch - err := response.err - if err != nil { - return nil, err - } - if l.config.MessageMode { - return &win32MessageBytePipe{ - win32Pipe: win32Pipe{win32File: response.f, path: l.path}, - }, nil - } - return &win32Pipe{win32File: response.f, path: l.path}, nil - case <-l.doneCh: - return nil, ErrPipeListenerClosed - } -} - -func (l *win32PipeListener) Close() error { - select { - case l.closeCh <- 1: - <-l.doneCh - case <-l.doneCh: - } - return nil -} - -func (l *win32PipeListener) Addr() net.Addr { - return pipeAddress(l.path) -} diff --git a/vendor/github.com/Microsoft/go-winio/pkg/guid/guid.go b/vendor/github.com/Microsoft/go-winio/pkg/guid/guid.go deleted file mode 100644 index 58640657..00000000 --- a/vendor/github.com/Microsoft/go-winio/pkg/guid/guid.go +++ /dev/null @@ -1,235 +0,0 @@ -// Package guid provides a GUID type. The backing structure for a GUID is -// identical to that used by the golang.org/x/sys/windows GUID type. -// There are two main binary encodings used for a GUID, the big-endian encoding, -// and the Windows (mixed-endian) encoding. See here for details: -// https://en.wikipedia.org/wiki/Universally_unique_identifier#Encoding -package guid - -import ( - "crypto/rand" - "crypto/sha1" - "encoding" - "encoding/binary" - "fmt" - "strconv" - - "golang.org/x/sys/windows" -) - -// Variant specifies which GUID variant (or "type") of the GUID. It determines -// how the entirety of the rest of the GUID is interpreted. -type Variant uint8 - -// The variants specified by RFC 4122. -const ( - // VariantUnknown specifies a GUID variant which does not conform to one of - // the variant encodings specified in RFC 4122. - VariantUnknown Variant = iota - VariantNCS - VariantRFC4122 - VariantMicrosoft - VariantFuture -) - -// Version specifies how the bits in the GUID were generated. For instance, a -// version 4 GUID is randomly generated, and a version 5 is generated from the -// hash of an input string. -type Version uint8 - -var _ = (encoding.TextMarshaler)(GUID{}) -var _ = (encoding.TextUnmarshaler)(&GUID{}) - -// GUID represents a GUID/UUID. It has the same structure as -// golang.org/x/sys/windows.GUID so that it can be used with functions expecting -// that type. It is defined as its own type so that stringification and -// marshaling can be supported. The representation matches that used by native -// Windows code. -type GUID windows.GUID - -// NewV4 returns a new version 4 (pseudorandom) GUID, as defined by RFC 4122. -func NewV4() (GUID, error) { - var b [16]byte - if _, err := rand.Read(b[:]); err != nil { - return GUID{}, err - } - - g := FromArray(b) - g.setVersion(4) // Version 4 means randomly generated. - g.setVariant(VariantRFC4122) - - return g, nil -} - -// NewV5 returns a new version 5 (generated from a string via SHA-1 hashing) -// GUID, as defined by RFC 4122. The RFC is unclear on the encoding of the name, -// and the sample code treats it as a series of bytes, so we do the same here. -// -// Some implementations, such as those found on Windows, treat the name as a -// big-endian UTF16 stream of bytes. If that is desired, the string can be -// encoded as such before being passed to this function. -func NewV5(namespace GUID, name []byte) (GUID, error) { - b := sha1.New() - namespaceBytes := namespace.ToArray() - b.Write(namespaceBytes[:]) - b.Write(name) - - a := [16]byte{} - copy(a[:], b.Sum(nil)) - - g := FromArray(a) - g.setVersion(5) // Version 5 means generated from a string. - g.setVariant(VariantRFC4122) - - return g, nil -} - -func fromArray(b [16]byte, order binary.ByteOrder) GUID { - var g GUID - g.Data1 = order.Uint32(b[0:4]) - g.Data2 = order.Uint16(b[4:6]) - g.Data3 = order.Uint16(b[6:8]) - copy(g.Data4[:], b[8:16]) - return g -} - -func (g GUID) toArray(order binary.ByteOrder) [16]byte { - b := [16]byte{} - order.PutUint32(b[0:4], g.Data1) - order.PutUint16(b[4:6], g.Data2) - order.PutUint16(b[6:8], g.Data3) - copy(b[8:16], g.Data4[:]) - return b -} - -// FromArray constructs a GUID from a big-endian encoding array of 16 bytes. -func FromArray(b [16]byte) GUID { - return fromArray(b, binary.BigEndian) -} - -// ToArray returns an array of 16 bytes representing the GUID in big-endian -// encoding. -func (g GUID) ToArray() [16]byte { - return g.toArray(binary.BigEndian) -} - -// FromWindowsArray constructs a GUID from a Windows encoding array of bytes. -func FromWindowsArray(b [16]byte) GUID { - return fromArray(b, binary.LittleEndian) -} - -// ToWindowsArray returns an array of 16 bytes representing the GUID in Windows -// encoding. -func (g GUID) ToWindowsArray() [16]byte { - return g.toArray(binary.LittleEndian) -} - -func (g GUID) String() string { - return fmt.Sprintf( - "%08x-%04x-%04x-%04x-%012x", - g.Data1, - g.Data2, - g.Data3, - g.Data4[:2], - g.Data4[2:]) -} - -// FromString parses a string containing a GUID and returns the GUID. The only -// format currently supported is the `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` -// format. -func FromString(s string) (GUID, error) { - if len(s) != 36 { - return GUID{}, fmt.Errorf("invalid GUID %q", s) - } - if s[8] != '-' || s[13] != '-' || s[18] != '-' || s[23] != '-' { - return GUID{}, fmt.Errorf("invalid GUID %q", s) - } - - var g GUID - - data1, err := strconv.ParseUint(s[0:8], 16, 32) - if err != nil { - return GUID{}, fmt.Errorf("invalid GUID %q", s) - } - g.Data1 = uint32(data1) - - data2, err := strconv.ParseUint(s[9:13], 16, 16) - if err != nil { - return GUID{}, fmt.Errorf("invalid GUID %q", s) - } - g.Data2 = uint16(data2) - - data3, err := strconv.ParseUint(s[14:18], 16, 16) - if err != nil { - return GUID{}, fmt.Errorf("invalid GUID %q", s) - } - g.Data3 = uint16(data3) - - for i, x := range []int{19, 21, 24, 26, 28, 30, 32, 34} { - v, err := strconv.ParseUint(s[x:x+2], 16, 8) - if err != nil { - return GUID{}, fmt.Errorf("invalid GUID %q", s) - } - g.Data4[i] = uint8(v) - } - - return g, nil -} - -func (g *GUID) setVariant(v Variant) { - d := g.Data4[0] - switch v { - case VariantNCS: - d = (d & 0x7f) - case VariantRFC4122: - d = (d & 0x3f) | 0x80 - case VariantMicrosoft: - d = (d & 0x1f) | 0xc0 - case VariantFuture: - d = (d & 0x0f) | 0xe0 - case VariantUnknown: - fallthrough - default: - panic(fmt.Sprintf("invalid variant: %d", v)) - } - g.Data4[0] = d -} - -// Variant returns the GUID variant, as defined in RFC 4122. -func (g GUID) Variant() Variant { - b := g.Data4[0] - if b&0x80 == 0 { - return VariantNCS - } else if b&0xc0 == 0x80 { - return VariantRFC4122 - } else if b&0xe0 == 0xc0 { - return VariantMicrosoft - } else if b&0xe0 == 0xe0 { - return VariantFuture - } - return VariantUnknown -} - -func (g *GUID) setVersion(v Version) { - g.Data3 = (g.Data3 & 0x0fff) | (uint16(v) << 12) -} - -// Version returns the GUID version, as defined in RFC 4122. -func (g GUID) Version() Version { - return Version((g.Data3 & 0xF000) >> 12) -} - -// MarshalText returns the textual representation of the GUID. -func (g GUID) MarshalText() ([]byte, error) { - return []byte(g.String()), nil -} - -// UnmarshalText takes the textual representation of a GUID, and unmarhals it -// into this GUID. -func (g *GUID) UnmarshalText(text []byte) error { - g2, err := FromString(string(text)) - if err != nil { - return err - } - *g = g2 - return nil -} diff --git a/vendor/github.com/Microsoft/go-winio/privilege.go b/vendor/github.com/Microsoft/go-winio/privilege.go deleted file mode 100644 index 9c83d36f..00000000 --- a/vendor/github.com/Microsoft/go-winio/privilege.go +++ /dev/null @@ -1,202 +0,0 @@ -// +build windows - -package winio - -import ( - "bytes" - "encoding/binary" - "fmt" - "runtime" - "sync" - "syscall" - "unicode/utf16" - - "golang.org/x/sys/windows" -) - -//sys adjustTokenPrivileges(token windows.Token, releaseAll bool, input *byte, outputSize uint32, output *byte, requiredSize *uint32) (success bool, err error) [true] = advapi32.AdjustTokenPrivileges -//sys impersonateSelf(level uint32) (err error) = advapi32.ImpersonateSelf -//sys revertToSelf() (err error) = advapi32.RevertToSelf -//sys openThreadToken(thread syscall.Handle, accessMask uint32, openAsSelf bool, token *windows.Token) (err error) = advapi32.OpenThreadToken -//sys getCurrentThread() (h syscall.Handle) = GetCurrentThread -//sys lookupPrivilegeValue(systemName string, name string, luid *uint64) (err error) = advapi32.LookupPrivilegeValueW -//sys lookupPrivilegeName(systemName string, luid *uint64, buffer *uint16, size *uint32) (err error) = advapi32.LookupPrivilegeNameW -//sys lookupPrivilegeDisplayName(systemName string, name *uint16, buffer *uint16, size *uint32, languageId *uint32) (err error) = advapi32.LookupPrivilegeDisplayNameW - -const ( - SE_PRIVILEGE_ENABLED = 2 - - ERROR_NOT_ALL_ASSIGNED syscall.Errno = 1300 - - SeBackupPrivilege = "SeBackupPrivilege" - SeRestorePrivilege = "SeRestorePrivilege" -) - -const ( - securityAnonymous = iota - securityIdentification - securityImpersonation - securityDelegation -) - -var ( - privNames = make(map[string]uint64) - privNameMutex sync.Mutex -) - -// PrivilegeError represents an error enabling privileges. -type PrivilegeError struct { - privileges []uint64 -} - -func (e *PrivilegeError) Error() string { - s := "" - if len(e.privileges) > 1 { - s = "Could not enable privileges " - } else { - s = "Could not enable privilege " - } - for i, p := range e.privileges { - if i != 0 { - s += ", " - } - s += `"` - s += getPrivilegeName(p) - s += `"` - } - return s -} - -// RunWithPrivilege enables a single privilege for a function call. -func RunWithPrivilege(name string, fn func() error) error { - return RunWithPrivileges([]string{name}, fn) -} - -// RunWithPrivileges enables privileges for a function call. -func RunWithPrivileges(names []string, fn func() error) error { - privileges, err := mapPrivileges(names) - if err != nil { - return err - } - runtime.LockOSThread() - defer runtime.UnlockOSThread() - token, err := newThreadToken() - if err != nil { - return err - } - defer releaseThreadToken(token) - err = adjustPrivileges(token, privileges, SE_PRIVILEGE_ENABLED) - if err != nil { - return err - } - return fn() -} - -func mapPrivileges(names []string) ([]uint64, error) { - var privileges []uint64 - privNameMutex.Lock() - defer privNameMutex.Unlock() - for _, name := range names { - p, ok := privNames[name] - if !ok { - err := lookupPrivilegeValue("", name, &p) - if err != nil { - return nil, err - } - privNames[name] = p - } - privileges = append(privileges, p) - } - return privileges, nil -} - -// EnableProcessPrivileges enables privileges globally for the process. -func EnableProcessPrivileges(names []string) error { - return enableDisableProcessPrivilege(names, SE_PRIVILEGE_ENABLED) -} - -// DisableProcessPrivileges disables privileges globally for the process. -func DisableProcessPrivileges(names []string) error { - return enableDisableProcessPrivilege(names, 0) -} - -func enableDisableProcessPrivilege(names []string, action uint32) error { - privileges, err := mapPrivileges(names) - if err != nil { - return err - } - - p, _ := windows.GetCurrentProcess() - var token windows.Token - err = windows.OpenProcessToken(p, windows.TOKEN_ADJUST_PRIVILEGES|windows.TOKEN_QUERY, &token) - if err != nil { - return err - } - - defer token.Close() - return adjustPrivileges(token, privileges, action) -} - -func adjustPrivileges(token windows.Token, privileges []uint64, action uint32) error { - var b bytes.Buffer - binary.Write(&b, binary.LittleEndian, uint32(len(privileges))) - for _, p := range privileges { - binary.Write(&b, binary.LittleEndian, p) - binary.Write(&b, binary.LittleEndian, action) - } - prevState := make([]byte, b.Len()) - reqSize := uint32(0) - success, err := adjustTokenPrivileges(token, false, &b.Bytes()[0], uint32(len(prevState)), &prevState[0], &reqSize) - if !success { - return err - } - if err == ERROR_NOT_ALL_ASSIGNED { - return &PrivilegeError{privileges} - } - return nil -} - -func getPrivilegeName(luid uint64) string { - var nameBuffer [256]uint16 - bufSize := uint32(len(nameBuffer)) - err := lookupPrivilegeName("", &luid, &nameBuffer[0], &bufSize) - if err != nil { - return fmt.Sprintf("", luid) - } - - var displayNameBuffer [256]uint16 - displayBufSize := uint32(len(displayNameBuffer)) - var langID uint32 - err = lookupPrivilegeDisplayName("", &nameBuffer[0], &displayNameBuffer[0], &displayBufSize, &langID) - if err != nil { - return fmt.Sprintf("", string(utf16.Decode(nameBuffer[:bufSize]))) - } - - return string(utf16.Decode(displayNameBuffer[:displayBufSize])) -} - -func newThreadToken() (windows.Token, error) { - err := impersonateSelf(securityImpersonation) - if err != nil { - return 0, err - } - - var token windows.Token - err = openThreadToken(getCurrentThread(), syscall.TOKEN_ADJUST_PRIVILEGES|syscall.TOKEN_QUERY, false, &token) - if err != nil { - rerr := revertToSelf() - if rerr != nil { - panic(rerr) - } - return 0, err - } - return token, nil -} - -func releaseThreadToken(h windows.Token) { - err := revertToSelf() - if err != nil { - panic(err) - } - h.Close() -} diff --git a/vendor/github.com/Microsoft/go-winio/reparse.go b/vendor/github.com/Microsoft/go-winio/reparse.go deleted file mode 100644 index fc1ee4d3..00000000 --- a/vendor/github.com/Microsoft/go-winio/reparse.go +++ /dev/null @@ -1,128 +0,0 @@ -package winio - -import ( - "bytes" - "encoding/binary" - "fmt" - "strings" - "unicode/utf16" - "unsafe" -) - -const ( - reparseTagMountPoint = 0xA0000003 - reparseTagSymlink = 0xA000000C -) - -type reparseDataBuffer struct { - ReparseTag uint32 - ReparseDataLength uint16 - Reserved uint16 - SubstituteNameOffset uint16 - SubstituteNameLength uint16 - PrintNameOffset uint16 - PrintNameLength uint16 -} - -// ReparsePoint describes a Win32 symlink or mount point. -type ReparsePoint struct { - Target string - IsMountPoint bool -} - -// UnsupportedReparsePointError is returned when trying to decode a non-symlink or -// mount point reparse point. -type UnsupportedReparsePointError struct { - Tag uint32 -} - -func (e *UnsupportedReparsePointError) Error() string { - return fmt.Sprintf("unsupported reparse point %x", e.Tag) -} - -// DecodeReparsePoint decodes a Win32 REPARSE_DATA_BUFFER structure containing either a symlink -// or a mount point. -func DecodeReparsePoint(b []byte) (*ReparsePoint, error) { - tag := binary.LittleEndian.Uint32(b[0:4]) - return DecodeReparsePointData(tag, b[8:]) -} - -func DecodeReparsePointData(tag uint32, b []byte) (*ReparsePoint, error) { - isMountPoint := false - switch tag { - case reparseTagMountPoint: - isMountPoint = true - case reparseTagSymlink: - default: - return nil, &UnsupportedReparsePointError{tag} - } - nameOffset := 8 + binary.LittleEndian.Uint16(b[4:6]) - if !isMountPoint { - nameOffset += 4 - } - nameLength := binary.LittleEndian.Uint16(b[6:8]) - name := make([]uint16, nameLength/2) - err := binary.Read(bytes.NewReader(b[nameOffset:nameOffset+nameLength]), binary.LittleEndian, &name) - if err != nil { - return nil, err - } - return &ReparsePoint{string(utf16.Decode(name)), isMountPoint}, nil -} - -func isDriveLetter(c byte) bool { - return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') -} - -// EncodeReparsePoint encodes a Win32 REPARSE_DATA_BUFFER structure describing a symlink or -// mount point. -func EncodeReparsePoint(rp *ReparsePoint) []byte { - // Generate an NT path and determine if this is a relative path. - var ntTarget string - relative := false - if strings.HasPrefix(rp.Target, `\\?\`) { - ntTarget = `\??\` + rp.Target[4:] - } else if strings.HasPrefix(rp.Target, `\\`) { - ntTarget = `\??\UNC\` + rp.Target[2:] - } else if len(rp.Target) >= 2 && isDriveLetter(rp.Target[0]) && rp.Target[1] == ':' { - ntTarget = `\??\` + rp.Target - } else { - ntTarget = rp.Target - relative = true - } - - // The paths must be NUL-terminated even though they are counted strings. - target16 := utf16.Encode([]rune(rp.Target + "\x00")) - ntTarget16 := utf16.Encode([]rune(ntTarget + "\x00")) - - size := int(unsafe.Sizeof(reparseDataBuffer{})) - 8 - size += len(ntTarget16)*2 + len(target16)*2 - - tag := uint32(reparseTagMountPoint) - if !rp.IsMountPoint { - tag = reparseTagSymlink - size += 4 // Add room for symlink flags - } - - data := reparseDataBuffer{ - ReparseTag: tag, - ReparseDataLength: uint16(size), - SubstituteNameOffset: 0, - SubstituteNameLength: uint16((len(ntTarget16) - 1) * 2), - PrintNameOffset: uint16(len(ntTarget16) * 2), - PrintNameLength: uint16((len(target16) - 1) * 2), - } - - var b bytes.Buffer - binary.Write(&b, binary.LittleEndian, &data) - if !rp.IsMountPoint { - flags := uint32(0) - if relative { - flags |= 1 - } - binary.Write(&b, binary.LittleEndian, flags) - } - - binary.Write(&b, binary.LittleEndian, ntTarget16) - binary.Write(&b, binary.LittleEndian, target16) - return b.Bytes() -} diff --git a/vendor/github.com/Microsoft/go-winio/sd.go b/vendor/github.com/Microsoft/go-winio/sd.go deleted file mode 100644 index db1b370a..00000000 --- a/vendor/github.com/Microsoft/go-winio/sd.go +++ /dev/null @@ -1,98 +0,0 @@ -// +build windows - -package winio - -import ( - "syscall" - "unsafe" -) - -//sys lookupAccountName(systemName *uint16, accountName string, sid *byte, sidSize *uint32, refDomain *uint16, refDomainSize *uint32, sidNameUse *uint32) (err error) = advapi32.LookupAccountNameW -//sys convertSidToStringSid(sid *byte, str **uint16) (err error) = advapi32.ConvertSidToStringSidW -//sys convertStringSecurityDescriptorToSecurityDescriptor(str string, revision uint32, sd *uintptr, size *uint32) (err error) = advapi32.ConvertStringSecurityDescriptorToSecurityDescriptorW -//sys convertSecurityDescriptorToStringSecurityDescriptor(sd *byte, revision uint32, secInfo uint32, sddl **uint16, sddlSize *uint32) (err error) = advapi32.ConvertSecurityDescriptorToStringSecurityDescriptorW -//sys localFree(mem uintptr) = LocalFree -//sys getSecurityDescriptorLength(sd uintptr) (len uint32) = advapi32.GetSecurityDescriptorLength - -const ( - cERROR_NONE_MAPPED = syscall.Errno(1332) -) - -type AccountLookupError struct { - Name string - Err error -} - -func (e *AccountLookupError) Error() string { - if e.Name == "" { - return "lookup account: empty account name specified" - } - var s string - switch e.Err { - case cERROR_NONE_MAPPED: - s = "not found" - default: - s = e.Err.Error() - } - return "lookup account " + e.Name + ": " + s -} - -type SddlConversionError struct { - Sddl string - Err error -} - -func (e *SddlConversionError) Error() string { - return "convert " + e.Sddl + ": " + e.Err.Error() -} - -// LookupSidByName looks up the SID of an account by name -func LookupSidByName(name string) (sid string, err error) { - if name == "" { - return "", &AccountLookupError{name, cERROR_NONE_MAPPED} - } - - var sidSize, sidNameUse, refDomainSize uint32 - err = lookupAccountName(nil, name, nil, &sidSize, nil, &refDomainSize, &sidNameUse) - if err != nil && err != syscall.ERROR_INSUFFICIENT_BUFFER { - return "", &AccountLookupError{name, err} - } - sidBuffer := make([]byte, sidSize) - refDomainBuffer := make([]uint16, refDomainSize) - err = lookupAccountName(nil, name, &sidBuffer[0], &sidSize, &refDomainBuffer[0], &refDomainSize, &sidNameUse) - if err != nil { - return "", &AccountLookupError{name, err} - } - var strBuffer *uint16 - err = convertSidToStringSid(&sidBuffer[0], &strBuffer) - if err != nil { - return "", &AccountLookupError{name, err} - } - sid = syscall.UTF16ToString((*[0xffff]uint16)(unsafe.Pointer(strBuffer))[:]) - localFree(uintptr(unsafe.Pointer(strBuffer))) - return sid, nil -} - -func SddlToSecurityDescriptor(sddl string) ([]byte, error) { - var sdBuffer uintptr - err := convertStringSecurityDescriptorToSecurityDescriptor(sddl, 1, &sdBuffer, nil) - if err != nil { - return nil, &SddlConversionError{sddl, err} - } - defer localFree(sdBuffer) - sd := make([]byte, getSecurityDescriptorLength(sdBuffer)) - copy(sd, (*[0xffff]byte)(unsafe.Pointer(sdBuffer))[:len(sd)]) - return sd, nil -} - -func SecurityDescriptorToSddl(sd []byte) (string, error) { - var sddl *uint16 - // The returned string length seems to including an aribtrary number of terminating NULs. - // Don't use it. - err := convertSecurityDescriptorToStringSecurityDescriptor(&sd[0], 1, 0xff, &sddl, nil) - if err != nil { - return "", err - } - defer localFree(uintptr(unsafe.Pointer(sddl))) - return syscall.UTF16ToString((*[0xffff]uint16)(unsafe.Pointer(sddl))[:]), nil -} diff --git a/vendor/github.com/Microsoft/go-winio/syscall.go b/vendor/github.com/Microsoft/go-winio/syscall.go deleted file mode 100644 index 5cb52bc7..00000000 --- a/vendor/github.com/Microsoft/go-winio/syscall.go +++ /dev/null @@ -1,3 +0,0 @@ -package winio - -//go:generate go run $GOROOT/src/syscall/mksyscall_windows.go -output zsyscall_windows.go file.go pipe.go sd.go fileinfo.go privilege.go backup.go hvsock.go diff --git a/vendor/github.com/Microsoft/go-winio/zsyscall_windows.go b/vendor/github.com/Microsoft/go-winio/zsyscall_windows.go deleted file mode 100644 index e26b01fa..00000000 --- a/vendor/github.com/Microsoft/go-winio/zsyscall_windows.go +++ /dev/null @@ -1,562 +0,0 @@ -// Code generated by 'go generate'; DO NOT EDIT. - -package winio - -import ( - "syscall" - "unsafe" - - "golang.org/x/sys/windows" -) - -var _ unsafe.Pointer - -// Do the interface allocations only once for common -// Errno values. -const ( - errnoERROR_IO_PENDING = 997 -) - -var ( - errERROR_IO_PENDING error = syscall.Errno(errnoERROR_IO_PENDING) -) - -// errnoErr returns common boxed Errno values, to prevent -// allocations at runtime. -func errnoErr(e syscall.Errno) error { - switch e { - case 0: - return nil - case errnoERROR_IO_PENDING: - return errERROR_IO_PENDING - } - // TODO: add more here, after collecting data on the common - // error values see on Windows. (perhaps when running - // all.bat?) - return e -} - -var ( - modkernel32 = windows.NewLazySystemDLL("kernel32.dll") - modws2_32 = windows.NewLazySystemDLL("ws2_32.dll") - modntdll = windows.NewLazySystemDLL("ntdll.dll") - modadvapi32 = windows.NewLazySystemDLL("advapi32.dll") - - procCancelIoEx = modkernel32.NewProc("CancelIoEx") - procCreateIoCompletionPort = modkernel32.NewProc("CreateIoCompletionPort") - procGetQueuedCompletionStatus = modkernel32.NewProc("GetQueuedCompletionStatus") - procSetFileCompletionNotificationModes = modkernel32.NewProc("SetFileCompletionNotificationModes") - procWSAGetOverlappedResult = modws2_32.NewProc("WSAGetOverlappedResult") - procConnectNamedPipe = modkernel32.NewProc("ConnectNamedPipe") - procCreateNamedPipeW = modkernel32.NewProc("CreateNamedPipeW") - procCreateFileW = modkernel32.NewProc("CreateFileW") - procGetNamedPipeInfo = modkernel32.NewProc("GetNamedPipeInfo") - procGetNamedPipeHandleStateW = modkernel32.NewProc("GetNamedPipeHandleStateW") - procLocalAlloc = modkernel32.NewProc("LocalAlloc") - procNtCreateNamedPipeFile = modntdll.NewProc("NtCreateNamedPipeFile") - procRtlNtStatusToDosErrorNoTeb = modntdll.NewProc("RtlNtStatusToDosErrorNoTeb") - procRtlDosPathNameToNtPathName_U = modntdll.NewProc("RtlDosPathNameToNtPathName_U") - procRtlDefaultNpAcl = modntdll.NewProc("RtlDefaultNpAcl") - procLookupAccountNameW = modadvapi32.NewProc("LookupAccountNameW") - procConvertSidToStringSidW = modadvapi32.NewProc("ConvertSidToStringSidW") - procConvertStringSecurityDescriptorToSecurityDescriptorW = modadvapi32.NewProc("ConvertStringSecurityDescriptorToSecurityDescriptorW") - procConvertSecurityDescriptorToStringSecurityDescriptorW = modadvapi32.NewProc("ConvertSecurityDescriptorToStringSecurityDescriptorW") - procLocalFree = modkernel32.NewProc("LocalFree") - procGetSecurityDescriptorLength = modadvapi32.NewProc("GetSecurityDescriptorLength") - procGetFileInformationByHandleEx = modkernel32.NewProc("GetFileInformationByHandleEx") - procSetFileInformationByHandle = modkernel32.NewProc("SetFileInformationByHandle") - procAdjustTokenPrivileges = modadvapi32.NewProc("AdjustTokenPrivileges") - procImpersonateSelf = modadvapi32.NewProc("ImpersonateSelf") - procRevertToSelf = modadvapi32.NewProc("RevertToSelf") - procOpenThreadToken = modadvapi32.NewProc("OpenThreadToken") - procGetCurrentThread = modkernel32.NewProc("GetCurrentThread") - procLookupPrivilegeValueW = modadvapi32.NewProc("LookupPrivilegeValueW") - procLookupPrivilegeNameW = modadvapi32.NewProc("LookupPrivilegeNameW") - procLookupPrivilegeDisplayNameW = modadvapi32.NewProc("LookupPrivilegeDisplayNameW") - procBackupRead = modkernel32.NewProc("BackupRead") - procBackupWrite = modkernel32.NewProc("BackupWrite") - procbind = modws2_32.NewProc("bind") -) - -func cancelIoEx(file syscall.Handle, o *syscall.Overlapped) (err error) { - r1, _, e1 := syscall.Syscall(procCancelIoEx.Addr(), 2, uintptr(file), uintptr(unsafe.Pointer(o)), 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func createIoCompletionPort(file syscall.Handle, port syscall.Handle, key uintptr, threadCount uint32) (newport syscall.Handle, err error) { - r0, _, e1 := syscall.Syscall6(procCreateIoCompletionPort.Addr(), 4, uintptr(file), uintptr(port), uintptr(key), uintptr(threadCount), 0, 0) - newport = syscall.Handle(r0) - if newport == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func getQueuedCompletionStatus(port syscall.Handle, bytes *uint32, key *uintptr, o **ioOperation, timeout uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procGetQueuedCompletionStatus.Addr(), 5, uintptr(port), uintptr(unsafe.Pointer(bytes)), uintptr(unsafe.Pointer(key)), uintptr(unsafe.Pointer(o)), uintptr(timeout), 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func setFileCompletionNotificationModes(h syscall.Handle, flags uint8) (err error) { - r1, _, e1 := syscall.Syscall(procSetFileCompletionNotificationModes.Addr(), 2, uintptr(h), uintptr(flags), 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func wsaGetOverlappedResult(h syscall.Handle, o *syscall.Overlapped, bytes *uint32, wait bool, flags *uint32) (err error) { - var _p0 uint32 - if wait { - _p0 = 1 - } else { - _p0 = 0 - } - r1, _, e1 := syscall.Syscall6(procWSAGetOverlappedResult.Addr(), 5, uintptr(h), uintptr(unsafe.Pointer(o)), uintptr(unsafe.Pointer(bytes)), uintptr(_p0), uintptr(unsafe.Pointer(flags)), 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func connectNamedPipe(pipe syscall.Handle, o *syscall.Overlapped) (err error) { - r1, _, e1 := syscall.Syscall(procConnectNamedPipe.Addr(), 2, uintptr(pipe), uintptr(unsafe.Pointer(o)), 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func createNamedPipe(name string, flags uint32, pipeMode uint32, maxInstances uint32, outSize uint32, inSize uint32, defaultTimeout uint32, sa *syscall.SecurityAttributes) (handle syscall.Handle, err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(name) - if err != nil { - return - } - return _createNamedPipe(_p0, flags, pipeMode, maxInstances, outSize, inSize, defaultTimeout, sa) -} - -func _createNamedPipe(name *uint16, flags uint32, pipeMode uint32, maxInstances uint32, outSize uint32, inSize uint32, defaultTimeout uint32, sa *syscall.SecurityAttributes) (handle syscall.Handle, err error) { - r0, _, e1 := syscall.Syscall9(procCreateNamedPipeW.Addr(), 8, uintptr(unsafe.Pointer(name)), uintptr(flags), uintptr(pipeMode), uintptr(maxInstances), uintptr(outSize), uintptr(inSize), uintptr(defaultTimeout), uintptr(unsafe.Pointer(sa)), 0) - handle = syscall.Handle(r0) - if handle == syscall.InvalidHandle { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func createFile(name string, access uint32, mode uint32, sa *syscall.SecurityAttributes, createmode uint32, attrs uint32, templatefile syscall.Handle) (handle syscall.Handle, err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(name) - if err != nil { - return - } - return _createFile(_p0, access, mode, sa, createmode, attrs, templatefile) -} - -func _createFile(name *uint16, access uint32, mode uint32, sa *syscall.SecurityAttributes, createmode uint32, attrs uint32, templatefile syscall.Handle) (handle syscall.Handle, err error) { - r0, _, e1 := syscall.Syscall9(procCreateFileW.Addr(), 7, uintptr(unsafe.Pointer(name)), uintptr(access), uintptr(mode), uintptr(unsafe.Pointer(sa)), uintptr(createmode), uintptr(attrs), uintptr(templatefile), 0, 0) - handle = syscall.Handle(r0) - if handle == syscall.InvalidHandle { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func getNamedPipeInfo(pipe syscall.Handle, flags *uint32, outSize *uint32, inSize *uint32, maxInstances *uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procGetNamedPipeInfo.Addr(), 5, uintptr(pipe), uintptr(unsafe.Pointer(flags)), uintptr(unsafe.Pointer(outSize)), uintptr(unsafe.Pointer(inSize)), uintptr(unsafe.Pointer(maxInstances)), 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func getNamedPipeHandleState(pipe syscall.Handle, state *uint32, curInstances *uint32, maxCollectionCount *uint32, collectDataTimeout *uint32, userName *uint16, maxUserNameSize uint32) (err error) { - r1, _, e1 := syscall.Syscall9(procGetNamedPipeHandleStateW.Addr(), 7, uintptr(pipe), uintptr(unsafe.Pointer(state)), uintptr(unsafe.Pointer(curInstances)), uintptr(unsafe.Pointer(maxCollectionCount)), uintptr(unsafe.Pointer(collectDataTimeout)), uintptr(unsafe.Pointer(userName)), uintptr(maxUserNameSize), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func localAlloc(uFlags uint32, length uint32) (ptr uintptr) { - r0, _, _ := syscall.Syscall(procLocalAlloc.Addr(), 2, uintptr(uFlags), uintptr(length), 0) - ptr = uintptr(r0) - return -} - -func ntCreateNamedPipeFile(pipe *syscall.Handle, access uint32, oa *objectAttributes, iosb *ioStatusBlock, share uint32, disposition uint32, options uint32, typ uint32, readMode uint32, completionMode uint32, maxInstances uint32, inboundQuota uint32, outputQuota uint32, timeout *int64) (status ntstatus) { - r0, _, _ := syscall.Syscall15(procNtCreateNamedPipeFile.Addr(), 14, uintptr(unsafe.Pointer(pipe)), uintptr(access), uintptr(unsafe.Pointer(oa)), uintptr(unsafe.Pointer(iosb)), uintptr(share), uintptr(disposition), uintptr(options), uintptr(typ), uintptr(readMode), uintptr(completionMode), uintptr(maxInstances), uintptr(inboundQuota), uintptr(outputQuota), uintptr(unsafe.Pointer(timeout)), 0) - status = ntstatus(r0) - return -} - -func rtlNtStatusToDosError(status ntstatus) (winerr error) { - r0, _, _ := syscall.Syscall(procRtlNtStatusToDosErrorNoTeb.Addr(), 1, uintptr(status), 0, 0) - if r0 != 0 { - winerr = syscall.Errno(r0) - } - return -} - -func rtlDosPathNameToNtPathName(name *uint16, ntName *unicodeString, filePart uintptr, reserved uintptr) (status ntstatus) { - r0, _, _ := syscall.Syscall6(procRtlDosPathNameToNtPathName_U.Addr(), 4, uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(ntName)), uintptr(filePart), uintptr(reserved), 0, 0) - status = ntstatus(r0) - return -} - -func rtlDefaultNpAcl(dacl *uintptr) (status ntstatus) { - r0, _, _ := syscall.Syscall(procRtlDefaultNpAcl.Addr(), 1, uintptr(unsafe.Pointer(dacl)), 0, 0) - status = ntstatus(r0) - return -} - -func lookupAccountName(systemName *uint16, accountName string, sid *byte, sidSize *uint32, refDomain *uint16, refDomainSize *uint32, sidNameUse *uint32) (err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(accountName) - if err != nil { - return - } - return _lookupAccountName(systemName, _p0, sid, sidSize, refDomain, refDomainSize, sidNameUse) -} - -func _lookupAccountName(systemName *uint16, accountName *uint16, sid *byte, sidSize *uint32, refDomain *uint16, refDomainSize *uint32, sidNameUse *uint32) (err error) { - r1, _, e1 := syscall.Syscall9(procLookupAccountNameW.Addr(), 7, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(accountName)), uintptr(unsafe.Pointer(sid)), uintptr(unsafe.Pointer(sidSize)), uintptr(unsafe.Pointer(refDomain)), uintptr(unsafe.Pointer(refDomainSize)), uintptr(unsafe.Pointer(sidNameUse)), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func convertSidToStringSid(sid *byte, str **uint16) (err error) { - r1, _, e1 := syscall.Syscall(procConvertSidToStringSidW.Addr(), 2, uintptr(unsafe.Pointer(sid)), uintptr(unsafe.Pointer(str)), 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func convertStringSecurityDescriptorToSecurityDescriptor(str string, revision uint32, sd *uintptr, size *uint32) (err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(str) - if err != nil { - return - } - return _convertStringSecurityDescriptorToSecurityDescriptor(_p0, revision, sd, size) -} - -func _convertStringSecurityDescriptorToSecurityDescriptor(str *uint16, revision uint32, sd *uintptr, size *uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procConvertStringSecurityDescriptorToSecurityDescriptorW.Addr(), 4, uintptr(unsafe.Pointer(str)), uintptr(revision), uintptr(unsafe.Pointer(sd)), uintptr(unsafe.Pointer(size)), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func convertSecurityDescriptorToStringSecurityDescriptor(sd *byte, revision uint32, secInfo uint32, sddl **uint16, sddlSize *uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procConvertSecurityDescriptorToStringSecurityDescriptorW.Addr(), 5, uintptr(unsafe.Pointer(sd)), uintptr(revision), uintptr(secInfo), uintptr(unsafe.Pointer(sddl)), uintptr(unsafe.Pointer(sddlSize)), 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func localFree(mem uintptr) { - syscall.Syscall(procLocalFree.Addr(), 1, uintptr(mem), 0, 0) - return -} - -func getSecurityDescriptorLength(sd uintptr) (len uint32) { - r0, _, _ := syscall.Syscall(procGetSecurityDescriptorLength.Addr(), 1, uintptr(sd), 0, 0) - len = uint32(r0) - return -} - -func getFileInformationByHandleEx(h syscall.Handle, class uint32, buffer *byte, size uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procGetFileInformationByHandleEx.Addr(), 4, uintptr(h), uintptr(class), uintptr(unsafe.Pointer(buffer)), uintptr(size), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func setFileInformationByHandle(h syscall.Handle, class uint32, buffer *byte, size uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procSetFileInformationByHandle.Addr(), 4, uintptr(h), uintptr(class), uintptr(unsafe.Pointer(buffer)), uintptr(size), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func adjustTokenPrivileges(token windows.Token, releaseAll bool, input *byte, outputSize uint32, output *byte, requiredSize *uint32) (success bool, err error) { - var _p0 uint32 - if releaseAll { - _p0 = 1 - } else { - _p0 = 0 - } - r0, _, e1 := syscall.Syscall6(procAdjustTokenPrivileges.Addr(), 6, uintptr(token), uintptr(_p0), uintptr(unsafe.Pointer(input)), uintptr(outputSize), uintptr(unsafe.Pointer(output)), uintptr(unsafe.Pointer(requiredSize))) - success = r0 != 0 - if true { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func impersonateSelf(level uint32) (err error) { - r1, _, e1 := syscall.Syscall(procImpersonateSelf.Addr(), 1, uintptr(level), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func revertToSelf() (err error) { - r1, _, e1 := syscall.Syscall(procRevertToSelf.Addr(), 0, 0, 0, 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func openThreadToken(thread syscall.Handle, accessMask uint32, openAsSelf bool, token *windows.Token) (err error) { - var _p0 uint32 - if openAsSelf { - _p0 = 1 - } else { - _p0 = 0 - } - r1, _, e1 := syscall.Syscall6(procOpenThreadToken.Addr(), 4, uintptr(thread), uintptr(accessMask), uintptr(_p0), uintptr(unsafe.Pointer(token)), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func getCurrentThread() (h syscall.Handle) { - r0, _, _ := syscall.Syscall(procGetCurrentThread.Addr(), 0, 0, 0, 0) - h = syscall.Handle(r0) - return -} - -func lookupPrivilegeValue(systemName string, name string, luid *uint64) (err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(systemName) - if err != nil { - return - } - var _p1 *uint16 - _p1, err = syscall.UTF16PtrFromString(name) - if err != nil { - return - } - return _lookupPrivilegeValue(_p0, _p1, luid) -} - -func _lookupPrivilegeValue(systemName *uint16, name *uint16, luid *uint64) (err error) { - r1, _, e1 := syscall.Syscall(procLookupPrivilegeValueW.Addr(), 3, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(luid))) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func lookupPrivilegeName(systemName string, luid *uint64, buffer *uint16, size *uint32) (err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(systemName) - if err != nil { - return - } - return _lookupPrivilegeName(_p0, luid, buffer, size) -} - -func _lookupPrivilegeName(systemName *uint16, luid *uint64, buffer *uint16, size *uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procLookupPrivilegeNameW.Addr(), 4, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(luid)), uintptr(unsafe.Pointer(buffer)), uintptr(unsafe.Pointer(size)), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func lookupPrivilegeDisplayName(systemName string, name *uint16, buffer *uint16, size *uint32, languageId *uint32) (err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(systemName) - if err != nil { - return - } - return _lookupPrivilegeDisplayName(_p0, name, buffer, size, languageId) -} - -func _lookupPrivilegeDisplayName(systemName *uint16, name *uint16, buffer *uint16, size *uint32, languageId *uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procLookupPrivilegeDisplayNameW.Addr(), 5, uintptr(unsafe.Pointer(systemName)), uintptr(unsafe.Pointer(name)), uintptr(unsafe.Pointer(buffer)), uintptr(unsafe.Pointer(size)), uintptr(unsafe.Pointer(languageId)), 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func backupRead(h syscall.Handle, b []byte, bytesRead *uint32, abort bool, processSecurity bool, context *uintptr) (err error) { - var _p0 *byte - if len(b) > 0 { - _p0 = &b[0] - } - var _p1 uint32 - if abort { - _p1 = 1 - } else { - _p1 = 0 - } - var _p2 uint32 - if processSecurity { - _p2 = 1 - } else { - _p2 = 0 - } - r1, _, e1 := syscall.Syscall9(procBackupRead.Addr(), 7, uintptr(h), uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), uintptr(unsafe.Pointer(bytesRead)), uintptr(_p1), uintptr(_p2), uintptr(unsafe.Pointer(context)), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func backupWrite(h syscall.Handle, b []byte, bytesWritten *uint32, abort bool, processSecurity bool, context *uintptr) (err error) { - var _p0 *byte - if len(b) > 0 { - _p0 = &b[0] - } - var _p1 uint32 - if abort { - _p1 = 1 - } else { - _p1 = 0 - } - var _p2 uint32 - if processSecurity { - _p2 = 1 - } else { - _p2 = 0 - } - r1, _, e1 := syscall.Syscall9(procBackupWrite.Addr(), 7, uintptr(h), uintptr(unsafe.Pointer(_p0)), uintptr(len(b)), uintptr(unsafe.Pointer(bytesWritten)), uintptr(_p1), uintptr(_p2), uintptr(unsafe.Pointer(context)), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func bind(s syscall.Handle, name unsafe.Pointer, namelen int32) (err error) { - r1, _, e1 := syscall.Syscall(procbind.Addr(), 3, uintptr(s), uintptr(name), uintptr(namelen)) - if r1 == socketError { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} diff --git a/vendor/github.com/emirpasic/gods/LICENSE b/vendor/github.com/emirpasic/gods/LICENSE deleted file mode 100644 index e5e449b6..00000000 --- a/vendor/github.com/emirpasic/gods/LICENSE +++ /dev/null @@ -1,41 +0,0 @@ -Copyright (c) 2015, Emir Pasic -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -------------------------------------------------------------------------------- - -AVL Tree: - -Copyright (c) 2017 Benjamin Scher Purcell - -Permission to use, copy, modify, and distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/vendor/github.com/emirpasic/gods/containers/containers.go b/vendor/github.com/emirpasic/gods/containers/containers.go deleted file mode 100644 index c35ab36d..00000000 --- a/vendor/github.com/emirpasic/gods/containers/containers.go +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) 2015, Emir Pasic. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package containers provides core interfaces and functions for data structures. -// -// Container is the base interface for all data structures to implement. -// -// Iterators provide stateful iterators. -// -// Enumerable provides Ruby inspired (each, select, map, find, any?, etc.) container functions. -// -// Serialization provides serializers (marshalers) and deserializers (unmarshalers). -package containers - -import "github.com/emirpasic/gods/utils" - -// Container is base interface that all data structures implement. -type Container interface { - Empty() bool - Size() int - Clear() - Values() []interface{} -} - -// GetSortedValues returns sorted container's elements with respect to the passed comparator. -// Does not effect the ordering of elements within the container. -func GetSortedValues(container Container, comparator utils.Comparator) []interface{} { - values := container.Values() - if len(values) < 2 { - return values - } - utils.Sort(values, comparator) - return values -} diff --git a/vendor/github.com/emirpasic/gods/containers/enumerable.go b/vendor/github.com/emirpasic/gods/containers/enumerable.go deleted file mode 100644 index ac48b545..00000000 --- a/vendor/github.com/emirpasic/gods/containers/enumerable.go +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) 2015, Emir Pasic. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package containers - -// EnumerableWithIndex provides functions for ordered containers whose values can be fetched by an index. -type EnumerableWithIndex interface { - // Each calls the given function once for each element, passing that element's index and value. - Each(func(index int, value interface{})) - - // Map invokes the given function once for each element and returns a - // container containing the values returned by the given function. - // TODO would appreciate help on how to enforce this in containers (don't want to type assert when chaining) - // Map(func(index int, value interface{}) interface{}) Container - - // Select returns a new container containing all elements for which the given function returns a true value. - // TODO need help on how to enforce this in containers (don't want to type assert when chaining) - // Select(func(index int, value interface{}) bool) Container - - // Any passes each element of the container to the given function and - // returns true if the function ever returns true for any element. - Any(func(index int, value interface{}) bool) bool - - // All passes each element of the container to the given function and - // returns true if the function returns true for all elements. - All(func(index int, value interface{}) bool) bool - - // Find passes each element of the container to the given function and returns - // the first (index,value) for which the function is true or -1,nil otherwise - // if no element matches the criteria. - Find(func(index int, value interface{}) bool) (int, interface{}) -} - -// EnumerableWithKey provides functions for ordered containers whose values whose elements are key/value pairs. -type EnumerableWithKey interface { - // Each calls the given function once for each element, passing that element's key and value. - Each(func(key interface{}, value interface{})) - - // Map invokes the given function once for each element and returns a container - // containing the values returned by the given function as key/value pairs. - // TODO need help on how to enforce this in containers (don't want to type assert when chaining) - // Map(func(key interface{}, value interface{}) (interface{}, interface{})) Container - - // Select returns a new container containing all elements for which the given function returns a true value. - // TODO need help on how to enforce this in containers (don't want to type assert when chaining) - // Select(func(key interface{}, value interface{}) bool) Container - - // Any passes each element of the container to the given function and - // returns true if the function ever returns true for any element. - Any(func(key interface{}, value interface{}) bool) bool - - // All passes each element of the container to the given function and - // returns true if the function returns true for all elements. - All(func(key interface{}, value interface{}) bool) bool - - // Find passes each element of the container to the given function and returns - // the first (key,value) for which the function is true or nil,nil otherwise if no element - // matches the criteria. - Find(func(key interface{}, value interface{}) bool) (interface{}, interface{}) -} diff --git a/vendor/github.com/emirpasic/gods/containers/iterator.go b/vendor/github.com/emirpasic/gods/containers/iterator.go deleted file mode 100644 index f1a52a36..00000000 --- a/vendor/github.com/emirpasic/gods/containers/iterator.go +++ /dev/null @@ -1,109 +0,0 @@ -// Copyright (c) 2015, Emir Pasic. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package containers - -// IteratorWithIndex is stateful iterator for ordered containers whose values can be fetched by an index. -type IteratorWithIndex interface { - // Next moves the iterator to the next element and returns true if there was a next element in the container. - // If Next() returns true, then next element's index and value can be retrieved by Index() and Value(). - // If Next() was called for the first time, then it will point the iterator to the first element if it exists. - // Modifies the state of the iterator. - Next() bool - - // Value returns the current element's value. - // Does not modify the state of the iterator. - Value() interface{} - - // Index returns the current element's index. - // Does not modify the state of the iterator. - Index() int - - // Begin resets the iterator to its initial state (one-before-first) - // Call Next() to fetch the first element if any. - Begin() - - // First moves the iterator to the first element and returns true if there was a first element in the container. - // If First() returns true, then first element's index and value can be retrieved by Index() and Value(). - // Modifies the state of the iterator. - First() bool -} - -// IteratorWithKey is a stateful iterator for ordered containers whose elements are key value pairs. -type IteratorWithKey interface { - // Next moves the iterator to the next element and returns true if there was a next element in the container. - // If Next() returns true, then next element's key and value can be retrieved by Key() and Value(). - // If Next() was called for the first time, then it will point the iterator to the first element if it exists. - // Modifies the state of the iterator. - Next() bool - - // Value returns the current element's value. - // Does not modify the state of the iterator. - Value() interface{} - - // Key returns the current element's key. - // Does not modify the state of the iterator. - Key() interface{} - - // Begin resets the iterator to its initial state (one-before-first) - // Call Next() to fetch the first element if any. - Begin() - - // First moves the iterator to the first element and returns true if there was a first element in the container. - // If First() returns true, then first element's key and value can be retrieved by Key() and Value(). - // Modifies the state of the iterator. - First() bool -} - -// ReverseIteratorWithIndex is stateful iterator for ordered containers whose values can be fetched by an index. -// -// Essentially it is the same as IteratorWithIndex, but provides additional: -// -// Prev() function to enable traversal in reverse -// -// Last() function to move the iterator to the last element. -// -// End() function to move the iterator past the last element (one-past-the-end). -type ReverseIteratorWithIndex interface { - // Prev moves the iterator to the previous element and returns true if there was a previous element in the container. - // If Prev() returns true, then previous element's index and value can be retrieved by Index() and Value(). - // Modifies the state of the iterator. - Prev() bool - - // End moves the iterator past the last element (one-past-the-end). - // Call Prev() to fetch the last element if any. - End() - - // Last moves the iterator to the last element and returns true if there was a last element in the container. - // If Last() returns true, then last element's index and value can be retrieved by Index() and Value(). - // Modifies the state of the iterator. - Last() bool - - IteratorWithIndex -} - -// ReverseIteratorWithKey is a stateful iterator for ordered containers whose elements are key value pairs. -// -// Essentially it is the same as IteratorWithKey, but provides additional: -// -// Prev() function to enable traversal in reverse -// -// Last() function to move the iterator to the last element. -type ReverseIteratorWithKey interface { - // Prev moves the iterator to the previous element and returns true if there was a previous element in the container. - // If Prev() returns true, then previous element's key and value can be retrieved by Key() and Value(). - // Modifies the state of the iterator. - Prev() bool - - // End moves the iterator past the last element (one-past-the-end). - // Call Prev() to fetch the last element if any. - End() - - // Last moves the iterator to the last element and returns true if there was a last element in the container. - // If Last() returns true, then last element's key and value can be retrieved by Key() and Value(). - // Modifies the state of the iterator. - Last() bool - - IteratorWithKey -} diff --git a/vendor/github.com/emirpasic/gods/containers/serialization.go b/vendor/github.com/emirpasic/gods/containers/serialization.go deleted file mode 100644 index d7c90c83..00000000 --- a/vendor/github.com/emirpasic/gods/containers/serialization.go +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) 2015, Emir Pasic. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package containers - -// JSONSerializer provides JSON serialization -type JSONSerializer interface { - // ToJSON outputs the JSON representation of containers's elements. - ToJSON() ([]byte, error) -} - -// JSONDeserializer provides JSON deserialization -type JSONDeserializer interface { - // FromJSON populates containers's elements from the input JSON representation. - FromJSON([]byte) error -} diff --git a/vendor/github.com/emirpasic/gods/lists/arraylist/arraylist.go b/vendor/github.com/emirpasic/gods/lists/arraylist/arraylist.go deleted file mode 100644 index bfedac9e..00000000 --- a/vendor/github.com/emirpasic/gods/lists/arraylist/arraylist.go +++ /dev/null @@ -1,228 +0,0 @@ -// Copyright (c) 2015, Emir Pasic. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package arraylist implements the array list. -// -// Structure is not thread safe. -// -// Reference: https://en.wikipedia.org/wiki/List_%28abstract_data_type%29 -package arraylist - -import ( - "fmt" - "strings" - - "github.com/emirpasic/gods/lists" - "github.com/emirpasic/gods/utils" -) - -func assertListImplementation() { - var _ lists.List = (*List)(nil) -} - -// List holds the elements in a slice -type List struct { - elements []interface{} - size int -} - -const ( - growthFactor = float32(2.0) // growth by 100% - shrinkFactor = float32(0.25) // shrink when size is 25% of capacity (0 means never shrink) -) - -// New instantiates a new list and adds the passed values, if any, to the list -func New(values ...interface{}) *List { - list := &List{} - if len(values) > 0 { - list.Add(values...) - } - return list -} - -// Add appends a value at the end of the list -func (list *List) Add(values ...interface{}) { - list.growBy(len(values)) - for _, value := range values { - list.elements[list.size] = value - list.size++ - } -} - -// Get returns the element at index. -// Second return parameter is true if index is within bounds of the array and array is not empty, otherwise false. -func (list *List) Get(index int) (interface{}, bool) { - - if !list.withinRange(index) { - return nil, false - } - - return list.elements[index], true -} - -// Remove removes the element at the given index from the list. -func (list *List) Remove(index int) { - - if !list.withinRange(index) { - return - } - - list.elements[index] = nil // cleanup reference - copy(list.elements[index:], list.elements[index+1:list.size]) // shift to the left by one (slow operation, need ways to optimize this) - list.size-- - - list.shrink() -} - -// Contains checks if elements (one or more) are present in the set. -// All elements have to be present in the set for the method to return true. -// Performance time complexity of n^2. -// Returns true if no arguments are passed at all, i.e. set is always super-set of empty set. -func (list *List) Contains(values ...interface{}) bool { - - for _, searchValue := range values { - found := false - for _, element := range list.elements { - if element == searchValue { - found = true - break - } - } - if !found { - return false - } - } - return true -} - -// Values returns all elements in the list. -func (list *List) Values() []interface{} { - newElements := make([]interface{}, list.size, list.size) - copy(newElements, list.elements[:list.size]) - return newElements -} - -//IndexOf returns index of provided element -func (list *List) IndexOf(value interface{}) int { - if list.size == 0 { - return -1 - } - for index, element := range list.elements { - if element == value { - return index - } - } - return -1 -} - -// Empty returns true if list does not contain any elements. -func (list *List) Empty() bool { - return list.size == 0 -} - -// Size returns number of elements within the list. -func (list *List) Size() int { - return list.size -} - -// Clear removes all elements from the list. -func (list *List) Clear() { - list.size = 0 - list.elements = []interface{}{} -} - -// Sort sorts values (in-place) using. -func (list *List) Sort(comparator utils.Comparator) { - if len(list.elements) < 2 { - return - } - utils.Sort(list.elements[:list.size], comparator) -} - -// Swap swaps the two values at the specified positions. -func (list *List) Swap(i, j int) { - if list.withinRange(i) && list.withinRange(j) { - list.elements[i], list.elements[j] = list.elements[j], list.elements[i] - } -} - -// Insert inserts values at specified index position shifting the value at that position (if any) and any subsequent elements to the right. -// Does not do anything if position is negative or bigger than list's size -// Note: position equal to list's size is valid, i.e. append. -func (list *List) Insert(index int, values ...interface{}) { - - if !list.withinRange(index) { - // Append - if index == list.size { - list.Add(values...) - } - return - } - - l := len(values) - list.growBy(l) - list.size += l - copy(list.elements[index+l:], list.elements[index:list.size-l]) - copy(list.elements[index:], values) -} - -// Set the value at specified index -// Does not do anything if position is negative or bigger than list's size -// Note: position equal to list's size is valid, i.e. append. -func (list *List) Set(index int, value interface{}) { - - if !list.withinRange(index) { - // Append - if index == list.size { - list.Add(value) - } - return - } - - list.elements[index] = value -} - -// String returns a string representation of container -func (list *List) String() string { - str := "ArrayList\n" - values := []string{} - for _, value := range list.elements[:list.size] { - values = append(values, fmt.Sprintf("%v", value)) - } - str += strings.Join(values, ", ") - return str -} - -// Check that the index is within bounds of the list -func (list *List) withinRange(index int) bool { - return index >= 0 && index < list.size -} - -func (list *List) resize(cap int) { - newElements := make([]interface{}, cap, cap) - copy(newElements, list.elements) - list.elements = newElements -} - -// Expand the array if necessary, i.e. capacity will be reached if we add n elements -func (list *List) growBy(n int) { - // When capacity is reached, grow by a factor of growthFactor and add number of elements - currentCapacity := cap(list.elements) - if list.size+n >= currentCapacity { - newCapacity := int(growthFactor * float32(currentCapacity+n)) - list.resize(newCapacity) - } -} - -// Shrink the array if necessary, i.e. when size is shrinkFactor percent of current capacity -func (list *List) shrink() { - if shrinkFactor == 0.0 { - return - } - // Shrink when size is at shrinkFactor * capacity - currentCapacity := cap(list.elements) - if list.size <= int(float32(currentCapacity)*shrinkFactor) { - list.resize(list.size) - } -} diff --git a/vendor/github.com/emirpasic/gods/lists/arraylist/enumerable.go b/vendor/github.com/emirpasic/gods/lists/arraylist/enumerable.go deleted file mode 100644 index b3a87388..00000000 --- a/vendor/github.com/emirpasic/gods/lists/arraylist/enumerable.go +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright (c) 2015, Emir Pasic. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package arraylist - -import "github.com/emirpasic/gods/containers" - -func assertEnumerableImplementation() { - var _ containers.EnumerableWithIndex = (*List)(nil) -} - -// Each calls the given function once for each element, passing that element's index and value. -func (list *List) Each(f func(index int, value interface{})) { - iterator := list.Iterator() - for iterator.Next() { - f(iterator.Index(), iterator.Value()) - } -} - -// Map invokes the given function once for each element and returns a -// container containing the values returned by the given function. -func (list *List) Map(f func(index int, value interface{}) interface{}) *List { - newList := &List{} - iterator := list.Iterator() - for iterator.Next() { - newList.Add(f(iterator.Index(), iterator.Value())) - } - return newList -} - -// Select returns a new container containing all elements for which the given function returns a true value. -func (list *List) Select(f func(index int, value interface{}) bool) *List { - newList := &List{} - iterator := list.Iterator() - for iterator.Next() { - if f(iterator.Index(), iterator.Value()) { - newList.Add(iterator.Value()) - } - } - return newList -} - -// Any passes each element of the collection to the given function and -// returns true if the function ever returns true for any element. -func (list *List) Any(f func(index int, value interface{}) bool) bool { - iterator := list.Iterator() - for iterator.Next() { - if f(iterator.Index(), iterator.Value()) { - return true - } - } - return false -} - -// All passes each element of the collection to the given function and -// returns true if the function returns true for all elements. -func (list *List) All(f func(index int, value interface{}) bool) bool { - iterator := list.Iterator() - for iterator.Next() { - if !f(iterator.Index(), iterator.Value()) { - return false - } - } - return true -} - -// Find passes each element of the container to the given function and returns -// the first (index,value) for which the function is true or -1,nil otherwise -// if no element matches the criteria. -func (list *List) Find(f func(index int, value interface{}) bool) (int, interface{}) { - iterator := list.Iterator() - for iterator.Next() { - if f(iterator.Index(), iterator.Value()) { - return iterator.Index(), iterator.Value() - } - } - return -1, nil -} diff --git a/vendor/github.com/emirpasic/gods/lists/arraylist/iterator.go b/vendor/github.com/emirpasic/gods/lists/arraylist/iterator.go deleted file mode 100644 index 38a93f3a..00000000 --- a/vendor/github.com/emirpasic/gods/lists/arraylist/iterator.go +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright (c) 2015, Emir Pasic. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package arraylist - -import "github.com/emirpasic/gods/containers" - -func assertIteratorImplementation() { - var _ containers.ReverseIteratorWithIndex = (*Iterator)(nil) -} - -// Iterator holding the iterator's state -type Iterator struct { - list *List - index int -} - -// Iterator returns a stateful iterator whose values can be fetched by an index. -func (list *List) Iterator() Iterator { - return Iterator{list: list, index: -1} -} - -// Next moves the iterator to the next element and returns true if there was a next element in the container. -// If Next() returns true, then next element's index and value can be retrieved by Index() and Value(). -// If Next() was called for the first time, then it will point the iterator to the first element if it exists. -// Modifies the state of the iterator. -func (iterator *Iterator) Next() bool { - if iterator.index < iterator.list.size { - iterator.index++ - } - return iterator.list.withinRange(iterator.index) -} - -// Prev moves the iterator to the previous element and returns true if there was a previous element in the container. -// If Prev() returns true, then previous element's index and value can be retrieved by Index() and Value(). -// Modifies the state of the iterator. -func (iterator *Iterator) Prev() bool { - if iterator.index >= 0 { - iterator.index-- - } - return iterator.list.withinRange(iterator.index) -} - -// Value returns the current element's value. -// Does not modify the state of the iterator. -func (iterator *Iterator) Value() interface{} { - return iterator.list.elements[iterator.index] -} - -// Index returns the current element's index. -// Does not modify the state of the iterator. -func (iterator *Iterator) Index() int { - return iterator.index -} - -// Begin resets the iterator to its initial state (one-before-first) -// Call Next() to fetch the first element if any. -func (iterator *Iterator) Begin() { - iterator.index = -1 -} - -// End moves the iterator past the last element (one-past-the-end). -// Call Prev() to fetch the last element if any. -func (iterator *Iterator) End() { - iterator.index = iterator.list.size -} - -// First moves the iterator to the first element and returns true if there was a first element in the container. -// If First() returns true, then first element's index and value can be retrieved by Index() and Value(). -// Modifies the state of the iterator. -func (iterator *Iterator) First() bool { - iterator.Begin() - return iterator.Next() -} - -// Last moves the iterator to the last element and returns true if there was a last element in the container. -// If Last() returns true, then last element's index and value can be retrieved by Index() and Value(). -// Modifies the state of the iterator. -func (iterator *Iterator) Last() bool { - iterator.End() - return iterator.Prev() -} diff --git a/vendor/github.com/emirpasic/gods/lists/arraylist/serialization.go b/vendor/github.com/emirpasic/gods/lists/arraylist/serialization.go deleted file mode 100644 index 2f283fb9..00000000 --- a/vendor/github.com/emirpasic/gods/lists/arraylist/serialization.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2015, Emir Pasic. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package arraylist - -import ( - "encoding/json" - "github.com/emirpasic/gods/containers" -) - -func assertSerializationImplementation() { - var _ containers.JSONSerializer = (*List)(nil) - var _ containers.JSONDeserializer = (*List)(nil) -} - -// ToJSON outputs the JSON representation of list's elements. -func (list *List) ToJSON() ([]byte, error) { - return json.Marshal(list.elements[:list.size]) -} - -// FromJSON populates list's elements from the input JSON representation. -func (list *List) FromJSON(data []byte) error { - err := json.Unmarshal(data, &list.elements) - if err == nil { - list.size = len(list.elements) - } - return err -} diff --git a/vendor/github.com/emirpasic/gods/lists/lists.go b/vendor/github.com/emirpasic/gods/lists/lists.go deleted file mode 100644 index 1f6bb08e..00000000 --- a/vendor/github.com/emirpasic/gods/lists/lists.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2015, Emir Pasic. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package lists provides an abstract List interface. -// -// In computer science, a list or sequence is an abstract data type that represents an ordered sequence of values, where the same value may occur more than once. An instance of a list is a computer representation of the mathematical concept of a finite sequence; the (potentially) infinite analog of a list is a stream. Lists are a basic example of containers, as they contain other values. If the same value occurs multiple times, each occurrence is considered a distinct item. -// -// Reference: https://en.wikipedia.org/wiki/List_%28abstract_data_type%29 -package lists - -import ( - "github.com/emirpasic/gods/containers" - "github.com/emirpasic/gods/utils" -) - -// List interface that all lists implement -type List interface { - Get(index int) (interface{}, bool) - Remove(index int) - Add(values ...interface{}) - Contains(values ...interface{}) bool - Sort(comparator utils.Comparator) - Swap(index1, index2 int) - Insert(index int, values ...interface{}) - Set(index int, value interface{}) - - containers.Container - // Empty() bool - // Size() int - // Clear() - // Values() []interface{} -} diff --git a/vendor/github.com/emirpasic/gods/trees/binaryheap/binaryheap.go b/vendor/github.com/emirpasic/gods/trees/binaryheap/binaryheap.go deleted file mode 100644 index 70b28cf5..00000000 --- a/vendor/github.com/emirpasic/gods/trees/binaryheap/binaryheap.go +++ /dev/null @@ -1,163 +0,0 @@ -// Copyright (c) 2015, Emir Pasic. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package binaryheap implements a binary heap backed by array list. -// -// Comparator defines this heap as either min or max heap. -// -// Structure is not thread safe. -// -// References: http://en.wikipedia.org/wiki/Binary_heap -package binaryheap - -import ( - "fmt" - "github.com/emirpasic/gods/lists/arraylist" - "github.com/emirpasic/gods/trees" - "github.com/emirpasic/gods/utils" - "strings" -) - -func assertTreeImplementation() { - var _ trees.Tree = (*Heap)(nil) -} - -// Heap holds elements in an array-list -type Heap struct { - list *arraylist.List - Comparator utils.Comparator -} - -// NewWith instantiates a new empty heap tree with the custom comparator. -func NewWith(comparator utils.Comparator) *Heap { - return &Heap{list: arraylist.New(), Comparator: comparator} -} - -// NewWithIntComparator instantiates a new empty heap with the IntComparator, i.e. elements are of type int. -func NewWithIntComparator() *Heap { - return &Heap{list: arraylist.New(), Comparator: utils.IntComparator} -} - -// NewWithStringComparator instantiates a new empty heap with the StringComparator, i.e. elements are of type string. -func NewWithStringComparator() *Heap { - return &Heap{list: arraylist.New(), Comparator: utils.StringComparator} -} - -// Push adds a value onto the heap and bubbles it up accordingly. -func (heap *Heap) Push(values ...interface{}) { - if len(values) == 1 { - heap.list.Add(values[0]) - heap.bubbleUp() - } else { - // Reference: https://en.wikipedia.org/wiki/Binary_heap#Building_a_heap - for _, value := range values { - heap.list.Add(value) - } - size := heap.list.Size()/2 + 1 - for i := size; i >= 0; i-- { - heap.bubbleDownIndex(i) - } - } -} - -// Pop removes top element on heap and returns it, or nil if heap is empty. -// Second return parameter is true, unless the heap was empty and there was nothing to pop. -func (heap *Heap) Pop() (value interface{}, ok bool) { - value, ok = heap.list.Get(0) - if !ok { - return - } - lastIndex := heap.list.Size() - 1 - heap.list.Swap(0, lastIndex) - heap.list.Remove(lastIndex) - heap.bubbleDown() - return -} - -// Peek returns top element on the heap without removing it, or nil if heap is empty. -// Second return parameter is true, unless the heap was empty and there was nothing to peek. -func (heap *Heap) Peek() (value interface{}, ok bool) { - return heap.list.Get(0) -} - -// Empty returns true if heap does not contain any elements. -func (heap *Heap) Empty() bool { - return heap.list.Empty() -} - -// Size returns number of elements within the heap. -func (heap *Heap) Size() int { - return heap.list.Size() -} - -// Clear removes all elements from the heap. -func (heap *Heap) Clear() { - heap.list.Clear() -} - -// Values returns all elements in the heap. -func (heap *Heap) Values() []interface{} { - return heap.list.Values() -} - -// String returns a string representation of container -func (heap *Heap) String() string { - str := "BinaryHeap\n" - values := []string{} - for _, value := range heap.list.Values() { - values = append(values, fmt.Sprintf("%v", value)) - } - str += strings.Join(values, ", ") - return str -} - -// Performs the "bubble down" operation. This is to place the element that is at the root -// of the heap in its correct place so that the heap maintains the min/max-heap order property. -func (heap *Heap) bubbleDown() { - heap.bubbleDownIndex(0) -} - -// Performs the "bubble down" operation. This is to place the element that is at the index -// of the heap in its correct place so that the heap maintains the min/max-heap order property. -func (heap *Heap) bubbleDownIndex(index int) { - size := heap.list.Size() - for leftIndex := index<<1 + 1; leftIndex < size; leftIndex = index<<1 + 1 { - rightIndex := index<<1 + 2 - smallerIndex := leftIndex - leftValue, _ := heap.list.Get(leftIndex) - rightValue, _ := heap.list.Get(rightIndex) - if rightIndex < size && heap.Comparator(leftValue, rightValue) > 0 { - smallerIndex = rightIndex - } - indexValue, _ := heap.list.Get(index) - smallerValue, _ := heap.list.Get(smallerIndex) - if heap.Comparator(indexValue, smallerValue) > 0 { - heap.list.Swap(index, smallerIndex) - } else { - break - } - index = smallerIndex - } -} - -// Performs the "bubble up" operation. This is to place a newly inserted -// element (i.e. last element in the list) in its correct place so that -// the heap maintains the min/max-heap order property. -func (heap *Heap) bubbleUp() { - index := heap.list.Size() - 1 - for parentIndex := (index - 1) >> 1; index > 0; parentIndex = (index - 1) >> 1 { - indexValue, _ := heap.list.Get(index) - parentValue, _ := heap.list.Get(parentIndex) - if heap.Comparator(parentValue, indexValue) <= 0 { - break - } - heap.list.Swap(index, parentIndex) - index = parentIndex - } -} - -// Check that the index is within bounds of the list -func (heap *Heap) withinRange(index int) bool { - return index >= 0 && index < heap.list.Size() -} diff --git a/vendor/github.com/emirpasic/gods/trees/binaryheap/iterator.go b/vendor/github.com/emirpasic/gods/trees/binaryheap/iterator.go deleted file mode 100644 index beeb8d70..00000000 --- a/vendor/github.com/emirpasic/gods/trees/binaryheap/iterator.go +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright (c) 2015, Emir Pasic. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package binaryheap - -import "github.com/emirpasic/gods/containers" - -func assertIteratorImplementation() { - var _ containers.ReverseIteratorWithIndex = (*Iterator)(nil) -} - -// Iterator returns a stateful iterator whose values can be fetched by an index. -type Iterator struct { - heap *Heap - index int -} - -// Iterator returns a stateful iterator whose values can be fetched by an index. -func (heap *Heap) Iterator() Iterator { - return Iterator{heap: heap, index: -1} -} - -// Next moves the iterator to the next element and returns true if there was a next element in the container. -// If Next() returns true, then next element's index and value can be retrieved by Index() and Value(). -// If Next() was called for the first time, then it will point the iterator to the first element if it exists. -// Modifies the state of the iterator. -func (iterator *Iterator) Next() bool { - if iterator.index < iterator.heap.Size() { - iterator.index++ - } - return iterator.heap.withinRange(iterator.index) -} - -// Prev moves the iterator to the previous element and returns true if there was a previous element in the container. -// If Prev() returns true, then previous element's index and value can be retrieved by Index() and Value(). -// Modifies the state of the iterator. -func (iterator *Iterator) Prev() bool { - if iterator.index >= 0 { - iterator.index-- - } - return iterator.heap.withinRange(iterator.index) -} - -// Value returns the current element's value. -// Does not modify the state of the iterator. -func (iterator *Iterator) Value() interface{} { - value, _ := iterator.heap.list.Get(iterator.index) - return value -} - -// Index returns the current element's index. -// Does not modify the state of the iterator. -func (iterator *Iterator) Index() int { - return iterator.index -} - -// Begin resets the iterator to its initial state (one-before-first) -// Call Next() to fetch the first element if any. -func (iterator *Iterator) Begin() { - iterator.index = -1 -} - -// End moves the iterator past the last element (one-past-the-end). -// Call Prev() to fetch the last element if any. -func (iterator *Iterator) End() { - iterator.index = iterator.heap.Size() -} - -// First moves the iterator to the first element and returns true if there was a first element in the container. -// If First() returns true, then first element's index and value can be retrieved by Index() and Value(). -// Modifies the state of the iterator. -func (iterator *Iterator) First() bool { - iterator.Begin() - return iterator.Next() -} - -// Last moves the iterator to the last element and returns true if there was a last element in the container. -// If Last() returns true, then last element's index and value can be retrieved by Index() and Value(). -// Modifies the state of the iterator. -func (iterator *Iterator) Last() bool { - iterator.End() - return iterator.Prev() -} diff --git a/vendor/github.com/emirpasic/gods/trees/binaryheap/serialization.go b/vendor/github.com/emirpasic/gods/trees/binaryheap/serialization.go deleted file mode 100644 index 00d0c771..00000000 --- a/vendor/github.com/emirpasic/gods/trees/binaryheap/serialization.go +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) 2015, Emir Pasic. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package binaryheap - -import "github.com/emirpasic/gods/containers" - -func assertSerializationImplementation() { - var _ containers.JSONSerializer = (*Heap)(nil) - var _ containers.JSONDeserializer = (*Heap)(nil) -} - -// ToJSON outputs the JSON representation of the heap. -func (heap *Heap) ToJSON() ([]byte, error) { - return heap.list.ToJSON() -} - -// FromJSON populates the heap from the input JSON representation. -func (heap *Heap) FromJSON(data []byte) error { - return heap.list.FromJSON(data) -} diff --git a/vendor/github.com/emirpasic/gods/trees/trees.go b/vendor/github.com/emirpasic/gods/trees/trees.go deleted file mode 100644 index a5a7427d..00000000 --- a/vendor/github.com/emirpasic/gods/trees/trees.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) 2015, Emir Pasic. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package trees provides an abstract Tree interface. -// -// In computer science, a tree is a widely used abstract data type (ADT) or data structure implementing this ADT that simulates a hierarchical tree structure, with a root value and subtrees of children with a parent node, represented as a set of linked nodes. -// -// Reference: https://en.wikipedia.org/wiki/Tree_%28data_structure%29 -package trees - -import "github.com/emirpasic/gods/containers" - -// Tree interface that all trees implement -type Tree interface { - containers.Container - // Empty() bool - // Size() int - // Clear() - // Values() []interface{} -} diff --git a/vendor/github.com/emirpasic/gods/utils/comparator.go b/vendor/github.com/emirpasic/gods/utils/comparator.go deleted file mode 100644 index 6a9afbf3..00000000 --- a/vendor/github.com/emirpasic/gods/utils/comparator.go +++ /dev/null @@ -1,251 +0,0 @@ -// Copyright (c) 2015, Emir Pasic. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package utils - -import "time" - -// Comparator will make type assertion (see IntComparator for example), -// which will panic if a or b are not of the asserted type. -// -// Should return a number: -// negative , if a < b -// zero , if a == b -// positive , if a > b -type Comparator func(a, b interface{}) int - -// StringComparator provides a fast comparison on strings -func StringComparator(a, b interface{}) int { - s1 := a.(string) - s2 := b.(string) - min := len(s2) - if len(s1) < len(s2) { - min = len(s1) - } - diff := 0 - for i := 0; i < min && diff == 0; i++ { - diff = int(s1[i]) - int(s2[i]) - } - if diff == 0 { - diff = len(s1) - len(s2) - } - if diff < 0 { - return -1 - } - if diff > 0 { - return 1 - } - return 0 -} - -// IntComparator provides a basic comparison on int -func IntComparator(a, b interface{}) int { - aAsserted := a.(int) - bAsserted := b.(int) - switch { - case aAsserted > bAsserted: - return 1 - case aAsserted < bAsserted: - return -1 - default: - return 0 - } -} - -// Int8Comparator provides a basic comparison on int8 -func Int8Comparator(a, b interface{}) int { - aAsserted := a.(int8) - bAsserted := b.(int8) - switch { - case aAsserted > bAsserted: - return 1 - case aAsserted < bAsserted: - return -1 - default: - return 0 - } -} - -// Int16Comparator provides a basic comparison on int16 -func Int16Comparator(a, b interface{}) int { - aAsserted := a.(int16) - bAsserted := b.(int16) - switch { - case aAsserted > bAsserted: - return 1 - case aAsserted < bAsserted: - return -1 - default: - return 0 - } -} - -// Int32Comparator provides a basic comparison on int32 -func Int32Comparator(a, b interface{}) int { - aAsserted := a.(int32) - bAsserted := b.(int32) - switch { - case aAsserted > bAsserted: - return 1 - case aAsserted < bAsserted: - return -1 - default: - return 0 - } -} - -// Int64Comparator provides a basic comparison on int64 -func Int64Comparator(a, b interface{}) int { - aAsserted := a.(int64) - bAsserted := b.(int64) - switch { - case aAsserted > bAsserted: - return 1 - case aAsserted < bAsserted: - return -1 - default: - return 0 - } -} - -// UIntComparator provides a basic comparison on uint -func UIntComparator(a, b interface{}) int { - aAsserted := a.(uint) - bAsserted := b.(uint) - switch { - case aAsserted > bAsserted: - return 1 - case aAsserted < bAsserted: - return -1 - default: - return 0 - } -} - -// UInt8Comparator provides a basic comparison on uint8 -func UInt8Comparator(a, b interface{}) int { - aAsserted := a.(uint8) - bAsserted := b.(uint8) - switch { - case aAsserted > bAsserted: - return 1 - case aAsserted < bAsserted: - return -1 - default: - return 0 - } -} - -// UInt16Comparator provides a basic comparison on uint16 -func UInt16Comparator(a, b interface{}) int { - aAsserted := a.(uint16) - bAsserted := b.(uint16) - switch { - case aAsserted > bAsserted: - return 1 - case aAsserted < bAsserted: - return -1 - default: - return 0 - } -} - -// UInt32Comparator provides a basic comparison on uint32 -func UInt32Comparator(a, b interface{}) int { - aAsserted := a.(uint32) - bAsserted := b.(uint32) - switch { - case aAsserted > bAsserted: - return 1 - case aAsserted < bAsserted: - return -1 - default: - return 0 - } -} - -// UInt64Comparator provides a basic comparison on uint64 -func UInt64Comparator(a, b interface{}) int { - aAsserted := a.(uint64) - bAsserted := b.(uint64) - switch { - case aAsserted > bAsserted: - return 1 - case aAsserted < bAsserted: - return -1 - default: - return 0 - } -} - -// Float32Comparator provides a basic comparison on float32 -func Float32Comparator(a, b interface{}) int { - aAsserted := a.(float32) - bAsserted := b.(float32) - switch { - case aAsserted > bAsserted: - return 1 - case aAsserted < bAsserted: - return -1 - default: - return 0 - } -} - -// Float64Comparator provides a basic comparison on float64 -func Float64Comparator(a, b interface{}) int { - aAsserted := a.(float64) - bAsserted := b.(float64) - switch { - case aAsserted > bAsserted: - return 1 - case aAsserted < bAsserted: - return -1 - default: - return 0 - } -} - -// ByteComparator provides a basic comparison on byte -func ByteComparator(a, b interface{}) int { - aAsserted := a.(byte) - bAsserted := b.(byte) - switch { - case aAsserted > bAsserted: - return 1 - case aAsserted < bAsserted: - return -1 - default: - return 0 - } -} - -// RuneComparator provides a basic comparison on rune -func RuneComparator(a, b interface{}) int { - aAsserted := a.(rune) - bAsserted := b.(rune) - switch { - case aAsserted > bAsserted: - return 1 - case aAsserted < bAsserted: - return -1 - default: - return 0 - } -} - -// TimeComparator provides a basic comparison on time.Time -func TimeComparator(a, b interface{}) int { - aAsserted := a.(time.Time) - bAsserted := b.(time.Time) - - switch { - case aAsserted.After(bAsserted): - return 1 - case aAsserted.Before(bAsserted): - return -1 - default: - return 0 - } -} diff --git a/vendor/github.com/emirpasic/gods/utils/sort.go b/vendor/github.com/emirpasic/gods/utils/sort.go deleted file mode 100644 index 79ced1f5..00000000 --- a/vendor/github.com/emirpasic/gods/utils/sort.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) 2015, Emir Pasic. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package utils - -import "sort" - -// Sort sorts values (in-place) with respect to the given comparator. -// -// Uses Go's sort (hybrid of quicksort for large and then insertion sort for smaller slices). -func Sort(values []interface{}, comparator Comparator) { - sort.Sort(sortable{values, comparator}) -} - -type sortable struct { - values []interface{} - comparator Comparator -} - -func (s sortable) Len() int { - return len(s.values) -} -func (s sortable) Swap(i, j int) { - s.values[i], s.values[j] = s.values[j], s.values[i] -} -func (s sortable) Less(i, j int) bool { - return s.comparator(s.values[i], s.values[j]) < 0 -} diff --git a/vendor/github.com/emirpasic/gods/utils/utils.go b/vendor/github.com/emirpasic/gods/utils/utils.go deleted file mode 100644 index 1ad49cbc..00000000 --- a/vendor/github.com/emirpasic/gods/utils/utils.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) 2015, Emir Pasic. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package utils provides common utility functions. -// -// Provided functionalities: -// - sorting -// - comparators -package utils - -import ( - "fmt" - "strconv" -) - -// ToString converts a value to string. -func ToString(value interface{}) string { - switch value.(type) { - case string: - return value.(string) - case int8: - return strconv.FormatInt(int64(value.(int8)), 10) - case int16: - return strconv.FormatInt(int64(value.(int16)), 10) - case int32: - return strconv.FormatInt(int64(value.(int32)), 10) - case int64: - return strconv.FormatInt(int64(value.(int64)), 10) - case uint8: - return strconv.FormatUint(uint64(value.(uint8)), 10) - case uint16: - return strconv.FormatUint(uint64(value.(uint16)), 10) - case uint32: - return strconv.FormatUint(uint64(value.(uint32)), 10) - case uint64: - return strconv.FormatUint(uint64(value.(uint64)), 10) - case float32: - return strconv.FormatFloat(float64(value.(float32)), 'g', -1, 64) - case float64: - return strconv.FormatFloat(float64(value.(float64)), 'g', -1, 64) - case bool: - return strconv.FormatBool(value.(bool)) - default: - return fmt.Sprintf("%+v", value) - } -} diff --git a/vendor/github.com/go-git/gcfg/LICENSE b/vendor/github.com/go-git/gcfg/LICENSE deleted file mode 100644 index 87a5cede..00000000 --- a/vendor/github.com/go-git/gcfg/LICENSE +++ /dev/null @@ -1,28 +0,0 @@ -Copyright (c) 2012 Péter Surányi. Portions Copyright (c) 2009 The Go -Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/go-git/gcfg/README b/vendor/github.com/go-git/gcfg/README deleted file mode 100644 index 1ff233a5..00000000 --- a/vendor/github.com/go-git/gcfg/README +++ /dev/null @@ -1,4 +0,0 @@ -Gcfg reads INI-style configuration files into Go structs; -supports user-defined types and subsections. - -Package docs: https://godoc.org/gopkg.in/gcfg.v1 diff --git a/vendor/github.com/go-git/gcfg/doc.go b/vendor/github.com/go-git/gcfg/doc.go deleted file mode 100644 index 7bdefbf0..00000000 --- a/vendor/github.com/go-git/gcfg/doc.go +++ /dev/null @@ -1,145 +0,0 @@ -// Package gcfg reads "INI-style" text-based configuration files with -// "name=value" pairs grouped into sections (gcfg files). -// -// This package is still a work in progress; see the sections below for planned -// changes. -// -// Syntax -// -// The syntax is based on that used by git config: -// http://git-scm.com/docs/git-config#_syntax . -// There are some (planned) differences compared to the git config format: -// - improve data portability: -// - must be encoded in UTF-8 (for now) and must not contain the 0 byte -// - include and "path" type is not supported -// (path type may be implementable as a user-defined type) -// - internationalization -// - section and variable names can contain unicode letters, unicode digits -// (as defined in http://golang.org/ref/spec#Characters ) and hyphens -// (U+002D), starting with a unicode letter -// - disallow potentially ambiguous or misleading definitions: -// - `[sec.sub]` format is not allowed (deprecated in gitconfig) -// - `[sec ""]` is not allowed -// - use `[sec]` for section name "sec" and empty subsection name -// - (planned) within a single file, definitions must be contiguous for each: -// - section: '[secA]' -> '[secB]' -> '[secA]' is an error -// - subsection: '[sec "A"]' -> '[sec "B"]' -> '[sec "A"]' is an error -// - multivalued variable: 'multi=a' -> 'other=x' -> 'multi=b' is an error -// -// Data structure -// -// The functions in this package read values into a user-defined struct. -// Each section corresponds to a struct field in the config struct, and each -// variable in a section corresponds to a data field in the section struct. -// The mapping of each section or variable name to fields is done either based -// on the "gcfg" struct tag or by matching the name of the section or variable, -// ignoring case. In the latter case, hyphens '-' in section and variable names -// correspond to underscores '_' in field names. -// Fields must be exported; to use a section or variable name starting with a -// letter that is neither upper- or lower-case, prefix the field name with 'X'. -// (See https://code.google.com/p/go/issues/detail?id=5763#c4 .) -// -// For sections with subsections, the corresponding field in config must be a -// map, rather than a struct, with string keys and pointer-to-struct values. -// Values for subsection variables are stored in the map with the subsection -// name used as the map key. -// (Note that unlike section and variable names, subsection names are case -// sensitive.) -// When using a map, and there is a section with the same section name but -// without a subsection name, its values are stored with the empty string used -// as the key. -// It is possible to provide default values for subsections in the section -// "default-" (or by setting values in the corresponding struct -// field "Default_"). -// -// The functions in this package panic if config is not a pointer to a struct, -// or when a field is not of a suitable type (either a struct or a map with -// string keys and pointer-to-struct values). -// -// Parsing of values -// -// The section structs in the config struct may contain single-valued or -// multi-valued variables. Variables of unnamed slice type (that is, a type -// starting with `[]`) are treated as multi-value; all others (including named -// slice types) are treated as single-valued variables. -// -// Single-valued variables are handled based on the type as follows. -// Unnamed pointer types (that is, types starting with `*`) are dereferenced, -// and if necessary, a new instance is allocated. -// -// For types implementing the encoding.TextUnmarshaler interface, the -// UnmarshalText method is used to set the value. Implementing this method is -// the recommended way for parsing user-defined types. -// -// For fields of string kind, the value string is assigned to the field, after -// unquoting and unescaping as needed. -// For fields of bool kind, the field is set to true if the value is "true", -// "yes", "on" or "1", and set to false if the value is "false", "no", "off" or -// "0", ignoring case. In addition, single-valued bool fields can be specified -// with a "blank" value (variable name without equals sign and value); in such -// case the value is set to true. -// -// Predefined integer types [u]int(|8|16|32|64) and big.Int are parsed as -// decimal or hexadecimal (if having '0x' prefix). (This is to prevent -// unintuitively handling zero-padded numbers as octal.) Other types having -// [u]int* as the underlying type, such as os.FileMode and uintptr allow -// decimal, hexadecimal, or octal values. -// Parsing mode for integer types can be overridden using the struct tag option -// ",int=mode" where mode is a combination of the 'd', 'h', and 'o' characters -// (each standing for decimal, hexadecimal, and octal, respectively.) -// -// All other types are parsed using fmt.Sscanf with the "%v" verb. -// -// For multi-valued variables, each individual value is parsed as above and -// appended to the slice. If the first value is specified as a "blank" value -// (variable name without equals sign and value), a new slice is allocated; -// that is any values previously set in the slice will be ignored. -// -// The types subpackage for provides helpers for parsing "enum-like" and integer -// types. -// -// Error handling -// -// There are 3 types of errors: -// -// - programmer errors / panics: -// - invalid configuration structure -// - data errors: -// - fatal errors: -// - invalid configuration syntax -// - warnings: -// - data that doesn't belong to any part of the config structure -// -// Programmer errors trigger panics. These are should be fixed by the programmer -// before releasing code that uses gcfg. -// -// Data errors cause gcfg to return a non-nil error value. This includes the -// case when there are extra unknown key-value definitions in the configuration -// data (extra data). -// However, in some occasions it is desirable to be able to proceed in -// situations when the only data error is that of extra data. -// These errors are handled at a different (warning) priority and can be -// filtered out programmatically. To ignore extra data warnings, wrap the -// gcfg.Read*Into invocation into a call to gcfg.FatalOnly. -// -// TODO -// -// The following is a list of changes under consideration: -// - documentation -// - self-contained syntax documentation -// - more practical examples -// - move TODOs to issue tracker (eventually) -// - syntax -// - reconsider valid escape sequences -// (gitconfig doesn't support \r in value, \t in subsection name, etc.) -// - reading / parsing gcfg files -// - define internal representation structure -// - support multiple inputs (readers, strings, files) -// - support declaring encoding (?) -// - support varying fields sets for subsections (?) -// - writing gcfg files -// - error handling -// - make error context accessible programmatically? -// - limit input size? -// -package gcfg // import "github.com/go-git/gcfg" diff --git a/vendor/github.com/go-git/gcfg/errors.go b/vendor/github.com/go-git/gcfg/errors.go deleted file mode 100644 index 853c7602..00000000 --- a/vendor/github.com/go-git/gcfg/errors.go +++ /dev/null @@ -1,41 +0,0 @@ -package gcfg - -import ( - "gopkg.in/warnings.v0" -) - -// FatalOnly filters the results of a Read*Into invocation and returns only -// fatal errors. That is, errors (warnings) indicating data for unknown -// sections / variables is ignored. Example invocation: -// -// err := gcfg.FatalOnly(gcfg.ReadFileInto(&cfg, configFile)) -// if err != nil { -// ... -// -func FatalOnly(err error) error { - return warnings.FatalOnly(err) -} - -func isFatal(err error) bool { - _, ok := err.(extraData) - return !ok -} - -type extraData struct { - section string - subsection *string - variable *string -} - -func (e extraData) Error() string { - s := "can't store data at section \"" + e.section + "\"" - if e.subsection != nil { - s += ", subsection \"" + *e.subsection + "\"" - } - if e.variable != nil { - s += ", variable \"" + *e.variable + "\"" - } - return s -} - -var _ error = extraData{} diff --git a/vendor/github.com/go-git/gcfg/go1_0.go b/vendor/github.com/go-git/gcfg/go1_0.go deleted file mode 100644 index 66702107..00000000 --- a/vendor/github.com/go-git/gcfg/go1_0.go +++ /dev/null @@ -1,7 +0,0 @@ -// +build !go1.2 - -package gcfg - -type textUnmarshaler interface { - UnmarshalText(text []byte) error -} diff --git a/vendor/github.com/go-git/gcfg/go1_2.go b/vendor/github.com/go-git/gcfg/go1_2.go deleted file mode 100644 index 6f5843bc..00000000 --- a/vendor/github.com/go-git/gcfg/go1_2.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build go1.2 - -package gcfg - -import ( - "encoding" -) - -type textUnmarshaler encoding.TextUnmarshaler diff --git a/vendor/github.com/go-git/gcfg/read.go b/vendor/github.com/go-git/gcfg/read.go deleted file mode 100644 index 4dfdc5cf..00000000 --- a/vendor/github.com/go-git/gcfg/read.go +++ /dev/null @@ -1,273 +0,0 @@ -package gcfg - -import ( - "fmt" - "io" - "io/ioutil" - "os" - "strings" - - "github.com/go-git/gcfg/scanner" - "github.com/go-git/gcfg/token" - "gopkg.in/warnings.v0" -) - -var unescape = map[rune]rune{'\\': '\\', '"': '"', 'n': '\n', 't': '\t', 'b': '\b'} - -// no error: invalid literals should be caught by scanner -func unquote(s string) string { - u, q, esc := make([]rune, 0, len(s)), false, false - for _, c := range s { - if esc { - uc, ok := unescape[c] - switch { - case ok: - u = append(u, uc) - fallthrough - case !q && c == '\n': - esc = false - continue - } - panic("invalid escape sequence") - } - switch c { - case '"': - q = !q - case '\\': - esc = true - default: - u = append(u, c) - } - } - if q { - panic("missing end quote") - } - if esc { - panic("invalid escape sequence") - } - return string(u) -} - -func read(c *warnings.Collector, callback func(string, string, string, string, bool) error, - fset *token.FileSet, file *token.File, src []byte) error { - // - var s scanner.Scanner - var errs scanner.ErrorList - s.Init(file, src, func(p token.Position, m string) { errs.Add(p, m) }, 0) - sect, sectsub := "", "" - pos, tok, lit := s.Scan() - errfn := func(msg string) error { - return fmt.Errorf("%s: %s", fset.Position(pos), msg) - } - for { - if errs.Len() > 0 { - if err := c.Collect(errs.Err()); err != nil { - return err - } - } - switch tok { - case token.EOF: - return nil - case token.EOL, token.COMMENT: - pos, tok, lit = s.Scan() - case token.LBRACK: - pos, tok, lit = s.Scan() - if errs.Len() > 0 { - if err := c.Collect(errs.Err()); err != nil { - return err - } - } - if tok != token.IDENT { - if err := c.Collect(errfn("expected section name")); err != nil { - return err - } - } - sect, sectsub = lit, "" - pos, tok, lit = s.Scan() - if errs.Len() > 0 { - if err := c.Collect(errs.Err()); err != nil { - return err - } - } - if tok == token.STRING { - sectsub = unquote(lit) - if sectsub == "" { - if err := c.Collect(errfn("empty subsection name")); err != nil { - return err - } - } - pos, tok, lit = s.Scan() - if errs.Len() > 0 { - if err := c.Collect(errs.Err()); err != nil { - return err - } - } - } - if tok != token.RBRACK { - if sectsub == "" { - if err := c.Collect(errfn("expected subsection name or right bracket")); err != nil { - return err - } - } - if err := c.Collect(errfn("expected right bracket")); err != nil { - return err - } - } - pos, tok, lit = s.Scan() - if tok != token.EOL && tok != token.EOF && tok != token.COMMENT { - if err := c.Collect(errfn("expected EOL, EOF, or comment")); err != nil { - return err - } - } - // If a section/subsection header was found, ensure a - // container object is created, even if there are no - // variables further down. - err := c.Collect(callback(sect, sectsub, "", "", true)) - if err != nil { - return err - } - case token.IDENT: - if sect == "" { - if err := c.Collect(errfn("expected section header")); err != nil { - return err - } - } - n := lit - pos, tok, lit = s.Scan() - if errs.Len() > 0 { - return errs.Err() - } - blank, v := tok == token.EOF || tok == token.EOL || tok == token.COMMENT, "" - if !blank { - if tok != token.ASSIGN { - if err := c.Collect(errfn("expected '='")); err != nil { - return err - } - } - pos, tok, lit = s.Scan() - if errs.Len() > 0 { - if err := c.Collect(errs.Err()); err != nil { - return err - } - } - if tok != token.STRING { - if err := c.Collect(errfn("expected value")); err != nil { - return err - } - } - v = unquote(lit) - pos, tok, lit = s.Scan() - if errs.Len() > 0 { - if err := c.Collect(errs.Err()); err != nil { - return err - } - } - if tok != token.EOL && tok != token.EOF && tok != token.COMMENT { - if err := c.Collect(errfn("expected EOL, EOF, or comment")); err != nil { - return err - } - } - } - err := c.Collect(callback(sect, sectsub, n, v, blank)) - if err != nil { - return err - } - default: - if sect == "" { - if err := c.Collect(errfn("expected section header")); err != nil { - return err - } - } - if err := c.Collect(errfn("expected section header or variable declaration")); err != nil { - return err - } - } - } - panic("never reached") -} - -func readInto(config interface{}, fset *token.FileSet, file *token.File, - src []byte) error { - // - c := warnings.NewCollector(isFatal) - firstPassCallback := func(s string, ss string, k string, v string, bv bool) error { - return set(c, config, s, ss, k, v, bv, false) - } - err := read(c, firstPassCallback, fset, file, src) - if err != nil { - return err - } - secondPassCallback := func(s string, ss string, k string, v string, bv bool) error { - return set(c, config, s, ss, k, v, bv, true) - } - err = read(c, secondPassCallback, fset, file, src) - if err != nil { - return err - } - return c.Done() -} - -// ReadWithCallback reads gcfg formatted data from reader and calls -// callback with each section and option found. -// -// Callback is called with section, subsection, option key, option value -// and blank value flag as arguments. -// -// When a section is found, callback is called with nil subsection, option key -// and option value. -// -// When a subsection is found, callback is called with nil option key and -// option value. -// -// If blank value flag is true, it means that the value was not set for an option -// (as opposed to set to empty string). -// -// If callback returns an error, ReadWithCallback terminates with an error too. -func ReadWithCallback(reader io.Reader, callback func(string, string, string, string, bool) error) error { - src, err := ioutil.ReadAll(reader) - if err != nil { - return err - } - - fset := token.NewFileSet() - file := fset.AddFile("", fset.Base(), len(src)) - c := warnings.NewCollector(isFatal) - - return read(c, callback, fset, file, src) -} - -// ReadInto reads gcfg formatted data from reader and sets the values into the -// corresponding fields in config. -func ReadInto(config interface{}, reader io.Reader) error { - src, err := ioutil.ReadAll(reader) - if err != nil { - return err - } - fset := token.NewFileSet() - file := fset.AddFile("", fset.Base(), len(src)) - return readInto(config, fset, file, src) -} - -// ReadStringInto reads gcfg formatted data from str and sets the values into -// the corresponding fields in config. -func ReadStringInto(config interface{}, str string) error { - r := strings.NewReader(str) - return ReadInto(config, r) -} - -// ReadFileInto reads gcfg formatted data from the file filename and sets the -// values into the corresponding fields in config. -func ReadFileInto(config interface{}, filename string) error { - f, err := os.Open(filename) - if err != nil { - return err - } - defer f.Close() - src, err := ioutil.ReadAll(f) - if err != nil { - return err - } - fset := token.NewFileSet() - file := fset.AddFile(filename, fset.Base(), len(src)) - return readInto(config, fset, file, src) -} diff --git a/vendor/github.com/go-git/gcfg/scanner/errors.go b/vendor/github.com/go-git/gcfg/scanner/errors.go deleted file mode 100644 index a6e00f5c..00000000 --- a/vendor/github.com/go-git/gcfg/scanner/errors.go +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright 2009 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 scanner - -import ( - "fmt" - "io" - "sort" -) - -import ( - "github.com/go-git/gcfg/token" -) - -// In an ErrorList, an error is represented by an *Error. -// The position Pos, if valid, points to the beginning of -// the offending token, and the error condition is described -// by Msg. -// -type Error struct { - Pos token.Position - Msg string -} - -// Error implements the error interface. -func (e Error) Error() string { - if e.Pos.Filename != "" || e.Pos.IsValid() { - // don't print "" - // TODO(gri) reconsider the semantics of Position.IsValid - return e.Pos.String() + ": " + e.Msg - } - return e.Msg -} - -// ErrorList is a list of *Errors. -// The zero value for an ErrorList is an empty ErrorList ready to use. -// -type ErrorList []*Error - -// Add adds an Error with given position and error message to an ErrorList. -func (p *ErrorList) Add(pos token.Position, msg string) { - *p = append(*p, &Error{pos, msg}) -} - -// Reset resets an ErrorList to no errors. -func (p *ErrorList) Reset() { *p = (*p)[0:0] } - -// ErrorList implements the sort Interface. -func (p ErrorList) Len() int { return len(p) } -func (p ErrorList) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -func (p ErrorList) Less(i, j int) bool { - e := &p[i].Pos - f := &p[j].Pos - if e.Filename < f.Filename { - return true - } - if e.Filename == f.Filename { - return e.Offset < f.Offset - } - return false -} - -// Sort sorts an ErrorList. *Error entries are sorted by position, -// other errors are sorted by error message, and before any *Error -// entry. -// -func (p ErrorList) Sort() { - sort.Sort(p) -} - -// RemoveMultiples sorts an ErrorList and removes all but the first error per line. -func (p *ErrorList) RemoveMultiples() { - sort.Sort(p) - var last token.Position // initial last.Line is != any legal error line - i := 0 - for _, e := range *p { - if e.Pos.Filename != last.Filename || e.Pos.Line != last.Line { - last = e.Pos - (*p)[i] = e - i++ - } - } - (*p) = (*p)[0:i] -} - -// An ErrorList implements the error interface. -func (p ErrorList) Error() string { - switch len(p) { - case 0: - return "no errors" - case 1: - return p[0].Error() - } - return fmt.Sprintf("%s (and %d more errors)", p[0], len(p)-1) -} - -// Err returns an error equivalent to this error list. -// If the list is empty, Err returns nil. -func (p ErrorList) Err() error { - if len(p) == 0 { - return nil - } - return p -} - -// PrintError is a utility function that prints a list of errors to w, -// one error per line, if the err parameter is an ErrorList. Otherwise -// it prints the err string. -// -func PrintError(w io.Writer, err error) { - if list, ok := err.(ErrorList); ok { - for _, e := range list { - fmt.Fprintf(w, "%s\n", e) - } - } else if err != nil { - fmt.Fprintf(w, "%s\n", err) - } -} diff --git a/vendor/github.com/go-git/gcfg/scanner/scanner.go b/vendor/github.com/go-git/gcfg/scanner/scanner.go deleted file mode 100644 index 41aafec7..00000000 --- a/vendor/github.com/go-git/gcfg/scanner/scanner.go +++ /dev/null @@ -1,342 +0,0 @@ -// Copyright 2009 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 scanner implements a scanner for gcfg configuration text. -// It takes a []byte as source which can then be tokenized -// through repeated calls to the Scan method. -// -// Note that the API for the scanner package may change to accommodate new -// features or implementation changes in gcfg. -// -package scanner - -import ( - "fmt" - "path/filepath" - "unicode" - "unicode/utf8" -) - -import ( - "github.com/go-git/gcfg/token" -) - -// An ErrorHandler may be provided to Scanner.Init. If a syntax error is -// encountered and a handler was installed, the handler is called with a -// position and an error message. The position points to the beginning of -// the offending token. -// -type ErrorHandler func(pos token.Position, msg string) - -// A Scanner holds the scanner's internal state while processing -// a given text. It can be allocated as part of another data -// structure but must be initialized via Init before use. -// -type Scanner struct { - // immutable state - file *token.File // source file handle - dir string // directory portion of file.Name() - src []byte // source - err ErrorHandler // error reporting; or nil - mode Mode // scanning mode - - // scanning state - ch rune // current character - offset int // character offset - rdOffset int // reading offset (position after current character) - lineOffset int // current line offset - nextVal bool // next token is expected to be a value - - // public state - ok to modify - ErrorCount int // number of errors encountered -} - -// Read the next Unicode char into s.ch. -// s.ch < 0 means end-of-file. -// -func (s *Scanner) next() { - if s.rdOffset < len(s.src) { - s.offset = s.rdOffset - if s.ch == '\n' { - s.lineOffset = s.offset - s.file.AddLine(s.offset) - } - r, w := rune(s.src[s.rdOffset]), 1 - switch { - case r == 0: - s.error(s.offset, "illegal character NUL") - case r >= 0x80: - // not ASCII - r, w = utf8.DecodeRune(s.src[s.rdOffset:]) - if r == utf8.RuneError && w == 1 { - s.error(s.offset, "illegal UTF-8 encoding") - } - } - s.rdOffset += w - s.ch = r - } else { - s.offset = len(s.src) - if s.ch == '\n' { - s.lineOffset = s.offset - s.file.AddLine(s.offset) - } - s.ch = -1 // eof - } -} - -// A mode value is a set of flags (or 0). -// They control scanner behavior. -// -type Mode uint - -const ( - ScanComments Mode = 1 << iota // return comments as COMMENT tokens -) - -// Init prepares the scanner s to tokenize the text src by setting the -// scanner at the beginning of src. The scanner uses the file set file -// for position information and it adds line information for each line. -// It is ok to re-use the same file when re-scanning the same file as -// line information which is already present is ignored. Init causes a -// panic if the file size does not match the src size. -// -// Calls to Scan will invoke the error handler err if they encounter a -// syntax error and err is not nil. Also, for each error encountered, -// the Scanner field ErrorCount is incremented by one. The mode parameter -// determines how comments are handled. -// -// Note that Init may call err if there is an error in the first character -// of the file. -// -func (s *Scanner) Init(file *token.File, src []byte, err ErrorHandler, mode Mode) { - // Explicitly initialize all fields since a scanner may be reused. - if file.Size() != len(src) { - panic(fmt.Sprintf("file size (%d) does not match src len (%d)", file.Size(), len(src))) - } - s.file = file - s.dir, _ = filepath.Split(file.Name()) - s.src = src - s.err = err - s.mode = mode - - s.ch = ' ' - s.offset = 0 - s.rdOffset = 0 - s.lineOffset = 0 - s.ErrorCount = 0 - s.nextVal = false - - s.next() -} - -func (s *Scanner) error(offs int, msg string) { - if s.err != nil { - s.err(s.file.Position(s.file.Pos(offs)), msg) - } - s.ErrorCount++ -} - -func (s *Scanner) scanComment() string { - // initial [;#] already consumed - offs := s.offset - 1 // position of initial [;#] - - for s.ch != '\n' && s.ch >= 0 { - s.next() - } - return string(s.src[offs:s.offset]) -} - -func isLetter(ch rune) bool { - return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch >= 0x80 && unicode.IsLetter(ch) -} - -func isDigit(ch rune) bool { - return '0' <= ch && ch <= '9' || ch >= 0x80 && unicode.IsDigit(ch) -} - -func (s *Scanner) scanIdentifier() string { - offs := s.offset - for isLetter(s.ch) || isDigit(s.ch) || s.ch == '-' { - s.next() - } - return string(s.src[offs:s.offset]) -} - -func (s *Scanner) scanEscape(val bool) { - offs := s.offset - ch := s.ch - s.next() // always make progress - switch ch { - case '\\', '"': - // ok - case 'n', 't', 'b': - if val { - break // ok - } - fallthrough - default: - s.error(offs, "unknown escape sequence") - } -} - -func (s *Scanner) scanString() string { - // '"' opening already consumed - offs := s.offset - 1 - - for s.ch != '"' { - ch := s.ch - s.next() - if ch == '\n' || ch < 0 { - s.error(offs, "string not terminated") - break - } - if ch == '\\' { - s.scanEscape(false) - } - } - - s.next() - - return string(s.src[offs:s.offset]) -} - -func stripCR(b []byte) []byte { - c := make([]byte, len(b)) - i := 0 - for _, ch := range b { - if ch != '\r' { - c[i] = ch - i++ - } - } - return c[:i] -} - -func (s *Scanner) scanValString() string { - offs := s.offset - - hasCR := false - end := offs - inQuote := false -loop: - for inQuote || s.ch >= 0 && s.ch != '\n' && s.ch != ';' && s.ch != '#' { - ch := s.ch - s.next() - switch { - case inQuote && ch == '\\': - s.scanEscape(true) - case !inQuote && ch == '\\': - if s.ch == '\r' { - hasCR = true - s.next() - } - if s.ch != '\n' { - s.scanEscape(true) - } else { - s.next() - } - case ch == '"': - inQuote = !inQuote - case ch == '\r': - hasCR = true - case ch < 0 || inQuote && ch == '\n': - s.error(offs, "string not terminated") - break loop - } - if inQuote || !isWhiteSpace(ch) { - end = s.offset - } - } - - lit := s.src[offs:end] - if hasCR { - lit = stripCR(lit) - } - - return string(lit) -} - -func isWhiteSpace(ch rune) bool { - return ch == ' ' || ch == '\t' || ch == '\r' -} - -func (s *Scanner) skipWhitespace() { - for isWhiteSpace(s.ch) { - s.next() - } -} - -// Scan scans the next token and returns the token position, the token, -// and its literal string if applicable. The source end is indicated by -// token.EOF. -// -// If the returned token is a literal (token.IDENT, token.STRING) or -// token.COMMENT, the literal string has the corresponding value. -// -// If the returned token is token.ILLEGAL, the literal string is the -// offending character. -// -// In all other cases, Scan returns an empty literal string. -// -// For more tolerant parsing, Scan will return a valid token if -// possible even if a syntax error was encountered. Thus, even -// if the resulting token sequence contains no illegal tokens, -// a client may not assume that no error occurred. Instead it -// must check the scanner's ErrorCount or the number of calls -// of the error handler, if there was one installed. -// -// Scan adds line information to the file added to the file -// set with Init. Token positions are relative to that file -// and thus relative to the file set. -// -func (s *Scanner) Scan() (pos token.Pos, tok token.Token, lit string) { -scanAgain: - s.skipWhitespace() - - // current token start - pos = s.file.Pos(s.offset) - - // determine token value - switch ch := s.ch; { - case s.nextVal: - lit = s.scanValString() - tok = token.STRING - s.nextVal = false - case isLetter(ch): - lit = s.scanIdentifier() - tok = token.IDENT - default: - s.next() // always make progress - switch ch { - case -1: - tok = token.EOF - case '\n': - tok = token.EOL - case '"': - tok = token.STRING - lit = s.scanString() - case '[': - tok = token.LBRACK - case ']': - tok = token.RBRACK - case ';', '#': - // comment - lit = s.scanComment() - if s.mode&ScanComments == 0 { - // skip comment - goto scanAgain - } - tok = token.COMMENT - case '=': - tok = token.ASSIGN - s.nextVal = true - default: - s.error(s.file.Offset(pos), fmt.Sprintf("illegal character %#U", ch)) - tok = token.ILLEGAL - lit = string(ch) - } - } - - return -} diff --git a/vendor/github.com/go-git/gcfg/set.go b/vendor/github.com/go-git/gcfg/set.go deleted file mode 100644 index e2d92780..00000000 --- a/vendor/github.com/go-git/gcfg/set.go +++ /dev/null @@ -1,332 +0,0 @@ -package gcfg - -import ( - "bytes" - "encoding/gob" - "fmt" - "math/big" - "reflect" - "strings" - "unicode" - "unicode/utf8" - - "github.com/go-git/gcfg/types" - "gopkg.in/warnings.v0" -) - -type tag struct { - ident string - intMode string -} - -func newTag(ts string) tag { - t := tag{} - s := strings.Split(ts, ",") - t.ident = s[0] - for _, tse := range s[1:] { - if strings.HasPrefix(tse, "int=") { - t.intMode = tse[len("int="):] - } - } - return t -} - -func fieldFold(v reflect.Value, name string) (reflect.Value, tag) { - var n string - r0, _ := utf8.DecodeRuneInString(name) - if unicode.IsLetter(r0) && !unicode.IsLower(r0) && !unicode.IsUpper(r0) { - n = "X" - } - n += strings.Replace(name, "-", "_", -1) - f, ok := v.Type().FieldByNameFunc(func(fieldName string) bool { - if !v.FieldByName(fieldName).CanSet() { - return false - } - f, _ := v.Type().FieldByName(fieldName) - t := newTag(f.Tag.Get("gcfg")) - if t.ident != "" { - return strings.EqualFold(t.ident, name) - } - return strings.EqualFold(n, fieldName) - }) - if !ok { - return reflect.Value{}, tag{} - } - return v.FieldByName(f.Name), newTag(f.Tag.Get("gcfg")) -} - -type setter func(destp interface{}, blank bool, val string, t tag) error - -var errUnsupportedType = fmt.Errorf("unsupported type") -var errBlankUnsupported = fmt.Errorf("blank value not supported for type") - -var setters = []setter{ - typeSetter, textUnmarshalerSetter, kindSetter, scanSetter, -} - -func textUnmarshalerSetter(d interface{}, blank bool, val string, t tag) error { - dtu, ok := d.(textUnmarshaler) - if !ok { - return errUnsupportedType - } - if blank { - return errBlankUnsupported - } - return dtu.UnmarshalText([]byte(val)) -} - -func boolSetter(d interface{}, blank bool, val string, t tag) error { - if blank { - reflect.ValueOf(d).Elem().Set(reflect.ValueOf(true)) - return nil - } - b, err := types.ParseBool(val) - if err == nil { - reflect.ValueOf(d).Elem().Set(reflect.ValueOf(b)) - } - return err -} - -func intMode(mode string) types.IntMode { - var m types.IntMode - if strings.ContainsAny(mode, "dD") { - m |= types.Dec - } - if strings.ContainsAny(mode, "hH") { - m |= types.Hex - } - if strings.ContainsAny(mode, "oO") { - m |= types.Oct - } - return m -} - -var typeModes = map[reflect.Type]types.IntMode{ - reflect.TypeOf(int(0)): types.Dec | types.Hex, - reflect.TypeOf(int8(0)): types.Dec | types.Hex, - reflect.TypeOf(int16(0)): types.Dec | types.Hex, - reflect.TypeOf(int32(0)): types.Dec | types.Hex, - reflect.TypeOf(int64(0)): types.Dec | types.Hex, - reflect.TypeOf(uint(0)): types.Dec | types.Hex, - reflect.TypeOf(uint8(0)): types.Dec | types.Hex, - reflect.TypeOf(uint16(0)): types.Dec | types.Hex, - reflect.TypeOf(uint32(0)): types.Dec | types.Hex, - reflect.TypeOf(uint64(0)): types.Dec | types.Hex, - // use default mode (allow dec/hex/oct) for uintptr type - reflect.TypeOf(big.Int{}): types.Dec | types.Hex, -} - -func intModeDefault(t reflect.Type) types.IntMode { - m, ok := typeModes[t] - if !ok { - m = types.Dec | types.Hex | types.Oct - } - return m -} - -func intSetter(d interface{}, blank bool, val string, t tag) error { - if blank { - return errBlankUnsupported - } - mode := intMode(t.intMode) - if mode == 0 { - mode = intModeDefault(reflect.TypeOf(d).Elem()) - } - return types.ParseInt(d, val, mode) -} - -func stringSetter(d interface{}, blank bool, val string, t tag) error { - if blank { - return errBlankUnsupported - } - dsp, ok := d.(*string) - if !ok { - return errUnsupportedType - } - *dsp = val - return nil -} - -var kindSetters = map[reflect.Kind]setter{ - reflect.String: stringSetter, - reflect.Bool: boolSetter, - reflect.Int: intSetter, - reflect.Int8: intSetter, - reflect.Int16: intSetter, - reflect.Int32: intSetter, - reflect.Int64: intSetter, - reflect.Uint: intSetter, - reflect.Uint8: intSetter, - reflect.Uint16: intSetter, - reflect.Uint32: intSetter, - reflect.Uint64: intSetter, - reflect.Uintptr: intSetter, -} - -var typeSetters = map[reflect.Type]setter{ - reflect.TypeOf(big.Int{}): intSetter, -} - -func typeSetter(d interface{}, blank bool, val string, tt tag) error { - t := reflect.ValueOf(d).Type().Elem() - setter, ok := typeSetters[t] - if !ok { - return errUnsupportedType - } - return setter(d, blank, val, tt) -} - -func kindSetter(d interface{}, blank bool, val string, tt tag) error { - k := reflect.ValueOf(d).Type().Elem().Kind() - setter, ok := kindSetters[k] - if !ok { - return errUnsupportedType - } - return setter(d, blank, val, tt) -} - -func scanSetter(d interface{}, blank bool, val string, tt tag) error { - if blank { - return errBlankUnsupported - } - return types.ScanFully(d, val, 'v') -} - -func newValue(c *warnings.Collector, sect string, vCfg reflect.Value, - vType reflect.Type) (reflect.Value, error) { - // - pv := reflect.New(vType) - dfltName := "default-" + sect - dfltField, _ := fieldFold(vCfg, dfltName) - var err error - if dfltField.IsValid() { - b := bytes.NewBuffer(nil) - ge := gob.NewEncoder(b) - if err = c.Collect(ge.EncodeValue(dfltField)); err != nil { - return pv, err - } - gd := gob.NewDecoder(bytes.NewReader(b.Bytes())) - if err = c.Collect(gd.DecodeValue(pv.Elem())); err != nil { - return pv, err - } - } - return pv, nil -} - -func set(c *warnings.Collector, cfg interface{}, sect, sub, name string, - value string, blankValue bool, subsectPass bool) error { - // - vPCfg := reflect.ValueOf(cfg) - if vPCfg.Kind() != reflect.Ptr || vPCfg.Elem().Kind() != reflect.Struct { - panic(fmt.Errorf("config must be a pointer to a struct")) - } - vCfg := vPCfg.Elem() - vSect, _ := fieldFold(vCfg, sect) - if !vSect.IsValid() { - err := extraData{section: sect} - return c.Collect(err) - } - isSubsect := vSect.Kind() == reflect.Map - if subsectPass != isSubsect { - return nil - } - if isSubsect { - vst := vSect.Type() - if vst.Key().Kind() != reflect.String || - vst.Elem().Kind() != reflect.Ptr || - vst.Elem().Elem().Kind() != reflect.Struct { - panic(fmt.Errorf("map field for section must have string keys and "+ - " pointer-to-struct values: section %q", sect)) - } - if vSect.IsNil() { - vSect.Set(reflect.MakeMap(vst)) - } - k := reflect.ValueOf(sub) - pv := vSect.MapIndex(k) - if !pv.IsValid() { - vType := vSect.Type().Elem().Elem() - var err error - if pv, err = newValue(c, sect, vCfg, vType); err != nil { - return err - } - vSect.SetMapIndex(k, pv) - } - vSect = pv.Elem() - } else if vSect.Kind() != reflect.Struct { - panic(fmt.Errorf("field for section must be a map or a struct: "+ - "section %q", sect)) - } else if sub != "" { - err := extraData{section: sect, subsection: &sub} - return c.Collect(err) - } - // Empty name is a special value, meaning that only the - // section/subsection object is to be created, with no values set. - if name == "" { - return nil - } - vVar, t := fieldFold(vSect, name) - if !vVar.IsValid() { - var err error - if isSubsect { - err = extraData{section: sect, subsection: &sub, variable: &name} - } else { - err = extraData{section: sect, variable: &name} - } - return c.Collect(err) - } - // vVal is either single-valued var, or newly allocated value within multi-valued var - var vVal reflect.Value - // multi-value if unnamed slice type - isMulti := vVar.Type().Name() == "" && vVar.Kind() == reflect.Slice || - vVar.Type().Name() == "" && vVar.Kind() == reflect.Ptr && vVar.Type().Elem().Name() == "" && vVar.Type().Elem().Kind() == reflect.Slice - if isMulti && vVar.Kind() == reflect.Ptr { - if vVar.IsNil() { - vVar.Set(reflect.New(vVar.Type().Elem())) - } - vVar = vVar.Elem() - } - if isMulti && blankValue { - vVar.Set(reflect.Zero(vVar.Type())) - return nil - } - if isMulti { - vVal = reflect.New(vVar.Type().Elem()).Elem() - } else { - vVal = vVar - } - isDeref := vVal.Type().Name() == "" && vVal.Type().Kind() == reflect.Ptr - isNew := isDeref && vVal.IsNil() - // vAddr is address of value to set (dereferenced & allocated as needed) - var vAddr reflect.Value - switch { - case isNew: - vAddr = reflect.New(vVal.Type().Elem()) - case isDeref && !isNew: - vAddr = vVal - default: - vAddr = vVal.Addr() - } - vAddrI := vAddr.Interface() - err, ok := error(nil), false - for _, s := range setters { - err = s(vAddrI, blankValue, value, t) - if err == nil { - ok = true - break - } - if err != errUnsupportedType { - return err - } - } - if !ok { - // in case all setters returned errUnsupportedType - return err - } - if isNew { // set reference if it was dereferenced and newly allocated - vVal.Set(vAddr) - } - if isMulti { // append if multi-valued - vVar.Set(reflect.Append(vVar, vVal)) - } - return nil -} diff --git a/vendor/github.com/go-git/gcfg/token/position.go b/vendor/github.com/go-git/gcfg/token/position.go deleted file mode 100644 index fc45c1e7..00000000 --- a/vendor/github.com/go-git/gcfg/token/position.go +++ /dev/null @@ -1,435 +0,0 @@ -// Copyright 2010 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. - -// TODO(gri) consider making this a separate package outside the go directory. - -package token - -import ( - "fmt" - "sort" - "sync" -) - -// ----------------------------------------------------------------------------- -// Positions - -// Position describes an arbitrary source position -// including the file, line, and column location. -// A Position is valid if the line number is > 0. -// -type Position struct { - Filename string // filename, if any - Offset int // offset, starting at 0 - Line int // line number, starting at 1 - Column int // column number, starting at 1 (character count) -} - -// IsValid returns true if the position is valid. -func (pos *Position) IsValid() bool { return pos.Line > 0 } - -// String returns a string in one of several forms: -// -// file:line:column valid position with file name -// line:column valid position without file name -// file invalid position with file name -// - invalid position without file name -// -func (pos Position) String() string { - s := pos.Filename - if pos.IsValid() { - if s != "" { - s += ":" - } - s += fmt.Sprintf("%d:%d", pos.Line, pos.Column) - } - if s == "" { - s = "-" - } - return s -} - -// Pos is a compact encoding of a source position within a file set. -// It can be converted into a Position for a more convenient, but much -// larger, representation. -// -// The Pos value for a given file is a number in the range [base, base+size], -// where base and size are specified when adding the file to the file set via -// AddFile. -// -// To create the Pos value for a specific source offset, first add -// the respective file to the current file set (via FileSet.AddFile) -// and then call File.Pos(offset) for that file. Given a Pos value p -// for a specific file set fset, the corresponding Position value is -// obtained by calling fset.Position(p). -// -// Pos values can be compared directly with the usual comparison operators: -// If two Pos values p and q are in the same file, comparing p and q is -// equivalent to comparing the respective source file offsets. If p and q -// are in different files, p < q is true if the file implied by p was added -// to the respective file set before the file implied by q. -// -type Pos int - -// The zero value for Pos is NoPos; there is no file and line information -// associated with it, and NoPos().IsValid() is false. NoPos is always -// smaller than any other Pos value. The corresponding Position value -// for NoPos is the zero value for Position. -// -const NoPos Pos = 0 - -// IsValid returns true if the position is valid. -func (p Pos) IsValid() bool { - return p != NoPos -} - -// ----------------------------------------------------------------------------- -// File - -// A File is a handle for a file belonging to a FileSet. -// A File has a name, size, and line offset table. -// -type File struct { - set *FileSet - name string // file name as provided to AddFile - base int // Pos value range for this file is [base...base+size] - size int // file size as provided to AddFile - - // lines and infos are protected by set.mutex - lines []int - infos []lineInfo -} - -// Name returns the file name of file f as registered with AddFile. -func (f *File) Name() string { - return f.name -} - -// Base returns the base offset of file f as registered with AddFile. -func (f *File) Base() int { - return f.base -} - -// Size returns the size of file f as registered with AddFile. -func (f *File) Size() int { - return f.size -} - -// LineCount returns the number of lines in file f. -func (f *File) LineCount() int { - f.set.mutex.RLock() - n := len(f.lines) - f.set.mutex.RUnlock() - return n -} - -// AddLine adds the line offset for a new line. -// The line offset must be larger than the offset for the previous line -// and smaller than the file size; otherwise the line offset is ignored. -// -func (f *File) AddLine(offset int) { - f.set.mutex.Lock() - if i := len(f.lines); (i == 0 || f.lines[i-1] < offset) && offset < f.size { - f.lines = append(f.lines, offset) - } - f.set.mutex.Unlock() -} - -// SetLines sets the line offsets for a file and returns true if successful. -// The line offsets are the offsets of the first character of each line; -// for instance for the content "ab\nc\n" the line offsets are {0, 3}. -// An empty file has an empty line offset table. -// Each line offset must be larger than the offset for the previous line -// and smaller than the file size; otherwise SetLines fails and returns -// false. -// -func (f *File) SetLines(lines []int) bool { - // verify validity of lines table - size := f.size - for i, offset := range lines { - if i > 0 && offset <= lines[i-1] || size <= offset { - return false - } - } - - // set lines table - f.set.mutex.Lock() - f.lines = lines - f.set.mutex.Unlock() - return true -} - -// SetLinesForContent sets the line offsets for the given file content. -func (f *File) SetLinesForContent(content []byte) { - var lines []int - line := 0 - for offset, b := range content { - if line >= 0 { - lines = append(lines, line) - } - line = -1 - if b == '\n' { - line = offset + 1 - } - } - - // set lines table - f.set.mutex.Lock() - f.lines = lines - f.set.mutex.Unlock() -} - -// A lineInfo object describes alternative file and line number -// information (such as provided via a //line comment in a .go -// file) for a given file offset. -type lineInfo struct { - // fields are exported to make them accessible to gob - Offset int - Filename string - Line int -} - -// AddLineInfo adds alternative file and line number information for -// a given file offset. The offset must be larger than the offset for -// the previously added alternative line info and smaller than the -// file size; otherwise the information is ignored. -// -// AddLineInfo is typically used to register alternative position -// information for //line filename:line comments in source files. -// -func (f *File) AddLineInfo(offset int, filename string, line int) { - f.set.mutex.Lock() - if i := len(f.infos); i == 0 || f.infos[i-1].Offset < offset && offset < f.size { - f.infos = append(f.infos, lineInfo{offset, filename, line}) - } - f.set.mutex.Unlock() -} - -// Pos returns the Pos value for the given file offset; -// the offset must be <= f.Size(). -// f.Pos(f.Offset(p)) == p. -// -func (f *File) Pos(offset int) Pos { - if offset > f.size { - panic("illegal file offset") - } - return Pos(f.base + offset) -} - -// Offset returns the offset for the given file position p; -// p must be a valid Pos value in that file. -// f.Offset(f.Pos(offset)) == offset. -// -func (f *File) Offset(p Pos) int { - if int(p) < f.base || int(p) > f.base+f.size { - panic("illegal Pos value") - } - return int(p) - f.base -} - -// Line returns the line number for the given file position p; -// p must be a Pos value in that file or NoPos. -// -func (f *File) Line(p Pos) int { - // TODO(gri) this can be implemented much more efficiently - return f.Position(p).Line -} - -func searchLineInfos(a []lineInfo, x int) int { - return sort.Search(len(a), func(i int) bool { return a[i].Offset > x }) - 1 -} - -// info returns the file name, line, and column number for a file offset. -func (f *File) info(offset int) (filename string, line, column int) { - filename = f.name - if i := searchInts(f.lines, offset); i >= 0 { - line, column = i+1, offset-f.lines[i]+1 - } - if len(f.infos) > 0 { - // almost no files have extra line infos - if i := searchLineInfos(f.infos, offset); i >= 0 { - alt := &f.infos[i] - filename = alt.Filename - if i := searchInts(f.lines, alt.Offset); i >= 0 { - line += alt.Line - i - 1 - } - } - } - return -} - -func (f *File) position(p Pos) (pos Position) { - offset := int(p) - f.base - pos.Offset = offset - pos.Filename, pos.Line, pos.Column = f.info(offset) - return -} - -// Position returns the Position value for the given file position p; -// p must be a Pos value in that file or NoPos. -// -func (f *File) Position(p Pos) (pos Position) { - if p != NoPos { - if int(p) < f.base || int(p) > f.base+f.size { - panic("illegal Pos value") - } - pos = f.position(p) - } - return -} - -// ----------------------------------------------------------------------------- -// FileSet - -// A FileSet represents a set of source files. -// Methods of file sets are synchronized; multiple goroutines -// may invoke them concurrently. -// -type FileSet struct { - mutex sync.RWMutex // protects the file set - base int // base offset for the next file - files []*File // list of files in the order added to the set - last *File // cache of last file looked up -} - -// NewFileSet creates a new file set. -func NewFileSet() *FileSet { - s := new(FileSet) - s.base = 1 // 0 == NoPos - return s -} - -// Base returns the minimum base offset that must be provided to -// AddFile when adding the next file. -// -func (s *FileSet) Base() int { - s.mutex.RLock() - b := s.base - s.mutex.RUnlock() - return b - -} - -// AddFile adds a new file with a given filename, base offset, and file size -// to the file set s and returns the file. Multiple files may have the same -// name. The base offset must not be smaller than the FileSet's Base(), and -// size must not be negative. -// -// Adding the file will set the file set's Base() value to base + size + 1 -// as the minimum base value for the next file. The following relationship -// exists between a Pos value p for a given file offset offs: -// -// int(p) = base + offs -// -// with offs in the range [0, size] and thus p in the range [base, base+size]. -// For convenience, File.Pos may be used to create file-specific position -// values from a file offset. -// -func (s *FileSet) AddFile(filename string, base, size int) *File { - s.mutex.Lock() - defer s.mutex.Unlock() - if base < s.base || size < 0 { - panic("illegal base or size") - } - // base >= s.base && size >= 0 - f := &File{s, filename, base, size, []int{0}, nil} - base += size + 1 // +1 because EOF also has a position - if base < 0 { - panic("token.Pos offset overflow (> 2G of source code in file set)") - } - // add the file to the file set - s.base = base - s.files = append(s.files, f) - s.last = f - return f -} - -// Iterate calls f for the files in the file set in the order they were added -// until f returns false. -// -func (s *FileSet) Iterate(f func(*File) bool) { - for i := 0; ; i++ { - var file *File - s.mutex.RLock() - if i < len(s.files) { - file = s.files[i] - } - s.mutex.RUnlock() - if file == nil || !f(file) { - break - } - } -} - -func searchFiles(a []*File, x int) int { - return sort.Search(len(a), func(i int) bool { return a[i].base > x }) - 1 -} - -func (s *FileSet) file(p Pos) *File { - // common case: p is in last file - if f := s.last; f != nil && f.base <= int(p) && int(p) <= f.base+f.size { - return f - } - // p is not in last file - search all files - if i := searchFiles(s.files, int(p)); i >= 0 { - f := s.files[i] - // f.base <= int(p) by definition of searchFiles - if int(p) <= f.base+f.size { - s.last = f - return f - } - } - return nil -} - -// File returns the file that contains the position p. -// If no such file is found (for instance for p == NoPos), -// the result is nil. -// -func (s *FileSet) File(p Pos) (f *File) { - if p != NoPos { - s.mutex.RLock() - f = s.file(p) - s.mutex.RUnlock() - } - return -} - -// Position converts a Pos in the fileset into a general Position. -func (s *FileSet) Position(p Pos) (pos Position) { - if p != NoPos { - s.mutex.RLock() - if f := s.file(p); f != nil { - pos = f.position(p) - } - s.mutex.RUnlock() - } - return -} - -// ----------------------------------------------------------------------------- -// Helper functions - -func searchInts(a []int, x int) int { - // This function body is a manually inlined version of: - // - // return sort.Search(len(a), func(i int) bool { return a[i] > x }) - 1 - // - // With better compiler optimizations, this may not be needed in the - // future, but at the moment this change improves the go/printer - // benchmark performance by ~30%. This has a direct impact on the - // speed of gofmt and thus seems worthwhile (2011-04-29). - // TODO(gri): Remove this when compilers have caught up. - i, j := 0, len(a) - for i < j { - h := i + (j-i)/2 // avoid overflow when computing h - // i ≤ h < j - if a[h] <= x { - i = h + 1 - } else { - j = h - } - } - return i - 1 -} diff --git a/vendor/github.com/go-git/gcfg/token/serialize.go b/vendor/github.com/go-git/gcfg/token/serialize.go deleted file mode 100644 index 4adc8f9e..00000000 --- a/vendor/github.com/go-git/gcfg/token/serialize.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package token - -type serializedFile struct { - // fields correspond 1:1 to fields with same (lower-case) name in File - Name string - Base int - Size int - Lines []int - Infos []lineInfo -} - -type serializedFileSet struct { - Base int - Files []serializedFile -} - -// Read calls decode to deserialize a file set into s; s must not be nil. -func (s *FileSet) Read(decode func(interface{}) error) error { - var ss serializedFileSet - if err := decode(&ss); err != nil { - return err - } - - s.mutex.Lock() - s.base = ss.Base - files := make([]*File, len(ss.Files)) - for i := 0; i < len(ss.Files); i++ { - f := &ss.Files[i] - files[i] = &File{s, f.Name, f.Base, f.Size, f.Lines, f.Infos} - } - s.files = files - s.last = nil - s.mutex.Unlock() - - return nil -} - -// Write calls encode to serialize the file set s. -func (s *FileSet) Write(encode func(interface{}) error) error { - var ss serializedFileSet - - s.mutex.Lock() - ss.Base = s.base - files := make([]serializedFile, len(s.files)) - for i, f := range s.files { - files[i] = serializedFile{f.name, f.base, f.size, f.lines, f.infos} - } - ss.Files = files - s.mutex.Unlock() - - return encode(ss) -} diff --git a/vendor/github.com/go-git/gcfg/token/token.go b/vendor/github.com/go-git/gcfg/token/token.go deleted file mode 100644 index b3c7c83f..00000000 --- a/vendor/github.com/go-git/gcfg/token/token.go +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright 2009 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 token defines constants representing the lexical tokens of the gcfg -// configuration syntax and basic operations on tokens (printing, predicates). -// -// Note that the API for the token package may change to accommodate new -// features or implementation changes in gcfg. -// -package token - -import "strconv" - -// Token is the set of lexical tokens of the gcfg configuration syntax. -type Token int - -// The list of tokens. -const ( - // Special tokens - ILLEGAL Token = iota - EOF - COMMENT - - literal_beg - // Identifiers and basic type literals - // (these tokens stand for classes of literals) - IDENT // section-name, variable-name - STRING // "subsection-name", variable value - literal_end - - operator_beg - // Operators and delimiters - ASSIGN // = - LBRACK // [ - RBRACK // ] - EOL // \n - operator_end -) - -var tokens = [...]string{ - ILLEGAL: "ILLEGAL", - - EOF: "EOF", - COMMENT: "COMMENT", - - IDENT: "IDENT", - STRING: "STRING", - - ASSIGN: "=", - LBRACK: "[", - RBRACK: "]", - EOL: "\n", -} - -// String returns the string corresponding to the token tok. -// For operators and delimiters, the string is the actual token character -// sequence (e.g., for the token ASSIGN, the string is "="). For all other -// tokens the string corresponds to the token constant name (e.g. for the -// token IDENT, the string is "IDENT"). -// -func (tok Token) String() string { - s := "" - if 0 <= tok && tok < Token(len(tokens)) { - s = tokens[tok] - } - if s == "" { - s = "token(" + strconv.Itoa(int(tok)) + ")" - } - return s -} - -// Predicates - -// IsLiteral returns true for tokens corresponding to identifiers -// and basic type literals; it returns false otherwise. -// -func (tok Token) IsLiteral() bool { return literal_beg < tok && tok < literal_end } - -// IsOperator returns true for tokens corresponding to operators and -// delimiters; it returns false otherwise. -// -func (tok Token) IsOperator() bool { return operator_beg < tok && tok < operator_end } diff --git a/vendor/github.com/go-git/gcfg/types/bool.go b/vendor/github.com/go-git/gcfg/types/bool.go deleted file mode 100644 index 8dcae0d8..00000000 --- a/vendor/github.com/go-git/gcfg/types/bool.go +++ /dev/null @@ -1,23 +0,0 @@ -package types - -// BoolValues defines the name and value mappings for ParseBool. -var BoolValues = map[string]interface{}{ - "true": true, "yes": true, "on": true, "1": true, - "false": false, "no": false, "off": false, "0": false, -} - -var boolParser = func() *EnumParser { - ep := &EnumParser{} - ep.AddVals(BoolValues) - return ep -}() - -// ParseBool parses bool values according to the definitions in BoolValues. -// Parsing is case-insensitive. -func ParseBool(s string) (bool, error) { - v, err := boolParser.Parse(s) - if err != nil { - return false, err - } - return v.(bool), nil -} diff --git a/vendor/github.com/go-git/gcfg/types/doc.go b/vendor/github.com/go-git/gcfg/types/doc.go deleted file mode 100644 index 9f9c345f..00000000 --- a/vendor/github.com/go-git/gcfg/types/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// Package types defines helpers for type conversions. -// -// The API for this package is not finalized yet. -package types diff --git a/vendor/github.com/go-git/gcfg/types/enum.go b/vendor/github.com/go-git/gcfg/types/enum.go deleted file mode 100644 index 1a0c7ef4..00000000 --- a/vendor/github.com/go-git/gcfg/types/enum.go +++ /dev/null @@ -1,44 +0,0 @@ -package types - -import ( - "fmt" - "reflect" - "strings" -) - -// EnumParser parses "enum" values; i.e. a predefined set of strings to -// predefined values. -type EnumParser struct { - Type string // type name; if not set, use type of first value added - CaseMatch bool // if true, matching of strings is case-sensitive - // PrefixMatch bool - vals map[string]interface{} -} - -// AddVals adds strings and values to an EnumParser. -func (ep *EnumParser) AddVals(vals map[string]interface{}) { - if ep.vals == nil { - ep.vals = make(map[string]interface{}) - } - for k, v := range vals { - if ep.Type == "" { - ep.Type = reflect.TypeOf(v).Name() - } - if !ep.CaseMatch { - k = strings.ToLower(k) - } - ep.vals[k] = v - } -} - -// Parse parses the string and returns the value or an error. -func (ep EnumParser) Parse(s string) (interface{}, error) { - if !ep.CaseMatch { - s = strings.ToLower(s) - } - v, ok := ep.vals[s] - if !ok { - return false, fmt.Errorf("failed to parse %s %#q", ep.Type, s) - } - return v, nil -} diff --git a/vendor/github.com/go-git/gcfg/types/int.go b/vendor/github.com/go-git/gcfg/types/int.go deleted file mode 100644 index af7e75c1..00000000 --- a/vendor/github.com/go-git/gcfg/types/int.go +++ /dev/null @@ -1,86 +0,0 @@ -package types - -import ( - "fmt" - "strings" -) - -// An IntMode is a mode for parsing integer values, representing a set of -// accepted bases. -type IntMode uint8 - -// IntMode values for ParseInt; can be combined using binary or. -const ( - Dec IntMode = 1 << iota - Hex - Oct -) - -// String returns a string representation of IntMode; e.g. `IntMode(Dec|Hex)`. -func (m IntMode) String() string { - var modes []string - if m&Dec != 0 { - modes = append(modes, "Dec") - } - if m&Hex != 0 { - modes = append(modes, "Hex") - } - if m&Oct != 0 { - modes = append(modes, "Oct") - } - return "IntMode(" + strings.Join(modes, "|") + ")" -} - -var errIntAmbig = fmt.Errorf("ambiguous integer value; must include '0' prefix") - -func prefix0(val string) bool { - return strings.HasPrefix(val, "0") || strings.HasPrefix(val, "-0") -} - -func prefix0x(val string) bool { - return strings.HasPrefix(val, "0x") || strings.HasPrefix(val, "-0x") -} - -// ParseInt parses val using mode into intptr, which must be a pointer to an -// integer kind type. Non-decimal value require prefix `0` or `0x` in the cases -// when mode permits ambiguity of base; otherwise the prefix can be omitted. -func ParseInt(intptr interface{}, val string, mode IntMode) error { - val = strings.TrimSpace(val) - verb := byte(0) - switch mode { - case Dec: - verb = 'd' - case Dec + Hex: - if prefix0x(val) { - verb = 'v' - } else { - verb = 'd' - } - case Dec + Oct: - if prefix0(val) && !prefix0x(val) { - verb = 'v' - } else { - verb = 'd' - } - case Dec + Hex + Oct: - verb = 'v' - case Hex: - if prefix0x(val) { - verb = 'v' - } else { - verb = 'x' - } - case Oct: - verb = 'o' - case Hex + Oct: - if prefix0(val) { - verb = 'v' - } else { - return errIntAmbig - } - } - if verb == 0 { - panic("unsupported mode") - } - return ScanFully(intptr, val, verb) -} diff --git a/vendor/github.com/go-git/gcfg/types/scan.go b/vendor/github.com/go-git/gcfg/types/scan.go deleted file mode 100644 index db2f6ed3..00000000 --- a/vendor/github.com/go-git/gcfg/types/scan.go +++ /dev/null @@ -1,23 +0,0 @@ -package types - -import ( - "fmt" - "io" - "reflect" -) - -// ScanFully uses fmt.Sscanf with verb to fully scan val into ptr. -func ScanFully(ptr interface{}, val string, verb byte) error { - t := reflect.ValueOf(ptr).Elem().Type() - // attempt to read extra bytes to make sure the value is consumed - var b []byte - n, err := fmt.Sscanf(val, "%"+string(verb)+"%s", ptr, &b) - switch { - case n < 1 || n == 1 && err != io.EOF: - return fmt.Errorf("failed to parse %q as %v: %v", val, t, err) - case n > 1: - return fmt.Errorf("failed to parse %q as %v: extra characters %q", val, t, string(b)) - } - // n == 1 && err == io.EOF - return nil -} diff --git a/vendor/github.com/go-git/go-billy/v5/.gitignore b/vendor/github.com/go-git/go-billy/v5/.gitignore deleted file mode 100644 index 7aeb4669..00000000 --- a/vendor/github.com/go-git/go-billy/v5/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -/coverage.txt -/vendor -Gopkg.lock -Gopkg.toml diff --git a/vendor/github.com/go-git/go-billy/v5/LICENSE b/vendor/github.com/go-git/go-billy/v5/LICENSE deleted file mode 100644 index 9d607568..00000000 --- a/vendor/github.com/go-git/go-billy/v5/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright 2017 Sourced Technologies S.L. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/go-git/go-billy/v5/README.md b/vendor/github.com/go-git/go-billy/v5/README.md deleted file mode 100644 index da5c0747..00000000 --- a/vendor/github.com/go-git/go-billy/v5/README.md +++ /dev/null @@ -1,73 +0,0 @@ -# go-billy [![GoDoc](https://godoc.org/gopkg.in/go-git/go-billy.v5?status.svg)](https://pkg.go.dev/github.com/go-git/go-billy/v5) [![Test](https://github.com/go-git/go-billy/workflows/Test/badge.svg)](https://github.com/go-git/go-billy/actions?query=workflow%3ATest) - -The missing interface filesystem abstraction for Go. -Billy implements an interface based on the `os` standard library, allowing to develop applications without dependency on the underlying storage. Makes it virtually free to implement mocks and testing over filesystem operations. - -Billy was born as part of [go-git/go-git](https://github.com/go-git/go-git) project. - -## Installation - -```go -import "github.com/go-git/go-billy/v5" // with go modules enabled (GO111MODULE=on or outside GOPATH) -import "github.com/go-git/go-billy" // with go modules disabled -``` - -## Usage - -Billy exposes filesystems using the -[`Filesystem` interface](https://pkg.go.dev/github.com/go-git/go-billy/v5?tab=doc#Filesystem). -Each filesystem implementation gives you a `New` method, whose arguments depend on -the implementation itself, that returns a new `Filesystem`. - -The following example caches in memory all readable files in a directory from any -billy's filesystem implementation. - -```go -func LoadToMemory(origin billy.Filesystem, path string) (*memory.Memory, error) { - memory := memory.New() - - files, err := origin.ReadDir("/") - if err != nil { - return nil, err - } - - for _, file := range files { - if file.IsDir() { - continue - } - - src, err := origin.Open(file.Name()) - if err != nil { - return nil, err - } - - dst, err := memory.Create(file.Name()) - if err != nil { - return nil, err - } - - if _, err = io.Copy(dst, src); err != nil { - return nil, err - } - - if err := dst.Close(); err != nil { - return nil, err - } - - if err := src.Close(); err != nil { - return nil, err - } - } - - return memory, nil -} -``` - -## Why billy? - -The library billy deals with storage systems and Billy is the name of a well-known, IKEA -bookcase. That's it. - -## License - -Apache License Version 2.0, see [LICENSE](LICENSE) diff --git a/vendor/github.com/go-git/go-billy/v5/fs.go b/vendor/github.com/go-git/go-billy/v5/fs.go deleted file mode 100644 index a9efccde..00000000 --- a/vendor/github.com/go-git/go-billy/v5/fs.go +++ /dev/null @@ -1,202 +0,0 @@ -package billy - -import ( - "errors" - "io" - "os" - "time" -) - -var ( - ErrReadOnly = errors.New("read-only filesystem") - ErrNotSupported = errors.New("feature not supported") - ErrCrossedBoundary = errors.New("chroot boundary crossed") -) - -// Capability holds the supported features of a billy filesystem. This does -// not mean that the capability has to be supported by the underlying storage. -// For example, a billy filesystem may support WriteCapability but the -// storage be mounted in read only mode. -type Capability uint64 - -const ( - // WriteCapability means that the fs is writable. - WriteCapability Capability = 1 << iota - // ReadCapability means that the fs is readable. - ReadCapability - // ReadAndWriteCapability is the ability to open a file in read and write mode. - ReadAndWriteCapability - // SeekCapability means it is able to move position inside the file. - SeekCapability - // TruncateCapability means that a file can be truncated. - TruncateCapability - // LockCapability is the ability to lock a file. - LockCapability - - // DefaultCapabilities lists all capable features supported by filesystems - // without Capability interface. This list should not be changed until a - // major version is released. - DefaultCapabilities Capability = WriteCapability | ReadCapability | - ReadAndWriteCapability | SeekCapability | TruncateCapability | - LockCapability - - // AllCapabilities lists all capable features. - AllCapabilities Capability = WriteCapability | ReadCapability | - ReadAndWriteCapability | SeekCapability | TruncateCapability | - LockCapability -) - -// Filesystem abstract the operations in a storage-agnostic interface. -// Each method implementation mimics the behavior of the equivalent functions -// at the os package from the standard library. -type Filesystem interface { - Basic - TempFile - Dir - Symlink - Chroot -} - -// Basic abstract the basic operations in a storage-agnostic interface as -// an extension to the Basic interface. -type Basic interface { - // Create creates the named file with mode 0666 (before umask), truncating - // it if it already exists. If successful, methods on the returned File can - // be used for I/O; the associated file descriptor has mode O_RDWR. - Create(filename string) (File, error) - // Open opens the named file for reading. If successful, methods on the - // returned file can be used for reading; the associated file descriptor has - // mode O_RDONLY. - Open(filename string) (File, error) - // OpenFile is the generalized open call; most users will use Open or Create - // instead. It opens the named file with specified flag (O_RDONLY etc.) and - // perm, (0666 etc.) if applicable. If successful, methods on the returned - // File can be used for I/O. - OpenFile(filename string, flag int, perm os.FileMode) (File, error) - // Stat returns a FileInfo describing the named file. - Stat(filename string) (os.FileInfo, error) - // Rename renames (moves) oldpath to newpath. If newpath already exists and - // is not a directory, Rename replaces it. OS-specific restrictions may - // apply when oldpath and newpath are in different directories. - Rename(oldpath, newpath string) error - // Remove removes the named file or directory. - Remove(filename string) error - // Join joins any number of path elements into a single path, adding a - // Separator if necessary. Join calls filepath.Clean on the result; in - // particular, all empty strings are ignored. On Windows, the result is a - // UNC path if and only if the first path element is a UNC path. - Join(elem ...string) string -} - -type TempFile interface { - // TempFile creates a new temporary file in the directory dir with a name - // beginning with prefix, opens the file for reading and writing, and - // returns the resulting *os.File. If dir is the empty string, TempFile - // uses the default directory for temporary files (see os.TempDir). - // Multiple programs calling TempFile simultaneously will not choose the - // same file. The caller can use f.Name() to find the pathname of the file. - // It is the caller's responsibility to remove the file when no longer - // needed. - TempFile(dir, prefix string) (File, error) -} - -// Dir abstract the dir related operations in a storage-agnostic interface as -// an extension to the Basic interface. -type Dir interface { - // ReadDir reads the directory named by dirname and returns a list of - // directory entries sorted by filename. - ReadDir(path string) ([]os.FileInfo, error) - // MkdirAll creates a directory named path, along with any necessary - // parents, and returns nil, or else returns an error. The permission bits - // perm are used for all directories that MkdirAll creates. If path is/ - // already a directory, MkdirAll does nothing and returns nil. - MkdirAll(filename string, perm os.FileMode) error -} - -// Symlink abstract the symlink related operations in a storage-agnostic -// interface as an extension to the Basic interface. -type Symlink interface { - // Lstat returns a FileInfo describing the named file. If the file is a - // symbolic link, the returned FileInfo describes the symbolic link. Lstat - // makes no attempt to follow the link. - Lstat(filename string) (os.FileInfo, error) - // Symlink creates a symbolic-link from link to target. target may be an - // absolute or relative path, and need not refer to an existing node. - // Parent directories of link are created as necessary. - Symlink(target, link string) error - // Readlink returns the target path of link. - Readlink(link string) (string, error) -} - -// Change abstract the FileInfo change related operations in a storage-agnostic -// interface as an extension to the Basic interface -type Change interface { - // Chmod changes the mode of the named file to mode. If the file is a - // symbolic link, it changes the mode of the link's target. - Chmod(name string, mode os.FileMode) error - // Lchown changes the numeric uid and gid of the named file. If the file is - // a symbolic link, it changes the uid and gid of the link itself. - Lchown(name string, uid, gid int) error - // Chown changes the numeric uid and gid of the named file. If the file is a - // symbolic link, it changes the uid and gid of the link's target. - Chown(name string, uid, gid int) error - // Chtimes changes the access and modification times of the named file, - // similar to the Unix utime() or utimes() functions. - // - // The underlying filesystem may truncate or round the values to a less - // precise time unit. - Chtimes(name string, atime time.Time, mtime time.Time) error -} - -// Chroot abstract the chroot related operations in a storage-agnostic interface -// as an extension to the Basic interface. -type Chroot interface { - // Chroot returns a new filesystem from the same type where the new root is - // the given path. Files outside of the designated directory tree cannot be - // accessed. - Chroot(path string) (Filesystem, error) - // Root returns the root path of the filesystem. - Root() string -} - -// File represent a file, being a subset of the os.File -type File interface { - // Name returns the name of the file as presented to Open. - Name() string - io.Writer - io.Reader - io.ReaderAt - io.Seeker - io.Closer - // Lock locks the file like e.g. flock. It protects against access from - // other processes. - Lock() error - // Unlock unlocks the file. - Unlock() error - // Truncate the file. - Truncate(size int64) error -} - -// Capable interface can return the available features of a filesystem. -type Capable interface { - // Capabilities returns the capabilities of a filesystem in bit flags. - Capabilities() Capability -} - -// Capabilities returns the features supported by a filesystem. If the FS -// does not implement Capable interface it returns all features. -func Capabilities(fs Basic) Capability { - capable, ok := fs.(Capable) - if !ok { - return DefaultCapabilities - } - - return capable.Capabilities() -} - -// CapabilityCheck tests the filesystem for the provided capabilities and -// returns true in case it supports all of them. -func CapabilityCheck(fs Basic, capabilities Capability) bool { - fsCaps := Capabilities(fs) - return fsCaps&capabilities == capabilities -} diff --git a/vendor/github.com/go-git/go-billy/v5/helper/chroot/chroot.go b/vendor/github.com/go-git/go-billy/v5/helper/chroot/chroot.go deleted file mode 100644 index 8b44e784..00000000 --- a/vendor/github.com/go-git/go-billy/v5/helper/chroot/chroot.go +++ /dev/null @@ -1,242 +0,0 @@ -package chroot - -import ( - "os" - "path/filepath" - "strings" - - "github.com/go-git/go-billy/v5" - "github.com/go-git/go-billy/v5/helper/polyfill" -) - -// ChrootHelper is a helper to implement billy.Chroot. -type ChrootHelper struct { - underlying billy.Filesystem - base string -} - -// New creates a new filesystem wrapping up the given 'fs'. -// The created filesystem has its base in the given ChrootHelperectory of the -// underlying filesystem. -func New(fs billy.Basic, base string) billy.Filesystem { - return &ChrootHelper{ - underlying: polyfill.New(fs), - base: base, - } -} - -func (fs *ChrootHelper) underlyingPath(filename string) (string, error) { - if isCrossBoundaries(filename) { - return "", billy.ErrCrossedBoundary - } - - return fs.Join(fs.Root(), filename), nil -} - -func isCrossBoundaries(path string) bool { - path = filepath.ToSlash(path) - path = filepath.Clean(path) - - return strings.HasPrefix(path, ".."+string(filepath.Separator)) -} - -func (fs *ChrootHelper) Create(filename string) (billy.File, error) { - fullpath, err := fs.underlyingPath(filename) - if err != nil { - return nil, err - } - - f, err := fs.underlying.Create(fullpath) - if err != nil { - return nil, err - } - - return newFile(fs, f, filename), nil -} - -func (fs *ChrootHelper) Open(filename string) (billy.File, error) { - fullpath, err := fs.underlyingPath(filename) - if err != nil { - return nil, err - } - - f, err := fs.underlying.Open(fullpath) - if err != nil { - return nil, err - } - - return newFile(fs, f, filename), nil -} - -func (fs *ChrootHelper) OpenFile(filename string, flag int, mode os.FileMode) (billy.File, error) { - fullpath, err := fs.underlyingPath(filename) - if err != nil { - return nil, err - } - - f, err := fs.underlying.OpenFile(fullpath, flag, mode) - if err != nil { - return nil, err - } - - return newFile(fs, f, filename), nil -} - -func (fs *ChrootHelper) Stat(filename string) (os.FileInfo, error) { - fullpath, err := fs.underlyingPath(filename) - if err != nil { - return nil, err - } - - return fs.underlying.Stat(fullpath) -} - -func (fs *ChrootHelper) Rename(from, to string) error { - var err error - from, err = fs.underlyingPath(from) - if err != nil { - return err - } - - to, err = fs.underlyingPath(to) - if err != nil { - return err - } - - return fs.underlying.Rename(from, to) -} - -func (fs *ChrootHelper) Remove(path string) error { - fullpath, err := fs.underlyingPath(path) - if err != nil { - return err - } - - return fs.underlying.Remove(fullpath) -} - -func (fs *ChrootHelper) Join(elem ...string) string { - return fs.underlying.Join(elem...) -} - -func (fs *ChrootHelper) TempFile(dir, prefix string) (billy.File, error) { - fullpath, err := fs.underlyingPath(dir) - if err != nil { - return nil, err - } - - f, err := fs.underlying.(billy.TempFile).TempFile(fullpath, prefix) - if err != nil { - return nil, err - } - - return newFile(fs, f, fs.Join(dir, filepath.Base(f.Name()))), nil -} - -func (fs *ChrootHelper) ReadDir(path string) ([]os.FileInfo, error) { - fullpath, err := fs.underlyingPath(path) - if err != nil { - return nil, err - } - - return fs.underlying.(billy.Dir).ReadDir(fullpath) -} - -func (fs *ChrootHelper) MkdirAll(filename string, perm os.FileMode) error { - fullpath, err := fs.underlyingPath(filename) - if err != nil { - return err - } - - return fs.underlying.(billy.Dir).MkdirAll(fullpath, perm) -} - -func (fs *ChrootHelper) Lstat(filename string) (os.FileInfo, error) { - fullpath, err := fs.underlyingPath(filename) - if err != nil { - return nil, err - } - - return fs.underlying.(billy.Symlink).Lstat(fullpath) -} - -func (fs *ChrootHelper) Symlink(target, link string) error { - target = filepath.FromSlash(target) - - // only rewrite target if it's already absolute - if filepath.IsAbs(target) || strings.HasPrefix(target, string(filepath.Separator)) { - target = fs.Join(fs.Root(), target) - target = filepath.Clean(filepath.FromSlash(target)) - } - - link, err := fs.underlyingPath(link) - if err != nil { - return err - } - - return fs.underlying.(billy.Symlink).Symlink(target, link) -} - -func (fs *ChrootHelper) Readlink(link string) (string, error) { - fullpath, err := fs.underlyingPath(link) - if err != nil { - return "", err - } - - target, err := fs.underlying.(billy.Symlink).Readlink(fullpath) - if err != nil { - return "", err - } - - if !filepath.IsAbs(target) && !strings.HasPrefix(target, string(filepath.Separator)) { - return target, nil - } - - target, err = filepath.Rel(fs.base, target) - if err != nil { - return "", err - } - - return string(os.PathSeparator) + target, nil -} - -func (fs *ChrootHelper) Chroot(path string) (billy.Filesystem, error) { - fullpath, err := fs.underlyingPath(path) - if err != nil { - return nil, err - } - - return New(fs.underlying, fullpath), nil -} - -func (fs *ChrootHelper) Root() string { - return fs.base -} - -func (fs *ChrootHelper) Underlying() billy.Basic { - return fs.underlying -} - -// Capabilities implements the Capable interface. -func (fs *ChrootHelper) Capabilities() billy.Capability { - return billy.Capabilities(fs.underlying) -} - -type file struct { - billy.File - name string -} - -func newFile(fs billy.Filesystem, f billy.File, filename string) billy.File { - filename = fs.Join(fs.Root(), filename) - filename, _ = filepath.Rel(fs.Root(), filename) - - return &file{ - File: f, - name: filename, - } -} - -func (f *file) Name() string { - return f.name -} diff --git a/vendor/github.com/go-git/go-billy/v5/helper/polyfill/polyfill.go b/vendor/github.com/go-git/go-billy/v5/helper/polyfill/polyfill.go deleted file mode 100644 index 1efce0e7..00000000 --- a/vendor/github.com/go-git/go-billy/v5/helper/polyfill/polyfill.go +++ /dev/null @@ -1,105 +0,0 @@ -package polyfill - -import ( - "os" - "path/filepath" - - "github.com/go-git/go-billy/v5" -) - -// Polyfill is a helper that implements all missing method from billy.Filesystem. -type Polyfill struct { - billy.Basic - c capabilities -} - -type capabilities struct{ tempfile, dir, symlink, chroot bool } - -// New creates a new filesystem wrapping up 'fs' the intercepts all the calls -// made and errors if fs doesn't implement any of the billy interfaces. -func New(fs billy.Basic) billy.Filesystem { - if original, ok := fs.(billy.Filesystem); ok { - return original - } - - h := &Polyfill{Basic: fs} - - _, h.c.tempfile = h.Basic.(billy.TempFile) - _, h.c.dir = h.Basic.(billy.Dir) - _, h.c.symlink = h.Basic.(billy.Symlink) - _, h.c.chroot = h.Basic.(billy.Chroot) - return h -} - -func (h *Polyfill) TempFile(dir, prefix string) (billy.File, error) { - if !h.c.tempfile { - return nil, billy.ErrNotSupported - } - - return h.Basic.(billy.TempFile).TempFile(dir, prefix) -} - -func (h *Polyfill) ReadDir(path string) ([]os.FileInfo, error) { - if !h.c.dir { - return nil, billy.ErrNotSupported - } - - return h.Basic.(billy.Dir).ReadDir(path) -} - -func (h *Polyfill) MkdirAll(filename string, perm os.FileMode) error { - if !h.c.dir { - return billy.ErrNotSupported - } - - return h.Basic.(billy.Dir).MkdirAll(filename, perm) -} - -func (h *Polyfill) Symlink(target, link string) error { - if !h.c.symlink { - return billy.ErrNotSupported - } - - return h.Basic.(billy.Symlink).Symlink(target, link) -} - -func (h *Polyfill) Readlink(link string) (string, error) { - if !h.c.symlink { - return "", billy.ErrNotSupported - } - - return h.Basic.(billy.Symlink).Readlink(link) -} - -func (h *Polyfill) Lstat(path string) (os.FileInfo, error) { - if !h.c.symlink { - return nil, billy.ErrNotSupported - } - - return h.Basic.(billy.Symlink).Lstat(path) -} - -func (h *Polyfill) Chroot(path string) (billy.Filesystem, error) { - if !h.c.chroot { - return nil, billy.ErrNotSupported - } - - return h.Basic.(billy.Chroot).Chroot(path) -} - -func (h *Polyfill) Root() string { - if !h.c.chroot { - return string(filepath.Separator) - } - - return h.Basic.(billy.Chroot).Root() -} - -func (h *Polyfill) Underlying() billy.Basic { - return h.Basic -} - -// Capabilities implements the Capable interface. -func (h *Polyfill) Capabilities() billy.Capability { - return billy.Capabilities(h.Basic) -} diff --git a/vendor/github.com/go-git/go-billy/v5/osfs/os.go b/vendor/github.com/go-git/go-billy/v5/osfs/os.go deleted file mode 100644 index 880389ff..00000000 --- a/vendor/github.com/go-git/go-billy/v5/osfs/os.go +++ /dev/null @@ -1,139 +0,0 @@ -// Package osfs provides a billy filesystem for the OS. -package osfs // import "github.com/go-git/go-billy/v5/osfs" - -import ( - "io/ioutil" - "os" - "path/filepath" - "sync" - - "github.com/go-git/go-billy/v5" - "github.com/go-git/go-billy/v5/helper/chroot" -) - -const ( - defaultDirectoryMode = 0755 - defaultCreateMode = 0666 -) - -// OS is a filesystem based on the os filesystem. -type OS struct{} - -// New returns a new OS filesystem. -func New(baseDir string) billy.Filesystem { - return chroot.New(&OS{}, baseDir) -} - -func (fs *OS) Create(filename string) (billy.File, error) { - return fs.OpenFile(filename, os.O_RDWR|os.O_CREATE|os.O_TRUNC, defaultCreateMode) -} - -func (fs *OS) OpenFile(filename string, flag int, perm os.FileMode) (billy.File, error) { - if flag&os.O_CREATE != 0 { - if err := fs.createDir(filename); err != nil { - return nil, err - } - } - - f, err := os.OpenFile(filename, flag, perm) - if err != nil { - return nil, err - } - return &file{File: f}, err -} - -func (fs *OS) createDir(fullpath string) error { - dir := filepath.Dir(fullpath) - if dir != "." { - if err := os.MkdirAll(dir, defaultDirectoryMode); err != nil { - return err - } - } - - return nil -} - -func (fs *OS) ReadDir(path string) ([]os.FileInfo, error) { - l, err := ioutil.ReadDir(path) - if err != nil { - return nil, err - } - - var s = make([]os.FileInfo, len(l)) - for i, f := range l { - s[i] = f - } - - return s, nil -} - -func (fs *OS) Rename(from, to string) error { - if err := fs.createDir(to); err != nil { - return err - } - - return rename(from, to) -} - -func (fs *OS) MkdirAll(path string, perm os.FileMode) error { - return os.MkdirAll(path, defaultDirectoryMode) -} - -func (fs *OS) Open(filename string) (billy.File, error) { - return fs.OpenFile(filename, os.O_RDONLY, 0) -} - -func (fs *OS) Stat(filename string) (os.FileInfo, error) { - return os.Stat(filename) -} - -func (fs *OS) Remove(filename string) error { - return os.Remove(filename) -} - -func (fs *OS) TempFile(dir, prefix string) (billy.File, error) { - if err := fs.createDir(dir + string(os.PathSeparator)); err != nil { - return nil, err - } - - f, err := ioutil.TempFile(dir, prefix) - if err != nil { - return nil, err - } - return &file{File: f}, nil -} - -func (fs *OS) Join(elem ...string) string { - return filepath.Join(elem...) -} - -func (fs *OS) RemoveAll(path string) error { - return os.RemoveAll(filepath.Clean(path)) -} - -func (fs *OS) Lstat(filename string) (os.FileInfo, error) { - return os.Lstat(filepath.Clean(filename)) -} - -func (fs *OS) Symlink(target, link string) error { - if err := fs.createDir(link); err != nil { - return err - } - - return os.Symlink(target, link) -} - -func (fs *OS) Readlink(link string) (string, error) { - return os.Readlink(link) -} - -// Capabilities implements the Capable interface. -func (fs *OS) Capabilities() billy.Capability { - return billy.DefaultCapabilities -} - -// file is a wrapper for an os.File which adds support for file locking. -type file struct { - *os.File - m sync.Mutex -} diff --git a/vendor/github.com/go-git/go-billy/v5/osfs/os_plan9.go b/vendor/github.com/go-git/go-billy/v5/osfs/os_plan9.go deleted file mode 100644 index fe1eb85d..00000000 --- a/vendor/github.com/go-git/go-billy/v5/osfs/os_plan9.go +++ /dev/null @@ -1,83 +0,0 @@ -package osfs - -import ( - "io" - "os" - "path/filepath" - "syscall" -) - -func (f *file) Lock() error { - // Plan 9 uses a mode bit instead of explicit lock/unlock syscalls. - // - // Per http://man.cat-v.org/plan_9/5/stat: “Exclusive use files may be open - // for I/O by only one fid at a time across all clients of the server. If a - // second open is attempted, it draws an error.” - // - // There is no obvious way to implement this function using the exclusive use bit. - // See https://golang.org/src/cmd/go/internal/lockedfile/lockedfile_plan9.go - // for how file locking is done by the go tool on Plan 9. - return nil -} - -func (f *file) Unlock() error { - return nil -} - -func rename(from, to string) error { - // If from and to are in different directories, copy the file - // since Plan 9 does not support cross-directory rename. - if filepath.Dir(from) != filepath.Dir(to) { - fi, err := os.Stat(from) - if err != nil { - return &os.LinkError{"rename", from, to, err} - } - if fi.Mode().IsDir() { - return &os.LinkError{"rename", from, to, syscall.EISDIR} - } - fromFile, err := os.Open(from) - if err != nil { - return &os.LinkError{"rename", from, to, err} - } - toFile, err := os.OpenFile(to, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, fi.Mode()) - if err != nil { - return &os.LinkError{"rename", from, to, err} - } - _, err = io.Copy(toFile, fromFile) - if err != nil { - return &os.LinkError{"rename", from, to, err} - } - - // Copy mtime and mode from original file. - // We need only one syscall if we avoid os.Chmod and os.Chtimes. - dir := fi.Sys().(*syscall.Dir) - var d syscall.Dir - d.Null() - d.Mtime = dir.Mtime - d.Mode = dir.Mode - if err = dirwstat(to, &d); err != nil { - return &os.LinkError{"rename", from, to, err} - } - - // Remove original file. - err = os.Remove(from) - if err != nil { - return &os.LinkError{"rename", from, to, err} - } - return nil - } - return os.Rename(from, to) -} - -func dirwstat(name string, d *syscall.Dir) error { - var buf [syscall.STATFIXLEN]byte - - n, err := d.Marshal(buf[:]) - if err != nil { - return &os.PathError{"dirwstat", name, err} - } - if err = syscall.Wstat(name, buf[:n]); err != nil { - return &os.PathError{"dirwstat", name, err} - } - return nil -} diff --git a/vendor/github.com/go-git/go-billy/v5/osfs/os_posix.go b/vendor/github.com/go-git/go-billy/v5/osfs/os_posix.go deleted file mode 100644 index 7645dd52..00000000 --- a/vendor/github.com/go-git/go-billy/v5/osfs/os_posix.go +++ /dev/null @@ -1,27 +0,0 @@ -// +build !plan9,!windows - -package osfs - -import ( - "os" - - "golang.org/x/sys/unix" -) - -func (f *file) Lock() error { - f.m.Lock() - defer f.m.Unlock() - - return unix.Flock(int(f.File.Fd()), unix.LOCK_EX) -} - -func (f *file) Unlock() error { - f.m.Lock() - defer f.m.Unlock() - - return unix.Flock(int(f.File.Fd()), unix.LOCK_UN) -} - -func rename(from, to string) error { - return os.Rename(from, to) -} diff --git a/vendor/github.com/go-git/go-billy/v5/osfs/os_windows.go b/vendor/github.com/go-git/go-billy/v5/osfs/os_windows.go deleted file mode 100644 index 8f5caeb0..00000000 --- a/vendor/github.com/go-git/go-billy/v5/osfs/os_windows.go +++ /dev/null @@ -1,61 +0,0 @@ -// +build windows - -package osfs - -import ( - "os" - "runtime" - "unsafe" - - "golang.org/x/sys/windows" -) - -type fileInfo struct { - os.FileInfo - name string -} - -func (fi *fileInfo) Name() string { - return fi.name -} - -var ( - kernel32DLL = windows.NewLazySystemDLL("kernel32.dll") - lockFileExProc = kernel32DLL.NewProc("LockFileEx") - unlockFileProc = kernel32DLL.NewProc("UnlockFile") -) - -const ( - lockfileExclusiveLock = 0x2 -) - -func (f *file) Lock() error { - f.m.Lock() - defer f.m.Unlock() - - var overlapped windows.Overlapped - // err is always non-nil as per sys/windows semantics. - ret, _, err := lockFileExProc.Call(f.File.Fd(), lockfileExclusiveLock, 0, 0xFFFFFFFF, 0, - uintptr(unsafe.Pointer(&overlapped))) - runtime.KeepAlive(&overlapped) - if ret == 0 { - return err - } - return nil -} - -func (f *file) Unlock() error { - f.m.Lock() - defer f.m.Unlock() - - // err is always non-nil as per sys/windows semantics. - ret, _, err := unlockFileProc.Call(f.File.Fd(), 0, 0, 0xFFFFFFFF, 0) - if ret == 0 { - return err - } - return nil -} - -func rename(from, to string) error { - return os.Rename(from, to) -} diff --git a/vendor/github.com/go-git/go-billy/v5/util/glob.go b/vendor/github.com/go-git/go-billy/v5/util/glob.go deleted file mode 100644 index f7cb1de8..00000000 --- a/vendor/github.com/go-git/go-billy/v5/util/glob.go +++ /dev/null @@ -1,111 +0,0 @@ -package util - -import ( - "path/filepath" - "sort" - "strings" - - "github.com/go-git/go-billy/v5" -) - -// Glob returns the names of all files matching pattern or nil -// if there is no matching file. The syntax of patterns is the same -// as in Match. The pattern may describe hierarchical names such as -// /usr/*/bin/ed (assuming the Separator is '/'). -// -// Glob ignores file system errors such as I/O errors reading directories. -// The only possible returned error is ErrBadPattern, when pattern -// is malformed. -// -// Function originally from https://golang.org/src/path/filepath/match_test.go -func Glob(fs billy.Filesystem, pattern string) (matches []string, err error) { - if !hasMeta(pattern) { - if _, err = fs.Lstat(pattern); err != nil { - return nil, nil - } - return []string{pattern}, nil - } - - dir, file := filepath.Split(pattern) - // Prevent infinite recursion. See issue 15879. - if dir == pattern { - return nil, filepath.ErrBadPattern - } - - var m []string - m, err = Glob(fs, cleanGlobPath(dir)) - if err != nil { - return - } - for _, d := range m { - matches, err = glob(fs, d, file, matches) - if err != nil { - return - } - } - return -} - -// cleanGlobPath prepares path for glob matching. -func cleanGlobPath(path string) string { - switch path { - case "": - return "." - case string(filepath.Separator): - // do nothing to the path - return path - default: - return path[0 : len(path)-1] // chop off trailing separator - } -} - -// glob searches for files matching pattern in the directory dir -// and appends them to matches. If the directory cannot be -// opened, it returns the existing matches. New matches are -// added in lexicographical order. -func glob(fs billy.Filesystem, dir, pattern string, matches []string) (m []string, e error) { - m = matches - fi, err := fs.Stat(dir) - if err != nil { - return - } - - if !fi.IsDir() { - return - } - - names, _ := readdirnames(fs, dir) - sort.Strings(names) - - for _, n := range names { - matched, err := filepath.Match(pattern, n) - if err != nil { - return m, err - } - if matched { - m = append(m, filepath.Join(dir, n)) - } - } - return -} - -// hasMeta reports whether path contains any of the magic characters -// recognized by Match. -func hasMeta(path string) bool { - // TODO(niemeyer): Should other magic characters be added here? - return strings.ContainsAny(path, "*?[") -} - -func readdirnames(fs billy.Filesystem, dir string) ([]string, error) { - files, err := fs.ReadDir(dir) - if err != nil { - return nil, err - } - - var names []string - for _, file := range files { - names = append(names, file.Name()) - } - - return names, nil -} diff --git a/vendor/github.com/go-git/go-billy/v5/util/util.go b/vendor/github.com/go-git/go-billy/v5/util/util.go deleted file mode 100644 index 34c1d9e7..00000000 --- a/vendor/github.com/go-git/go-billy/v5/util/util.go +++ /dev/null @@ -1,224 +0,0 @@ -package util - -import ( - "io" - "os" - "path/filepath" - "strconv" - "sync" - "time" - - "github.com/go-git/go-billy/v5" -) - -// RemoveAll removes path and any children it contains. It removes everything it -// can but returns the first error it encounters. If the path does not exist, -// RemoveAll returns nil (no error). -func RemoveAll(fs billy.Basic, path string) error { - fs, path = getUnderlyingAndPath(fs, path) - - if r, ok := fs.(removerAll); ok { - return r.RemoveAll(path) - } - - return removeAll(fs, path) -} - -type removerAll interface { - RemoveAll(string) error -} - -func removeAll(fs billy.Basic, path string) error { - // This implementation is adapted from os.RemoveAll. - - // Simple case: if Remove works, we're done. - err := fs.Remove(path) - if err == nil || os.IsNotExist(err) { - return nil - } - - // Otherwise, is this a directory we need to recurse into? - dir, serr := fs.Stat(path) - if serr != nil { - if os.IsNotExist(serr) { - return nil - } - - return serr - } - - if !dir.IsDir() { - // Not a directory; return the error from Remove. - return err - } - - dirfs, ok := fs.(billy.Dir) - if !ok { - return billy.ErrNotSupported - } - - // Directory. - fis, err := dirfs.ReadDir(path) - if err != nil { - if os.IsNotExist(err) { - // Race. It was deleted between the Lstat and Open. - // Return nil per RemoveAll's docs. - return nil - } - - return err - } - - // Remove contents & return first error. - err = nil - for _, fi := range fis { - cpath := fs.Join(path, fi.Name()) - err1 := removeAll(fs, cpath) - if err == nil { - err = err1 - } - } - - // Remove directory. - err1 := fs.Remove(path) - if err1 == nil || os.IsNotExist(err1) { - return nil - } - - if err == nil { - err = err1 - } - - return err - -} - -// WriteFile writes data to a file named by filename in the given filesystem. -// If the file does not exist, WriteFile creates it with permissions perm; -// otherwise WriteFile truncates it before writing. -func WriteFile(fs billy.Basic, filename string, data []byte, perm os.FileMode) error { - f, err := fs.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm) - if err != nil { - return err - } - - n, err := f.Write(data) - if err == nil && n < len(data) { - err = io.ErrShortWrite - } - - if err1 := f.Close(); err == nil { - err = err1 - } - - return err -} - -// Random number state. -// We generate random temporary file names so that there's a good -// chance the file doesn't exist yet - keeps the number of tries in -// TempFile to a minimum. -var rand uint32 -var randmu sync.Mutex - -func reseed() uint32 { - return uint32(time.Now().UnixNano() + int64(os.Getpid())) -} - -func nextSuffix() string { - randmu.Lock() - r := rand - if r == 0 { - r = reseed() - } - r = r*1664525 + 1013904223 // constants from Numerical Recipes - rand = r - randmu.Unlock() - return strconv.Itoa(int(1e9 + r%1e9))[1:] -} - -// TempFile creates a new temporary file in the directory dir with a name -// beginning with prefix, opens the file for reading and writing, and returns -// the resulting *os.File. If dir is the empty string, TempFile uses the default -// directory for temporary files (see os.TempDir). Multiple programs calling -// TempFile simultaneously will not choose the same file. The caller can use -// f.Name() to find the pathname of the file. It is the caller's responsibility -// to remove the file when no longer needed. -func TempFile(fs billy.Basic, dir, prefix string) (f billy.File, err error) { - // This implementation is based on stdlib ioutil.TempFile. - - if dir == "" { - dir = os.TempDir() - } - - nconflict := 0 - for i := 0; i < 10000; i++ { - name := filepath.Join(dir, prefix+nextSuffix()) - f, err = fs.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600) - if os.IsExist(err) { - if nconflict++; nconflict > 10 { - randmu.Lock() - rand = reseed() - randmu.Unlock() - } - continue - } - break - } - return -} - -// TempDir creates a new temporary directory in the directory dir -// with a name beginning with prefix and returns the path of the -// new directory. If dir is the empty string, TempDir uses the -// default directory for temporary files (see os.TempDir). -// Multiple programs calling TempDir simultaneously -// will not choose the same directory. It is the caller's responsibility -// to remove the directory when no longer needed. -func TempDir(fs billy.Dir, dir, prefix string) (name string, err error) { - // This implementation is based on stdlib ioutil.TempDir - - if dir == "" { - dir = os.TempDir() - } - - nconflict := 0 - for i := 0; i < 10000; i++ { - try := filepath.Join(dir, prefix+nextSuffix()) - err = fs.MkdirAll(try, 0700) - if os.IsExist(err) { - if nconflict++; nconflict > 10 { - randmu.Lock() - rand = reseed() - randmu.Unlock() - } - continue - } - if os.IsNotExist(err) { - if _, err := os.Stat(dir); os.IsNotExist(err) { - return "", err - } - } - if err == nil { - name = try - } - break - } - return -} - -type underlying interface { - Underlying() billy.Basic -} - -func getUnderlyingAndPath(fs billy.Basic, path string) (billy.Basic, string) { - u, ok := fs.(underlying) - if !ok { - return fs, path - } - if ch, ok := fs.(billy.Chroot); ok { - path = fs.Join(ch.Root(), path) - } - - return u.Underlying(), path -} diff --git a/vendor/github.com/go-git/go-git/v5/.gitignore b/vendor/github.com/go-git/go-git/v5/.gitignore deleted file mode 100644 index 038dd9f1..00000000 --- a/vendor/github.com/go-git/go-git/v5/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -coverage.out -*~ -coverage.txt -profile.out diff --git a/vendor/github.com/go-git/go-git/v5/CODE_OF_CONDUCT.md b/vendor/github.com/go-git/go-git/v5/CODE_OF_CONDUCT.md deleted file mode 100644 index a689fa3c..00000000 --- a/vendor/github.com/go-git/go-git/v5/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,74 +0,0 @@ -# Contributor Covenant Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and maintainers pledge to making participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, gender identity and expression, level of experience, -education, socio-economic status, nationality, personal appearance, race, -religion, or sexual identity and orientation. - -## Our Standards - -Examples of behavior that contributes to creating a positive environment -include: - -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and unwelcome sexual attention or - advances -* Trolling, insulting/derogatory comments, and personal or political attacks -* Public or private harassment -* Publishing others' private information, such as a physical or electronic - address, without explicit permission -* Other conduct which could reasonably be considered inappropriate in a - professional setting - -## Our Responsibilities - -Project maintainers are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project maintainers have the right and responsibility to remove, edit, or -reject comments, commits, code, wiki edits, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any contributor for other behaviors that they deem inappropriate, -threatening, offensive, or harmful. - -## Scope - -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. Examples of -representing a project or community include using an official project e-mail -address, posting via an official social media account, or acting as an appointed -representative at an online or offline event. Representation of a project may be -further defined and clarified by project maintainers. - -## Enforcement - -Instances of abusive, harassing, or otherwise unacceptable behavior may be -reported by contacting the project team at conduct@sourced.tech. All -complaints will be reviewed and investigated and will result in a response that -is deemed necessary and appropriate to the circumstances. The project team is -obligated to maintain confidentiality with regard to the reporter of an incident. -Further details of specific enforcement policies may be posted separately. - -Project maintainers who do not follow or enforce the Code of Conduct in good -faith may face temporary or permanent repercussions as determined by other -members of the project's leadership. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, -available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html - -[homepage]: https://www.contributor-covenant.org - diff --git a/vendor/github.com/go-git/go-git/v5/COMPATIBILITY.md b/vendor/github.com/go-git/go-git/v5/COMPATIBILITY.md deleted file mode 100644 index 2a72b501..00000000 --- a/vendor/github.com/go-git/go-git/v5/COMPATIBILITY.md +++ /dev/null @@ -1,111 +0,0 @@ -Supported Capabilities -====================== - -Here is a non-comprehensive table of git commands and features whose equivalent -is supported by go-git. - -| Feature | Status | Notes | -|---------------------------------------|--------|-------| -| **config** | -| config | ✔ | Reading and modifying per-repository configuration (`.git/config`) is supported. Global configuration (`$HOME/.gitconfig`) is not. | -| **getting and creating repositories** | -| init | ✔ | Plain init and `--bare` are supported. Flags `--template`, `--separate-git-dir` and `--shared` are not. | -| clone | ✔ | Plain clone and equivalents to `--progress`, `--single-branch`, `--depth`, `--origin`, `--recurse-submodules` are supported. Others are not. | -| **basic snapshotting** | -| add | ✔ | Plain add is supported. Any other flags aren't supported | -| status | ✔ | -| commit | ✔ | -| reset | ✔ | -| rm | ✔ | -| mv | ✔ | -| **branching and merging** | -| branch | ✔ | -| checkout | ✔ | Basic usages of checkout are supported. | -| merge | ✖ | -| mergetool | ✖ | -| stash | ✖ | -| tag | ✔ | -| **sharing and updating projects** | -| fetch | ✔ | -| pull | ✔ | Only supports merges where the merge can be resolved as a fast-forward. | -| push | ✔ | -| remote | ✔ | -| submodule | ✔ | -| **inspection and comparison** | -| show | ✔ | -| log | ✔ | -| shortlog | (see log) | -| describe | | -| **patching** | -| apply | ✖ | -| cherry-pick | ✖ | -| diff | ✔ | Patch object with UnifiedDiff output representation | -| rebase | ✖ | -| revert | ✖ | -| **debugging** | -| bisect | ✖ | -| blame | ✔ | -| grep | ✔ | -| **email** || -| am | ✖ | -| apply | ✖ | -| format-patch | ✖ | -| send-email | ✖ | -| request-pull | ✖ | -| **external systems** | -| svn | ✖ | -| fast-import | ✖ | -| **administration** | -| clean | ✔ | -| gc | ✖ | -| fsck | ✖ | -| reflog | ✖ | -| filter-branch | ✖ | -| instaweb | ✖ | -| archive | ✖ | -| bundle | ✖ | -| prune | ✖ | -| repack | ✖ | -| **server admin** | -| daemon | | -| update-server-info | | -| **advanced** | -| notes | ✖ | -| replace | ✖ | -| worktree | ✖ | -| annotate | (see blame) | -| **gpg** | -| git-verify-commit | ✔ | -| git-verify-tag | ✔ | -| **plumbing commands** | -| cat-file | ✔ | -| check-ignore | | -| commit-tree | | -| count-objects | | -| diff-index | | -| for-each-ref | ✔ | -| hash-object | ✔ | -| ls-files | ✔ | -| merge-base | ✔ | Calculates the merge-base only between two commits, and supports `--independent` and `--is-ancestor` modifiers; Does not support `--fork-point` nor `--octopus` modifiers. | -| read-tree | | -| rev-list | ✔ | -| rev-parse | | -| show-ref | ✔ | -| symbolic-ref | ✔ | -| update-index | | -| update-ref | | -| verify-pack | | -| write-tree | | -| **protocols** | -| http(s):// (dumb) | ✖ | -| http(s):// (smart) | ✔ | -| git:// | ✔ | -| ssh:// | ✔ | -| file:// | partial | Warning: this is not pure Golang. This shells out to the `git` binary. | -| custom | ✔ | -| **other features** | -| gitignore | ✔ | -| gitattributes | ✖ | -| index version | | -| packfile version | | -| push-certs | ✖ | diff --git a/vendor/github.com/go-git/go-git/v5/CONTRIBUTING.md b/vendor/github.com/go-git/go-git/v5/CONTRIBUTING.md deleted file mode 100644 index fce25328..00000000 --- a/vendor/github.com/go-git/go-git/v5/CONTRIBUTING.md +++ /dev/null @@ -1,46 +0,0 @@ -# Contributing Guidelines - -source{d} go-git project is [Apache 2.0 licensed](LICENSE) and accepts -contributions via GitHub pull requests. This document outlines some of the -conventions on development workflow, commit message formatting, contact points, -and other resources to make it easier to get your contribution accepted. - -## Support Channels - -The official support channels, for both users and contributors, are: - -- [StackOverflow go-git tag](https://stackoverflow.com/questions/tagged/go-git) for user questions. -- GitHub [Issues](https://github.com/src-d/go-git/issues)* for bug reports and feature requests. - -*Before opening a new issue or submitting a new pull request, it's helpful to -search the project - it's likely that another user has already reported the -issue you're facing, or it's a known issue that we're already aware of. - - -## How to Contribute - -Pull Requests (PRs) are the main and exclusive way to contribute to the official go-git project. -In order for a PR to be accepted it needs to pass a list of requirements: - -- You should be able to run the same query using `git`. We don't accept features that are not implemented in the official git implementation. -- The expected behavior must match the [official git implementation](https://github.com/git/git). -- The actual behavior must be correctly explained with natural language and providing a minimum working example in Go that reproduces it. -- All PRs must be written in idiomatic Go, formatted according to [gofmt](https://golang.org/cmd/gofmt/), and without any warnings from [go lint](https://github.com/golang/lint) nor [go vet](https://golang.org/cmd/vet/). -- They should in general include tests, and those shall pass. -- If the PR is a bug fix, it has to include a suite of unit tests for the new functionality. -- If the PR is a new feature, it has to come with a suite of unit tests, that tests the new functionality. -- In any case, all the PRs have to pass the personal evaluation of at least one of the maintainers of go-git. - -### Format of the commit message - -Every commit message should describe what was changed, under which context and, if applicable, the GitHub issue it relates to: - -``` -plumbing: packp, Skip argument validations for unknown capabilities. Fixes #623 -``` - -The format can be described more formally as follows: - -``` -: , . [Fixes #] -``` diff --git a/vendor/github.com/go-git/go-git/v5/LICENSE b/vendor/github.com/go-git/go-git/v5/LICENSE deleted file mode 100644 index 8aa3d854..00000000 --- a/vendor/github.com/go-git/go-git/v5/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright 2018 Sourced Technologies, S.L. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/go-git/go-git/v5/Makefile b/vendor/github.com/go-git/go-git/v5/Makefile deleted file mode 100644 index d10922fb..00000000 --- a/vendor/github.com/go-git/go-git/v5/Makefile +++ /dev/null @@ -1,38 +0,0 @@ -# General -WORKDIR = $(PWD) - -# Go parameters -GOCMD = go -GOTEST = $(GOCMD) test - -# Git config -GIT_VERSION ?= -GIT_DIST_PATH ?= $(PWD)/.git-dist -GIT_REPOSITORY = http://github.com/git/git.git - -# Coverage -COVERAGE_REPORT = coverage.out -COVERAGE_MODE = count - -build-git: - @if [ -f $(GIT_DIST_PATH)/git ]; then \ - echo "nothing to do, using cache $(GIT_DIST_PATH)"; \ - else \ - git clone $(GIT_REPOSITORY) -b $(GIT_VERSION) --depth 1 --single-branch $(GIT_DIST_PATH); \ - cd $(GIT_DIST_PATH); \ - make configure; \ - ./configure; \ - make all; \ - fi - -test: - @echo "running against `git version`"; \ - $(GOTEST) ./... - -test-coverage: - @echo "running against `git version`"; \ - echo "" > $(COVERAGE_REPORT); \ - $(GOTEST) -coverprofile=$(COVERAGE_REPORT) -coverpkg=./... -covermode=$(COVERAGE_MODE) ./... - -clean: - rm -rf $(GIT_DIST_PATH) \ No newline at end of file diff --git a/vendor/github.com/go-git/go-git/v5/README.md b/vendor/github.com/go-git/go-git/v5/README.md deleted file mode 100644 index ff0c9b72..00000000 --- a/vendor/github.com/go-git/go-git/v5/README.md +++ /dev/null @@ -1,131 +0,0 @@ -![go-git logo](https://cdn.rawgit.com/src-d/artwork/02036484/go-git/files/go-git-github-readme-header.png) -[![GoDoc](https://godoc.org/github.com/go-git/go-git/v5?status.svg)](https://pkg.go.dev/github.com/go-git/go-git/v5) [![Build Status](https://github.com/go-git/go-git/workflows/Test/badge.svg)](https://github.com/go-git/go-git/actions) [![Go Report Card](https://goreportcard.com/badge/github.com/go-git/go-git)](https://goreportcard.com/report/github.com/go-git/go-git) - -*go-git* is a highly extensible git implementation library written in **pure Go**. - -It can be used to manipulate git repositories at low level *(plumbing)* or high level *(porcelain)*, through an idiomatic Go API. It also supports several types of storage, such as in-memory filesystems, or custom implementations, thanks to the [`Storer`](https://pkg.go.dev/github.com/go-git/go-git/v5/plumbing/storer) interface. - -It's being actively developed since 2015 and is being used extensively by [Keybase](https://keybase.io/blog/encrypted-git-for-everyone), [Gitea](https://gitea.io/en-us/) or [Pulumi](https://github.com/search?q=org%3Apulumi+go-git&type=Code), and by many other libraries and tools. - -Project Status --------------- - -After the legal issues with the [`src-d`](https://github.com/src-d) organization, the lack of update for four months and the requirement to make a hard fork, the project is **now back to normality**. - -The project is currently actively maintained by individual contributors, including several of the original authors, but also backed by a new company, [gitsight](https://github.com/gitsight), where `go-git` is a critical component used at scale. - - -Comparison with git -------------------- - -*go-git* aims to be fully compatible with [git](https://github.com/git/git), all the *porcelain* operations are implemented to work exactly as *git* does. - -*git* is a humongous project with years of development by thousands of contributors, making it challenging for *go-git* to implement all the features. You can find a comparison of *go-git* vs *git* in the [compatibility documentation](COMPATIBILITY.md). - - -Installation ------------- - -The recommended way to install *go-git* is: - -```go -import "github.com/go-git/go-git/v5" // with go modules enabled (GO111MODULE=on or outside GOPATH) -import "github.com/go-git/go-git" // with go modules disabled -``` - - -Examples --------- - -> Please note that the `CheckIfError` and `Info` functions used in the examples are from the [examples package](https://github.com/go-git/go-git/blob/master/_examples/common.go#L19) just to be used in the examples. - - -### Basic example - -A basic example that mimics the standard `git clone` command - -```go -// Clone the given repository to the given directory -Info("git clone https://github.com/go-git/go-git") - -_, err := git.PlainClone("/tmp/foo", false, &git.CloneOptions{ - URL: "https://github.com/go-git/go-git", - Progress: os.Stdout, -}) - -CheckIfError(err) -``` - -Outputs: -``` -Counting objects: 4924, done. -Compressing objects: 100% (1333/1333), done. -Total 4924 (delta 530), reused 6 (delta 6), pack-reused 3533 -``` - -### In-memory example - -Cloning a repository into memory and printing the history of HEAD, just like `git log` does - - -```go -// Clones the given repository in memory, creating the remote, the local -// branches and fetching the objects, exactly as: -Info("git clone https://github.com/go-git/go-billy") - -r, err := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{ - URL: "https://github.com/go-git/go-billy", -}) - -CheckIfError(err) - -// Gets the HEAD history from HEAD, just like this command: -Info("git log") - -// ... retrieves the branch pointed by HEAD -ref, err := r.Head() -CheckIfError(err) - - -// ... retrieves the commit history -cIter, err := r.Log(&git.LogOptions{From: ref.Hash()}) -CheckIfError(err) - -// ... just iterates over the commits, printing it -err = cIter.ForEach(func(c *object.Commit) error { - fmt.Println(c) - return nil -}) -CheckIfError(err) -``` - -Outputs: -``` -commit ded8054fd0c3994453e9c8aacaf48d118d42991e -Author: Santiago M. Mola -Date: Sat Nov 12 21:18:41 2016 +0100 - - index: ReadFrom/WriteTo returns IndexReadError/IndexWriteError. (#9) - -commit df707095626f384ce2dc1a83b30f9a21d69b9dfc -Author: Santiago M. Mola -Date: Fri Nov 11 13:23:22 2016 +0100 - - readwriter: fix bug when writing index. (#10) - - When using ReadWriter on an existing siva file, absolute offset for - index entries was not being calculated correctly. -... -``` - -You can find this [example](_examples/log/main.go) and many others in the [examples](_examples) folder. - -Contribute ----------- - -[Contributions](https://github.com/go-git/go-git/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22) are more than welcome, if you are interested please take a look to -our [Contributing Guidelines](CONTRIBUTING.md). - -License -------- -Apache License Version 2.0, see [LICENSE](LICENSE) diff --git a/vendor/github.com/go-git/go-git/v5/blame.go b/vendor/github.com/go-git/go-git/v5/blame.go deleted file mode 100644 index 43634b32..00000000 --- a/vendor/github.com/go-git/go-git/v5/blame.go +++ /dev/null @@ -1,302 +0,0 @@ -package git - -import ( - "bytes" - "errors" - "fmt" - "strconv" - "strings" - "time" - "unicode/utf8" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/plumbing/object" - "github.com/go-git/go-git/v5/utils/diff" -) - -// BlameResult represents the result of a Blame operation. -type BlameResult struct { - // Path is the path of the File that we're blaming. - Path string - // Rev (Revision) is the hash of the specified Commit used to generate this result. - Rev plumbing.Hash - // Lines contains every line with its authorship. - Lines []*Line -} - -// Blame returns a BlameResult with the information about the last author of -// each line from file `path` at commit `c`. -func Blame(c *object.Commit, path string) (*BlameResult, error) { - // The file to blame is identified by the input arguments: - // commit and path. commit is a Commit object obtained from a Repository. Path - // represents a path to a specific file contained into the repository. - // - // Blaming a file is a two step process: - // - // 1. Create a linear history of the commits affecting a file. We use - // revlist.New for that. - // - // 2. Then build a graph with a node for every line in every file in - // the history of the file. - // - // Each node is assigned a commit: Start by the nodes in the first - // commit. Assign that commit as the creator of all its lines. - // - // Then jump to the nodes in the next commit, and calculate the diff - // between the two files. Newly created lines get - // assigned the new commit as its origin. Modified lines also get - // this new commit. Untouched lines retain the old commit. - // - // All this work is done in the assignOrigin function which holds all - // the internal relevant data in a "blame" struct, that is not - // exported. - // - // TODO: ways to improve the efficiency of this function: - // 1. Improve revlist - // 2. Improve how to traverse the history (example a backward traversal will - // be much more efficient) - // - // TODO: ways to improve the function in general: - // 1. Add memoization between revlist and assign. - // 2. It is using much more memory than needed, see the TODOs below. - - b := new(blame) - b.fRev = c - b.path = path - - // get all the file revisions - if err := b.fillRevs(); err != nil { - return nil, err - } - - // calculate the line tracking graph and fill in - // file contents in data. - if err := b.fillGraphAndData(); err != nil { - return nil, err - } - - file, err := b.fRev.File(b.path) - if err != nil { - return nil, err - } - finalLines, err := file.Lines() - if err != nil { - return nil, err - } - - // Each node (line) holds the commit where it was introduced or - // last modified. To achieve that we use the FORWARD algorithm - // described in Zimmermann, et al. "Mining Version Archives for - // Co-changed Lines", in proceedings of the Mining Software - // Repositories workshop, Shanghai, May 22-23, 2006. - lines, err := newLines(finalLines, b.sliceGraph(len(b.graph)-1)) - if err != nil { - return nil, err - } - - return &BlameResult{ - Path: path, - Rev: c.Hash, - Lines: lines, - }, nil -} - -// Line values represent the contents and author of a line in BlamedResult values. -type Line struct { - // Author is the email address of the last author that modified the line. - Author string - // Text is the original text of the line. - Text string - // Date is when the original text of the line was introduced - Date time.Time - // Hash is the commit hash that introduced the original line - Hash plumbing.Hash -} - -func newLine(author, text string, date time.Time, hash plumbing.Hash) *Line { - return &Line{ - Author: author, - Text: text, - Hash: hash, - Date: date, - } -} - -func newLines(contents []string, commits []*object.Commit) ([]*Line, error) { - lcontents := len(contents) - lcommits := len(commits) - - if lcontents != lcommits { - if lcontents == lcommits-1 && contents[lcontents-1] != "\n" { - contents = append(contents, "\n") - } else { - return nil, errors.New("contents and commits have different length") - } - } - - result := make([]*Line, 0, lcontents) - for i := range contents { - result = append(result, newLine( - commits[i].Author.Email, contents[i], - commits[i].Author.When, commits[i].Hash, - )) - } - - return result, nil -} - -// this struct is internally used by the blame function to hold its -// inputs, outputs and state. -type blame struct { - // the path of the file to blame - path string - // the commit of the final revision of the file to blame - fRev *object.Commit - // the chain of revisions affecting the the file to blame - revs []*object.Commit - // the contents of the file across all its revisions - data []string - // the graph of the lines in the file across all the revisions - graph [][]*object.Commit -} - -// calculate the history of a file "path", starting from commit "from", sorted by commit date. -func (b *blame) fillRevs() error { - var err error - - b.revs, err = references(b.fRev, b.path) - return err -} - -// build graph of a file from its revision history -func (b *blame) fillGraphAndData() error { - //TODO: not all commits are needed, only the current rev and the prev - b.graph = make([][]*object.Commit, len(b.revs)) - b.data = make([]string, len(b.revs)) // file contents in all the revisions - // for every revision of the file, starting with the first - // one... - for i, rev := range b.revs { - // get the contents of the file - file, err := rev.File(b.path) - if err != nil { - return nil - } - b.data[i], err = file.Contents() - if err != nil { - return err - } - nLines := countLines(b.data[i]) - // create a node for each line - b.graph[i] = make([]*object.Commit, nLines) - // assign a commit to each node - // if this is the first revision, then the node is assigned to - // this first commit. - if i == 0 { - for j := 0; j < nLines; j++ { - b.graph[i][j] = b.revs[i] - } - } else { - // if this is not the first commit, then assign to the old - // commit or to the new one, depending on what the diff - // says. - b.assignOrigin(i, i-1) - } - } - return nil -} - -// sliceGraph returns a slice of commits (one per line) for a particular -// revision of a file (0=first revision). -func (b *blame) sliceGraph(i int) []*object.Commit { - fVs := b.graph[i] - result := make([]*object.Commit, 0, len(fVs)) - for _, v := range fVs { - c := *v - result = append(result, &c) - } - return result -} - -// Assigns origin to vertexes in current (c) rev from data in its previous (p) -// revision -func (b *blame) assignOrigin(c, p int) { - // assign origin based on diff info - hunks := diff.Do(b.data[p], b.data[c]) - sl := -1 // source line - dl := -1 // destination line - for h := range hunks { - hLines := countLines(hunks[h].Text) - for hl := 0; hl < hLines; hl++ { - switch { - case hunks[h].Type == 0: - sl++ - dl++ - b.graph[c][dl] = b.graph[p][sl] - case hunks[h].Type == 1: - dl++ - b.graph[c][dl] = b.revs[c] - case hunks[h].Type == -1: - sl++ - default: - panic("unreachable") - } - } - } -} - -// GoString prints the results of a Blame using git-blame's style. -func (b *blame) GoString() string { - var buf bytes.Buffer - - file, err := b.fRev.File(b.path) - if err != nil { - panic("PrettyPrint: internal error in repo.Data") - } - contents, err := file.Contents() - if err != nil { - panic("PrettyPrint: internal error in repo.Data") - } - - lines := strings.Split(contents, "\n") - // max line number length - mlnl := len(strconv.Itoa(len(lines))) - // max author length - mal := b.maxAuthorLength() - format := fmt.Sprintf("%%s (%%-%ds %%%dd) %%s\n", - mal, mlnl) - - fVs := b.graph[len(b.graph)-1] - for ln, v := range fVs { - fmt.Fprintf(&buf, format, v.Hash.String()[:8], - prettyPrintAuthor(fVs[ln]), ln+1, lines[ln]) - } - return buf.String() -} - -// utility function to pretty print the author. -func prettyPrintAuthor(c *object.Commit) string { - return fmt.Sprintf("%s %s", c.Author.Name, c.Author.When.Format("2006-01-02")) -} - -// utility function to calculate the number of runes needed -// to print the longest author name in the blame of a file. -func (b *blame) maxAuthorLength() int { - memo := make(map[plumbing.Hash]struct{}, len(b.graph)-1) - fVs := b.graph[len(b.graph)-1] - m := 0 - for ln := range fVs { - if _, ok := memo[fVs[ln].Hash]; ok { - continue - } - memo[fVs[ln].Hash] = struct{}{} - m = max(m, utf8.RuneCountInString(prettyPrintAuthor(fVs[ln]))) - } - return m -} - -func max(a, b int) int { - if a > b { - return a - } - return b -} diff --git a/vendor/github.com/go-git/go-git/v5/common.go b/vendor/github.com/go-git/go-git/v5/common.go deleted file mode 100644 index f837a265..00000000 --- a/vendor/github.com/go-git/go-git/v5/common.go +++ /dev/null @@ -1,22 +0,0 @@ -package git - -import "strings" - -const defaultDotGitPath = ".git" - -// countLines returns the number of lines in a string à la git, this is -// The newline character is assumed to be '\n'. The empty string -// contains 0 lines. If the last line of the string doesn't end with a -// newline, it will still be considered a line. -func countLines(s string) int { - if s == "" { - return 0 - } - - nEOL := strings.Count(s, "\n") - if strings.HasSuffix(s, "\n") { - return nEOL - } - - return nEOL + 1 -} diff --git a/vendor/github.com/go-git/go-git/v5/config/branch.go b/vendor/github.com/go-git/go-git/v5/config/branch.go deleted file mode 100644 index fe86cf54..00000000 --- a/vendor/github.com/go-git/go-git/v5/config/branch.go +++ /dev/null @@ -1,90 +0,0 @@ -package config - -import ( - "errors" - - "github.com/go-git/go-git/v5/plumbing" - format "github.com/go-git/go-git/v5/plumbing/format/config" -) - -var ( - errBranchEmptyName = errors.New("branch config: empty name") - errBranchInvalidMerge = errors.New("branch config: invalid merge") - errBranchInvalidRebase = errors.New("branch config: rebase must be one of 'true' or 'interactive'") -) - -// Branch contains information on the -// local branches and which remote to track -type Branch struct { - // Name of branch - Name string - // Remote name of remote to track - Remote string - // Merge is the local refspec for the branch - Merge plumbing.ReferenceName - // Rebase instead of merge when pulling. Valid values are - // "true" and "interactive". "false" is undocumented and - // typically represented by the non-existence of this field - Rebase string - - raw *format.Subsection -} - -// Validate validates fields of branch -func (b *Branch) Validate() error { - if b.Name == "" { - return errBranchEmptyName - } - - if b.Merge != "" && !b.Merge.IsBranch() { - return errBranchInvalidMerge - } - - if b.Rebase != "" && - b.Rebase != "true" && - b.Rebase != "interactive" && - b.Rebase != "false" { - return errBranchInvalidRebase - } - - return nil -} - -func (b *Branch) marshal() *format.Subsection { - if b.raw == nil { - b.raw = &format.Subsection{} - } - - b.raw.Name = b.Name - - if b.Remote == "" { - b.raw.RemoveOption(remoteSection) - } else { - b.raw.SetOption(remoteSection, b.Remote) - } - - if b.Merge == "" { - b.raw.RemoveOption(mergeKey) - } else { - b.raw.SetOption(mergeKey, string(b.Merge)) - } - - if b.Rebase == "" { - b.raw.RemoveOption(rebaseKey) - } else { - b.raw.SetOption(rebaseKey, b.Rebase) - } - - return b.raw -} - -func (b *Branch) unmarshal(s *format.Subsection) error { - b.raw = s - - b.Name = b.raw.Name - b.Remote = b.raw.Options.Get(remoteSection) - b.Merge = plumbing.ReferenceName(b.raw.Options.Get(mergeKey)) - b.Rebase = b.raw.Options.Get(rebaseKey) - - return b.Validate() -} diff --git a/vendor/github.com/go-git/go-git/v5/config/config.go b/vendor/github.com/go-git/go-git/v5/config/config.go deleted file mode 100644 index 1f737b5d..00000000 --- a/vendor/github.com/go-git/go-git/v5/config/config.go +++ /dev/null @@ -1,658 +0,0 @@ -// Package config contains the abstraction of multiple config files -package config - -import ( - "bytes" - "errors" - "fmt" - "io" - "io/ioutil" - "os" - "path/filepath" - "sort" - "strconv" - - "github.com/go-git/go-git/v5/internal/url" - format "github.com/go-git/go-git/v5/plumbing/format/config" - "github.com/mitchellh/go-homedir" -) - -const ( - // DefaultFetchRefSpec is the default refspec used for fetch. - DefaultFetchRefSpec = "+refs/heads/*:refs/remotes/%s/*" - // DefaultPushRefSpec is the default refspec used for push. - DefaultPushRefSpec = "refs/heads/*:refs/heads/*" -) - -// ConfigStorer generic storage of Config object -type ConfigStorer interface { - Config() (*Config, error) - SetConfig(*Config) error -} - -var ( - ErrInvalid = errors.New("config invalid key in remote or branch") - ErrRemoteConfigNotFound = errors.New("remote config not found") - ErrRemoteConfigEmptyURL = errors.New("remote config: empty URL") - ErrRemoteConfigEmptyName = errors.New("remote config: empty name") -) - -// Scope defines the scope of a config file, such as local, global or system. -type Scope int - -// Available ConfigScope's -const ( - LocalScope Scope = iota - GlobalScope - SystemScope -) - -// Config contains the repository configuration -// https://www.kernel.org/pub/software/scm/git/docs/git-config.html#FILES -type Config struct { - Core struct { - // IsBare if true this repository is assumed to be bare and has no - // working directory associated with it. - IsBare bool - // Worktree is the path to the root of the working tree. - Worktree string - // CommentChar is the character indicating the start of a - // comment for commands like commit and tag - CommentChar string - } - - User struct { - // Name is the personal name of the author and the commiter of a commit. - Name string - // Email is the email of the author and the commiter of a commit. - Email string - } - - Author struct { - // Name is the personal name of the author of a commit. - Name string - // Email is the email of the author of a commit. - Email string - } - - Committer struct { - // Name is the personal name of the commiter of a commit. - Name string - // Email is the email of the the commiter of a commit. - Email string - } - - Pack struct { - // Window controls the size of the sliding window for delta - // compression. The default is 10. A value of 0 turns off - // delta compression entirely. - Window uint - } - - Init struct { - // DefaultBranch Allows overriding the default branch name - // e.g. when initializing a new repository or when cloning - // an empty repository. - DefaultBranch string - } - - // Remotes list of repository remotes, the key of the map is the name - // of the remote, should equal to RemoteConfig.Name. - Remotes map[string]*RemoteConfig - // Submodules list of repository submodules, the key of the map is the name - // of the submodule, should equal to Submodule.Name. - Submodules map[string]*Submodule - // Branches list of branches, the key is the branch name and should - // equal Branch.Name - Branches map[string]*Branch - // URLs list of url rewrite rules, if repo url starts with URL.InsteadOf value, it will be replaced with the - // key instead. - URLs map[string]*URL - // Raw contains the raw information of a config file. The main goal is - // preserve the parsed information from the original format, to avoid - // dropping unsupported fields. - Raw *format.Config -} - -// NewConfig returns a new empty Config. -func NewConfig() *Config { - config := &Config{ - Remotes: make(map[string]*RemoteConfig), - Submodules: make(map[string]*Submodule), - Branches: make(map[string]*Branch), - URLs: make(map[string]*URL), - Raw: format.New(), - } - - config.Pack.Window = DefaultPackWindow - - return config -} - -// ReadConfig reads a config file from a io.Reader. -func ReadConfig(r io.Reader) (*Config, error) { - b, err := ioutil.ReadAll(r) - if err != nil { - return nil, err - } - - cfg := NewConfig() - if err = cfg.Unmarshal(b); err != nil { - return nil, err - } - - return cfg, nil -} - -// LoadConfig loads a config file from a given scope. The returned Config, -// contains exclusively information fom the given scope. If couldn't find a -// config file to the given scope, a empty one is returned. -func LoadConfig(scope Scope) (*Config, error) { - if scope == LocalScope { - return nil, fmt.Errorf("LocalScope should be read from the a ConfigStorer.") - } - - files, err := Paths(scope) - if err != nil { - return nil, err - } - - for _, file := range files { - f, err := os.Open(file) - if err != nil { - if os.IsNotExist(err) { - continue - } - - return nil, err - } - - defer f.Close() - return ReadConfig(f) - } - - return NewConfig(), nil -} - -// Paths returns the config file location for a given scope. -func Paths(scope Scope) ([]string, error) { - var files []string - switch scope { - case GlobalScope: - xdg := os.Getenv("XDG_CONFIG_HOME") - if xdg != "" { - files = append(files, filepath.Join(xdg, "git/config")) - } - - home, err := homedir.Dir() - if err != nil { - return nil, err - } - - files = append(files, - filepath.Join(home, ".gitconfig"), - filepath.Join(home, ".config/git/config"), - ) - case SystemScope: - files = append(files, "/etc/gitconfig") - } - - return files, nil -} - -// Validate validates the fields and sets the default values. -func (c *Config) Validate() error { - for name, r := range c.Remotes { - if r.Name != name { - return ErrInvalid - } - - if err := r.Validate(); err != nil { - return err - } - } - - for name, b := range c.Branches { - if b.Name != name { - return ErrInvalid - } - - if err := b.Validate(); err != nil { - return err - } - } - - return nil -} - -const ( - remoteSection = "remote" - submoduleSection = "submodule" - branchSection = "branch" - coreSection = "core" - packSection = "pack" - userSection = "user" - authorSection = "author" - committerSection = "committer" - initSection = "init" - urlSection = "url" - fetchKey = "fetch" - urlKey = "url" - bareKey = "bare" - worktreeKey = "worktree" - commentCharKey = "commentChar" - windowKey = "window" - mergeKey = "merge" - rebaseKey = "rebase" - nameKey = "name" - emailKey = "email" - defaultBranchKey = "defaultBranch" - - // DefaultPackWindow holds the number of previous objects used to - // generate deltas. The value 10 is the same used by git command. - DefaultPackWindow = uint(10) -) - -// Unmarshal parses a git-config file and stores it. -func (c *Config) Unmarshal(b []byte) error { - r := bytes.NewBuffer(b) - d := format.NewDecoder(r) - - c.Raw = format.New() - if err := d.Decode(c.Raw); err != nil { - return err - } - - c.unmarshalCore() - c.unmarshalUser() - c.unmarshalInit() - if err := c.unmarshalPack(); err != nil { - return err - } - unmarshalSubmodules(c.Raw, c.Submodules) - - if err := c.unmarshalBranches(); err != nil { - return err - } - - if err := c.unmarshalURLs(); err != nil { - return err - } - - return c.unmarshalRemotes() -} - -func (c *Config) unmarshalCore() { - s := c.Raw.Section(coreSection) - if s.Options.Get(bareKey) == "true" { - c.Core.IsBare = true - } - - c.Core.Worktree = s.Options.Get(worktreeKey) - c.Core.CommentChar = s.Options.Get(commentCharKey) -} - -func (c *Config) unmarshalUser() { - s := c.Raw.Section(userSection) - c.User.Name = s.Options.Get(nameKey) - c.User.Email = s.Options.Get(emailKey) - - s = c.Raw.Section(authorSection) - c.Author.Name = s.Options.Get(nameKey) - c.Author.Email = s.Options.Get(emailKey) - - s = c.Raw.Section(committerSection) - c.Committer.Name = s.Options.Get(nameKey) - c.Committer.Email = s.Options.Get(emailKey) -} - -func (c *Config) unmarshalPack() error { - s := c.Raw.Section(packSection) - window := s.Options.Get(windowKey) - if window == "" { - c.Pack.Window = DefaultPackWindow - } else { - winUint, err := strconv.ParseUint(window, 10, 32) - if err != nil { - return err - } - c.Pack.Window = uint(winUint) - } - return nil -} - -func (c *Config) unmarshalRemotes() error { - s := c.Raw.Section(remoteSection) - for _, sub := range s.Subsections { - r := &RemoteConfig{} - if err := r.unmarshal(sub); err != nil { - return err - } - - c.Remotes[r.Name] = r - } - - // Apply insteadOf url rules - for _, r := range c.Remotes { - r.applyURLRules(c.URLs) - } - - return nil -} - -func (c *Config) unmarshalURLs() error { - s := c.Raw.Section(urlSection) - for _, sub := range s.Subsections { - r := &URL{} - if err := r.unmarshal(sub); err != nil { - return err - } - - c.URLs[r.Name] = r - } - - return nil -} - -func unmarshalSubmodules(fc *format.Config, submodules map[string]*Submodule) { - s := fc.Section(submoduleSection) - for _, sub := range s.Subsections { - m := &Submodule{} - m.unmarshal(sub) - - if m.Validate() == ErrModuleBadPath { - continue - } - - submodules[m.Name] = m - } -} - -func (c *Config) unmarshalBranches() error { - bs := c.Raw.Section(branchSection) - for _, sub := range bs.Subsections { - b := &Branch{} - - if err := b.unmarshal(sub); err != nil { - return err - } - - c.Branches[b.Name] = b - } - return nil -} - -func (c *Config) unmarshalInit() { - s := c.Raw.Section(initSection) - c.Init.DefaultBranch = s.Options.Get(defaultBranchKey) -} - -// Marshal returns Config encoded as a git-config file. -func (c *Config) Marshal() ([]byte, error) { - c.marshalCore() - c.marshalUser() - c.marshalPack() - c.marshalRemotes() - c.marshalSubmodules() - c.marshalBranches() - c.marshalURLs() - c.marshalInit() - - buf := bytes.NewBuffer(nil) - if err := format.NewEncoder(buf).Encode(c.Raw); err != nil { - return nil, err - } - - return buf.Bytes(), nil -} - -func (c *Config) marshalCore() { - s := c.Raw.Section(coreSection) - s.SetOption(bareKey, fmt.Sprintf("%t", c.Core.IsBare)) - - if c.Core.Worktree != "" { - s.SetOption(worktreeKey, c.Core.Worktree) - } -} - -func (c *Config) marshalUser() { - s := c.Raw.Section(userSection) - if c.User.Name != "" { - s.SetOption(nameKey, c.User.Name) - } - - if c.User.Email != "" { - s.SetOption(emailKey, c.User.Email) - } - - s = c.Raw.Section(authorSection) - if c.Author.Name != "" { - s.SetOption(nameKey, c.Author.Name) - } - - if c.Author.Email != "" { - s.SetOption(emailKey, c.Author.Email) - } - - s = c.Raw.Section(committerSection) - if c.Committer.Name != "" { - s.SetOption(nameKey, c.Committer.Name) - } - - if c.Committer.Email != "" { - s.SetOption(emailKey, c.Committer.Email) - } -} - -func (c *Config) marshalPack() { - s := c.Raw.Section(packSection) - if c.Pack.Window != DefaultPackWindow { - s.SetOption(windowKey, fmt.Sprintf("%d", c.Pack.Window)) - } -} - -func (c *Config) marshalRemotes() { - s := c.Raw.Section(remoteSection) - newSubsections := make(format.Subsections, 0, len(c.Remotes)) - added := make(map[string]bool) - for _, subsection := range s.Subsections { - if remote, ok := c.Remotes[subsection.Name]; ok { - newSubsections = append(newSubsections, remote.marshal()) - added[subsection.Name] = true - } - } - - remoteNames := make([]string, 0, len(c.Remotes)) - for name := range c.Remotes { - remoteNames = append(remoteNames, name) - } - - sort.Strings(remoteNames) - - for _, name := range remoteNames { - if !added[name] { - newSubsections = append(newSubsections, c.Remotes[name].marshal()) - } - } - - s.Subsections = newSubsections -} - -func (c *Config) marshalSubmodules() { - s := c.Raw.Section(submoduleSection) - s.Subsections = make(format.Subsections, len(c.Submodules)) - - var i int - for _, r := range c.Submodules { - section := r.marshal() - // the submodule section at config is a subset of the .gitmodule file - // we should remove the non-valid options for the config file. - section.RemoveOption(pathKey) - s.Subsections[i] = section - i++ - } -} - -func (c *Config) marshalBranches() { - s := c.Raw.Section(branchSection) - newSubsections := make(format.Subsections, 0, len(c.Branches)) - added := make(map[string]bool) - for _, subsection := range s.Subsections { - if branch, ok := c.Branches[subsection.Name]; ok { - newSubsections = append(newSubsections, branch.marshal()) - added[subsection.Name] = true - } - } - - branchNames := make([]string, 0, len(c.Branches)) - for name := range c.Branches { - branchNames = append(branchNames, name) - } - - sort.Strings(branchNames) - - for _, name := range branchNames { - if !added[name] { - newSubsections = append(newSubsections, c.Branches[name].marshal()) - } - } - - s.Subsections = newSubsections -} - -func (c *Config) marshalURLs() { - s := c.Raw.Section(urlSection) - s.Subsections = make(format.Subsections, len(c.URLs)) - - var i int - for _, r := range c.URLs { - section := r.marshal() - // the submodule section at config is a subset of the .gitmodule file - // we should remove the non-valid options for the config file. - s.Subsections[i] = section - i++ - } -} - -func (c *Config) marshalInit() { - s := c.Raw.Section(initSection) - if c.Init.DefaultBranch != "" { - s.SetOption(defaultBranchKey, c.Init.DefaultBranch) - } -} - -// RemoteConfig contains the configuration for a given remote repository. -type RemoteConfig struct { - // Name of the remote - Name string - // URLs the URLs of a remote repository. It must be non-empty. Fetch will - // always use the first URL, while push will use all of them. - URLs []string - - // insteadOfRulesApplied have urls been modified - insteadOfRulesApplied bool - // originalURLs are the urls before applying insteadOf rules - originalURLs []string - - // Fetch the default set of "refspec" for fetch operation - Fetch []RefSpec - - // raw representation of the subsection, filled by marshal or unmarshal are - // called - raw *format.Subsection -} - -// Validate validates the fields and sets the default values. -func (c *RemoteConfig) Validate() error { - if c.Name == "" { - return ErrRemoteConfigEmptyName - } - - if len(c.URLs) == 0 { - return ErrRemoteConfigEmptyURL - } - - for _, r := range c.Fetch { - if err := r.Validate(); err != nil { - return err - } - } - - if len(c.Fetch) == 0 { - c.Fetch = []RefSpec{RefSpec(fmt.Sprintf(DefaultFetchRefSpec, c.Name))} - } - - return nil -} - -func (c *RemoteConfig) unmarshal(s *format.Subsection) error { - c.raw = s - - fetch := []RefSpec{} - for _, f := range c.raw.Options.GetAll(fetchKey) { - rs := RefSpec(f) - if err := rs.Validate(); err != nil { - return err - } - - fetch = append(fetch, rs) - } - - c.Name = c.raw.Name - c.URLs = append([]string(nil), c.raw.Options.GetAll(urlKey)...) - c.Fetch = fetch - - return nil -} - -func (c *RemoteConfig) marshal() *format.Subsection { - if c.raw == nil { - c.raw = &format.Subsection{} - } - - c.raw.Name = c.Name - if len(c.URLs) == 0 { - c.raw.RemoveOption(urlKey) - } else { - urls := c.URLs - if c.insteadOfRulesApplied { - urls = c.originalURLs - } - - c.raw.SetOption(urlKey, urls...) - } - - if len(c.Fetch) == 0 { - c.raw.RemoveOption(fetchKey) - } else { - var values []string - for _, rs := range c.Fetch { - values = append(values, rs.String()) - } - - c.raw.SetOption(fetchKey, values...) - } - - return c.raw -} - -func (c *RemoteConfig) IsFirstURLLocal() bool { - return url.IsLocalEndpoint(c.URLs[0]) -} - -func (c *RemoteConfig) applyURLRules(urlRules map[string]*URL) { - // save original urls - originalURLs := make([]string, len(c.URLs)) - copy(originalURLs, c.URLs) - - for i, url := range c.URLs { - if matchingURLRule := findLongestInsteadOfMatch(url, urlRules); matchingURLRule != nil { - c.URLs[i] = matchingURLRule.ApplyInsteadOf(c.URLs[i]) - c.insteadOfRulesApplied = true - } - } - - if c.insteadOfRulesApplied { - c.originalURLs = originalURLs - } -} diff --git a/vendor/github.com/go-git/go-git/v5/config/modules.go b/vendor/github.com/go-git/go-git/v5/config/modules.go deleted file mode 100644 index 1c10aa35..00000000 --- a/vendor/github.com/go-git/go-git/v5/config/modules.go +++ /dev/null @@ -1,139 +0,0 @@ -package config - -import ( - "bytes" - "errors" - "regexp" - - format "github.com/go-git/go-git/v5/plumbing/format/config" -) - -var ( - ErrModuleEmptyURL = errors.New("module config: empty URL") - ErrModuleEmptyPath = errors.New("module config: empty path") - ErrModuleBadPath = errors.New("submodule has an invalid path") -) - -var ( - // Matches module paths with dotdot ".." components. - dotdotPath = regexp.MustCompile(`(^|[/\\])\.\.([/\\]|$)`) -) - -// Modules defines the submodules properties, represents a .gitmodules file -// https://www.kernel.org/pub/software/scm/git/docs/gitmodules.html -type Modules struct { - // Submodules is a map of submodules being the key the name of the submodule. - Submodules map[string]*Submodule - - raw *format.Config -} - -// NewModules returns a new empty Modules -func NewModules() *Modules { - return &Modules{ - Submodules: make(map[string]*Submodule), - raw: format.New(), - } -} - -const ( - pathKey = "path" - branchKey = "branch" -) - -// Unmarshal parses a git-config file and stores it. -func (m *Modules) Unmarshal(b []byte) error { - r := bytes.NewBuffer(b) - d := format.NewDecoder(r) - - m.raw = format.New() - if err := d.Decode(m.raw); err != nil { - return err - } - - unmarshalSubmodules(m.raw, m.Submodules) - return nil -} - -// Marshal returns Modules encoded as a git-config file. -func (m *Modules) Marshal() ([]byte, error) { - s := m.raw.Section(submoduleSection) - s.Subsections = make(format.Subsections, len(m.Submodules)) - - var i int - for _, r := range m.Submodules { - s.Subsections[i] = r.marshal() - i++ - } - - buf := bytes.NewBuffer(nil) - if err := format.NewEncoder(buf).Encode(m.raw); err != nil { - return nil, err - } - - return buf.Bytes(), nil -} - -// Submodule defines a submodule. -type Submodule struct { - // Name module name - Name string - // Path defines the path, relative to the top-level directory of the Git - // working tree. - Path string - // URL defines a URL from which the submodule repository can be cloned. - URL string - // Branch is a remote branch name for tracking updates in the upstream - // submodule. Optional value. - Branch string - - // raw representation of the subsection, filled by marshal or unmarshal are - // called. - raw *format.Subsection -} - -// Validate validates the fields and sets the default values. -func (m *Submodule) Validate() error { - if m.Path == "" { - return ErrModuleEmptyPath - } - - if m.URL == "" { - return ErrModuleEmptyURL - } - - if dotdotPath.MatchString(m.Path) { - return ErrModuleBadPath - } - - return nil -} - -func (m *Submodule) unmarshal(s *format.Subsection) { - m.raw = s - - m.Name = m.raw.Name - m.Path = m.raw.Option(pathKey) - m.URL = m.raw.Option(urlKey) - m.Branch = m.raw.Option(branchKey) -} - -func (m *Submodule) marshal() *format.Subsection { - if m.raw == nil { - m.raw = &format.Subsection{} - } - - m.raw.Name = m.Name - if m.raw.Name == "" { - m.raw.Name = m.Path - } - - m.raw.SetOption(pathKey, m.Path) - m.raw.SetOption(urlKey, m.URL) - - if m.Branch != "" { - m.raw.SetOption(branchKey, m.Branch) - } - - return m.raw -} diff --git a/vendor/github.com/go-git/go-git/v5/config/refspec.go b/vendor/github.com/go-git/go-git/v5/config/refspec.go deleted file mode 100644 index 4bfaa37b..00000000 --- a/vendor/github.com/go-git/go-git/v5/config/refspec.go +++ /dev/null @@ -1,155 +0,0 @@ -package config - -import ( - "errors" - "strings" - - "github.com/go-git/go-git/v5/plumbing" -) - -const ( - refSpecWildcard = "*" - refSpecForce = "+" - refSpecSeparator = ":" -) - -var ( - ErrRefSpecMalformedSeparator = errors.New("malformed refspec, separators are wrong") - ErrRefSpecMalformedWildcard = errors.New("malformed refspec, mismatched number of wildcards") -) - -// RefSpec is a mapping from local branches to remote references. -// The format of the refspec is an optional +, followed by :, where -// is the pattern for references on the remote side and is where -// those references will be written locally. The + tells Git to update the -// reference even if it isn’t a fast-forward. -// eg.: "+refs/heads/*:refs/remotes/origin/*" -// -// https://git-scm.com/book/en/v2/Git-Internals-The-Refspec -type RefSpec string - -// Validate validates the RefSpec -func (s RefSpec) Validate() error { - spec := string(s) - if strings.Count(spec, refSpecSeparator) != 1 { - return ErrRefSpecMalformedSeparator - } - - sep := strings.Index(spec, refSpecSeparator) - if sep == len(spec)-1 { - return ErrRefSpecMalformedSeparator - } - - ws := strings.Count(spec[0:sep], refSpecWildcard) - wd := strings.Count(spec[sep+1:], refSpecWildcard) - if ws == wd && ws < 2 && wd < 2 { - return nil - } - - return ErrRefSpecMalformedWildcard -} - -// IsForceUpdate returns if update is allowed in non fast-forward merges. -func (s RefSpec) IsForceUpdate() bool { - return s[0] == refSpecForce[0] -} - -// IsDelete returns true if the refspec indicates a delete (empty src). -func (s RefSpec) IsDelete() bool { - return s[0] == refSpecSeparator[0] -} - -// IsExactSHA1 returns true if the source is a SHA1 hash. -func (s RefSpec) IsExactSHA1() bool { - return plumbing.IsHash(s.Src()) -} - -// Src return the src side. -func (s RefSpec) Src() string { - spec := string(s) - - var start int - if s.IsForceUpdate() { - start = 1 - } else { - start = 0 - } - - end := strings.Index(spec, refSpecSeparator) - return spec[start:end] -} - -// Match match the given plumbing.ReferenceName against the source. -func (s RefSpec) Match(n plumbing.ReferenceName) bool { - if !s.IsWildcard() { - return s.matchExact(n) - } - - return s.matchGlob(n) -} - -// IsWildcard returns true if the RefSpec contains a wildcard. -func (s RefSpec) IsWildcard() bool { - return strings.Contains(string(s), refSpecWildcard) -} - -func (s RefSpec) matchExact(n plumbing.ReferenceName) bool { - return s.Src() == n.String() -} - -func (s RefSpec) matchGlob(n plumbing.ReferenceName) bool { - src := s.Src() - name := n.String() - wildcard := strings.Index(src, refSpecWildcard) - - var prefix, suffix string - prefix = src[0:wildcard] - if len(src) > wildcard+1 { - suffix = src[wildcard+1:] - } - - return len(name) >= len(prefix)+len(suffix) && - strings.HasPrefix(name, prefix) && - strings.HasSuffix(name, suffix) -} - -// Dst returns the destination for the given remote reference. -func (s RefSpec) Dst(n plumbing.ReferenceName) plumbing.ReferenceName { - spec := string(s) - start := strings.Index(spec, refSpecSeparator) + 1 - dst := spec[start:] - src := s.Src() - - if !s.IsWildcard() { - return plumbing.ReferenceName(dst) - } - - name := n.String() - ws := strings.Index(src, refSpecWildcard) - wd := strings.Index(dst, refSpecWildcard) - match := name[ws : len(name)-(len(src)-(ws+1))] - - return plumbing.ReferenceName(dst[0:wd] + match + dst[wd+1:]) -} - -func (s RefSpec) Reverse() RefSpec { - spec := string(s) - separator := strings.Index(spec, refSpecSeparator) - - return RefSpec(spec[separator+1:] + refSpecSeparator + spec[:separator]) -} - -func (s RefSpec) String() string { - return string(s) -} - -// MatchAny returns true if any of the RefSpec match with the given ReferenceName. -func MatchAny(l []RefSpec, n plumbing.ReferenceName) bool { - for _, r := range l { - if r.Match(n) { - return true - } - } - - return false -} diff --git a/vendor/github.com/go-git/go-git/v5/config/url.go b/vendor/github.com/go-git/go-git/v5/config/url.go deleted file mode 100644 index 114d6b26..00000000 --- a/vendor/github.com/go-git/go-git/v5/config/url.go +++ /dev/null @@ -1,81 +0,0 @@ -package config - -import ( - "errors" - "strings" - - format "github.com/go-git/go-git/v5/plumbing/format/config" -) - -var ( - errURLEmptyInsteadOf = errors.New("url config: empty insteadOf") -) - -// Url defines Url rewrite rules -type URL struct { - // Name new base url - Name string - // Any URL that starts with this value will be rewritten to start, instead, with . - // When more than one insteadOf strings match a given URL, the longest match is used. - InsteadOf string - - // raw representation of the subsection, filled by marshal or unmarshal are - // called. - raw *format.Subsection -} - -// Validate validates fields of branch -func (b *URL) Validate() error { - if b.InsteadOf == "" { - return errURLEmptyInsteadOf - } - - return nil -} - -const ( - insteadOfKey = "insteadOf" -) - -func (u *URL) unmarshal(s *format.Subsection) error { - u.raw = s - - u.Name = s.Name - u.InsteadOf = u.raw.Option(insteadOfKey) - return nil -} - -func (u *URL) marshal() *format.Subsection { - if u.raw == nil { - u.raw = &format.Subsection{} - } - - u.raw.Name = u.Name - u.raw.SetOption(insteadOfKey, u.InsteadOf) - - return u.raw -} - -func findLongestInsteadOfMatch(remoteURL string, urls map[string]*URL) *URL { - var longestMatch *URL - for _, u := range urls { - if !strings.HasPrefix(remoteURL, u.InsteadOf) { - continue - } - - // according to spec if there is more than one match, take the logest - if longestMatch == nil || len(longestMatch.InsteadOf) < len(u.InsteadOf) { - longestMatch = u - } - } - - return longestMatch -} - -func (u *URL) ApplyInsteadOf(url string) string { - if !strings.HasPrefix(url, u.InsteadOf) { - return url - } - - return u.Name + url[len(u.InsteadOf):] -} diff --git a/vendor/github.com/go-git/go-git/v5/doc.go b/vendor/github.com/go-git/go-git/v5/doc.go deleted file mode 100644 index 3d817fe9..00000000 --- a/vendor/github.com/go-git/go-git/v5/doc.go +++ /dev/null @@ -1,10 +0,0 @@ -// A highly extensible git implementation in pure Go. -// -// go-git aims to reach the completeness of libgit2 or jgit, nowadays covers the -// majority of the plumbing read operations and some of the main write -// operations, but lacks the main porcelain operations such as merges. -// -// It is highly extensible, we have been following the open/close principle in -// its design to facilitate extensions, mainly focusing the efforts on the -// persistence of the objects. -package git diff --git a/vendor/github.com/go-git/go-git/v5/internal/revision/parser.go b/vendor/github.com/go-git/go-git/v5/internal/revision/parser.go deleted file mode 100644 index 8facf17f..00000000 --- a/vendor/github.com/go-git/go-git/v5/internal/revision/parser.go +++ /dev/null @@ -1,622 +0,0 @@ -// Package revision extracts git revision from string -// More information about revision : https://www.kernel.org/pub/software/scm/git/docs/gitrevisions.html -package revision - -import ( - "bytes" - "fmt" - "io" - "regexp" - "strconv" - "time" -) - -// ErrInvalidRevision is emitted if string doesn't match valid revision -type ErrInvalidRevision struct { - s string -} - -func (e *ErrInvalidRevision) Error() string { - return "Revision invalid : " + e.s -} - -// Revisioner represents a revision component. -// A revision is made of multiple revision components -// obtained after parsing a revision string, -// for instance revision "master~" will be converted in -// two revision components Ref and TildePath -type Revisioner interface { -} - -// Ref represents a reference name : HEAD, master, -type Ref string - -// TildePath represents ~, ~{n} -type TildePath struct { - Depth int -} - -// CaretPath represents ^, ^{n} -type CaretPath struct { - Depth int -} - -// CaretReg represents ^{/foo bar} -type CaretReg struct { - Regexp *regexp.Regexp - Negate bool -} - -// CaretType represents ^{commit} -type CaretType struct { - ObjectType string -} - -// AtReflog represents @{n} -type AtReflog struct { - Depth int -} - -// AtCheckout represents @{-n} -type AtCheckout struct { - Depth int -} - -// AtUpstream represents @{upstream}, @{u} -type AtUpstream struct { - BranchName string -} - -// AtPush represents @{push} -type AtPush struct { - BranchName string -} - -// AtDate represents @{"2006-01-02T15:04:05Z"} -type AtDate struct { - Date time.Time -} - -// ColonReg represents :/foo bar -type ColonReg struct { - Regexp *regexp.Regexp - Negate bool -} - -// ColonPath represents :./ : -type ColonPath struct { - Path string -} - -// ColonStagePath represents ::/ -type ColonStagePath struct { - Path string - Stage int -} - -// Parser represents a parser -// use to tokenize and transform to revisioner chunks -// a given string -type Parser struct { - s *scanner - currentParsedChar struct { - tok token - lit string - } - unreadLastChar bool -} - -// NewParserFromString returns a new instance of parser from a string. -func NewParserFromString(s string) *Parser { - return NewParser(bytes.NewBufferString(s)) -} - -// NewParser returns a new instance of parser. -func NewParser(r io.Reader) *Parser { - return &Parser{s: newScanner(r)} -} - -// scan returns the next token from the underlying scanner -// or the last scanned token if an unscan was requested -func (p *Parser) scan() (token, string, error) { - if p.unreadLastChar { - p.unreadLastChar = false - return p.currentParsedChar.tok, p.currentParsedChar.lit, nil - } - - tok, lit, err := p.s.scan() - - p.currentParsedChar.tok, p.currentParsedChar.lit = tok, lit - - return tok, lit, err -} - -// unscan pushes the previously read token back onto the buffer. -func (p *Parser) unscan() { p.unreadLastChar = true } - -// Parse explode a revision string into revisioner chunks -func (p *Parser) Parse() ([]Revisioner, error) { - var rev Revisioner - var revs []Revisioner - var tok token - var err error - - for { - tok, _, err = p.scan() - - if err != nil { - return nil, err - } - - switch tok { - case at: - rev, err = p.parseAt() - case tilde: - rev, err = p.parseTilde() - case caret: - rev, err = p.parseCaret() - case colon: - rev, err = p.parseColon() - case eof: - err = p.validateFullRevision(&revs) - - if err != nil { - return []Revisioner{}, err - } - - return revs, nil - default: - p.unscan() - rev, err = p.parseRef() - } - - if err != nil { - return []Revisioner{}, err - } - - revs = append(revs, rev) - } -} - -// validateFullRevision ensures all revisioner chunks make a valid revision -func (p *Parser) validateFullRevision(chunks *[]Revisioner) error { - var hasReference bool - - for i, chunk := range *chunks { - switch chunk.(type) { - case Ref: - if i == 0 { - hasReference = true - } else { - return &ErrInvalidRevision{`reference must be defined once at the beginning`} - } - case AtDate: - if len(*chunks) == 1 || hasReference && len(*chunks) == 2 { - return nil - } - - return &ErrInvalidRevision{`"@" statement is not valid, could be : @{}, @{}`} - case AtReflog: - if len(*chunks) == 1 || hasReference && len(*chunks) == 2 { - return nil - } - - return &ErrInvalidRevision{`"@" statement is not valid, could be : @{}, @{}`} - case AtCheckout: - if len(*chunks) == 1 { - return nil - } - - return &ErrInvalidRevision{`"@" statement is not valid, could be : @{-}`} - case AtUpstream: - if len(*chunks) == 1 || hasReference && len(*chunks) == 2 { - return nil - } - - return &ErrInvalidRevision{`"@" statement is not valid, could be : @{upstream}, @{upstream}, @{u}, @{u}`} - case AtPush: - if len(*chunks) == 1 || hasReference && len(*chunks) == 2 { - return nil - } - - return &ErrInvalidRevision{`"@" statement is not valid, could be : @{push}, @{push}`} - case TildePath, CaretPath, CaretReg: - if !hasReference { - return &ErrInvalidRevision{`"~" or "^" statement must have a reference defined at the beginning`} - } - case ColonReg: - if len(*chunks) == 1 { - return nil - } - - return &ErrInvalidRevision{`":" statement is not valid, could be : :/`} - case ColonPath: - if i == len(*chunks)-1 && hasReference || len(*chunks) == 1 { - return nil - } - - return &ErrInvalidRevision{`":" statement is not valid, could be : :`} - case ColonStagePath: - if len(*chunks) == 1 { - return nil - } - - return &ErrInvalidRevision{`":" statement is not valid, could be : ::`} - } - } - - return nil -} - -// parseAt extract @ statements -func (p *Parser) parseAt() (Revisioner, error) { - var tok, nextTok token - var lit, nextLit string - var err error - - tok, _, err = p.scan() - - if err != nil { - return nil, err - } - - if tok != obrace { - p.unscan() - - return Ref("HEAD"), nil - } - - tok, lit, err = p.scan() - - if err != nil { - return nil, err - } - - nextTok, nextLit, err = p.scan() - - if err != nil { - return nil, err - } - - switch { - case tok == word && (lit == "u" || lit == "upstream") && nextTok == cbrace: - return AtUpstream{}, nil - case tok == word && lit == "push" && nextTok == cbrace: - return AtPush{}, nil - case tok == number && nextTok == cbrace: - n, _ := strconv.Atoi(lit) - - return AtReflog{n}, nil - case tok == minus && nextTok == number: - n, _ := strconv.Atoi(nextLit) - - t, _, err := p.scan() - - if err != nil { - return nil, err - } - - if t != cbrace { - return nil, &ErrInvalidRevision{s: `missing "}" in @{-n} structure`} - } - - return AtCheckout{n}, nil - default: - p.unscan() - - date := lit - - for { - tok, lit, err = p.scan() - - if err != nil { - return nil, err - } - - switch { - case tok == cbrace: - t, err := time.Parse("2006-01-02T15:04:05Z", date) - - if err != nil { - return nil, &ErrInvalidRevision{fmt.Sprintf(`wrong date "%s" must fit ISO-8601 format : 2006-01-02T15:04:05Z`, date)} - } - - return AtDate{t}, nil - default: - date += lit - } - } - } -} - -// parseTilde extract ~ statements -func (p *Parser) parseTilde() (Revisioner, error) { - var tok token - var lit string - var err error - - tok, lit, err = p.scan() - - if err != nil { - return nil, err - } - - switch { - case tok == number: - n, _ := strconv.Atoi(lit) - - return TildePath{n}, nil - default: - p.unscan() - return TildePath{1}, nil - } -} - -// parseCaret extract ^ statements -func (p *Parser) parseCaret() (Revisioner, error) { - var tok token - var lit string - var err error - - tok, lit, err = p.scan() - - if err != nil { - return nil, err - } - - switch { - case tok == obrace: - r, err := p.parseCaretBraces() - - if err != nil { - return nil, err - } - - return r, nil - case tok == number: - n, _ := strconv.Atoi(lit) - - if n > 2 { - return nil, &ErrInvalidRevision{fmt.Sprintf(`"%s" found must be 0, 1 or 2 after "^"`, lit)} - } - - return CaretPath{n}, nil - default: - p.unscan() - return CaretPath{1}, nil - } -} - -// parseCaretBraces extract ^{} statements -func (p *Parser) parseCaretBraces() (Revisioner, error) { - var tok, nextTok token - var lit, _ string - start := true - var re string - var negate bool - var err error - - for { - tok, lit, err = p.scan() - - if err != nil { - return nil, err - } - - nextTok, _, err = p.scan() - - if err != nil { - return nil, err - } - - switch { - case tok == word && nextTok == cbrace && (lit == "commit" || lit == "tree" || lit == "blob" || lit == "tag" || lit == "object"): - return CaretType{lit}, nil - case re == "" && tok == cbrace: - return CaretType{"tag"}, nil - case re == "" && tok == emark && nextTok == emark: - re += lit - case re == "" && tok == emark && nextTok == minus: - negate = true - case re == "" && tok == emark: - return nil, &ErrInvalidRevision{s: `revision suffix brace component sequences starting with "/!" others than those defined are reserved`} - case re == "" && tok == slash: - p.unscan() - case tok != slash && start: - return nil, &ErrInvalidRevision{fmt.Sprintf(`"%s" is not a valid revision suffix brace component`, lit)} - case tok != cbrace: - p.unscan() - re += lit - case tok == cbrace: - p.unscan() - - reg, err := regexp.Compile(re) - - if err != nil { - return CaretReg{}, &ErrInvalidRevision{fmt.Sprintf(`revision suffix brace component, %s`, err.Error())} - } - - return CaretReg{reg, negate}, nil - } - - start = false - } -} - -// parseColon extract : statements -func (p *Parser) parseColon() (Revisioner, error) { - var tok token - var err error - - tok, _, err = p.scan() - - if err != nil { - return nil, err - } - - switch tok { - case slash: - return p.parseColonSlash() - default: - p.unscan() - return p.parseColonDefault() - } -} - -// parseColonSlash extract :/ statements -func (p *Parser) parseColonSlash() (Revisioner, error) { - var tok, nextTok token - var lit string - var re string - var negate bool - var err error - - for { - tok, lit, err = p.scan() - - if err != nil { - return nil, err - } - - nextTok, _, err = p.scan() - - if err != nil { - return nil, err - } - - switch { - case tok == emark && nextTok == emark: - re += lit - case re == "" && tok == emark && nextTok == minus: - negate = true - case re == "" && tok == emark: - return nil, &ErrInvalidRevision{s: `revision suffix brace component sequences starting with "/!" others than those defined are reserved`} - case tok == eof: - p.unscan() - reg, err := regexp.Compile(re) - - if err != nil { - return ColonReg{}, &ErrInvalidRevision{fmt.Sprintf(`revision suffix brace component, %s`, err.Error())} - } - - return ColonReg{reg, negate}, nil - default: - p.unscan() - re += lit - } - } -} - -// parseColonDefault extract : statements -func (p *Parser) parseColonDefault() (Revisioner, error) { - var tok token - var lit string - var path string - var stage int - var err error - var n = -1 - - tok, lit, err = p.scan() - - if err != nil { - return nil, err - } - - nextTok, _, err := p.scan() - - if err != nil { - return nil, err - } - - if tok == number && nextTok == colon { - n, _ = strconv.Atoi(lit) - } - - switch n { - case 0, 1, 2, 3: - stage = n - default: - path += lit - p.unscan() - } - - for { - tok, lit, err = p.scan() - - if err != nil { - return nil, err - } - - switch { - case tok == eof && n == -1: - return ColonPath{path}, nil - case tok == eof: - return ColonStagePath{path, stage}, nil - default: - path += lit - } - } -} - -// parseRef extract reference name -func (p *Parser) parseRef() (Revisioner, error) { - var tok, prevTok token - var lit, buf string - var endOfRef bool - var err error - - for { - tok, lit, err = p.scan() - - if err != nil { - return nil, err - } - - switch tok { - case eof, at, colon, tilde, caret: - endOfRef = true - } - - err := p.checkRefFormat(tok, lit, prevTok, buf, endOfRef) - - if err != nil { - return "", err - } - - if endOfRef { - p.unscan() - return Ref(buf), nil - } - - buf += lit - prevTok = tok - } -} - -// checkRefFormat ensure reference name follow rules defined here : -// https://git-scm.com/docs/git-check-ref-format -func (p *Parser) checkRefFormat(token token, literal string, previousToken token, buffer string, endOfRef bool) error { - switch token { - case aslash, space, control, qmark, asterisk, obracket: - return &ErrInvalidRevision{fmt.Sprintf(`must not contains "%s"`, literal)} - } - - switch { - case (token == dot || token == slash) && buffer == "": - return &ErrInvalidRevision{fmt.Sprintf(`must not start with "%s"`, literal)} - case previousToken == slash && endOfRef: - return &ErrInvalidRevision{`must not end with "/"`} - case previousToken == dot && endOfRef: - return &ErrInvalidRevision{`must not end with "."`} - case token == dot && previousToken == slash: - return &ErrInvalidRevision{`must not contains "/."`} - case previousToken == dot && token == dot: - return &ErrInvalidRevision{`must not contains ".."`} - case previousToken == slash && token == slash: - return &ErrInvalidRevision{`must not contains consecutively "/"`} - case (token == slash || endOfRef) && len(buffer) > 4 && buffer[len(buffer)-5:] == ".lock": - return &ErrInvalidRevision{"cannot end with .lock"} - } - - return nil -} diff --git a/vendor/github.com/go-git/go-git/v5/internal/revision/scanner.go b/vendor/github.com/go-git/go-git/v5/internal/revision/scanner.go deleted file mode 100644 index c46c21b7..00000000 --- a/vendor/github.com/go-git/go-git/v5/internal/revision/scanner.go +++ /dev/null @@ -1,117 +0,0 @@ -package revision - -import ( - "bufio" - "io" - "unicode" -) - -// runeCategoryValidator takes a rune as input and -// validates it belongs to a rune category -type runeCategoryValidator func(r rune) bool - -// tokenizeExpression aggregates a series of runes matching check predicate into a single -// string and provides given tokenType as token type -func tokenizeExpression(ch rune, tokenType token, check runeCategoryValidator, r *bufio.Reader) (token, string, error) { - var data []rune - data = append(data, ch) - - for { - c, _, err := r.ReadRune() - - if c == zeroRune { - break - } - - if err != nil { - return tokenError, "", err - } - - if check(c) { - data = append(data, c) - } else { - err := r.UnreadRune() - - if err != nil { - return tokenError, "", err - } - - return tokenType, string(data), nil - } - } - - return tokenType, string(data), nil -} - -var zeroRune = rune(0) - -// scanner represents a lexical scanner. -type scanner struct { - r *bufio.Reader -} - -// newScanner returns a new instance of scanner. -func newScanner(r io.Reader) *scanner { - return &scanner{r: bufio.NewReader(r)} -} - -// Scan extracts tokens and their strings counterpart -// from the reader -func (s *scanner) scan() (token, string, error) { - ch, _, err := s.r.ReadRune() - - if err != nil && err != io.EOF { - return tokenError, "", err - } - - switch ch { - case zeroRune: - return eof, "", nil - case ':': - return colon, string(ch), nil - case '~': - return tilde, string(ch), nil - case '^': - return caret, string(ch), nil - case '.': - return dot, string(ch), nil - case '/': - return slash, string(ch), nil - case '{': - return obrace, string(ch), nil - case '}': - return cbrace, string(ch), nil - case '-': - return minus, string(ch), nil - case '@': - return at, string(ch), nil - case '\\': - return aslash, string(ch), nil - case '?': - return qmark, string(ch), nil - case '*': - return asterisk, string(ch), nil - case '[': - return obracket, string(ch), nil - case '!': - return emark, string(ch), nil - } - - if unicode.IsSpace(ch) { - return space, string(ch), nil - } - - if unicode.IsControl(ch) { - return control, string(ch), nil - } - - if unicode.IsLetter(ch) { - return tokenizeExpression(ch, word, unicode.IsLetter, s.r) - } - - if unicode.IsNumber(ch) { - return tokenizeExpression(ch, number, unicode.IsNumber, s.r) - } - - return tokenError, string(ch), nil -} diff --git a/vendor/github.com/go-git/go-git/v5/internal/revision/token.go b/vendor/github.com/go-git/go-git/v5/internal/revision/token.go deleted file mode 100644 index abc40488..00000000 --- a/vendor/github.com/go-git/go-git/v5/internal/revision/token.go +++ /dev/null @@ -1,28 +0,0 @@ -package revision - -// token represents a entity extracted from string parsing -type token int - -const ( - eof token = iota - - aslash - asterisk - at - caret - cbrace - colon - control - dot - emark - minus - number - obrace - obracket - qmark - slash - space - tilde - tokenError - word -) diff --git a/vendor/github.com/go-git/go-git/v5/internal/url/url.go b/vendor/github.com/go-git/go-git/v5/internal/url/url.go deleted file mode 100644 index 14cf133d..00000000 --- a/vendor/github.com/go-git/go-git/v5/internal/url/url.go +++ /dev/null @@ -1,37 +0,0 @@ -package url - -import ( - "regexp" -) - -var ( - isSchemeRegExp = regexp.MustCompile(`^[^:]+://`) - scpLikeUrlRegExp = regexp.MustCompile(`^(?:(?P[^@]+)@)?(?P[^:\s]+):(?:(?P[0-9]{1,5})(?:\/|:))?(?P[^\\].*\/[^\\].*)$`) -) - -// MatchesScheme returns true if the given string matches a URL-like -// format scheme. -func MatchesScheme(url string) bool { - return isSchemeRegExp.MatchString(url) -} - -// MatchesScpLike returns true if the given string matches an SCP-like -// format scheme. -func MatchesScpLike(url string) bool { - return scpLikeUrlRegExp.MatchString(url) -} - -// FindScpLikeComponents returns the user, host, port and path of the -// given SCP-like URL. -func FindScpLikeComponents(url string) (user, host, port, path string) { - m := scpLikeUrlRegExp.FindStringSubmatch(url) - return m[1], m[2], m[3], m[4] -} - -// IsLocalEndpoint returns true if the given URL string specifies a -// local file endpoint. For example, on a Linux machine, -// `/home/user/src/go-git` would match as a local endpoint, but -// `https://github.com/src-d/go-git` would not. -func IsLocalEndpoint(url string) bool { - return !MatchesScheme(url) && !MatchesScpLike(url) -} diff --git a/vendor/github.com/go-git/go-git/v5/object_walker.go b/vendor/github.com/go-git/go-git/v5/object_walker.go deleted file mode 100644 index 3fcdd299..00000000 --- a/vendor/github.com/go-git/go-git/v5/object_walker.go +++ /dev/null @@ -1,104 +0,0 @@ -package git - -import ( - "fmt" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/plumbing/filemode" - "github.com/go-git/go-git/v5/plumbing/object" - "github.com/go-git/go-git/v5/storage" -) - -type objectWalker struct { - Storer storage.Storer - // seen is the set of objects seen in the repo. - // seen map can become huge if walking over large - // repos. Thus using struct{} as the value type. - seen map[plumbing.Hash]struct{} -} - -func newObjectWalker(s storage.Storer) *objectWalker { - return &objectWalker{s, map[plumbing.Hash]struct{}{}} -} - -// walkAllRefs walks all (hash) references from the repo. -func (p *objectWalker) walkAllRefs() error { - // Walk over all the references in the repo. - it, err := p.Storer.IterReferences() - if err != nil { - return err - } - defer it.Close() - err = it.ForEach(func(ref *plumbing.Reference) error { - // Exit this iteration early for non-hash references. - if ref.Type() != plumbing.HashReference { - return nil - } - return p.walkObjectTree(ref.Hash()) - }) - return err -} - -func (p *objectWalker) isSeen(hash plumbing.Hash) bool { - _, seen := p.seen[hash] - return seen -} - -func (p *objectWalker) add(hash plumbing.Hash) { - p.seen[hash] = struct{}{} -} - -// walkObjectTree walks over all objects and remembers references -// to them in the objectWalker. This is used instead of the revlist -// walks because memory usage is tight with huge repos. -func (p *objectWalker) walkObjectTree(hash plumbing.Hash) error { - // Check if we have already seen, and mark this object - if p.isSeen(hash) { - return nil - } - p.add(hash) - // Fetch the object. - obj, err := object.GetObject(p.Storer, hash) - if err != nil { - return fmt.Errorf("Getting object %s failed: %v", hash, err) - } - // Walk all children depending on object type. - switch obj := obj.(type) { - case *object.Commit: - err = p.walkObjectTree(obj.TreeHash) - if err != nil { - return err - } - for _, h := range obj.ParentHashes { - err = p.walkObjectTree(h) - if err != nil { - return err - } - } - case *object.Tree: - for i := range obj.Entries { - // Shortcut for blob objects: - // 'or' the lower bits of a mode and check that it - // it matches a filemode.Executable. The type information - // is in the higher bits, but this is the cleanest way - // to handle plain files with different modes. - // Other non-tree objects are somewhat rare, so they - // are not special-cased. - if obj.Entries[i].Mode|0755 == filemode.Executable { - p.add(obj.Entries[i].Hash) - continue - } - // Normal walk for sub-trees (and symlinks etc). - err = p.walkObjectTree(obj.Entries[i].Hash) - if err != nil { - return err - } - } - case *object.Tag: - return p.walkObjectTree(obj.Target) - default: - // Error out on unhandled object types. - return fmt.Errorf("Unknown object %X %s %T\n", obj.ID(), obj.Type(), obj) - } - return nil -} diff --git a/vendor/github.com/go-git/go-git/v5/options.go b/vendor/github.com/go-git/go-git/v5/options.go deleted file mode 100644 index b5d15037..00000000 --- a/vendor/github.com/go-git/go-git/v5/options.go +++ /dev/null @@ -1,634 +0,0 @@ -package git - -import ( - "errors" - "fmt" - "regexp" - "strings" - "time" - - "github.com/go-git/go-git/v5/config" - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/plumbing/object" - "github.com/go-git/go-git/v5/plumbing/protocol/packp/sideband" - "github.com/go-git/go-git/v5/plumbing/transport" - "golang.org/x/crypto/openpgp" -) - -// SubmoduleRescursivity defines how depth will affect any submodule recursive -// operation. -type SubmoduleRescursivity uint - -const ( - // DefaultRemoteName name of the default Remote, just like git command. - DefaultRemoteName = "origin" - - // NoRecurseSubmodules disables the recursion for a submodule operation. - NoRecurseSubmodules SubmoduleRescursivity = 0 - // DefaultSubmoduleRecursionDepth allow recursion in a submodule operation. - DefaultSubmoduleRecursionDepth SubmoduleRescursivity = 10 -) - -var ( - ErrMissingURL = errors.New("URL field is required") -) - -// CloneOptions describes how a clone should be performed. -type CloneOptions struct { - // The (possibly remote) repository URL to clone from. - URL string - // Auth credentials, if required, to use with the remote repository. - Auth transport.AuthMethod - // Name of the remote to be added, by default `origin`. - RemoteName string - // Remote branch to clone. - ReferenceName plumbing.ReferenceName - // Fetch only ReferenceName if true. - SingleBranch bool - // No checkout of HEAD after clone if true. - NoCheckout bool - // Limit fetching to the specified number of commits. - Depth int - // RecurseSubmodules after the clone is created, initialize all submodules - // within, using their default settings. This option is ignored if the - // cloned repository does not have a worktree. - RecurseSubmodules SubmoduleRescursivity - // Progress is where the human readable information sent by the server is - // stored, if nil nothing is stored and the capability (if supported) - // no-progress, is sent to the server to avoid send this information. - Progress sideband.Progress - // Tags describe how the tags will be fetched from the remote repository, - // by default is AllTags. - Tags TagMode - // InsecureSkipTLS skips ssl verify if protocol is https - InsecureSkipTLS bool - // CABundle specify additional ca bundle with system cert pool - CABundle []byte -} - -// Validate validates the fields and sets the default values. -func (o *CloneOptions) Validate() error { - if o.URL == "" { - return ErrMissingURL - } - - if o.RemoteName == "" { - o.RemoteName = DefaultRemoteName - } - - if o.ReferenceName == "" { - o.ReferenceName = plumbing.HEAD - } - - if o.Tags == InvalidTagMode { - o.Tags = AllTags - } - - return nil -} - -// PullOptions describes how a pull should be performed. -type PullOptions struct { - // Name of the remote to be pulled. If empty, uses the default. - RemoteName string - // Remote branch to clone. If empty, uses HEAD. - ReferenceName plumbing.ReferenceName - // Fetch only ReferenceName if true. - SingleBranch bool - // Limit fetching to the specified number of commits. - Depth int - // Auth credentials, if required, to use with the remote repository. - Auth transport.AuthMethod - // RecurseSubmodules controls if new commits of all populated submodules - // should be fetched too. - RecurseSubmodules SubmoduleRescursivity - // Progress is where the human readable information sent by the server is - // stored, if nil nothing is stored and the capability (if supported) - // no-progress, is sent to the server to avoid send this information. - Progress sideband.Progress - // Force allows the pull to update a local branch even when the remote - // branch does not descend from it. - Force bool - // InsecureSkipTLS skips ssl verify if protocol is https - InsecureSkipTLS bool - // CABundle specify additional ca bundle with system cert pool - CABundle []byte -} - -// Validate validates the fields and sets the default values. -func (o *PullOptions) Validate() error { - if o.RemoteName == "" { - o.RemoteName = DefaultRemoteName - } - - if o.ReferenceName == "" { - o.ReferenceName = plumbing.HEAD - } - - return nil -} - -type TagMode int - -const ( - InvalidTagMode TagMode = iota - // TagFollowing any tag that points into the histories being fetched is also - // fetched. TagFollowing requires a server with `include-tag` capability - // in order to fetch the annotated tags objects. - TagFollowing - // AllTags fetch all tags from the remote (i.e., fetch remote tags - // refs/tags/* into local tags with the same name) - AllTags - //NoTags fetch no tags from the remote at all - NoTags -) - -// FetchOptions describes how a fetch should be performed -type FetchOptions struct { - // Name of the remote to fetch from. Defaults to origin. - RemoteName string - RefSpecs []config.RefSpec - // Depth limit fetching to the specified number of commits from the tip of - // each remote branch history. - Depth int - // Auth credentials, if required, to use with the remote repository. - Auth transport.AuthMethod - // Progress is where the human readable information sent by the server is - // stored, if nil nothing is stored and the capability (if supported) - // no-progress, is sent to the server to avoid send this information. - Progress sideband.Progress - // Tags describe how the tags will be fetched from the remote repository, - // by default is TagFollowing. - Tags TagMode - // Force allows the fetch to update a local branch even when the remote - // branch does not descend from it. - Force bool - // InsecureSkipTLS skips ssl verify if protocol is https - InsecureSkipTLS bool - // CABundle specify additional ca bundle with system cert pool - CABundle []byte -} - -// Validate validates the fields and sets the default values. -func (o *FetchOptions) Validate() error { - if o.RemoteName == "" { - o.RemoteName = DefaultRemoteName - } - - if o.Tags == InvalidTagMode { - o.Tags = TagFollowing - } - - for _, r := range o.RefSpecs { - if err := r.Validate(); err != nil { - return err - } - } - - return nil -} - -// PushOptions describes how a push should be performed. -type PushOptions struct { - // RemoteName is the name of the remote to be pushed to. - RemoteName string - // RefSpecs specify what destination ref to update with what source - // object. A refspec with empty src can be used to delete a reference. - RefSpecs []config.RefSpec - // Auth credentials, if required, to use with the remote repository. - Auth transport.AuthMethod - // Progress is where the human readable information sent by the server is - // stored, if nil nothing is stored. - Progress sideband.Progress - // Prune specify that remote refs that match given RefSpecs and that do - // not exist locally will be removed. - Prune bool - // Force allows the push to update a remote branch even when the local - // branch does not descend from it. - Force bool - // InsecureSkipTLS skips ssl verify if protocal is https - InsecureSkipTLS bool - // CABundle specify additional ca bundle with system cert pool - CABundle []byte - // RequireRemoteRefs only allows a remote ref to be updated if its current - // value is the one specified here. - RequireRemoteRefs []config.RefSpec -} - -// Validate validates the fields and sets the default values. -func (o *PushOptions) Validate() error { - if o.RemoteName == "" { - o.RemoteName = DefaultRemoteName - } - - if len(o.RefSpecs) == 0 { - o.RefSpecs = []config.RefSpec{ - config.RefSpec(config.DefaultPushRefSpec), - } - } - - for _, r := range o.RefSpecs { - if err := r.Validate(); err != nil { - return err - } - } - - return nil -} - -// SubmoduleUpdateOptions describes how a submodule update should be performed. -type SubmoduleUpdateOptions struct { - // Init, if true initializes the submodules recorded in the index. - Init bool - // NoFetch tell to the update command to not fetch new objects from the - // remote site. - NoFetch bool - // RecurseSubmodules the update is performed not only in the submodules of - // the current repository but also in any nested submodules inside those - // submodules (and so on). Until the SubmoduleRescursivity is reached. - RecurseSubmodules SubmoduleRescursivity - // Auth credentials, if required, to use with the remote repository. - Auth transport.AuthMethod -} - -var ( - ErrBranchHashExclusive = errors.New("Branch and Hash are mutually exclusive") - ErrCreateRequiresBranch = errors.New("Branch is mandatory when Create is used") -) - -// CheckoutOptions describes how a checkout operation should be performed. -type CheckoutOptions struct { - // Hash is the hash of the commit to be checked out. If used, HEAD will be - // in detached mode. If Create is not used, Branch and Hash are mutually - // exclusive. - Hash plumbing.Hash - // Branch to be checked out, if Branch and Hash are empty is set to `master`. - Branch plumbing.ReferenceName - // Create a new branch named Branch and start it at Hash. - Create bool - // Force, if true when switching branches, proceed even if the index or the - // working tree differs from HEAD. This is used to throw away local changes - Force bool - // Keep, if true when switching branches, local changes (the index or the - // working tree changes) will be kept so that they can be committed to the - // target branch. Force and Keep are mutually exclusive, should not be both - // set to true. - Keep bool -} - -// Validate validates the fields and sets the default values. -func (o *CheckoutOptions) Validate() error { - if !o.Create && !o.Hash.IsZero() && o.Branch != "" { - return ErrBranchHashExclusive - } - - if o.Create && o.Branch == "" { - return ErrCreateRequiresBranch - } - - if o.Branch == "" { - o.Branch = plumbing.Master - } - - return nil -} - -// ResetMode defines the mode of a reset operation. -type ResetMode int8 - -const ( - // MixedReset resets the index but not the working tree (i.e., the changed - // files are preserved but not marked for commit) and reports what has not - // been updated. This is the default action. - MixedReset ResetMode = iota - // HardReset resets the index and working tree. Any changes to tracked files - // in the working tree are discarded. - HardReset - // MergeReset resets the index and updates the files in the working tree - // that are different between Commit and HEAD, but keeps those which are - // different between the index and working tree (i.e. which have changes - // which have not been added). - // - // If a file that is different between Commit and the index has unstaged - // changes, reset is aborted. - MergeReset - // SoftReset does not touch the index file or the working tree at all (but - // resets the head to , just like all modes do). This leaves all - // your changed files "Changes to be committed", as git status would put it. - SoftReset -) - -// ResetOptions describes how a reset operation should be performed. -type ResetOptions struct { - // Commit, if commit is present set the current branch head (HEAD) to it. - Commit plumbing.Hash - // Mode, form resets the current branch head to Commit and possibly updates - // the index (resetting it to the tree of Commit) and the working tree - // depending on Mode. If empty MixedReset is used. - Mode ResetMode -} - -// Validate validates the fields and sets the default values. -func (o *ResetOptions) Validate(r *Repository) error { - if o.Commit == plumbing.ZeroHash { - ref, err := r.Head() - if err != nil { - return err - } - - o.Commit = ref.Hash() - } - - return nil -} - -type LogOrder int8 - -const ( - LogOrderDefault LogOrder = iota - LogOrderDFS - LogOrderDFSPost - LogOrderBSF - LogOrderCommitterTime -) - -// LogOptions describes how a log action should be performed. -type LogOptions struct { - // When the From option is set the log will only contain commits - // reachable from it. If this option is not set, HEAD will be used as - // the default From. - From plumbing.Hash - - // The default traversal algorithm is Depth-first search - // set Order=LogOrderCommitterTime for ordering by committer time (more compatible with `git log`) - // set Order=LogOrderBSF for Breadth-first search - Order LogOrder - - // Show only those commits in which the specified file was inserted/updated. - // It is equivalent to running `git log -- `. - // this field is kept for compatility, it can be replaced with PathFilter - FileName *string - - // Filter commits based on the path of files that are updated - // takes file path as argument and should return true if the file is desired - // It can be used to implement `git log -- ` - // either is a file path, or directory path, or a regexp of file/directory path - PathFilter func(string) bool - - // Pretend as if all the refs in refs/, along with HEAD, are listed on the command line as . - // It is equivalent to running `git log --all`. - // If set on true, the From option will be ignored. - All bool - - // Show commits more recent than a specific date. - // It is equivalent to running `git log --since ` or `git log --after `. - Since *time.Time - - // Show commits older than a specific date. - // It is equivalent to running `git log --until ` or `git log --before `. - Until *time.Time -} - -var ( - ErrMissingAuthor = errors.New("author field is required") -) - -// AddOptions describes how a add operation should be performed -type AddOptions struct { - // All equivalent to `git add -A`, update the index not only where the - // working tree has a file matching `Path` but also where the index already - // has an entry. This adds, modifies, and removes index entries to match the - // working tree. If no `Path` nor `Glob` is given when `All` option is - // used, all files in the entire working tree are updated. - All bool - // Path is the exact filepath to a the file or directory to be added. - Path string - // Glob adds all paths, matching pattern, to the index. If pattern matches a - // directory path, all directory contents are added to the index recursively. - Glob string -} - -// Validate validates the fields and sets the default values. -func (o *AddOptions) Validate(r *Repository) error { - if o.Path != "" && o.Glob != "" { - return fmt.Errorf("fields Path and Glob are mutual exclusive") - } - - return nil -} - -// CommitOptions describes how a commit operation should be performed. -type CommitOptions struct { - // All automatically stage files that have been modified and deleted, but - // new files you have not told Git about are not affected. - All bool - // Author is the author's signature of the commit. If Author is empty the - // Name and Email is read from the config, and time.Now it's used as When. - Author *object.Signature - // Committer is the committer's signature of the commit. If Committer is - // nil the Author signature is used. - Committer *object.Signature - // Parents are the parents commits for the new commit, by default when - // len(Parents) is zero, the hash of HEAD reference is used. - Parents []plumbing.Hash - // SignKey denotes a key to sign the commit with. A nil value here means the - // commit will not be signed. The private key must be present and already - // decrypted. - SignKey *openpgp.Entity -} - -// Validate validates the fields and sets the default values. -func (o *CommitOptions) Validate(r *Repository) error { - if o.Author == nil { - if err := o.loadConfigAuthorAndCommitter(r); err != nil { - return err - } - } - - if o.Committer == nil { - o.Committer = o.Author - } - - if len(o.Parents) == 0 { - head, err := r.Head() - if err != nil && err != plumbing.ErrReferenceNotFound { - return err - } - - if head != nil { - o.Parents = []plumbing.Hash{head.Hash()} - } - } - - return nil -} - -func (o *CommitOptions) loadConfigAuthorAndCommitter(r *Repository) error { - cfg, err := r.ConfigScoped(config.SystemScope) - if err != nil { - return err - } - - if o.Author == nil && cfg.Author.Email != "" && cfg.Author.Name != "" { - o.Author = &object.Signature{ - Name: cfg.Author.Name, - Email: cfg.Author.Email, - When: time.Now(), - } - } - - if o.Committer == nil && cfg.Committer.Email != "" && cfg.Committer.Name != "" { - o.Committer = &object.Signature{ - Name: cfg.Committer.Name, - Email: cfg.Committer.Email, - When: time.Now(), - } - } - - if o.Author == nil && cfg.User.Email != "" && cfg.User.Name != "" { - o.Author = &object.Signature{ - Name: cfg.User.Name, - Email: cfg.User.Email, - When: time.Now(), - } - } - - if o.Author == nil { - return ErrMissingAuthor - } - - return nil -} - -var ( - ErrMissingName = errors.New("name field is required") - ErrMissingTagger = errors.New("tagger field is required") - ErrMissingMessage = errors.New("message field is required") -) - -// CreateTagOptions describes how a tag object should be created. -type CreateTagOptions struct { - // Tagger defines the signature of the tag creator. If Tagger is empty the - // Name and Email is read from the config, and time.Now it's used as When. - Tagger *object.Signature - // Message defines the annotation of the tag. It is canonicalized during - // validation into the format expected by git - no leading whitespace and - // ending in a newline. - Message string - // SignKey denotes a key to sign the tag with. A nil value here means the tag - // will not be signed. The private key must be present and already decrypted. - SignKey *openpgp.Entity -} - -// Validate validates the fields and sets the default values. -func (o *CreateTagOptions) Validate(r *Repository, hash plumbing.Hash) error { - if o.Tagger == nil { - if err := o.loadConfigTagger(r); err != nil { - return err - } - } - - if o.Message == "" { - return ErrMissingMessage - } - - // Canonicalize the message into the expected message format. - o.Message = strings.TrimSpace(o.Message) + "\n" - - return nil -} - -func (o *CreateTagOptions) loadConfigTagger(r *Repository) error { - cfg, err := r.ConfigScoped(config.SystemScope) - if err != nil { - return err - } - - if o.Tagger == nil && cfg.Author.Email != "" && cfg.Author.Name != "" { - o.Tagger = &object.Signature{ - Name: cfg.Author.Name, - Email: cfg.Author.Email, - When: time.Now(), - } - } - - if o.Tagger == nil && cfg.User.Email != "" && cfg.User.Name != "" { - o.Tagger = &object.Signature{ - Name: cfg.User.Name, - Email: cfg.User.Email, - When: time.Now(), - } - } - - if o.Tagger == nil { - return ErrMissingTagger - } - - return nil -} - -// ListOptions describes how a remote list should be performed. -type ListOptions struct { - // Auth credentials, if required, to use with the remote repository. - Auth transport.AuthMethod - // InsecureSkipTLS skips ssl verify if protocal is https - InsecureSkipTLS bool - // CABundle specify additional ca bundle with system cert pool - CABundle []byte -} - -// CleanOptions describes how a clean should be performed. -type CleanOptions struct { - Dir bool -} - -// GrepOptions describes how a grep should be performed. -type GrepOptions struct { - // Patterns are compiled Regexp objects to be matched. - Patterns []*regexp.Regexp - // InvertMatch selects non-matching lines. - InvertMatch bool - // CommitHash is the hash of the commit from which worktree should be derived. - CommitHash plumbing.Hash - // ReferenceName is the branch or tag name from which worktree should be derived. - ReferenceName plumbing.ReferenceName - // PathSpecs are compiled Regexp objects of pathspec to use in the matching. - PathSpecs []*regexp.Regexp -} - -var ( - ErrHashOrReference = errors.New("ambiguous options, only one of CommitHash or ReferenceName can be passed") -) - -// Validate validates the fields and sets the default values. -func (o *GrepOptions) Validate(w *Worktree) error { - if !o.CommitHash.IsZero() && o.ReferenceName != "" { - return ErrHashOrReference - } - - // If none of CommitHash and ReferenceName are provided, set commit hash of - // the repository's head. - if o.CommitHash.IsZero() && o.ReferenceName == "" { - ref, err := w.r.Head() - if err != nil { - return err - } - o.CommitHash = ref.Hash() - } - - return nil -} - -// PlainOpenOptions describes how opening a plain repository should be -// performed. -type PlainOpenOptions struct { - // DetectDotGit defines whether parent directories should be - // walked until a .git directory or file is found. - DetectDotGit bool - // Enable .git/commondir support (see https://git-scm.com/docs/gitrepository-layout#Documentation/gitrepository-layout.txt). - // NOTE: This option will only work with the filesystem storage. - EnableDotGitCommonDir bool -} - -// Validate validates the fields and sets the default values. -func (o *PlainOpenOptions) Validate() error { return nil } diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/cache/buffer_lru.go b/vendor/github.com/go-git/go-git/v5/plumbing/cache/buffer_lru.go deleted file mode 100644 index acaf1952..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/cache/buffer_lru.go +++ /dev/null @@ -1,98 +0,0 @@ -package cache - -import ( - "container/list" - "sync" -) - -// BufferLRU implements an object cache with an LRU eviction policy and a -// maximum size (measured in object size). -type BufferLRU struct { - MaxSize FileSize - - actualSize FileSize - ll *list.List - cache map[int64]*list.Element - mut sync.Mutex -} - -// NewBufferLRU creates a new BufferLRU with the given maximum size. The maximum -// size will never be exceeded. -func NewBufferLRU(maxSize FileSize) *BufferLRU { - return &BufferLRU{MaxSize: maxSize} -} - -// NewBufferLRUDefault creates a new BufferLRU with the default cache size. -func NewBufferLRUDefault() *BufferLRU { - return &BufferLRU{MaxSize: DefaultMaxSize} -} - -type buffer struct { - Key int64 - Slice []byte -} - -// Put puts a buffer into the cache. If the buffer is already in the cache, it -// will be marked as used. Otherwise, it will be inserted. A buffers might -// be evicted to make room for the new one. -func (c *BufferLRU) Put(key int64, slice []byte) { - c.mut.Lock() - defer c.mut.Unlock() - - if c.cache == nil { - c.actualSize = 0 - c.cache = make(map[int64]*list.Element, 1000) - c.ll = list.New() - } - - bufSize := FileSize(len(slice)) - if ee, ok := c.cache[key]; ok { - oldBuf := ee.Value.(buffer) - // in this case bufSize is a delta: new size - old size - bufSize -= FileSize(len(oldBuf.Slice)) - c.ll.MoveToFront(ee) - ee.Value = buffer{key, slice} - } else { - if bufSize > c.MaxSize { - return - } - ee := c.ll.PushFront(buffer{key, slice}) - c.cache[key] = ee - } - - c.actualSize += bufSize - for c.actualSize > c.MaxSize { - last := c.ll.Back() - lastObj := last.Value.(buffer) - lastSize := FileSize(len(lastObj.Slice)) - - c.ll.Remove(last) - delete(c.cache, lastObj.Key) - c.actualSize -= lastSize - } -} - -// Get returns a buffer by its key. It marks the buffer as used. If the buffer -// is not in the cache, (nil, false) will be returned. -func (c *BufferLRU) Get(key int64) ([]byte, bool) { - c.mut.Lock() - defer c.mut.Unlock() - - ee, ok := c.cache[key] - if !ok { - return nil, false - } - - c.ll.MoveToFront(ee) - return ee.Value.(buffer).Slice, true -} - -// Clear the content of this buffer cache. -func (c *BufferLRU) Clear() { - c.mut.Lock() - defer c.mut.Unlock() - - c.ll = nil - c.cache = nil - c.actualSize = 0 -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/cache/common.go b/vendor/github.com/go-git/go-git/v5/plumbing/cache/common.go deleted file mode 100644 index 7b0d0c76..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/cache/common.go +++ /dev/null @@ -1,39 +0,0 @@ -package cache - -import "github.com/go-git/go-git/v5/plumbing" - -const ( - Byte FileSize = 1 << (iota * 10) - KiByte - MiByte - GiByte -) - -type FileSize int64 - -const DefaultMaxSize FileSize = 96 * MiByte - -// Object is an interface to a object cache. -type Object interface { - // Put puts the given object into the cache. Whether this object will - // actually be put into the cache or not is implementation specific. - Put(o plumbing.EncodedObject) - // Get gets an object from the cache given its hash. The second return value - // is true if the object was returned, and false otherwise. - Get(k plumbing.Hash) (plumbing.EncodedObject, bool) - // Clear clears every object from the cache. - Clear() -} - -// Buffer is an interface to a buffer cache. -type Buffer interface { - // Put puts a buffer into the cache. If the buffer is already in the cache, - // it will be marked as used. Otherwise, it will be inserted. Buffer might - // be evicted to make room for the new one. - Put(key int64, slice []byte) - // Get returns a buffer by its key. It marks the buffer as used. If the - // buffer is not in the cache, (nil, false) will be returned. - Get(key int64) ([]byte, bool) - // Clear clears every object from the cache. - Clear() -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/cache/object_lru.go b/vendor/github.com/go-git/go-git/v5/plumbing/cache/object_lru.go deleted file mode 100644 index c50d0d1e..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/cache/object_lru.go +++ /dev/null @@ -1,101 +0,0 @@ -package cache - -import ( - "container/list" - "sync" - - "github.com/go-git/go-git/v5/plumbing" -) - -// ObjectLRU implements an object cache with an LRU eviction policy and a -// maximum size (measured in object size). -type ObjectLRU struct { - MaxSize FileSize - - actualSize FileSize - ll *list.List - cache map[interface{}]*list.Element - mut sync.Mutex -} - -// NewObjectLRU creates a new ObjectLRU with the given maximum size. The maximum -// size will never be exceeded. -func NewObjectLRU(maxSize FileSize) *ObjectLRU { - return &ObjectLRU{MaxSize: maxSize} -} - -// NewObjectLRUDefault creates a new ObjectLRU with the default cache size. -func NewObjectLRUDefault() *ObjectLRU { - return &ObjectLRU{MaxSize: DefaultMaxSize} -} - -// Put puts an object into the cache. If the object is already in the cache, it -// will be marked as used. Otherwise, it will be inserted. A single object might -// be evicted to make room for the new object. -func (c *ObjectLRU) Put(obj plumbing.EncodedObject) { - c.mut.Lock() - defer c.mut.Unlock() - - if c.cache == nil { - c.actualSize = 0 - c.cache = make(map[interface{}]*list.Element, 1000) - c.ll = list.New() - } - - objSize := FileSize(obj.Size()) - key := obj.Hash() - if ee, ok := c.cache[key]; ok { - oldObj := ee.Value.(plumbing.EncodedObject) - // in this case objSize is a delta: new size - old size - objSize -= FileSize(oldObj.Size()) - c.ll.MoveToFront(ee) - ee.Value = obj - } else { - if objSize > c.MaxSize { - return - } - ee := c.ll.PushFront(obj) - c.cache[key] = ee - } - - c.actualSize += objSize - for c.actualSize > c.MaxSize { - last := c.ll.Back() - if last == nil { - c.actualSize = 0 - break - } - - lastObj := last.Value.(plumbing.EncodedObject) - lastSize := FileSize(lastObj.Size()) - - c.ll.Remove(last) - delete(c.cache, lastObj.Hash()) - c.actualSize -= lastSize - } -} - -// Get returns an object by its hash. It marks the object as used. If the object -// is not in the cache, (nil, false) will be returned. -func (c *ObjectLRU) Get(k plumbing.Hash) (plumbing.EncodedObject, bool) { - c.mut.Lock() - defer c.mut.Unlock() - - ee, ok := c.cache[k] - if !ok { - return nil, false - } - - c.ll.MoveToFront(ee) - return ee.Value.(plumbing.EncodedObject), true -} - -// Clear the content of this object cache. -func (c *ObjectLRU) Clear() { - c.mut.Lock() - defer c.mut.Unlock() - - c.ll = nil - c.cache = nil - c.actualSize = 0 -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/color/color.go b/vendor/github.com/go-git/go-git/v5/plumbing/color/color.go deleted file mode 100644 index 2cd74bdc..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/color/color.go +++ /dev/null @@ -1,38 +0,0 @@ -package color - -// TODO read colors from a github.com/go-git/go-git/plumbing/format/config.Config struct -// TODO implement color parsing, see https://github.com/git/git/blob/v2.26.2/color.c - -// Colors. See https://github.com/git/git/blob/v2.26.2/color.h#L24-L53. -const ( - Normal = "" - Reset = "\033[m" - Bold = "\033[1m" - Red = "\033[31m" - Green = "\033[32m" - Yellow = "\033[33m" - Blue = "\033[34m" - Magenta = "\033[35m" - Cyan = "\033[36m" - BoldRed = "\033[1;31m" - BoldGreen = "\033[1;32m" - BoldYellow = "\033[1;33m" - BoldBlue = "\033[1;34m" - BoldMagenta = "\033[1;35m" - BoldCyan = "\033[1;36m" - FaintRed = "\033[2;31m" - FaintGreen = "\033[2;32m" - FaintYellow = "\033[2;33m" - FaintBlue = "\033[2;34m" - FaintMagenta = "\033[2;35m" - FaintCyan = "\033[2;36m" - BgRed = "\033[41m" - BgGreen = "\033[42m" - BgYellow = "\033[43m" - BgBlue = "\033[44m" - BgMagenta = "\033[45m" - BgCyan = "\033[46m" - Faint = "\033[2m" - FaintItalic = "\033[2;3m" - Reverse = "\033[7m" -) diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/error.go b/vendor/github.com/go-git/go-git/v5/plumbing/error.go deleted file mode 100644 index a3ebed3f..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/error.go +++ /dev/null @@ -1,35 +0,0 @@ -package plumbing - -import "fmt" - -type PermanentError struct { - Err error -} - -func NewPermanentError(err error) *PermanentError { - if err == nil { - return nil - } - - return &PermanentError{Err: err} -} - -func (e *PermanentError) Error() string { - return fmt.Sprintf("permanent client error: %s", e.Err.Error()) -} - -type UnexpectedError struct { - Err error -} - -func NewUnexpectedError(err error) *UnexpectedError { - if err == nil { - return nil - } - - return &UnexpectedError{Err: err} -} - -func (e *UnexpectedError) Error() string { - return fmt.Sprintf("unexpected client error: %s", e.Err.Error()) -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/filemode/filemode.go b/vendor/github.com/go-git/go-git/v5/plumbing/filemode/filemode.go deleted file mode 100644 index b848a979..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/filemode/filemode.go +++ /dev/null @@ -1,188 +0,0 @@ -package filemode - -import ( - "encoding/binary" - "fmt" - "os" - "strconv" -) - -// A FileMode represents the kind of tree entries used by git. It -// resembles regular file systems modes, although FileModes are -// considerably simpler (there are not so many), and there are some, -// like Submodule that has no file system equivalent. -type FileMode uint32 - -const ( - // Empty is used as the FileMode of tree elements when comparing - // trees in the following situations: - // - // - the mode of tree elements before their creation. - the mode of - // tree elements after their deletion. - the mode of unmerged - // elements when checking the index. - // - // Empty has no file system equivalent. As Empty is the zero value - // of FileMode, it is also returned by New and - // NewFromOsNewFromOSFileMode along with an error, when they fail. - Empty FileMode = 0 - // Dir represent a Directory. - Dir FileMode = 0040000 - // Regular represent non-executable files. Please note this is not - // the same as golang regular files, which include executable files. - Regular FileMode = 0100644 - // Deprecated represent non-executable files with the group writable - // bit set. This mode was supported by the first versions of git, - // but it has been deprecated nowadays. This library uses them - // internally, so you can read old packfiles, but will treat them as - // Regulars when interfacing with the outside world. This is the - // standard git behaviour. - Deprecated FileMode = 0100664 - // Executable represents executable files. - Executable FileMode = 0100755 - // Symlink represents symbolic links to files. - Symlink FileMode = 0120000 - // Submodule represents git submodules. This mode has no file system - // equivalent. - Submodule FileMode = 0160000 -) - -// New takes the octal string representation of a FileMode and returns -// the FileMode and a nil error. If the string can not be parsed to a -// 32 bit unsigned octal number, it returns Empty and the parsing error. -// -// Example: "40000" means Dir, "100644" means Regular. -// -// Please note this function does not check if the returned FileMode -// is valid in git or if it is malformed. For instance, "1" will -// return the malformed FileMode(1) and a nil error. -func New(s string) (FileMode, error) { - n, err := strconv.ParseUint(s, 8, 32) - if err != nil { - return Empty, err - } - - return FileMode(n), nil -} - -// NewFromOSFileMode returns the FileMode used by git to represent -// the provided file system modes and a nil error on success. If the -// file system mode cannot be mapped to any valid git mode (as with -// sockets or named pipes), it will return Empty and an error. -// -// Note that some git modes cannot be generated from os.FileModes, like -// Deprecated and Submodule; while Empty will be returned, along with an -// error, only when the method fails. -func NewFromOSFileMode(m os.FileMode) (FileMode, error) { - if m.IsRegular() { - if isSetTemporary(m) { - return Empty, fmt.Errorf("no equivalent git mode for %s", m) - } - if isSetCharDevice(m) { - return Empty, fmt.Errorf("no equivalent git mode for %s", m) - } - if isSetUserExecutable(m) { - return Executable, nil - } - return Regular, nil - } - - if m.IsDir() { - return Dir, nil - } - - if isSetSymLink(m) { - return Symlink, nil - } - - return Empty, fmt.Errorf("no equivalent git mode for %s", m) -} - -func isSetCharDevice(m os.FileMode) bool { - return m&os.ModeCharDevice != 0 -} - -func isSetTemporary(m os.FileMode) bool { - return m&os.ModeTemporary != 0 -} - -func isSetUserExecutable(m os.FileMode) bool { - return m&0100 != 0 -} - -func isSetSymLink(m os.FileMode) bool { - return m&os.ModeSymlink != 0 -} - -// Bytes return a slice of 4 bytes with the mode in little endian -// encoding. -func (m FileMode) Bytes() []byte { - ret := make([]byte, 4) - binary.LittleEndian.PutUint32(ret, uint32(m)) - return ret -} - -// IsMalformed returns if the FileMode should not appear in a git packfile, -// this is: Empty and any other mode not mentioned as a constant in this -// package. -func (m FileMode) IsMalformed() bool { - return m != Dir && - m != Regular && - m != Deprecated && - m != Executable && - m != Symlink && - m != Submodule -} - -// String returns the FileMode as a string in the standatd git format, -// this is, an octal number padded with ceros to 7 digits. Malformed -// modes are printed in that same format, for easier debugging. -// -// Example: Regular is "0100644", Empty is "0000000". -func (m FileMode) String() string { - return fmt.Sprintf("%07o", uint32(m)) -} - -// IsRegular returns if the FileMode represents that of a regular file, -// this is, either Regular or Deprecated. Please note that Executable -// are not regular even though in the UNIX tradition, they usually are: -// See the IsFile method. -func (m FileMode) IsRegular() bool { - return m == Regular || - m == Deprecated -} - -// IsFile returns if the FileMode represents that of a file, this is, -// Regular, Deprecated, Executable or Link. -func (m FileMode) IsFile() bool { - return m == Regular || - m == Deprecated || - m == Executable || - m == Symlink -} - -// ToOSFileMode returns the os.FileMode to be used when creating file -// system elements with the given git mode and a nil error on success. -// -// When the provided mode cannot be mapped to a valid file system mode -// (e.g. Submodule) it returns os.FileMode(0) and an error. -// -// The returned file mode does not take into account the umask. -func (m FileMode) ToOSFileMode() (os.FileMode, error) { - switch m { - case Dir: - return os.ModePerm | os.ModeDir, nil - case Submodule: - return os.ModePerm | os.ModeDir, nil - case Regular: - return os.FileMode(0644), nil - // Deprecated is no longer allowed: treated as a Regular instead - case Deprecated: - return os.FileMode(0644), nil - case Executable: - return os.FileMode(0755), nil - case Symlink: - return os.ModePerm | os.ModeSymlink, nil - } - - return os.FileMode(0), fmt.Errorf("malformed mode (%s)", m) -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/config/common.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/config/common.go deleted file mode 100644 index 6d689ea1..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/config/common.go +++ /dev/null @@ -1,109 +0,0 @@ -package config - -// New creates a new config instance. -func New() *Config { - return &Config{} -} - -// Config contains all the sections, comments and includes from a config file. -type Config struct { - Comment *Comment - Sections Sections - Includes Includes -} - -// Includes is a list of Includes in a config file. -type Includes []*Include - -// Include is a reference to an included config file. -type Include struct { - Path string - Config *Config -} - -// Comment string without the prefix '#' or ';'. -type Comment string - -const ( - // NoSubsection token is passed to Config.Section and Config.SetSection to - // represent the absence of a section. - NoSubsection = "" -) - -// Section returns a existing section with the given name or creates a new one. -func (c *Config) Section(name string) *Section { - for i := len(c.Sections) - 1; i >= 0; i-- { - s := c.Sections[i] - if s.IsName(name) { - return s - } - } - - s := &Section{Name: name} - c.Sections = append(c.Sections, s) - return s -} - -// HasSection checks if the Config has a section with the specified name. -func (c *Config) HasSection(name string) bool { - for _, s := range c.Sections { - if s.IsName(name) { - return true - } - } - return false -} - -// RemoveSection removes a section from a config file. -func (c *Config) RemoveSection(name string) *Config { - result := Sections{} - for _, s := range c.Sections { - if !s.IsName(name) { - result = append(result, s) - } - } - - c.Sections = result - return c -} - -// RemoveSubsection remove a subsection from a config file. -func (c *Config) RemoveSubsection(section string, subsection string) *Config { - for _, s := range c.Sections { - if s.IsName(section) { - result := Subsections{} - for _, ss := range s.Subsections { - if !ss.IsName(subsection) { - result = append(result, ss) - } - } - s.Subsections = result - } - } - - return c -} - -// AddOption adds an option to a given section and subsection. Use the -// NoSubsection constant for the subsection argument if no subsection is wanted. -func (c *Config) AddOption(section string, subsection string, key string, value string) *Config { - if subsection == "" { - c.Section(section).AddOption(key, value) - } else { - c.Section(section).Subsection(subsection).AddOption(key, value) - } - - return c -} - -// SetOption sets an option to a given section and subsection. Use the -// NoSubsection constant for the subsection argument if no subsection is wanted. -func (c *Config) SetOption(section string, subsection string, key string, value string) *Config { - if subsection == "" { - c.Section(section).SetOption(key, value) - } else { - c.Section(section).Subsection(subsection).SetOption(key, value) - } - - return c -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/config/decoder.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/config/decoder.go deleted file mode 100644 index 8e52d57f..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/config/decoder.go +++ /dev/null @@ -1,37 +0,0 @@ -package config - -import ( - "io" - - "github.com/go-git/gcfg" -) - -// A Decoder reads and decodes config files from an input stream. -type Decoder struct { - io.Reader -} - -// NewDecoder returns a new decoder that reads from r. -func NewDecoder(r io.Reader) *Decoder { - return &Decoder{r} -} - -// Decode reads the whole config from its input and stores it in the -// value pointed to by config. -func (d *Decoder) Decode(config *Config) error { - cb := func(s string, ss string, k string, v string, bv bool) error { - if ss == "" && k == "" { - config.Section(s) - return nil - } - - if ss != "" && k == "" { - config.Section(s).Subsection(ss) - return nil - } - - config.AddOption(s, ss, k, v) - return nil - } - return gcfg.ReadWithCallback(d, cb) -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/config/doc.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/config/doc.go deleted file mode 100644 index 3986c836..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/config/doc.go +++ /dev/null @@ -1,122 +0,0 @@ -// Package config implements encoding and decoding of git config files. -// -// Configuration File -// ------------------ -// -// The Git configuration file contains a number of variables that affect -// the Git commands' behavior. The `.git/config` file in each repository -// is used to store the configuration for that repository, and -// `$HOME/.gitconfig` is used to store a per-user configuration as -// fallback values for the `.git/config` file. The file `/etc/gitconfig` -// can be used to store a system-wide default configuration. -// -// The configuration variables are used by both the Git plumbing -// and the porcelains. The variables are divided into sections, wherein -// the fully qualified variable name of the variable itself is the last -// dot-separated segment and the section name is everything before the last -// dot. The variable names are case-insensitive, allow only alphanumeric -// characters and `-`, and must start with an alphabetic character. Some -// variables may appear multiple times; we say then that the variable is -// multivalued. -// -// Syntax -// ~~~~~~ -// -// The syntax is fairly flexible and permissive; whitespaces are mostly -// ignored. The '#' and ';' characters begin comments to the end of line, -// blank lines are ignored. -// -// The file consists of sections and variables. A section begins with -// the name of the section in square brackets and continues until the next -// section begins. Section names are case-insensitive. Only alphanumeric -// characters, `-` and `.` are allowed in section names. Each variable -// must belong to some section, which means that there must be a section -// header before the first setting of a variable. -// -// Sections can be further divided into subsections. To begin a subsection -// put its name in double quotes, separated by space from the section name, -// in the section header, like in the example below: -// -// -------- -// [section "subsection"] -// -// -------- -// -// Subsection names are case sensitive and can contain any characters except -// newline (doublequote `"` and backslash can be included by escaping them -// as `\"` and `\\`, respectively). Section headers cannot span multiple -// lines. Variables may belong directly to a section or to a given subsection. -// You can have `[section]` if you have `[section "subsection"]`, but you -// don't need to. -// -// There is also a deprecated `[section.subsection]` syntax. With this -// syntax, the subsection name is converted to lower-case and is also -// compared case sensitively. These subsection names follow the same -// restrictions as section names. -// -// All the other lines (and the remainder of the line after the section -// header) are recognized as setting variables, in the form -// 'name = value' (or just 'name', which is a short-hand to say that -// the variable is the boolean "true"). -// The variable names are case-insensitive, allow only alphanumeric characters -// and `-`, and must start with an alphabetic character. -// -// A line that defines a value can be continued to the next line by -// ending it with a `\`; the backquote and the end-of-line are -// stripped. Leading whitespaces after 'name =', the remainder of the -// line after the first comment character '#' or ';', and trailing -// whitespaces of the line are discarded unless they are enclosed in -// double quotes. Internal whitespaces within the value are retained -// verbatim. -// -// Inside double quotes, double quote `"` and backslash `\` characters -// must be escaped: use `\"` for `"` and `\\` for `\`. -// -// The following escape sequences (beside `\"` and `\\`) are recognized: -// `\n` for newline character (NL), `\t` for horizontal tabulation (HT, TAB) -// and `\b` for backspace (BS). Other char escape sequences (including octal -// escape sequences) are invalid. -// -// Includes -// ~~~~~~~~ -// -// You can include one config file from another by setting the special -// `include.path` variable to the name of the file to be included. The -// variable takes a pathname as its value, and is subject to tilde -// expansion. -// -// The included file is expanded immediately, as if its contents had been -// found at the location of the include directive. If the value of the -// `include.path` variable is a relative path, the path is considered to be -// relative to the configuration file in which the include directive was -// found. See below for examples. -// -// -// Example -// ~~~~~~~ -// -// # Core variables -// [core] -// ; Don't trust file modes -// filemode = false -// -// # Our diff algorithm -// [diff] -// external = /usr/local/bin/diff-wrapper -// renames = true -// -// [branch "devel"] -// remote = origin -// merge = refs/heads/devel -// -// # Proxy settings -// [core] -// gitProxy="ssh" for "kernel.org" -// gitProxy=default-proxy ; for the rest -// -// [include] -// path = /path/to/foo.inc ; include by absolute path -// path = foo ; expand "foo" relative to the current file -// path = ~/foo ; expand "foo" in your `$HOME` directory -// -package config diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/config/encoder.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/config/encoder.go deleted file mode 100644 index 4eac8968..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/config/encoder.go +++ /dev/null @@ -1,77 +0,0 @@ -package config - -import ( - "fmt" - "io" - "strings" -) - -// An Encoder writes config files to an output stream. -type Encoder struct { - w io.Writer -} - -// NewEncoder returns a new encoder that writes to w. -func NewEncoder(w io.Writer) *Encoder { - return &Encoder{w} -} - -// Encode writes the config in git config format to the stream of the encoder. -func (e *Encoder) Encode(cfg *Config) error { - for _, s := range cfg.Sections { - if err := e.encodeSection(s); err != nil { - return err - } - } - - return nil -} - -func (e *Encoder) encodeSection(s *Section) error { - if len(s.Options) > 0 { - if err := e.printf("[%s]\n", s.Name); err != nil { - return err - } - - if err := e.encodeOptions(s.Options); err != nil { - return err - } - } - - for _, ss := range s.Subsections { - if err := e.encodeSubsection(s.Name, ss); err != nil { - return err - } - } - - return nil -} - -func (e *Encoder) encodeSubsection(sectionName string, s *Subsection) error { - //TODO: escape - if err := e.printf("[%s \"%s\"]\n", sectionName, s.Name); err != nil { - return err - } - - return e.encodeOptions(s.Options) -} - -func (e *Encoder) encodeOptions(opts Options) error { - for _, o := range opts { - pattern := "\t%s = %s\n" - if strings.Contains(o.Value, "\\") { - pattern = "\t%s = %q\n" - } - - if err := e.printf(pattern, o.Key, o.Value); err != nil { - return err - } - } - - return nil -} - -func (e *Encoder) printf(msg string, args ...interface{}) error { - _, err := fmt.Fprintf(e.w, msg, args...) - return err -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/config/option.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/config/option.go deleted file mode 100644 index cad39481..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/config/option.go +++ /dev/null @@ -1,127 +0,0 @@ -package config - -import ( - "fmt" - "strings" -) - -// Option defines a key/value entity in a config file. -type Option struct { - // Key preserving original caseness. - // Use IsKey instead to compare key regardless of caseness. - Key string - // Original value as string, could be not normalized. - Value string -} - -type Options []*Option - -// IsKey returns true if the given key matches -// this option's key in a case-insensitive comparison. -func (o *Option) IsKey(key string) bool { - return strings.EqualFold(o.Key, key) -} - -func (opts Options) GoString() string { - var strs []string - for _, opt := range opts { - strs = append(strs, fmt.Sprintf("%#v", opt)) - } - - return strings.Join(strs, ", ") -} - -// Get gets the value for the given key if set, -// otherwise it returns the empty string. -// -// Note that there is no difference -// -// This matches git behaviour since git v1.8.1-rc1, -// if there are multiple definitions of a key, the -// last one wins. -// -// See: http://article.gmane.org/gmane.linux.kernel/1407184 -// -// In order to get all possible values for the same key, -// use GetAll. -func (opts Options) Get(key string) string { - for i := len(opts) - 1; i >= 0; i-- { - o := opts[i] - if o.IsKey(key) { - return o.Value - } - } - return "" -} - -// Has checks if an Option exist with the given key. -func (opts Options) Has(key string) bool { - for _, o := range opts { - if o.IsKey(key) { - return true - } - } - return false -} - -// GetAll returns all possible values for the same key. -func (opts Options) GetAll(key string) []string { - result := []string{} - for _, o := range opts { - if o.IsKey(key) { - result = append(result, o.Value) - } - } - return result -} - -func (opts Options) withoutOption(key string) Options { - result := Options{} - for _, o := range opts { - if !o.IsKey(key) { - result = append(result, o) - } - } - return result -} - -func (opts Options) withAddedOption(key string, value string) Options { - return append(opts, &Option{key, value}) -} - -func (opts Options) withSettedOption(key string, values ...string) Options { - var result Options - var added []string - for _, o := range opts { - if !o.IsKey(key) { - result = append(result, o) - continue - } - - if contains(values, o.Value) { - added = append(added, o.Value) - result = append(result, o) - continue - } - } - - for _, value := range values { - if contains(added, value) { - continue - } - - result = result.withAddedOption(key, value) - } - - return result -} - -func contains(haystack []string, needle string) bool { - for _, s := range haystack { - if s == needle { - return true - } - } - - return false -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/config/section.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/config/section.go deleted file mode 100644 index 07f72f35..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/config/section.go +++ /dev/null @@ -1,181 +0,0 @@ -package config - -import ( - "fmt" - "strings" -) - -// Section is the representation of a section inside git configuration files. -// Each Section contains Options that are used by both the Git plumbing -// and the porcelains. -// Sections can be further divided into subsections. To begin a subsection -// put its name in double quotes, separated by space from the section name, -// in the section header, like in the example below: -// -// [section "subsection"] -// -// All the other lines (and the remainder of the line after the section header) -// are recognized as option variables, in the form "name = value" (or just name, -// which is a short-hand to say that the variable is the boolean "true"). -// The variable names are case-insensitive, allow only alphanumeric characters -// and -, and must start with an alphabetic character: -// -// [section "subsection1"] -// option1 = value1 -// option2 -// [section "subsection2"] -// option3 = value2 -// -type Section struct { - Name string - Options Options - Subsections Subsections -} - -type Subsection struct { - Name string - Options Options -} - -type Sections []*Section - -func (s Sections) GoString() string { - var strs []string - for _, ss := range s { - strs = append(strs, fmt.Sprintf("%#v", ss)) - } - - return strings.Join(strs, ", ") -} - -type Subsections []*Subsection - -func (s Subsections) GoString() string { - var strs []string - for _, ss := range s { - strs = append(strs, fmt.Sprintf("%#v", ss)) - } - - return strings.Join(strs, ", ") -} - -// IsName checks if the name provided is equals to the Section name, case insensitive. -func (s *Section) IsName(name string) bool { - return strings.EqualFold(s.Name, name) -} - -// Subsection returns a Subsection from the specified Section. If the -// Subsection does not exists, new one is created and added to Section. -func (s *Section) Subsection(name string) *Subsection { - for i := len(s.Subsections) - 1; i >= 0; i-- { - ss := s.Subsections[i] - if ss.IsName(name) { - return ss - } - } - - ss := &Subsection{Name: name} - s.Subsections = append(s.Subsections, ss) - return ss -} - -// HasSubsection checks if the Section has a Subsection with the specified name. -func (s *Section) HasSubsection(name string) bool { - for _, ss := range s.Subsections { - if ss.IsName(name) { - return true - } - } - - return false -} - -// RemoveSubsection removes a subsection from a Section. -func (s *Section) RemoveSubsection(name string) *Section { - result := Subsections{} - for _, s := range s.Subsections { - if !s.IsName(name) { - result = append(result, s) - } - } - - s.Subsections = result - return s -} - -// Option return the value for the specified key. Empty string is returned if -// key does not exists. -func (s *Section) Option(key string) string { - return s.Options.Get(key) -} - -// OptionAll returns all possible values for an option with the specified key. -// If the option does not exists, an empty slice will be returned. -func (s *Section) OptionAll(key string) []string { - return s.Options.GetAll(key) -} - -// HasOption checks if the Section has an Option with the given key. -func (s *Section) HasOption(key string) bool { - return s.Options.Has(key) -} - -// AddOption adds a new Option to the Section. The updated Section is returned. -func (s *Section) AddOption(key string, value string) *Section { - s.Options = s.Options.withAddedOption(key, value) - return s -} - -// SetOption adds a new Option to the Section. If the option already exists, is replaced. -// The updated Section is returned. -func (s *Section) SetOption(key string, value string) *Section { - s.Options = s.Options.withSettedOption(key, value) - return s -} - -// Remove an option with the specified key. The updated Section is returned. -func (s *Section) RemoveOption(key string) *Section { - s.Options = s.Options.withoutOption(key) - return s -} - -// IsName checks if the name of the subsection is exactly the specified name. -func (s *Subsection) IsName(name string) bool { - return s.Name == name -} - -// Option returns an option with the specified key. If the option does not exists, -// empty spring will be returned. -func (s *Subsection) Option(key string) string { - return s.Options.Get(key) -} - -// OptionAll returns all possible values for an option with the specified key. -// If the option does not exists, an empty slice will be returned. -func (s *Subsection) OptionAll(key string) []string { - return s.Options.GetAll(key) -} - -// HasOption checks if the Subsection has an Option with the given key. -func (s *Subsection) HasOption(key string) bool { - return s.Options.Has(key) -} - -// AddOption adds a new Option to the Subsection. The updated Subsection is returned. -func (s *Subsection) AddOption(key string, value string) *Subsection { - s.Options = s.Options.withAddedOption(key, value) - return s -} - -// SetOption adds a new Option to the Subsection. If the option already exists, is replaced. -// The updated Subsection is returned. -func (s *Subsection) SetOption(key string, value ...string) *Subsection { - s.Options = s.Options.withSettedOption(key, value...) - return s -} - -// RemoveOption removes the option with the specified key. The updated Subsection is returned. -func (s *Subsection) RemoveOption(key string) *Subsection { - s.Options = s.Options.withoutOption(key) - return s -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/diff/colorconfig.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/diff/colorconfig.go deleted file mode 100644 index 6fd41584..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/diff/colorconfig.go +++ /dev/null @@ -1,97 +0,0 @@ -package diff - -import "github.com/go-git/go-git/v5/plumbing/color" - -// A ColorKey is a key into a ColorConfig map and also equal to the key in the -// diff.color subsection of the config. See -// https://github.com/git/git/blob/v2.26.2/diff.c#L83-L106. -type ColorKey string - -// ColorKeys. -const ( - Context ColorKey = "context" - Meta ColorKey = "meta" - Frag ColorKey = "frag" - Old ColorKey = "old" - New ColorKey = "new" - Commit ColorKey = "commit" - Whitespace ColorKey = "whitespace" - Func ColorKey = "func" - OldMoved ColorKey = "oldMoved" - OldMovedAlternative ColorKey = "oldMovedAlternative" - OldMovedDimmed ColorKey = "oldMovedDimmed" - OldMovedAlternativeDimmed ColorKey = "oldMovedAlternativeDimmed" - NewMoved ColorKey = "newMoved" - NewMovedAlternative ColorKey = "newMovedAlternative" - NewMovedDimmed ColorKey = "newMovedDimmed" - NewMovedAlternativeDimmed ColorKey = "newMovedAlternativeDimmed" - ContextDimmed ColorKey = "contextDimmed" - OldDimmed ColorKey = "oldDimmed" - NewDimmed ColorKey = "newDimmed" - ContextBold ColorKey = "contextBold" - OldBold ColorKey = "oldBold" - NewBold ColorKey = "newBold" -) - -// A ColorConfig is a color configuration. A nil or empty ColorConfig -// corresponds to no color. -type ColorConfig map[ColorKey]string - -// A ColorConfigOption sets an option on a ColorConfig. -type ColorConfigOption func(ColorConfig) - -// WithColor sets the color for key. -func WithColor(key ColorKey, color string) ColorConfigOption { - return func(cc ColorConfig) { - cc[key] = color - } -} - -// defaultColorConfig is the default color configuration. See -// https://github.com/git/git/blob/v2.26.2/diff.c#L57-L81. -var defaultColorConfig = ColorConfig{ - Context: color.Normal, - Meta: color.Bold, - Frag: color.Cyan, - Old: color.Red, - New: color.Green, - Commit: color.Yellow, - Whitespace: color.BgRed, - Func: color.Normal, - OldMoved: color.BoldMagenta, - OldMovedAlternative: color.BoldBlue, - OldMovedDimmed: color.Faint, - OldMovedAlternativeDimmed: color.FaintItalic, - NewMoved: color.BoldCyan, - NewMovedAlternative: color.BoldYellow, - NewMovedDimmed: color.Faint, - NewMovedAlternativeDimmed: color.FaintItalic, - ContextDimmed: color.Faint, - OldDimmed: color.FaintRed, - NewDimmed: color.FaintGreen, - ContextBold: color.Bold, - OldBold: color.BoldRed, - NewBold: color.BoldGreen, -} - -// NewColorConfig returns a new ColorConfig. -func NewColorConfig(options ...ColorConfigOption) ColorConfig { - cc := make(ColorConfig) - for key, value := range defaultColorConfig { - cc[key] = value - } - for _, option := range options { - option(cc) - } - return cc -} - -// Reset returns the ANSI escape sequence to reset the color with key set from -// cc. If no color was set then no reset is needed so it returns the empty -// string. -func (cc ColorConfig) Reset(key ColorKey) string { - if cc[key] == "" { - return "" - } - return color.Reset -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/diff/patch.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/diff/patch.go deleted file mode 100644 index 39a66a1a..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/diff/patch.go +++ /dev/null @@ -1,58 +0,0 @@ -package diff - -import ( - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/plumbing/filemode" -) - -// Operation defines the operation of a diff item. -type Operation int - -const ( - // Equal item represents a equals diff. - Equal Operation = iota - // Add item represents an insert diff. - Add - // Delete item represents a delete diff. - Delete -) - -// Patch represents a collection of steps to transform several files. -type Patch interface { - // FilePatches returns a slice of patches per file. - FilePatches() []FilePatch - // Message returns an optional message that can be at the top of the - // Patch representation. - Message() string -} - -// FilePatch represents the necessary steps to transform one file to another. -type FilePatch interface { - // IsBinary returns true if this patch is representing a binary file. - IsBinary() bool - // Files returns the from and to Files, with all the necessary metadata to - // about them. If the patch creates a new file, "from" will be nil. - // If the patch deletes a file, "to" will be nil. - Files() (from, to File) - // Chunks returns a slice of ordered changes to transform "from" File to - // "to" File. If the file is a binary one, Chunks will be empty. - Chunks() []Chunk -} - -// File contains all the file metadata necessary to print some patch formats. -type File interface { - // Hash returns the File Hash. - Hash() plumbing.Hash - // Mode returns the FileMode. - Mode() filemode.FileMode - // Path returns the complete Path to the file, including the filename. - Path() string -} - -// Chunk represents a portion of a file transformation to another. -type Chunk interface { - // Content contains the portion of the file. - Content() string - // Type contains the Operation to do with this Chunk. - Type() Operation -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/diff/unified_encoder.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/diff/unified_encoder.go deleted file mode 100644 index fa605b19..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/diff/unified_encoder.go +++ /dev/null @@ -1,395 +0,0 @@ -package diff - -import ( - "fmt" - "io" - "regexp" - "strconv" - "strings" - - "github.com/go-git/go-git/v5/plumbing" -) - -// DefaultContextLines is the default number of context lines. -const DefaultContextLines = 3 - -var ( - splitLinesRegexp = regexp.MustCompile(`[^\n]*(\n|$)`) - - operationChar = map[Operation]byte{ - Add: '+', - Delete: '-', - Equal: ' ', - } - - operationColorKey = map[Operation]ColorKey{ - Add: New, - Delete: Old, - Equal: Context, - } -) - -// UnifiedEncoder encodes an unified diff into the provided Writer. It does not -// support similarity index for renames or sorting hash representations. -type UnifiedEncoder struct { - io.Writer - - // contextLines is the count of unchanged lines that will appear surrounding - // a change. - contextLines int - - // srcPrefix and dstPrefix are prepended to file paths when encoding a diff. - srcPrefix string - dstPrefix string - - // colorConfig is the color configuration. The default is no color. - color ColorConfig -} - -// NewUnifiedEncoder returns a new UnifiedEncoder that writes to w. -func NewUnifiedEncoder(w io.Writer, contextLines int) *UnifiedEncoder { - return &UnifiedEncoder{ - Writer: w, - srcPrefix: "a/", - dstPrefix: "b/", - contextLines: contextLines, - } -} - -// SetColor sets e's color configuration and returns e. -func (e *UnifiedEncoder) SetColor(colorConfig ColorConfig) *UnifiedEncoder { - e.color = colorConfig - return e -} - -// SetSrcPrefix sets e's srcPrefix and returns e. -func (e *UnifiedEncoder) SetSrcPrefix(prefix string) *UnifiedEncoder { - e.srcPrefix = prefix - return e -} - -// SetDstPrefix sets e's dstPrefix and returns e. -func (e *UnifiedEncoder) SetDstPrefix(prefix string) *UnifiedEncoder { - e.dstPrefix = prefix - return e -} - -// Encode encodes patch. -func (e *UnifiedEncoder) Encode(patch Patch) error { - sb := &strings.Builder{} - - if message := patch.Message(); message != "" { - sb.WriteString(message) - if !strings.HasSuffix(message, "\n") { - sb.WriteByte('\n') - } - } - - for _, filePatch := range patch.FilePatches() { - e.writeFilePatchHeader(sb, filePatch) - g := newHunksGenerator(filePatch.Chunks(), e.contextLines) - for _, hunk := range g.Generate() { - hunk.writeTo(sb, e.color) - } - } - - _, err := e.Write([]byte(sb.String())) - return err -} - -func (e *UnifiedEncoder) writeFilePatchHeader(sb *strings.Builder, filePatch FilePatch) { - from, to := filePatch.Files() - if from == nil && to == nil { - return - } - isBinary := filePatch.IsBinary() - - var lines []string - switch { - case from != nil && to != nil: - hashEquals := from.Hash() == to.Hash() - lines = append(lines, - fmt.Sprintf("diff --git %s%s %s%s", - e.srcPrefix, from.Path(), e.dstPrefix, to.Path()), - ) - if from.Mode() != to.Mode() { - lines = append(lines, - fmt.Sprintf("old mode %o", from.Mode()), - fmt.Sprintf("new mode %o", to.Mode()), - ) - } - if from.Path() != to.Path() { - lines = append(lines, - fmt.Sprintf("rename from %s", from.Path()), - fmt.Sprintf("rename to %s", to.Path()), - ) - } - if from.Mode() != to.Mode() && !hashEquals { - lines = append(lines, - fmt.Sprintf("index %s..%s", from.Hash(), to.Hash()), - ) - } else if !hashEquals { - lines = append(lines, - fmt.Sprintf("index %s..%s %o", from.Hash(), to.Hash(), from.Mode()), - ) - } - if !hashEquals { - lines = e.appendPathLines(lines, e.srcPrefix+from.Path(), e.dstPrefix+to.Path(), isBinary) - } - case from == nil: - lines = append(lines, - fmt.Sprintf("diff --git %s %s", e.srcPrefix+to.Path(), e.dstPrefix+to.Path()), - fmt.Sprintf("new file mode %o", to.Mode()), - fmt.Sprintf("index %s..%s", plumbing.ZeroHash, to.Hash()), - ) - lines = e.appendPathLines(lines, "/dev/null", e.dstPrefix+to.Path(), isBinary) - case to == nil: - lines = append(lines, - fmt.Sprintf("diff --git %s %s", e.srcPrefix+from.Path(), e.dstPrefix+from.Path()), - fmt.Sprintf("deleted file mode %o", from.Mode()), - fmt.Sprintf("index %s..%s", from.Hash(), plumbing.ZeroHash), - ) - lines = e.appendPathLines(lines, e.srcPrefix+from.Path(), "/dev/null", isBinary) - } - - sb.WriteString(e.color[Meta]) - sb.WriteString(lines[0]) - for _, line := range lines[1:] { - sb.WriteByte('\n') - sb.WriteString(line) - } - sb.WriteString(e.color.Reset(Meta)) - sb.WriteByte('\n') -} - -func (e *UnifiedEncoder) appendPathLines(lines []string, fromPath, toPath string, isBinary bool) []string { - if isBinary { - return append(lines, - fmt.Sprintf("Binary files %s and %s differ", fromPath, toPath), - ) - } - return append(lines, - fmt.Sprintf("--- %s", fromPath), - fmt.Sprintf("+++ %s", toPath), - ) -} - -type hunksGenerator struct { - fromLine, toLine int - ctxLines int - chunks []Chunk - current *hunk - hunks []*hunk - beforeContext, afterContext []string -} - -func newHunksGenerator(chunks []Chunk, ctxLines int) *hunksGenerator { - return &hunksGenerator{ - chunks: chunks, - ctxLines: ctxLines, - } -} - -func (g *hunksGenerator) Generate() []*hunk { - for i, chunk := range g.chunks { - lines := splitLines(chunk.Content()) - nLines := len(lines) - - switch chunk.Type() { - case Equal: - g.fromLine += nLines - g.toLine += nLines - g.processEqualsLines(lines, i) - case Delete: - if nLines != 0 { - g.fromLine++ - } - - g.processHunk(i, chunk.Type()) - g.fromLine += nLines - 1 - g.current.AddOp(chunk.Type(), lines...) - case Add: - if nLines != 0 { - g.toLine++ - } - g.processHunk(i, chunk.Type()) - g.toLine += nLines - 1 - g.current.AddOp(chunk.Type(), lines...) - } - - if i == len(g.chunks)-1 && g.current != nil { - g.hunks = append(g.hunks, g.current) - } - } - - return g.hunks -} - -func (g *hunksGenerator) processHunk(i int, op Operation) { - if g.current != nil { - return - } - - var ctxPrefix string - linesBefore := len(g.beforeContext) - if linesBefore > g.ctxLines { - ctxPrefix = g.beforeContext[linesBefore-g.ctxLines-1] - g.beforeContext = g.beforeContext[linesBefore-g.ctxLines:] - linesBefore = g.ctxLines - } - - g.current = &hunk{ctxPrefix: strings.TrimSuffix(ctxPrefix, "\n")} - g.current.AddOp(Equal, g.beforeContext...) - - switch op { - case Delete: - g.current.fromLine, g.current.toLine = - g.addLineNumbers(g.fromLine, g.toLine, linesBefore, i, Add) - case Add: - g.current.toLine, g.current.fromLine = - g.addLineNumbers(g.toLine, g.fromLine, linesBefore, i, Delete) - } - - g.beforeContext = nil -} - -// addLineNumbers obtains the line numbers in a new chunk. -func (g *hunksGenerator) addLineNumbers(la, lb int, linesBefore int, i int, op Operation) (cla, clb int) { - cla = la - linesBefore - // we need to search for a reference for the next diff - switch { - case linesBefore != 0 && g.ctxLines != 0: - if lb > g.ctxLines { - clb = lb - g.ctxLines + 1 - } else { - clb = 1 - } - case g.ctxLines == 0: - clb = lb - case i != len(g.chunks)-1: - next := g.chunks[i+1] - if next.Type() == op || next.Type() == Equal { - // this diff will be into this chunk - clb = lb + 1 - } - } - - return -} - -func (g *hunksGenerator) processEqualsLines(ls []string, i int) { - if g.current == nil { - g.beforeContext = append(g.beforeContext, ls...) - return - } - - g.afterContext = append(g.afterContext, ls...) - if len(g.afterContext) <= g.ctxLines*2 && i != len(g.chunks)-1 { - g.current.AddOp(Equal, g.afterContext...) - g.afterContext = nil - } else { - ctxLines := g.ctxLines - if ctxLines > len(g.afterContext) { - ctxLines = len(g.afterContext) - } - g.current.AddOp(Equal, g.afterContext[:ctxLines]...) - g.hunks = append(g.hunks, g.current) - - g.current = nil - g.beforeContext = g.afterContext[ctxLines:] - g.afterContext = nil - } -} - -func splitLines(s string) []string { - out := splitLinesRegexp.FindAllString(s, -1) - if out[len(out)-1] == "" { - out = out[:len(out)-1] - } - return out -} - -type hunk struct { - fromLine int - toLine int - - fromCount int - toCount int - - ctxPrefix string - ops []*op -} - -func (h *hunk) writeTo(sb *strings.Builder, color ColorConfig) { - sb.WriteString(color[Frag]) - sb.WriteString("@@ -") - - if h.fromCount == 1 { - sb.WriteString(strconv.Itoa(h.fromLine)) - } else { - sb.WriteString(strconv.Itoa(h.fromLine)) - sb.WriteByte(',') - sb.WriteString(strconv.Itoa(h.fromCount)) - } - - sb.WriteString(" +") - - if h.toCount == 1 { - sb.WriteString(strconv.Itoa(h.toLine)) - } else { - sb.WriteString(strconv.Itoa(h.toLine)) - sb.WriteByte(',') - sb.WriteString(strconv.Itoa(h.toCount)) - } - - sb.WriteString(" @@") - sb.WriteString(color.Reset(Frag)) - - if h.ctxPrefix != "" { - sb.WriteByte(' ') - sb.WriteString(color[Func]) - sb.WriteString(h.ctxPrefix) - sb.WriteString(color.Reset(Func)) - } - - sb.WriteByte('\n') - - for _, op := range h.ops { - op.writeTo(sb, color) - } -} - -func (h *hunk) AddOp(t Operation, ss ...string) { - n := len(ss) - switch t { - case Add: - h.toCount += n - case Delete: - h.fromCount += n - case Equal: - h.toCount += n - h.fromCount += n - } - - for _, s := range ss { - h.ops = append(h.ops, &op{s, t}) - } -} - -type op struct { - text string - t Operation -} - -func (o *op) writeTo(sb *strings.Builder, color ColorConfig) { - colorKey := operationColorKey[o.t] - sb.WriteString(color[colorKey]) - sb.WriteByte(operationChar[o.t]) - if strings.HasSuffix(o.text, "\n") { - sb.WriteString(strings.TrimSuffix(o.text, "\n")) - } else { - sb.WriteString(o.text + "\n\\ No newline at end of file") - } - sb.WriteString(color.Reset(colorKey)) - sb.WriteByte('\n') -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/gitignore/dir.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/gitignore/dir.go deleted file mode 100644 index 922c458d..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/gitignore/dir.go +++ /dev/null @@ -1,136 +0,0 @@ -package gitignore - -import ( - "bufio" - "bytes" - "io/ioutil" - "os" - "os/user" - "strings" - - "github.com/go-git/go-billy/v5" - "github.com/go-git/go-git/v5/plumbing/format/config" - gioutil "github.com/go-git/go-git/v5/utils/ioutil" -) - -const ( - commentPrefix = "#" - coreSection = "core" - excludesfile = "excludesfile" - gitDir = ".git" - gitignoreFile = ".gitignore" - gitconfigFile = ".gitconfig" - systemFile = "/etc/gitconfig" -) - -// readIgnoreFile reads a specific git ignore file. -func readIgnoreFile(fs billy.Filesystem, path []string, ignoreFile string) (ps []Pattern, err error) { - f, err := fs.Open(fs.Join(append(path, ignoreFile)...)) - if err == nil { - defer f.Close() - - scanner := bufio.NewScanner(f) - for scanner.Scan() { - s := scanner.Text() - if !strings.HasPrefix(s, commentPrefix) && len(strings.TrimSpace(s)) > 0 { - ps = append(ps, ParsePattern(s, path)) - } - } - } else if !os.IsNotExist(err) { - return nil, err - } - - return -} - -// ReadPatterns reads gitignore patterns recursively traversing through the directory -// structure. The result is in the ascending order of priority (last higher). -func ReadPatterns(fs billy.Filesystem, path []string) (ps []Pattern, err error) { - ps, _ = readIgnoreFile(fs, path, gitignoreFile) - - var fis []os.FileInfo - fis, err = fs.ReadDir(fs.Join(path...)) - if err != nil { - return - } - - for _, fi := range fis { - if fi.IsDir() && fi.Name() != gitDir { - var subps []Pattern - subps, err = ReadPatterns(fs, append(path, fi.Name())) - if err != nil { - return - } - - if len(subps) > 0 { - ps = append(ps, subps...) - } - } - } - - return -} - -func loadPatterns(fs billy.Filesystem, path string) (ps []Pattern, err error) { - f, err := fs.Open(path) - if err != nil { - if os.IsNotExist(err) { - return nil, nil - } - return nil, err - } - - defer gioutil.CheckClose(f, &err) - - b, err := ioutil.ReadAll(f) - if err != nil { - return - } - - d := config.NewDecoder(bytes.NewBuffer(b)) - - raw := config.New() - if err = d.Decode(raw); err != nil { - return - } - - s := raw.Section(coreSection) - efo := s.Options.Get(excludesfile) - if efo == "" { - return nil, nil - } - - ps, err = readIgnoreFile(fs, nil, efo) - if os.IsNotExist(err) { - return nil, nil - } - - return -} - -// LoadGlobalPatterns loads gitignore patterns from from the gitignore file -// declared in a user's ~/.gitconfig file. If the ~/.gitconfig file does not -// exist the function will return nil. If the core.excludesfile property -// is not declared, the function will return nil. If the file pointed to by -// the core.excludesfile property does not exist, the function will return nil. -// -// The function assumes fs is rooted at the root filesystem. -func LoadGlobalPatterns(fs billy.Filesystem) (ps []Pattern, err error) { - usr, err := user.Current() - if err != nil { - return - } - - return loadPatterns(fs, fs.Join(usr.HomeDir, gitconfigFile)) -} - -// LoadSystemPatterns loads gitignore patterns from from the gitignore file -// declared in a system's /etc/gitconfig file. If the /etc/gitconfig file does -// not exist the function will return nil. If the core.excludesfile property -// is not declared, the function will return nil. If the file pointed to by -// the core.excludesfile property does not exist, the function will return nil. -// -// The function assumes fs is rooted at the root filesystem. -func LoadSystemPatterns(fs billy.Filesystem) (ps []Pattern, err error) { - return loadPatterns(fs, systemFile) -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/gitignore/doc.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/gitignore/doc.go deleted file mode 100644 index eecd4bac..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/gitignore/doc.go +++ /dev/null @@ -1,70 +0,0 @@ -// Package gitignore implements matching file system paths to gitignore patterns that -// can be automatically read from a git repository tree in the order of definition -// priorities. It support all pattern formats as specified in the original gitignore -// documentation, copied below: -// -// Pattern format -// ============== -// -// - A blank line matches no files, so it can serve as a separator for readability. -// -// - A line starting with # serves as a comment. Put a backslash ("\") in front of -// the first hash for patterns that begin with a hash. -// -// - Trailing spaces are ignored unless they are quoted with backslash ("\"). -// -// - An optional prefix "!" which negates the pattern; any matching file excluded -// by a previous pattern will become included again. It is not possible to -// re-include a file if a parent directory of that file is excluded. -// Git doesn’t list excluded directories for performance reasons, so -// any patterns on contained files have no effect, no matter where they are -// defined. Put a backslash ("\") in front of the first "!" for patterns -// that begin with a literal "!", for example, "\!important!.txt". -// -// - If the pattern ends with a slash, it is removed for the purpose of the -// following description, but it would only find a match with a directory. -// In other words, foo/ will match a directory foo and paths underneath it, -// but will not match a regular file or a symbolic link foo (this is consistent -// with the way how pathspec works in general in Git). -// -// - If the pattern does not contain a slash /, Git treats it as a shell glob -// pattern and checks for a match against the pathname relative to the location -// of the .gitignore file (relative to the toplevel of the work tree if not -// from a .gitignore file). -// -// - Otherwise, Git treats the pattern as a shell glob suitable for consumption -// by fnmatch(3) with the FNM_PATHNAME flag: wildcards in the pattern will -// not match a / in the pathname. For example, "Documentation/*.html" matches -// "Documentation/git.html" but not "Documentation/ppc/ppc.html" or -// "tools/perf/Documentation/perf.html". -// -// - A leading slash matches the beginning of the pathname. For example, -// "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c". -// -// Two consecutive asterisks ("**") in patterns matched against full pathname -// may have special meaning: -// -// - A leading "**" followed by a slash means match in all directories. -// For example, "**/foo" matches file or directory "foo" anywhere, the same as -// pattern "foo". "**/foo/bar" matches file or directory "bar" -// anywhere that is directly under directory "foo". -// -// - A trailing "/**" matches everything inside. For example, "abc/**" matches -// all files inside directory "abc", relative to the location of the -// .gitignore file, with infinite depth. -// -// - A slash followed by two consecutive asterisks then a slash matches -// zero or more directories. For example, "a/**/b" matches "a/b", "a/x/b", -// "a/x/y/b" and so on. -// -// - Other consecutive asterisks are considered invalid. -// -// Copyright and license -// ===================== -// -// Copyright (c) Oleg Sklyar, Silvertern and source{d} -// -// The package code was donated to source{d} to include, modify and develop -// further as a part of the `go-git` project, release it on the license of -// the whole project or delete it from the project. -package gitignore diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/gitignore/matcher.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/gitignore/matcher.go deleted file mode 100644 index bd1e9e2d..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/gitignore/matcher.go +++ /dev/null @@ -1,30 +0,0 @@ -package gitignore - -// Matcher defines a global multi-pattern matcher for gitignore patterns -type Matcher interface { - // Match matches patterns in the order of priorities. As soon as an inclusion or - // exclusion is found, not further matching is performed. - Match(path []string, isDir bool) bool -} - -// NewMatcher constructs a new global matcher. Patterns must be given in the order of -// increasing priority. That is most generic settings files first, then the content of -// the repo .gitignore, then content of .gitignore down the path or the repo and then -// the content command line arguments. -func NewMatcher(ps []Pattern) Matcher { - return &matcher{ps} -} - -type matcher struct { - patterns []Pattern -} - -func (m *matcher) Match(path []string, isDir bool) bool { - n := len(m.patterns) - for i := n - 1; i >= 0; i-- { - if match := m.patterns[i].Match(path, isDir); match > NoMatch { - return match == Exclude - } - } - return false -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/gitignore/pattern.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/gitignore/pattern.go deleted file mode 100644 index 098cb502..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/gitignore/pattern.go +++ /dev/null @@ -1,153 +0,0 @@ -package gitignore - -import ( - "path/filepath" - "strings" -) - -// MatchResult defines outcomes of a match, no match, exclusion or inclusion. -type MatchResult int - -const ( - // NoMatch defines the no match outcome of a match check - NoMatch MatchResult = iota - // Exclude defines an exclusion of a file as a result of a match check - Exclude - // Include defines an explicit inclusion of a file as a result of a match check - Include -) - -const ( - inclusionPrefix = "!" - zeroToManyDirs = "**" - patternDirSep = "/" -) - -// Pattern defines a single gitignore pattern. -type Pattern interface { - // Match matches the given path to the pattern. - Match(path []string, isDir bool) MatchResult -} - -type pattern struct { - domain []string - pattern []string - inclusion bool - dirOnly bool - isGlob bool -} - -// ParsePattern parses a gitignore pattern string into the Pattern structure. -func ParsePattern(p string, domain []string) Pattern { - res := pattern{domain: domain} - - if strings.HasPrefix(p, inclusionPrefix) { - res.inclusion = true - p = p[1:] - } - - if !strings.HasSuffix(p, "\\ ") { - p = strings.TrimRight(p, " ") - } - - if strings.HasSuffix(p, patternDirSep) { - res.dirOnly = true - p = p[:len(p)-1] - } - - if strings.Contains(p, patternDirSep) { - res.isGlob = true - } - - res.pattern = strings.Split(p, patternDirSep) - return &res -} - -func (p *pattern) Match(path []string, isDir bool) MatchResult { - if len(path) <= len(p.domain) { - return NoMatch - } - for i, e := range p.domain { - if path[i] != e { - return NoMatch - } - } - - path = path[len(p.domain):] - if p.isGlob && !p.globMatch(path, isDir) { - return NoMatch - } else if !p.isGlob && !p.simpleNameMatch(path, isDir) { - return NoMatch - } - - if p.inclusion { - return Include - } else { - return Exclude - } -} - -func (p *pattern) simpleNameMatch(path []string, isDir bool) bool { - for i, name := range path { - if match, err := filepath.Match(p.pattern[0], name); err != nil { - return false - } else if !match { - continue - } - if p.dirOnly && !isDir && i == len(path)-1 { - return false - } - return true - } - return false -} - -func (p *pattern) globMatch(path []string, isDir bool) bool { - matched := false - canTraverse := false - for i, pattern := range p.pattern { - if pattern == "" { - canTraverse = false - continue - } - if pattern == zeroToManyDirs { - if i == len(p.pattern)-1 { - break - } - canTraverse = true - continue - } - if strings.Contains(pattern, zeroToManyDirs) { - return false - } - if len(path) == 0 { - return false - } - if canTraverse { - canTraverse = false - for len(path) > 0 { - e := path[0] - path = path[1:] - if match, err := filepath.Match(pattern, e); err != nil { - return false - } else if match { - matched = true - break - } else if len(path) == 0 { - // if nothing left then fail - matched = false - } - } - } else { - if match, err := filepath.Match(pattern, path[0]); err != nil || !match { - return false - } - matched = true - path = path[1:] - } - } - if matched && p.dirOnly && !isDir && len(path) == 0 { - matched = false - } - return matched -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/idxfile/decoder.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/idxfile/decoder.go deleted file mode 100644 index 7768bd65..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/idxfile/decoder.go +++ /dev/null @@ -1,177 +0,0 @@ -package idxfile - -import ( - "bufio" - "bytes" - "errors" - "io" - - "github.com/go-git/go-git/v5/utils/binary" -) - -var ( - // ErrUnsupportedVersion is returned by Decode when the idx file version - // is not supported. - ErrUnsupportedVersion = errors.New("Unsupported version") - // ErrMalformedIdxFile is returned by Decode when the idx file is corrupted. - ErrMalformedIdxFile = errors.New("Malformed IDX file") -) - -const ( - fanout = 256 - objectIDLength = 20 -) - -// Decoder reads and decodes idx files from an input stream. -type Decoder struct { - *bufio.Reader -} - -// NewDecoder builds a new idx stream decoder, that reads from r. -func NewDecoder(r io.Reader) *Decoder { - return &Decoder{bufio.NewReader(r)} -} - -// Decode reads from the stream and decode the content into the MemoryIndex struct. -func (d *Decoder) Decode(idx *MemoryIndex) error { - if err := validateHeader(d); err != nil { - return err - } - - flow := []func(*MemoryIndex, io.Reader) error{ - readVersion, - readFanout, - readObjectNames, - readCRC32, - readOffsets, - readChecksums, - } - - for _, f := range flow { - if err := f(idx, d); err != nil { - return err - } - } - - return nil -} - -func validateHeader(r io.Reader) error { - var h = make([]byte, 4) - if _, err := io.ReadFull(r, h); err != nil { - return err - } - - if !bytes.Equal(h, idxHeader) { - return ErrMalformedIdxFile - } - - return nil -} - -func readVersion(idx *MemoryIndex, r io.Reader) error { - v, err := binary.ReadUint32(r) - if err != nil { - return err - } - - if v > VersionSupported { - return ErrUnsupportedVersion - } - - idx.Version = v - return nil -} - -func readFanout(idx *MemoryIndex, r io.Reader) error { - for k := 0; k < fanout; k++ { - n, err := binary.ReadUint32(r) - if err != nil { - return err - } - - idx.Fanout[k] = n - idx.FanoutMapping[k] = noMapping - } - - return nil -} - -func readObjectNames(idx *MemoryIndex, r io.Reader) error { - for k := 0; k < fanout; k++ { - var buckets uint32 - if k == 0 { - buckets = idx.Fanout[k] - } else { - buckets = idx.Fanout[k] - idx.Fanout[k-1] - } - - if buckets == 0 { - continue - } - - idx.FanoutMapping[k] = len(idx.Names) - - nameLen := int(buckets * objectIDLength) - bin := make([]byte, nameLen) - if _, err := io.ReadFull(r, bin); err != nil { - return err - } - - idx.Names = append(idx.Names, bin) - idx.Offset32 = append(idx.Offset32, make([]byte, buckets*4)) - idx.CRC32 = append(idx.CRC32, make([]byte, buckets*4)) - } - - return nil -} - -func readCRC32(idx *MemoryIndex, r io.Reader) error { - for k := 0; k < fanout; k++ { - if pos := idx.FanoutMapping[k]; pos != noMapping { - if _, err := io.ReadFull(r, idx.CRC32[pos]); err != nil { - return err - } - } - } - - return nil -} - -func readOffsets(idx *MemoryIndex, r io.Reader) error { - var o64cnt int - for k := 0; k < fanout; k++ { - if pos := idx.FanoutMapping[k]; pos != noMapping { - if _, err := io.ReadFull(r, idx.Offset32[pos]); err != nil { - return err - } - - for p := 0; p < len(idx.Offset32[pos]); p += 4 { - if idx.Offset32[pos][p]&(byte(1)<<7) > 0 { - o64cnt++ - } - } - } - } - - if o64cnt > 0 { - idx.Offset64 = make([]byte, o64cnt*8) - if _, err := io.ReadFull(r, idx.Offset64); err != nil { - return err - } - } - - return nil -} - -func readChecksums(idx *MemoryIndex, r io.Reader) error { - if _, err := io.ReadFull(r, idx.PackfileChecksum[:]); err != nil { - return err - } - - if _, err := io.ReadFull(r, idx.IdxChecksum[:]); err != nil { - return err - } - - return nil -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/idxfile/doc.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/idxfile/doc.go deleted file mode 100644 index 1e628ab4..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/idxfile/doc.go +++ /dev/null @@ -1,128 +0,0 @@ -// Package idxfile implements encoding and decoding of packfile idx files. -// -// == Original (version 1) pack-*.idx files have the following format: -// -// - The header consists of 256 4-byte network byte order -// integers. N-th entry of this table records the number of -// objects in the corresponding pack, the first byte of whose -// object name is less than or equal to N. This is called the -// 'first-level fan-out' table. -// -// - The header is followed by sorted 24-byte entries, one entry -// per object in the pack. Each entry is: -// -// 4-byte network byte order integer, recording where the -// object is stored in the packfile as the offset from the -// beginning. -// -// 20-byte object name. -// -// - The file is concluded with a trailer: -// -// A copy of the 20-byte SHA1 checksum at the end of -// corresponding packfile. -// -// 20-byte SHA1-checksum of all of the above. -// -// Pack Idx file: -// -// -- +--------------------------------+ -// fanout | fanout[0] = 2 (for example) |-. -// table +--------------------------------+ | -// | fanout[1] | | -// +--------------------------------+ | -// | fanout[2] | | -// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | -// | fanout[255] = total objects |---. -// -- +--------------------------------+ | | -// main | offset | | | -// index | object name 00XXXXXXXXXXXXXXXX | | | -// tab +--------------------------------+ | | -// | offset | | | -// | object name 00XXXXXXXXXXXXXXXX | | | -// +--------------------------------+<+ | -// .-| offset | | -// | | object name 01XXXXXXXXXXXXXXXX | | -// | +--------------------------------+ | -// | | offset | | -// | | object name 01XXXXXXXXXXXXXXXX | | -// | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | -// | | offset | | -// | | object name FFXXXXXXXXXXXXXXXX | | -// --| +--------------------------------+<--+ -// trailer | | packfile checksum | -// | +--------------------------------+ -// | | idxfile checksum | -// | +--------------------------------+ -// .---------. -// | -// Pack file entry: <+ -// -// packed object header: -// 1-byte size extension bit (MSB) -// type (next 3 bit) -// size0 (lower 4-bit) -// n-byte sizeN (as long as MSB is set, each 7-bit) -// size0..sizeN form 4+7+7+..+7 bit integer, size0 -// is the least significant part, and sizeN is the -// most significant part. -// packed object data: -// If it is not DELTA, then deflated bytes (the size above -// is the size before compression). -// If it is REF_DELTA, then -// 20-byte base object name SHA1 (the size above is the -// size of the delta data that follows). -// delta data, deflated. -// If it is OFS_DELTA, then -// n-byte offset (see below) interpreted as a negative -// offset from the type-byte of the header of the -// ofs-delta entry (the size above is the size of -// the delta data that follows). -// delta data, deflated. -// -// offset encoding: -// n bytes with MSB set in all but the last one. -// The offset is then the number constructed by -// concatenating the lower 7 bit of each byte, and -// for n >= 2 adding 2^7 + 2^14 + ... + 2^(7*(n-1)) -// to the result. -// -// == Version 2 pack-*.idx files support packs larger than 4 GiB, and -// have some other reorganizations. They have the format: -// -// - A 4-byte magic number '\377tOc' which is an unreasonable -// fanout[0] value. -// -// - A 4-byte version number (= 2) -// -// - A 256-entry fan-out table just like v1. -// -// - A table of sorted 20-byte SHA1 object names. These are -// packed together without offset values to reduce the cache -// footprint of the binary search for a specific object name. -// -// - A table of 4-byte CRC32 values of the packed object data. -// This is new in v2 so compressed data can be copied directly -// from pack to pack during repacking without undetected -// data corruption. -// -// - A table of 4-byte offset values (in network byte order). -// These are usually 31-bit pack file offsets, but large -// offsets are encoded as an index into the next table with -// the msbit set. -// -// - A table of 8-byte offset entries (empty for pack files less -// than 2 GiB). Pack files are organized with heavily used -// objects toward the front, so most object references should -// not need to refer to this table. -// -// - The same trailer as a v1 pack file: -// -// A copy of the 20-byte SHA1 checksum at the end of -// corresponding packfile. -// -// 20-byte SHA1-checksum of all of the above. -// -// Source: -// https://www.kernel.org/pub/software/scm/git/docs/v1.7.5/technical/pack-format.txt -package idxfile diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/idxfile/encoder.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/idxfile/encoder.go deleted file mode 100644 index 26b2e4d6..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/idxfile/encoder.go +++ /dev/null @@ -1,142 +0,0 @@ -package idxfile - -import ( - "crypto/sha1" - "hash" - "io" - - "github.com/go-git/go-git/v5/utils/binary" -) - -// Encoder writes MemoryIndex structs to an output stream. -type Encoder struct { - io.Writer - hash hash.Hash -} - -// NewEncoder returns a new stream encoder that writes to w. -func NewEncoder(w io.Writer) *Encoder { - h := sha1.New() - mw := io.MultiWriter(w, h) - return &Encoder{mw, h} -} - -// Encode encodes an MemoryIndex to the encoder writer. -func (e *Encoder) Encode(idx *MemoryIndex) (int, error) { - flow := []func(*MemoryIndex) (int, error){ - e.encodeHeader, - e.encodeFanout, - e.encodeHashes, - e.encodeCRC32, - e.encodeOffsets, - e.encodeChecksums, - } - - sz := 0 - for _, f := range flow { - i, err := f(idx) - sz += i - - if err != nil { - return sz, err - } - } - - return sz, nil -} - -func (e *Encoder) encodeHeader(idx *MemoryIndex) (int, error) { - c, err := e.Write(idxHeader) - if err != nil { - return c, err - } - - return c + 4, binary.WriteUint32(e, idx.Version) -} - -func (e *Encoder) encodeFanout(idx *MemoryIndex) (int, error) { - for _, c := range idx.Fanout { - if err := binary.WriteUint32(e, c); err != nil { - return 0, err - } - } - - return fanout * 4, nil -} - -func (e *Encoder) encodeHashes(idx *MemoryIndex) (int, error) { - var size int - for k := 0; k < fanout; k++ { - pos := idx.FanoutMapping[k] - if pos == noMapping { - continue - } - - n, err := e.Write(idx.Names[pos]) - if err != nil { - return size, err - } - size += n - } - return size, nil -} - -func (e *Encoder) encodeCRC32(idx *MemoryIndex) (int, error) { - var size int - for k := 0; k < fanout; k++ { - pos := idx.FanoutMapping[k] - if pos == noMapping { - continue - } - - n, err := e.Write(idx.CRC32[pos]) - if err != nil { - return size, err - } - - size += n - } - - return size, nil -} - -func (e *Encoder) encodeOffsets(idx *MemoryIndex) (int, error) { - var size int - for k := 0; k < fanout; k++ { - pos := idx.FanoutMapping[k] - if pos == noMapping { - continue - } - - n, err := e.Write(idx.Offset32[pos]) - if err != nil { - return size, err - } - - size += n - } - - if len(idx.Offset64) > 0 { - n, err := e.Write(idx.Offset64) - if err != nil { - return size, err - } - - size += n - } - - return size, nil -} - -func (e *Encoder) encodeChecksums(idx *MemoryIndex) (int, error) { - if _, err := e.Write(idx.PackfileChecksum[:]); err != nil { - return 0, err - } - - copy(idx.IdxChecksum[:], e.hash.Sum(nil)[:20]) - if _, err := e.Write(idx.IdxChecksum[:]); err != nil { - return 0, err - } - - return 40, nil -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/idxfile/idxfile.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/idxfile/idxfile.go deleted file mode 100644 index 64dd8dce..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/idxfile/idxfile.go +++ /dev/null @@ -1,346 +0,0 @@ -package idxfile - -import ( - "bytes" - "io" - "sort" - - encbin "encoding/binary" - - "github.com/go-git/go-git/v5/plumbing" -) - -const ( - // VersionSupported is the only idx version supported. - VersionSupported = 2 - - noMapping = -1 -) - -var ( - idxHeader = []byte{255, 't', 'O', 'c'} -) - -// Index represents an index of a packfile. -type Index interface { - // Contains checks whether the given hash is in the index. - Contains(h plumbing.Hash) (bool, error) - // FindOffset finds the offset in the packfile for the object with - // the given hash. - FindOffset(h plumbing.Hash) (int64, error) - // FindCRC32 finds the CRC32 of the object with the given hash. - FindCRC32(h plumbing.Hash) (uint32, error) - // FindHash finds the hash for the object with the given offset. - FindHash(o int64) (plumbing.Hash, error) - // Count returns the number of entries in the index. - Count() (int64, error) - // Entries returns an iterator to retrieve all index entries. - Entries() (EntryIter, error) - // EntriesByOffset returns an iterator to retrieve all index entries ordered - // by offset. - EntriesByOffset() (EntryIter, error) -} - -// MemoryIndex is the in memory representation of an idx file. -type MemoryIndex struct { - Version uint32 - Fanout [256]uint32 - // FanoutMapping maps the position in the fanout table to the position - // in the Names, Offset32 and CRC32 slices. This improves the memory - // usage by not needing an array with unnecessary empty slots. - FanoutMapping [256]int - Names [][]byte - Offset32 [][]byte - CRC32 [][]byte - Offset64 []byte - PackfileChecksum [20]byte - IdxChecksum [20]byte - - offsetHash map[int64]plumbing.Hash - offsetHashIsFull bool -} - -var _ Index = (*MemoryIndex)(nil) - -// NewMemoryIndex returns an instance of a new MemoryIndex. -func NewMemoryIndex() *MemoryIndex { - return &MemoryIndex{} -} - -func (idx *MemoryIndex) findHashIndex(h plumbing.Hash) (int, bool) { - k := idx.FanoutMapping[h[0]] - if k == noMapping { - return 0, false - } - - if len(idx.Names) <= k { - return 0, false - } - - data := idx.Names[k] - high := uint64(len(idx.Offset32[k])) >> 2 - if high == 0 { - return 0, false - } - - low := uint64(0) - for { - mid := (low + high) >> 1 - offset := mid * objectIDLength - - cmp := bytes.Compare(h[:], data[offset:offset+objectIDLength]) - if cmp < 0 { - high = mid - } else if cmp == 0 { - return int(mid), true - } else { - low = mid + 1 - } - - if low >= high { - break - } - } - - return 0, false -} - -// Contains implements the Index interface. -func (idx *MemoryIndex) Contains(h plumbing.Hash) (bool, error) { - _, ok := idx.findHashIndex(h) - return ok, nil -} - -// FindOffset implements the Index interface. -func (idx *MemoryIndex) FindOffset(h plumbing.Hash) (int64, error) { - if len(idx.FanoutMapping) <= int(h[0]) { - return 0, plumbing.ErrObjectNotFound - } - - k := idx.FanoutMapping[h[0]] - i, ok := idx.findHashIndex(h) - if !ok { - return 0, plumbing.ErrObjectNotFound - } - - offset := idx.getOffset(k, i) - - if !idx.offsetHashIsFull { - // Save the offset for reverse lookup - if idx.offsetHash == nil { - idx.offsetHash = make(map[int64]plumbing.Hash) - } - idx.offsetHash[int64(offset)] = h - } - - return int64(offset), nil -} - -const isO64Mask = uint64(1) << 31 - -func (idx *MemoryIndex) getOffset(firstLevel, secondLevel int) uint64 { - offset := secondLevel << 2 - ofs := encbin.BigEndian.Uint32(idx.Offset32[firstLevel][offset : offset+4]) - - if (uint64(ofs) & isO64Mask) != 0 { - offset := 8 * (uint64(ofs) & ^isO64Mask) - n := encbin.BigEndian.Uint64(idx.Offset64[offset : offset+8]) - return n - } - - return uint64(ofs) -} - -// FindCRC32 implements the Index interface. -func (idx *MemoryIndex) FindCRC32(h plumbing.Hash) (uint32, error) { - k := idx.FanoutMapping[h[0]] - i, ok := idx.findHashIndex(h) - if !ok { - return 0, plumbing.ErrObjectNotFound - } - - return idx.getCRC32(k, i), nil -} - -func (idx *MemoryIndex) getCRC32(firstLevel, secondLevel int) uint32 { - offset := secondLevel << 2 - return encbin.BigEndian.Uint32(idx.CRC32[firstLevel][offset : offset+4]) -} - -// FindHash implements the Index interface. -func (idx *MemoryIndex) FindHash(o int64) (plumbing.Hash, error) { - var hash plumbing.Hash - var ok bool - - if idx.offsetHash != nil { - if hash, ok = idx.offsetHash[o]; ok { - return hash, nil - } - } - - // Lazily generate the reverse offset/hash map if required. - if !idx.offsetHashIsFull || idx.offsetHash == nil { - if err := idx.genOffsetHash(); err != nil { - return plumbing.ZeroHash, err - } - - hash, ok = idx.offsetHash[o] - } - - if !ok { - return plumbing.ZeroHash, plumbing.ErrObjectNotFound - } - - return hash, nil -} - -// genOffsetHash generates the offset/hash mapping for reverse search. -func (idx *MemoryIndex) genOffsetHash() error { - count, err := idx.Count() - if err != nil { - return err - } - - idx.offsetHash = make(map[int64]plumbing.Hash, count) - idx.offsetHashIsFull = true - - var hash plumbing.Hash - i := uint32(0) - for firstLevel, fanoutValue := range idx.Fanout { - mappedFirstLevel := idx.FanoutMapping[firstLevel] - for secondLevel := uint32(0); i < fanoutValue; i++ { - copy(hash[:], idx.Names[mappedFirstLevel][secondLevel*objectIDLength:]) - offset := int64(idx.getOffset(mappedFirstLevel, int(secondLevel))) - idx.offsetHash[offset] = hash - secondLevel++ - } - } - - return nil -} - -// Count implements the Index interface. -func (idx *MemoryIndex) Count() (int64, error) { - return int64(idx.Fanout[fanout-1]), nil -} - -// Entries implements the Index interface. -func (idx *MemoryIndex) Entries() (EntryIter, error) { - return &idxfileEntryIter{idx, 0, 0, 0}, nil -} - -// EntriesByOffset implements the Index interface. -func (idx *MemoryIndex) EntriesByOffset() (EntryIter, error) { - count, err := idx.Count() - if err != nil { - return nil, err - } - - iter := &idxfileEntryOffsetIter{ - entries: make(entriesByOffset, count), - } - - entries, err := idx.Entries() - if err != nil { - return nil, err - } - - for pos := 0; int64(pos) < count; pos++ { - entry, err := entries.Next() - if err != nil { - return nil, err - } - - iter.entries[pos] = entry - } - - sort.Sort(iter.entries) - - return iter, nil -} - -// EntryIter is an iterator that will return the entries in a packfile index. -type EntryIter interface { - // Next returns the next entry in the packfile index. - Next() (*Entry, error) - // Close closes the iterator. - Close() error -} - -type idxfileEntryIter struct { - idx *MemoryIndex - total int - firstLevel, secondLevel int -} - -func (i *idxfileEntryIter) Next() (*Entry, error) { - for { - if i.firstLevel >= fanout { - return nil, io.EOF - } - - if i.total >= int(i.idx.Fanout[i.firstLevel]) { - i.firstLevel++ - i.secondLevel = 0 - continue - } - - mappedFirstLevel := i.idx.FanoutMapping[i.firstLevel] - entry := new(Entry) - copy(entry.Hash[:], i.idx.Names[mappedFirstLevel][i.secondLevel*objectIDLength:]) - entry.Offset = i.idx.getOffset(mappedFirstLevel, i.secondLevel) - entry.CRC32 = i.idx.getCRC32(mappedFirstLevel, i.secondLevel) - - i.secondLevel++ - i.total++ - - return entry, nil - } -} - -func (i *idxfileEntryIter) Close() error { - i.firstLevel = fanout - return nil -} - -// Entry is the in memory representation of an object entry in the idx file. -type Entry struct { - Hash plumbing.Hash - CRC32 uint32 - Offset uint64 -} - -type idxfileEntryOffsetIter struct { - entries entriesByOffset - pos int -} - -func (i *idxfileEntryOffsetIter) Next() (*Entry, error) { - if i.pos >= len(i.entries) { - return nil, io.EOF - } - - entry := i.entries[i.pos] - i.pos++ - - return entry, nil -} - -func (i *idxfileEntryOffsetIter) Close() error { - i.pos = len(i.entries) + 1 - return nil -} - -type entriesByOffset []*Entry - -func (o entriesByOffset) Len() int { - return len(o) -} - -func (o entriesByOffset) Less(i int, j int) bool { - return o[i].Offset < o[j].Offset -} - -func (o entriesByOffset) Swap(i int, j int) { - o[i], o[j] = o[j], o[i] -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/idxfile/writer.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/idxfile/writer.go deleted file mode 100644 index daa16050..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/idxfile/writer.go +++ /dev/null @@ -1,186 +0,0 @@ -package idxfile - -import ( - "bytes" - "fmt" - "math" - "sort" - "sync" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/utils/binary" -) - -// objects implements sort.Interface and uses hash as sorting key. -type objects []Entry - -// Writer implements a packfile Observer interface and is used to generate -// indexes. -type Writer struct { - m sync.Mutex - - count uint32 - checksum plumbing.Hash - objects objects - offset64 uint32 - finished bool - index *MemoryIndex - added map[plumbing.Hash]struct{} -} - -// Index returns a previously created MemoryIndex or creates a new one if -// needed. -func (w *Writer) Index() (*MemoryIndex, error) { - w.m.Lock() - defer w.m.Unlock() - - if w.index == nil { - return w.createIndex() - } - - return w.index, nil -} - -// Add appends new object data. -func (w *Writer) Add(h plumbing.Hash, pos uint64, crc uint32) { - w.m.Lock() - defer w.m.Unlock() - - if w.added == nil { - w.added = make(map[plumbing.Hash]struct{}) - } - - if _, ok := w.added[h]; !ok { - w.added[h] = struct{}{} - w.objects = append(w.objects, Entry{h, crc, pos}) - } - -} - -func (w *Writer) Finished() bool { - return w.finished -} - -// OnHeader implements packfile.Observer interface. -func (w *Writer) OnHeader(count uint32) error { - w.count = count - w.objects = make(objects, 0, count) - return nil -} - -// OnInflatedObjectHeader implements packfile.Observer interface. -func (w *Writer) OnInflatedObjectHeader(t plumbing.ObjectType, objSize int64, pos int64) error { - return nil -} - -// OnInflatedObjectContent implements packfile.Observer interface. -func (w *Writer) OnInflatedObjectContent(h plumbing.Hash, pos int64, crc uint32, _ []byte) error { - w.Add(h, uint64(pos), crc) - return nil -} - -// OnFooter implements packfile.Observer interface. -func (w *Writer) OnFooter(h plumbing.Hash) error { - w.checksum = h - w.finished = true - _, err := w.createIndex() - if err != nil { - return err - } - - return nil -} - -// creatIndex returns a filled MemoryIndex with the information filled by -// the observer callbacks. -func (w *Writer) createIndex() (*MemoryIndex, error) { - if !w.finished { - return nil, fmt.Errorf("the index still hasn't finished building") - } - - idx := new(MemoryIndex) - w.index = idx - - sort.Sort(w.objects) - - // unmap all fans by default - for i := range idx.FanoutMapping { - idx.FanoutMapping[i] = noMapping - } - - buf := new(bytes.Buffer) - - last := -1 - bucket := -1 - for i, o := range w.objects { - fan := o.Hash[0] - - // fill the gaps between fans - for j := last + 1; j < int(fan); j++ { - idx.Fanout[j] = uint32(i) - } - - // update the number of objects for this position - idx.Fanout[fan] = uint32(i + 1) - - // we move from one bucket to another, update counters and allocate - // memory - if last != int(fan) { - bucket++ - idx.FanoutMapping[fan] = bucket - last = int(fan) - - idx.Names = append(idx.Names, make([]byte, 0)) - idx.Offset32 = append(idx.Offset32, make([]byte, 0)) - idx.CRC32 = append(idx.CRC32, make([]byte, 0)) - } - - idx.Names[bucket] = append(idx.Names[bucket], o.Hash[:]...) - - offset := o.Offset - if offset > math.MaxInt32 { - offset = w.addOffset64(offset) - } - - buf.Truncate(0) - binary.WriteUint32(buf, uint32(offset)) - idx.Offset32[bucket] = append(idx.Offset32[bucket], buf.Bytes()...) - - buf.Truncate(0) - binary.WriteUint32(buf, o.CRC32) - idx.CRC32[bucket] = append(idx.CRC32[bucket], buf.Bytes()...) - } - - for j := last + 1; j < 256; j++ { - idx.Fanout[j] = uint32(len(w.objects)) - } - - idx.Version = VersionSupported - idx.PackfileChecksum = w.checksum - - return idx, nil -} - -func (w *Writer) addOffset64(pos uint64) uint64 { - buf := new(bytes.Buffer) - binary.WriteUint64(buf, pos) - w.index.Offset64 = append(w.index.Offset64, buf.Bytes()...) - - index := uint64(w.offset64 | (1 << 31)) - w.offset64++ - - return index -} - -func (o objects) Len() int { - return len(o) -} - -func (o objects) Less(i int, j int) bool { - cmp := bytes.Compare(o[i].Hash[:], o[j].Hash[:]) - return cmp < 0 -} - -func (o objects) Swap(i int, j int) { - o[i], o[j] = o[j], o[i] -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/index/decoder.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/index/decoder.go deleted file mode 100644 index 036b6365..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/index/decoder.go +++ /dev/null @@ -1,479 +0,0 @@ -package index - -import ( - "bufio" - "bytes" - "crypto/sha1" - "errors" - "hash" - "io" - "io/ioutil" - "strconv" - "time" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/utils/binary" -) - -var ( - // DecodeVersionSupported is the range of supported index versions - DecodeVersionSupported = struct{ Min, Max uint32 }{Min: 2, Max: 4} - - // ErrMalformedSignature is returned by Decode when the index header file is - // malformed - ErrMalformedSignature = errors.New("malformed index signature file") - // ErrInvalidChecksum is returned by Decode if the SHA1 hash mismatch with - // the read content - ErrInvalidChecksum = errors.New("invalid checksum") - - errUnknownExtension = errors.New("unknown extension") -) - -const ( - entryHeaderLength = 62 - entryExtended = 0x4000 - entryValid = 0x8000 - nameMask = 0xfff - intentToAddMask = 1 << 13 - skipWorkTreeMask = 1 << 14 -) - -// A Decoder reads and decodes index files from an input stream. -type Decoder struct { - r io.Reader - hash hash.Hash - lastEntry *Entry - - extReader *bufio.Reader -} - -// NewDecoder returns a new decoder that reads from r. -func NewDecoder(r io.Reader) *Decoder { - h := sha1.New() - return &Decoder{ - r: io.TeeReader(r, h), - hash: h, - extReader: bufio.NewReader(nil), - } -} - -// Decode reads the whole index object from its input and stores it in the -// value pointed to by idx. -func (d *Decoder) Decode(idx *Index) error { - var err error - idx.Version, err = validateHeader(d.r) - if err != nil { - return err - } - - entryCount, err := binary.ReadUint32(d.r) - if err != nil { - return err - } - - if err := d.readEntries(idx, int(entryCount)); err != nil { - return err - } - - return d.readExtensions(idx) -} - -func (d *Decoder) readEntries(idx *Index, count int) error { - for i := 0; i < count; i++ { - e, err := d.readEntry(idx) - if err != nil { - return err - } - - d.lastEntry = e - idx.Entries = append(idx.Entries, e) - } - - return nil -} - -func (d *Decoder) readEntry(idx *Index) (*Entry, error) { - e := &Entry{} - - var msec, mnsec, sec, nsec uint32 - var flags uint16 - - flow := []interface{}{ - &sec, &nsec, - &msec, &mnsec, - &e.Dev, - &e.Inode, - &e.Mode, - &e.UID, - &e.GID, - &e.Size, - &e.Hash, - &flags, - } - - if err := binary.Read(d.r, flow...); err != nil { - return nil, err - } - - read := entryHeaderLength - - if sec != 0 || nsec != 0 { - e.CreatedAt = time.Unix(int64(sec), int64(nsec)) - } - - if msec != 0 || mnsec != 0 { - e.ModifiedAt = time.Unix(int64(msec), int64(mnsec)) - } - - e.Stage = Stage(flags>>12) & 0x3 - - if flags&entryExtended != 0 { - extended, err := binary.ReadUint16(d.r) - if err != nil { - return nil, err - } - - read += 2 - e.IntentToAdd = extended&intentToAddMask != 0 - e.SkipWorktree = extended&skipWorkTreeMask != 0 - } - - if err := d.readEntryName(idx, e, flags); err != nil { - return nil, err - } - - return e, d.padEntry(idx, e, read) -} - -func (d *Decoder) readEntryName(idx *Index, e *Entry, flags uint16) error { - var name string - var err error - - switch idx.Version { - case 2, 3: - len := flags & nameMask - name, err = d.doReadEntryName(len) - case 4: - name, err = d.doReadEntryNameV4() - default: - return ErrUnsupportedVersion - } - - if err != nil { - return err - } - - e.Name = name - return nil -} - -func (d *Decoder) doReadEntryNameV4() (string, error) { - l, err := binary.ReadVariableWidthInt(d.r) - if err != nil { - return "", err - } - - var base string - if d.lastEntry != nil { - base = d.lastEntry.Name[:len(d.lastEntry.Name)-int(l)] - } - - name, err := binary.ReadUntil(d.r, '\x00') - if err != nil { - return "", err - } - - return base + string(name), nil -} - -func (d *Decoder) doReadEntryName(len uint16) (string, error) { - name := make([]byte, len) - _, err := io.ReadFull(d.r, name) - - return string(name), err -} - -// Index entries are padded out to the next 8 byte alignment -// for historical reasons related to how C Git read the files. -func (d *Decoder) padEntry(idx *Index, e *Entry, read int) error { - if idx.Version == 4 { - return nil - } - - entrySize := read + len(e.Name) - padLen := 8 - entrySize%8 - _, err := io.CopyN(ioutil.Discard, d.r, int64(padLen)) - return err -} - -func (d *Decoder) readExtensions(idx *Index) error { - // TODO: support 'Split index' and 'Untracked cache' extensions, take in - // count that they are not supported by jgit or libgit - - var expected []byte - var err error - - var header [4]byte - for { - expected = d.hash.Sum(nil) - - var n int - if n, err = io.ReadFull(d.r, header[:]); err != nil { - if n == 0 { - err = io.EOF - } - - break - } - - err = d.readExtension(idx, header[:]) - if err != nil { - break - } - } - - if err != errUnknownExtension { - return err - } - - return d.readChecksum(expected, header) -} - -func (d *Decoder) readExtension(idx *Index, header []byte) error { - switch { - case bytes.Equal(header, treeExtSignature): - r, err := d.getExtensionReader() - if err != nil { - return err - } - - idx.Cache = &Tree{} - d := &treeExtensionDecoder{r} - if err := d.Decode(idx.Cache); err != nil { - return err - } - case bytes.Equal(header, resolveUndoExtSignature): - r, err := d.getExtensionReader() - if err != nil { - return err - } - - idx.ResolveUndo = &ResolveUndo{} - d := &resolveUndoDecoder{r} - if err := d.Decode(idx.ResolveUndo); err != nil { - return err - } - case bytes.Equal(header, endOfIndexEntryExtSignature): - r, err := d.getExtensionReader() - if err != nil { - return err - } - - idx.EndOfIndexEntry = &EndOfIndexEntry{} - d := &endOfIndexEntryDecoder{r} - if err := d.Decode(idx.EndOfIndexEntry); err != nil { - return err - } - default: - return errUnknownExtension - } - - return nil -} - -func (d *Decoder) getExtensionReader() (*bufio.Reader, error) { - len, err := binary.ReadUint32(d.r) - if err != nil { - return nil, err - } - - d.extReader.Reset(&io.LimitedReader{R: d.r, N: int64(len)}) - return d.extReader, nil -} - -func (d *Decoder) readChecksum(expected []byte, alreadyRead [4]byte) error { - var h plumbing.Hash - copy(h[:4], alreadyRead[:]) - - if _, err := io.ReadFull(d.r, h[4:]); err != nil { - return err - } - - if !bytes.Equal(h[:], expected) { - return ErrInvalidChecksum - } - - return nil -} - -func validateHeader(r io.Reader) (version uint32, err error) { - var s = make([]byte, 4) - if _, err := io.ReadFull(r, s); err != nil { - return 0, err - } - - if !bytes.Equal(s, indexSignature) { - return 0, ErrMalformedSignature - } - - version, err = binary.ReadUint32(r) - if err != nil { - return 0, err - } - - if version < DecodeVersionSupported.Min || version > DecodeVersionSupported.Max { - return 0, ErrUnsupportedVersion - } - - return -} - -type treeExtensionDecoder struct { - r *bufio.Reader -} - -func (d *treeExtensionDecoder) Decode(t *Tree) error { - for { - e, err := d.readEntry() - if err != nil { - if err == io.EOF { - return nil - } - - return err - } - - if e == nil { - continue - } - - t.Entries = append(t.Entries, *e) - } -} - -func (d *treeExtensionDecoder) readEntry() (*TreeEntry, error) { - e := &TreeEntry{} - - path, err := binary.ReadUntil(d.r, '\x00') - if err != nil { - return nil, err - } - - e.Path = string(path) - - count, err := binary.ReadUntil(d.r, ' ') - if err != nil { - return nil, err - } - - i, err := strconv.Atoi(string(count)) - if err != nil { - return nil, err - } - - // An entry can be in an invalidated state and is represented by having a - // negative number in the entry_count field. - if i == -1 { - return nil, nil - } - - e.Entries = i - trees, err := binary.ReadUntil(d.r, '\n') - if err != nil { - return nil, err - } - - i, err = strconv.Atoi(string(trees)) - if err != nil { - return nil, err - } - - e.Trees = i - _, err = io.ReadFull(d.r, e.Hash[:]) - if err != nil { - return nil, err - } - return e, nil -} - -type resolveUndoDecoder struct { - r *bufio.Reader -} - -func (d *resolveUndoDecoder) Decode(ru *ResolveUndo) error { - for { - e, err := d.readEntry() - if err != nil { - if err == io.EOF { - return nil - } - - return err - } - - ru.Entries = append(ru.Entries, *e) - } -} - -func (d *resolveUndoDecoder) readEntry() (*ResolveUndoEntry, error) { - e := &ResolveUndoEntry{ - Stages: make(map[Stage]plumbing.Hash), - } - - path, err := binary.ReadUntil(d.r, '\x00') - if err != nil { - return nil, err - } - - e.Path = string(path) - - for i := 0; i < 3; i++ { - if err := d.readStage(e, Stage(i+1)); err != nil { - return nil, err - } - } - - for s := range e.Stages { - var hash plumbing.Hash - if _, err := io.ReadFull(d.r, hash[:]); err != nil { - return nil, err - } - - e.Stages[s] = hash - } - - return e, nil -} - -func (d *resolveUndoDecoder) readStage(e *ResolveUndoEntry, s Stage) error { - ascii, err := binary.ReadUntil(d.r, '\x00') - if err != nil { - return err - } - - stage, err := strconv.ParseInt(string(ascii), 8, 64) - if err != nil { - return err - } - - if stage != 0 { - e.Stages[s] = plumbing.ZeroHash - } - - return nil -} - -type endOfIndexEntryDecoder struct { - r *bufio.Reader -} - -func (d *endOfIndexEntryDecoder) Decode(e *EndOfIndexEntry) error { - var err error - e.Offset, err = binary.ReadUint32(d.r) - if err != nil { - return err - } - - _, err = io.ReadFull(d.r, e.Hash[:]) - return err -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/index/doc.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/index/doc.go deleted file mode 100644 index 39ae6ad5..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/index/doc.go +++ /dev/null @@ -1,360 +0,0 @@ -// Package index implements encoding and decoding of index format files. -// -// Git index format -// ================ -// -// == The Git index file has the following format -// -// All binary numbers are in network byte order. Version 2 is described -// here unless stated otherwise. -// -// - A 12-byte header consisting of -// -// 4-byte signature: -// The signature is { 'D', 'I', 'R', 'C' } (stands for "dircache") -// -// 4-byte version number: -// The current supported versions are 2, 3 and 4. -// -// 32-bit number of index entries. -// -// - A number of sorted index entries (see below). -// -// - Extensions -// -// Extensions are identified by signature. Optional extensions can -// be ignored if Git does not understand them. -// -// Git currently supports cached tree and resolve undo extensions. -// -// 4-byte extension signature. If the first byte is 'A'..'Z' the -// extension is optional and can be ignored. -// -// 32-bit size of the extension -// -// Extension data -// -// - 160-bit SHA-1 over the content of the index file before this -// checksum. -// -// == Index entry -// -// Index entries are sorted in ascending order on the name field, -// interpreted as a string of unsigned bytes (i.e. memcmp() order, no -// localization, no special casing of directory separator '/'). Entries -// with the same name are sorted by their stage field. -// -// 32-bit ctime seconds, the last time a file's metadata changed -// this is stat(2) data -// -// 32-bit ctime nanosecond fractions -// this is stat(2) data -// -// 32-bit mtime seconds, the last time a file's data changed -// this is stat(2) data -// -// 32-bit mtime nanosecond fractions -// this is stat(2) data -// -// 32-bit dev -// this is stat(2) data -// -// 32-bit ino -// this is stat(2) data -// -// 32-bit mode, split into (high to low bits) -// -// 4-bit object type -// valid values in binary are 1000 (regular file), 1010 (symbolic link) -// and 1110 (gitlink) -// -// 3-bit unused -// -// 9-bit unix permission. Only 0755 and 0644 are valid for regular files. -// Symbolic links and gitlinks have value 0 in this field. -// -// 32-bit uid -// this is stat(2) data -// -// 32-bit gid -// this is stat(2) data -// -// 32-bit file size -// This is the on-disk size from stat(2), truncated to 32-bit. -// -// 160-bit SHA-1 for the represented object -// -// A 16-bit 'flags' field split into (high to low bits) -// -// 1-bit assume-valid flag -// -// 1-bit extended flag (must be zero in version 2) -// -// 2-bit stage (during merge) -// -// 12-bit name length if the length is less than 0xFFF; otherwise 0xFFF -// is stored in this field. -// -// (Version 3 or later) A 16-bit field, only applicable if the -// "extended flag" above is 1, split into (high to low bits). -// -// 1-bit reserved for future -// -// 1-bit skip-worktree flag (used by sparse checkout) -// -// 1-bit intent-to-add flag (used by "git add -N") -// -// 13-bit unused, must be zero -// -// Entry path name (variable length) relative to top level directory -// (without leading slash). '/' is used as path separator. The special -// path components ".", ".." and ".git" (without quotes) are disallowed. -// Trailing slash is also disallowed. -// -// The exact encoding is undefined, but the '.' and '/' characters -// are encoded in 7-bit ASCII and the encoding cannot contain a NUL -// byte (iow, this is a UNIX pathname). -// -// (Version 4) In version 4, the entry path name is prefix-compressed -// relative to the path name for the previous entry (the very first -// entry is encoded as if the path name for the previous entry is an -// empty string). At the beginning of an entry, an integer N in the -// variable width encoding (the same encoding as the offset is encoded -// for OFS_DELTA pack entries; see pack-format.txt) is stored, followed -// by a NUL-terminated string S. Removing N bytes from the end of the -// path name for the previous entry, and replacing it with the string S -// yields the path name for this entry. -// -// 1-8 nul bytes as necessary to pad the entry to a multiple of eight bytes -// while keeping the name NUL-terminated. -// -// (Version 4) In version 4, the padding after the pathname does not -// exist. -// -// Interpretation of index entries in split index mode is completely -// different. See below for details. -// -// == Extensions -// -// === Cached tree -// -// Cached tree extension contains pre-computed hashes for trees that can -// be derived from the index. It helps speed up tree object generation -// from index for a new commit. -// -// When a path is updated in index, the path must be invalidated and -// removed from tree cache. -// -// The signature for this extension is { 'T', 'R', 'E', 'E' }. -// -// A series of entries fill the entire extension; each of which -// consists of: -// -// - NUL-terminated path component (relative to its parent directory); -// -// - ASCII decimal number of entries in the index that is covered by the -// tree this entry represents (entry_count); -// -// - A space (ASCII 32); -// -// - ASCII decimal number that represents the number of subtrees this -// tree has; -// -// - A newline (ASCII 10); and -// -// - 160-bit object name for the object that would result from writing -// this span of index as a tree. -// -// An entry can be in an invalidated state and is represented by having -// a negative number in the entry_count field. In this case, there is no -// object name and the next entry starts immediately after the newline. -// When writing an invalid entry, -1 should always be used as entry_count. -// -// The entries are written out in the top-down, depth-first order. The -// first entry represents the root level of the repository, followed by the -// first subtree--let's call this A--of the root level (with its name -// relative to the root level), followed by the first subtree of A (with -// its name relative to A), ... -// -// === Resolve undo -// -// A conflict is represented in the index as a set of higher stage entries. -// When a conflict is resolved (e.g. with "git add path"), these higher -// stage entries will be removed and a stage-0 entry with proper resolution -// is added. -// -// When these higher stage entries are removed, they are saved in the -// resolve undo extension, so that conflicts can be recreated (e.g. with -// "git checkout -m"), in case users want to redo a conflict resolution -// from scratch. -// -// The signature for this extension is { 'R', 'E', 'U', 'C' }. -// -// A series of entries fill the entire extension; each of which -// consists of: -// -// - NUL-terminated pathname the entry describes (relative to the root of -// the repository, i.e. full pathname); -// -// - Three NUL-terminated ASCII octal numbers, entry mode of entries in -// stage 1 to 3 (a missing stage is represented by "0" in this field); -// and -// -// - At most three 160-bit object names of the entry in stages from 1 to 3 -// (nothing is written for a missing stage). -// -// === Split index -// -// In split index mode, the majority of index entries could be stored -// in a separate file. This extension records the changes to be made on -// top of that to produce the final index. -// -// The signature for this extension is { 'l', 'i', 'n', 'k' }. -// -// The extension consists of: -// -// - 160-bit SHA-1 of the shared index file. The shared index file path -// is $GIT_DIR/sharedindex.. If all 160 bits are zero, the -// index does not require a shared index file. -// -// - An ewah-encoded delete bitmap, each bit represents an entry in the -// shared index. If a bit is set, its corresponding entry in the -// shared index will be removed from the final index. Note, because -// a delete operation changes index entry positions, but we do need -// original positions in replace phase, it's best to just mark -// entries for removal, then do a mass deletion after replacement. -// -// - An ewah-encoded replace bitmap, each bit represents an entry in -// the shared index. If a bit is set, its corresponding entry in the -// shared index will be replaced with an entry in this index -// file. All replaced entries are stored in sorted order in this -// index. The first "1" bit in the replace bitmap corresponds to the -// first index entry, the second "1" bit to the second entry and so -// on. Replaced entries may have empty path names to save space. -// -// The remaining index entries after replaced ones will be added to the -// final index. These added entries are also sorted by entry name then -// stage. -// -// == Untracked cache -// -// Untracked cache saves the untracked file list and necessary data to -// verify the cache. The signature for this extension is { 'U', 'N', -// 'T', 'R' }. -// -// The extension starts with -// -// - A sequence of NUL-terminated strings, preceded by the size of the -// sequence in variable width encoding. Each string describes the -// environment where the cache can be used. -// -// - Stat data of $GIT_DIR/info/exclude. See "Index entry" section from -// ctime field until "file size". -// -// - Stat data of plumbing.excludesfile -// -// - 32-bit dir_flags (see struct dir_struct) -// -// - 160-bit SHA-1 of $GIT_DIR/info/exclude. Null SHA-1 means the file -// does not exist. -// -// - 160-bit SHA-1 of plumbing.excludesfile. Null SHA-1 means the file does -// not exist. -// -// - NUL-terminated string of per-dir exclude file name. This usually -// is ".gitignore". -// -// - The number of following directory blocks, variable width -// encoding. If this number is zero, the extension ends here with a -// following NUL. -// -// - A number of directory blocks in depth-first-search order, each -// consists of -// -// - The number of untracked entries, variable width encoding. -// -// - The number of sub-directory blocks, variable width encoding. -// -// - The directory name terminated by NUL. -// -// - A number of untracked file/dir names terminated by NUL. -// -// The remaining data of each directory block is grouped by type: -// -// - An ewah bitmap, the n-th bit marks whether the n-th directory has -// valid untracked cache entries. -// -// - An ewah bitmap, the n-th bit records "check-only" bit of -// read_directory_recursive() for the n-th directory. -// -// - An ewah bitmap, the n-th bit indicates whether SHA-1 and stat data -// is valid for the n-th directory and exists in the next data. -// -// - An array of stat data. The n-th data corresponds with the n-th -// "one" bit in the previous ewah bitmap. -// -// - An array of SHA-1. The n-th SHA-1 corresponds with the n-th "one" bit -// in the previous ewah bitmap. -// -// - One NUL. -// -// == File System Monitor cache -// -// The file system monitor cache tracks files for which the core.fsmonitor -// hook has told us about changes. The signature for this extension is -// { 'F', 'S', 'M', 'N' }. -// -// The extension starts with -// -// - 32-bit version number: the current supported version is 1. -// -// - 64-bit time: the extension data reflects all changes through the given -// time which is stored as the nanoseconds elapsed since midnight, -// January 1, 1970. -// -// - 32-bit bitmap size: the size of the CE_FSMONITOR_VALID bitmap. -// -// - An ewah bitmap, the n-th bit indicates whether the n-th index entry -// is not CE_FSMONITOR_VALID. -// -// == End of Index Entry -// -// The End of Index Entry (EOIE) is used to locate the end of the variable -// length index entries and the beginning of the extensions. Code can take -// advantage of this to quickly locate the index extensions without having -// to parse through all of the index entries. -// -// Because it must be able to be loaded before the variable length cache -// entries and other index extensions, this extension must be written last. -// The signature for this extension is { 'E', 'O', 'I', 'E' }. -// -// The extension consists of: -// -// - 32-bit offset to the end of the index entries -// -// - 160-bit SHA-1 over the extension types and their sizes (but not -// their contents). E.g. if we have "TREE" extension that is N-bytes -// long, "REUC" extension that is M-bytes long, followed by "EOIE", -// then the hash would be: -// -// SHA-1("TREE" + + -// "REUC" + ) -// -// == Index Entry Offset Table -// -// The Index Entry Offset Table (IEOT) is used to help address the CPU -// cost of loading the index by enabling multi-threading the process of -// converting cache entries from the on-disk format to the in-memory format. -// The signature for this extension is { 'I', 'E', 'O', 'T' }. -// -// The extension consists of: -// -// - 32-bit version (currently 1) -// -// - A number of index offset entries each consisting of: -// -// - 32-bit offset from the beginning of the file to the first cache entry -// in this block of entries. -// -// - 32-bit count of cache entries in this blockpackage index -package index diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/index/encoder.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/index/encoder.go deleted file mode 100644 index 00d4e7a3..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/index/encoder.go +++ /dev/null @@ -1,150 +0,0 @@ -package index - -import ( - "bytes" - "crypto/sha1" - "errors" - "hash" - "io" - "sort" - "time" - - "github.com/go-git/go-git/v5/utils/binary" -) - -var ( - // EncodeVersionSupported is the range of supported index versions - EncodeVersionSupported uint32 = 2 - - // ErrInvalidTimestamp is returned by Encode if a Index with a Entry with - // negative timestamp values - ErrInvalidTimestamp = errors.New("negative timestamps are not allowed") -) - -// An Encoder writes an Index to an output stream. -type Encoder struct { - w io.Writer - hash hash.Hash -} - -// NewEncoder returns a new encoder that writes to w. -func NewEncoder(w io.Writer) *Encoder { - h := sha1.New() - mw := io.MultiWriter(w, h) - return &Encoder{mw, h} -} - -// Encode writes the Index to the stream of the encoder. -func (e *Encoder) Encode(idx *Index) error { - // TODO: support versions v3 and v4 - // TODO: support extensions - if idx.Version != EncodeVersionSupported { - return ErrUnsupportedVersion - } - - if err := e.encodeHeader(idx); err != nil { - return err - } - - if err := e.encodeEntries(idx); err != nil { - return err - } - - return e.encodeFooter() -} - -func (e *Encoder) encodeHeader(idx *Index) error { - return binary.Write(e.w, - indexSignature, - idx.Version, - uint32(len(idx.Entries)), - ) -} - -func (e *Encoder) encodeEntries(idx *Index) error { - sort.Sort(byName(idx.Entries)) - - for _, entry := range idx.Entries { - if err := e.encodeEntry(entry); err != nil { - return err - } - - wrote := entryHeaderLength + len(entry.Name) - if err := e.padEntry(wrote); err != nil { - return err - } - } - - return nil -} - -func (e *Encoder) encodeEntry(entry *Entry) error { - if entry.IntentToAdd || entry.SkipWorktree { - return ErrUnsupportedVersion - } - - sec, nsec, err := e.timeToUint32(&entry.CreatedAt) - if err != nil { - return err - } - - msec, mnsec, err := e.timeToUint32(&entry.ModifiedAt) - if err != nil { - return err - } - - flags := uint16(entry.Stage&0x3) << 12 - if l := len(entry.Name); l < nameMask { - flags |= uint16(l) - } else { - flags |= nameMask - } - - flow := []interface{}{ - sec, nsec, - msec, mnsec, - entry.Dev, - entry.Inode, - entry.Mode, - entry.UID, - entry.GID, - entry.Size, - entry.Hash[:], - flags, - } - - if err := binary.Write(e.w, flow...); err != nil { - return err - } - - return binary.Write(e.w, []byte(entry.Name)) -} - -func (e *Encoder) timeToUint32(t *time.Time) (uint32, uint32, error) { - if t.IsZero() { - return 0, 0, nil - } - - if t.Unix() < 0 || t.UnixNano() < 0 { - return 0, 0, ErrInvalidTimestamp - } - - return uint32(t.Unix()), uint32(t.Nanosecond()), nil -} - -func (e *Encoder) padEntry(wrote int) error { - padLen := 8 - wrote%8 - - _, err := e.w.Write(bytes.Repeat([]byte{'\x00'}, padLen)) - return err -} - -func (e *Encoder) encodeFooter() error { - return binary.Write(e.w, e.hash.Sum(nil)) -} - -type byName []*Entry - -func (l byName) Len() int { return len(l) } -func (l byName) Swap(i, j int) { l[i], l[j] = l[j], l[i] } -func (l byName) Less(i, j int) bool { return l[i].Name < l[j].Name } diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/index/index.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/index/index.go deleted file mode 100644 index 649416a2..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/index/index.go +++ /dev/null @@ -1,213 +0,0 @@ -package index - -import ( - "bytes" - "errors" - "fmt" - "path/filepath" - "time" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/plumbing/filemode" -) - -var ( - // ErrUnsupportedVersion is returned by Decode when the index file version - // is not supported. - ErrUnsupportedVersion = errors.New("unsupported version") - // ErrEntryNotFound is returned by Index.Entry, if an entry is not found. - ErrEntryNotFound = errors.New("entry not found") - - indexSignature = []byte{'D', 'I', 'R', 'C'} - treeExtSignature = []byte{'T', 'R', 'E', 'E'} - resolveUndoExtSignature = []byte{'R', 'E', 'U', 'C'} - endOfIndexEntryExtSignature = []byte{'E', 'O', 'I', 'E'} -) - -// Stage during merge -type Stage int - -const ( - // Merged is the default stage, fully merged - Merged Stage = 1 - // AncestorMode is the base revision - AncestorMode Stage = 1 - // OurMode is the first tree revision, ours - OurMode Stage = 2 - // TheirMode is the second tree revision, theirs - TheirMode Stage = 3 -) - -// Index contains the information about which objects are currently checked out -// in the worktree, having information about the working files. Changes in -// worktree are detected using this Index. The Index is also used during merges -type Index struct { - // Version is index version - Version uint32 - // Entries collection of entries represented by this Index. The order of - // this collection is not guaranteed - Entries []*Entry - // Cache represents the 'Cached tree' extension - Cache *Tree - // ResolveUndo represents the 'Resolve undo' extension - ResolveUndo *ResolveUndo - // EndOfIndexEntry represents the 'End of Index Entry' extension - EndOfIndexEntry *EndOfIndexEntry -} - -// Add creates a new Entry and returns it. The caller should first check that -// another entry with the same path does not exist. -func (i *Index) Add(path string) *Entry { - e := &Entry{ - Name: filepath.ToSlash(path), - } - - i.Entries = append(i.Entries, e) - return e -} - -// Entry returns the entry that match the given path, if any. -func (i *Index) Entry(path string) (*Entry, error) { - path = filepath.ToSlash(path) - for _, e := range i.Entries { - if e.Name == path { - return e, nil - } - } - - return nil, ErrEntryNotFound -} - -// Remove remove the entry that match the give path and returns deleted entry. -func (i *Index) Remove(path string) (*Entry, error) { - path = filepath.ToSlash(path) - for index, e := range i.Entries { - if e.Name == path { - i.Entries = append(i.Entries[:index], i.Entries[index+1:]...) - return e, nil - } - } - - return nil, ErrEntryNotFound -} - -// Glob returns the all entries matching pattern or nil if there is no matching -// entry. The syntax of patterns is the same as in filepath.Glob. -func (i *Index) Glob(pattern string) (matches []*Entry, err error) { - pattern = filepath.ToSlash(pattern) - for _, e := range i.Entries { - m, err := match(pattern, e.Name) - if err != nil { - return nil, err - } - - if m { - matches = append(matches, e) - } - } - - return -} - -// String is equivalent to `git ls-files --stage --debug` -func (i *Index) String() string { - buf := bytes.NewBuffer(nil) - for _, e := range i.Entries { - buf.WriteString(e.String()) - } - - return buf.String() -} - -// Entry represents a single file (or stage of a file) in the cache. An entry -// represents exactly one stage of a file. If a file path is unmerged then -// multiple Entry instances may appear for the same path name. -type Entry struct { - // Hash is the SHA1 of the represented file - Hash plumbing.Hash - // Name is the Entry path name relative to top level directory - Name string - // CreatedAt time when the tracked path was created - CreatedAt time.Time - // ModifiedAt time when the tracked path was changed - ModifiedAt time.Time - // Dev and Inode of the tracked path - Dev, Inode uint32 - // Mode of the path - Mode filemode.FileMode - // UID and GID, userid and group id of the owner - UID, GID uint32 - // Size is the length in bytes for regular files - Size uint32 - // Stage on a merge is defines what stage is representing this entry - // https://git-scm.com/book/en/v2/Git-Tools-Advanced-Merging - Stage Stage - // SkipWorktree used in sparse checkouts - // https://git-scm.com/docs/git-read-tree#_sparse_checkout - SkipWorktree bool - // IntentToAdd record only the fact that the path will be added later - // https://git-scm.com/docs/git-add ("git add -N") - IntentToAdd bool -} - -func (e Entry) String() string { - buf := bytes.NewBuffer(nil) - - fmt.Fprintf(buf, "%06o %s %d\t%s\n", e.Mode, e.Hash, e.Stage, e.Name) - fmt.Fprintf(buf, " ctime: %d:%d\n", e.CreatedAt.Unix(), e.CreatedAt.Nanosecond()) - fmt.Fprintf(buf, " mtime: %d:%d\n", e.ModifiedAt.Unix(), e.ModifiedAt.Nanosecond()) - fmt.Fprintf(buf, " dev: %d\tino: %d\n", e.Dev, e.Inode) - fmt.Fprintf(buf, " uid: %d\tgid: %d\n", e.UID, e.GID) - fmt.Fprintf(buf, " size: %d\tflags: %x\n", e.Size, 0) - - return buf.String() -} - -// Tree contains pre-computed hashes for trees that can be derived from the -// index. It helps speed up tree object generation from index for a new commit. -type Tree struct { - Entries []TreeEntry -} - -// TreeEntry entry of a cached Tree -type TreeEntry struct { - // Path component (relative to its parent directory) - Path string - // Entries is the number of entries in the index that is covered by the tree - // this entry represents. - Entries int - // Trees is the number that represents the number of subtrees this tree has - Trees int - // Hash object name for the object that would result from writing this span - // of index as a tree. - Hash plumbing.Hash -} - -// ResolveUndo is used when a conflict is resolved (e.g. with "git add path"), -// these higher stage entries are removed and a stage-0 entry with proper -// resolution is added. When these higher stage entries are removed, they are -// saved in the resolve undo extension. -type ResolveUndo struct { - Entries []ResolveUndoEntry -} - -// ResolveUndoEntry contains the information about a conflict when is resolved -type ResolveUndoEntry struct { - Path string - Stages map[Stage]plumbing.Hash -} - -// EndOfIndexEntry is the End of Index Entry (EOIE) is used to locate the end of -// the variable length index entries and the beginning of the extensions. Code -// can take advantage of this to quickly locate the index extensions without -// having to parse through all of the index entries. -// -// Because it must be able to be loaded before the variable length cache -// entries and other index extensions, this extension must be written last. -type EndOfIndexEntry struct { - // Offset to the end of the index entries - Offset uint32 - // Hash is a SHA-1 over the extension types and their sizes (but not - // their contents). - Hash plumbing.Hash -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/index/match.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/index/match.go deleted file mode 100644 index 2891d7d3..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/index/match.go +++ /dev/null @@ -1,186 +0,0 @@ -package index - -import ( - "path/filepath" - "runtime" - "unicode/utf8" -) - -// match is filepath.Match with support to match fullpath and not only filenames -// code from: -// https://github.com/golang/go/blob/39852bf4cce6927e01d0136c7843f65a801738cb/src/path/filepath/match.go#L44-L224 -func match(pattern, name string) (matched bool, err error) { -Pattern: - for len(pattern) > 0 { - var star bool - var chunk string - star, chunk, pattern = scanChunk(pattern) - - // Look for match at current position. - t, ok, err := matchChunk(chunk, name) - // if we're the last chunk, make sure we've exhausted the name - // otherwise we'll give a false result even if we could still match - // using the star - if ok && (len(t) == 0 || len(pattern) > 0) { - name = t - continue - } - if err != nil { - return false, err - } - if star { - // Look for match skipping i+1 bytes. - // Cannot skip /. - for i := 0; i < len(name); i++ { - t, ok, err := matchChunk(chunk, name[i+1:]) - if ok { - // if we're the last chunk, make sure we exhausted the name - if len(pattern) == 0 && len(t) > 0 { - continue - } - name = t - continue Pattern - } - if err != nil { - return false, err - } - } - } - return false, nil - } - return len(name) == 0, nil -} - -// scanChunk gets the next segment of pattern, which is a non-star string -// possibly preceded by a star. -func scanChunk(pattern string) (star bool, chunk, rest string) { - for len(pattern) > 0 && pattern[0] == '*' { - pattern = pattern[1:] - star = true - } - inrange := false - var i int -Scan: - for i = 0; i < len(pattern); i++ { - switch pattern[i] { - case '\\': - if runtime.GOOS != "windows" { - // error check handled in matchChunk: bad pattern. - if i+1 < len(pattern) { - i++ - } - } - case '[': - inrange = true - case ']': - inrange = false - case '*': - if !inrange { - break Scan - } - } - } - return star, pattern[0:i], pattern[i:] -} - -// matchChunk checks whether chunk matches the beginning of s. -// If so, it returns the remainder of s (after the match). -// Chunk is all single-character operators: literals, char classes, and ?. -func matchChunk(chunk, s string) (rest string, ok bool, err error) { - for len(chunk) > 0 { - if len(s) == 0 { - return - } - switch chunk[0] { - case '[': - // character class - r, n := utf8.DecodeRuneInString(s) - s = s[n:] - chunk = chunk[1:] - // We can't end right after '[', we're expecting at least - // a closing bracket and possibly a caret. - if len(chunk) == 0 { - err = filepath.ErrBadPattern - return - } - // possibly negated - negated := chunk[0] == '^' - if negated { - chunk = chunk[1:] - } - // parse all ranges - match := false - nrange := 0 - for { - if len(chunk) > 0 && chunk[0] == ']' && nrange > 0 { - chunk = chunk[1:] - break - } - var lo, hi rune - if lo, chunk, err = getEsc(chunk); err != nil { - return - } - hi = lo - if chunk[0] == '-' { - if hi, chunk, err = getEsc(chunk[1:]); err != nil { - return - } - } - if lo <= r && r <= hi { - match = true - } - nrange++ - } - if match == negated { - return - } - - case '?': - _, n := utf8.DecodeRuneInString(s) - s = s[n:] - chunk = chunk[1:] - - case '\\': - if runtime.GOOS != "windows" { - chunk = chunk[1:] - if len(chunk) == 0 { - err = filepath.ErrBadPattern - return - } - } - fallthrough - - default: - if chunk[0] != s[0] { - return - } - s = s[1:] - chunk = chunk[1:] - } - } - return s, true, nil -} - -// getEsc gets a possibly-escaped character from chunk, for a character class. -func getEsc(chunk string) (r rune, nchunk string, err error) { - if len(chunk) == 0 || chunk[0] == '-' || chunk[0] == ']' { - err = filepath.ErrBadPattern - return - } - if chunk[0] == '\\' && runtime.GOOS != "windows" { - chunk = chunk[1:] - if len(chunk) == 0 { - err = filepath.ErrBadPattern - return - } - } - r, n := utf8.DecodeRuneInString(chunk) - if r == utf8.RuneError && n == 1 { - err = filepath.ErrBadPattern - } - nchunk = chunk[n:] - if len(nchunk) == 0 { - err = filepath.ErrBadPattern - } - return -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/objfile/doc.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/objfile/doc.go deleted file mode 100644 index a7145160..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/objfile/doc.go +++ /dev/null @@ -1,2 +0,0 @@ -// Package objfile implements encoding and decoding of object files. -package objfile diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/objfile/reader.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/objfile/reader.go deleted file mode 100644 index b6b2ca06..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/objfile/reader.go +++ /dev/null @@ -1,114 +0,0 @@ -package objfile - -import ( - "compress/zlib" - "errors" - "io" - "strconv" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/plumbing/format/packfile" -) - -var ( - ErrClosed = errors.New("objfile: already closed") - ErrHeader = errors.New("objfile: invalid header") - ErrNegativeSize = errors.New("objfile: negative object size") -) - -// Reader reads and decodes compressed objfile data from a provided io.Reader. -// Reader implements io.ReadCloser. Close should be called when finished with -// the Reader. Close will not close the underlying io.Reader. -type Reader struct { - multi io.Reader - zlib io.ReadCloser - hasher plumbing.Hasher -} - -// NewReader returns a new Reader reading from r. -func NewReader(r io.Reader) (*Reader, error) { - zlib, err := zlib.NewReader(r) - if err != nil { - return nil, packfile.ErrZLib.AddDetails(err.Error()) - } - - return &Reader{ - zlib: zlib, - }, nil -} - -// Header reads the type and the size of object, and prepares the reader for read -func (r *Reader) Header() (t plumbing.ObjectType, size int64, err error) { - var raw []byte - raw, err = r.readUntil(' ') - if err != nil { - return - } - - t, err = plumbing.ParseObjectType(string(raw)) - if err != nil { - return - } - - raw, err = r.readUntil(0) - if err != nil { - return - } - - size, err = strconv.ParseInt(string(raw), 10, 64) - if err != nil { - err = ErrHeader - return - } - - defer r.prepareForRead(t, size) - return -} - -// readSlice reads one byte at a time from r until it encounters delim or an -// error. -func (r *Reader) readUntil(delim byte) ([]byte, error) { - var buf [1]byte - value := make([]byte, 0, 16) - for { - if n, err := r.zlib.Read(buf[:]); err != nil && (err != io.EOF || n == 0) { - if err == io.EOF { - return nil, ErrHeader - } - return nil, err - } - - if buf[0] == delim { - return value, nil - } - - value = append(value, buf[0]) - } -} - -func (r *Reader) prepareForRead(t plumbing.ObjectType, size int64) { - r.hasher = plumbing.NewHasher(t, size) - r.multi = io.TeeReader(r.zlib, r.hasher) -} - -// Read reads len(p) bytes into p from the object data stream. It returns -// the number of bytes read (0 <= n <= len(p)) and any error encountered. Even -// if Read returns n < len(p), it may use all of p as scratch space during the -// call. -// -// If Read encounters the end of the data stream it will return err == io.EOF, -// either in the current call if n > 0 or in a subsequent call. -func (r *Reader) Read(p []byte) (n int, err error) { - return r.multi.Read(p) -} - -// Hash returns the hash of the object data stream that has been read so far. -func (r *Reader) Hash() plumbing.Hash { - return r.hasher.Sum() -} - -// Close releases any resources consumed by the Reader. Calling Close does not -// close the wrapped io.Reader originally passed to NewReader. -func (r *Reader) Close() error { - return r.zlib.Close() -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/objfile/writer.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/objfile/writer.go deleted file mode 100644 index 2a96a437..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/objfile/writer.go +++ /dev/null @@ -1,109 +0,0 @@ -package objfile - -import ( - "compress/zlib" - "errors" - "io" - "strconv" - - "github.com/go-git/go-git/v5/plumbing" -) - -var ( - ErrOverflow = errors.New("objfile: declared data length exceeded (overflow)") -) - -// Writer writes and encodes data in compressed objfile format to a provided -// io.Writer. Close should be called when finished with the Writer. Close will -// not close the underlying io.Writer. -type Writer struct { - raw io.Writer - zlib io.WriteCloser - hasher plumbing.Hasher - multi io.Writer - - closed bool - pending int64 // number of unwritten bytes -} - -// NewWriter returns a new Writer writing to w. -// -// The returned Writer implements io.WriteCloser. Close should be called when -// finished with the Writer. Close will not close the underlying io.Writer. -func NewWriter(w io.Writer) *Writer { - return &Writer{ - raw: w, - zlib: zlib.NewWriter(w), - } -} - -// WriteHeader writes the type and the size and prepares to accept the object's -// contents. If an invalid t is provided, plumbing.ErrInvalidType is returned. If a -// negative size is provided, ErrNegativeSize is returned. -func (w *Writer) WriteHeader(t plumbing.ObjectType, size int64) error { - if !t.Valid() { - return plumbing.ErrInvalidType - } - if size < 0 { - return ErrNegativeSize - } - - b := t.Bytes() - b = append(b, ' ') - b = append(b, []byte(strconv.FormatInt(size, 10))...) - b = append(b, 0) - - defer w.prepareForWrite(t, size) - _, err := w.zlib.Write(b) - - return err -} - -func (w *Writer) prepareForWrite(t plumbing.ObjectType, size int64) { - w.pending = size - - w.hasher = plumbing.NewHasher(t, size) - w.multi = io.MultiWriter(w.zlib, w.hasher) -} - -// Write writes the object's contents. Write returns the error ErrOverflow if -// more than size bytes are written after WriteHeader. -func (w *Writer) Write(p []byte) (n int, err error) { - if w.closed { - return 0, ErrClosed - } - - overwrite := false - if int64(len(p)) > w.pending { - p = p[0:w.pending] - overwrite = true - } - - n, err = w.multi.Write(p) - w.pending -= int64(n) - if err == nil && overwrite { - err = ErrOverflow - return - } - - return -} - -// Hash returns the hash of the object data stream that has been written so far. -// It can be called before or after Close. -func (w *Writer) Hash() plumbing.Hash { - return w.hasher.Sum() // Not yet closed, return hash of data written so far -} - -// Close releases any resources consumed by the Writer. -// -// Calling Close does not close the wrapped io.Writer originally passed to -// NewWriter. -func (w *Writer) Close() error { - if err := w.zlib.Close(); err != nil { - return err - } - - w.closed = true - return nil -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/common.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/common.go deleted file mode 100644 index df423ad5..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/common.go +++ /dev/null @@ -1,78 +0,0 @@ -package packfile - -import ( - "bytes" - "compress/zlib" - "io" - "sync" - - "github.com/go-git/go-git/v5/plumbing/storer" - "github.com/go-git/go-git/v5/utils/ioutil" -) - -var signature = []byte{'P', 'A', 'C', 'K'} - -const ( - // VersionSupported is the packfile version supported by this package - VersionSupported uint32 = 2 - - firstLengthBits = uint8(4) // the first byte into object header has 4 bits to store the length - lengthBits = uint8(7) // subsequent bytes has 7 bits to store the length - maskFirstLength = 15 // 0000 1111 - maskContinue = 0x80 // 1000 0000 - maskLength = uint8(127) // 0111 1111 - maskType = uint8(112) // 0111 0000 -) - -// UpdateObjectStorage updates the storer with the objects in the given -// packfile. -func UpdateObjectStorage(s storer.Storer, packfile io.Reader) error { - if pw, ok := s.(storer.PackfileWriter); ok { - return WritePackfileToObjectStorage(pw, packfile) - } - - p, err := NewParserWithStorage(NewScanner(packfile), s) - if err != nil { - return err - } - - _, err = p.Parse() - return err -} - -// WritePackfileToObjectStorage writes all the packfile objects into the given -// object storage. -func WritePackfileToObjectStorage( - sw storer.PackfileWriter, - packfile io.Reader, -) (err error) { - w, err := sw.PackfileWriter() - if err != nil { - return err - } - - defer ioutil.CheckClose(w, &err) - - var n int64 - n, err = io.Copy(w, packfile) - if err == nil && n == 0 { - return ErrEmptyPackfile - } - - return err -} - -var bufPool = sync.Pool{ - New: func() interface{} { - return bytes.NewBuffer(nil) - }, -} - -var zlibInitBytes = []byte{0x78, 0x9c, 0x01, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x01} - -var zlibReaderPool = sync.Pool{ - New: func() interface{} { - r, _ := zlib.NewReader(bytes.NewReader(zlibInitBytes)) - return r - }, -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/delta_index.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/delta_index.go deleted file mode 100644 index 07a61120..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/delta_index.go +++ /dev/null @@ -1,297 +0,0 @@ -package packfile - -const blksz = 16 -const maxChainLength = 64 - -// deltaIndex is a modified version of JGit's DeltaIndex adapted to our current -// design. -type deltaIndex struct { - table []int - entries []int - mask int -} - -func (idx *deltaIndex) init(buf []byte) { - scanner := newDeltaIndexScanner(buf, len(buf)) - idx.mask = scanner.mask - idx.table = scanner.table - idx.entries = make([]int, countEntries(scanner)+1) - idx.copyEntries(scanner) -} - -// findMatch returns the offset of src where the block starting at tgtOffset -// is and the length of the match. A length of 0 means there was no match. A -// length of -1 means the src length is lower than the blksz and whatever -// other positive length is the length of the match in bytes. -func (idx *deltaIndex) findMatch(src, tgt []byte, tgtOffset int) (srcOffset, l int) { - if len(tgt) < tgtOffset+s { - return 0, len(tgt) - tgtOffset - } - - if len(src) < blksz { - return 0, -1 - } - - if len(tgt) >= tgtOffset+s && len(src) >= blksz { - h := hashBlock(tgt, tgtOffset) - tIdx := h & idx.mask - eIdx := idx.table[tIdx] - if eIdx != 0 { - srcOffset = idx.entries[eIdx] - } else { - return - } - - l = matchLength(src, tgt, tgtOffset, srcOffset) - } - - return -} - -func matchLength(src, tgt []byte, otgt, osrc int) (l int) { - lensrc := len(src) - lentgt := len(tgt) - for (osrc < lensrc && otgt < lentgt) && src[osrc] == tgt[otgt] { - l++ - osrc++ - otgt++ - } - return -} - -func countEntries(scan *deltaIndexScanner) (cnt int) { - // Figure out exactly how many entries we need. As we do the - // enumeration truncate any delta chains longer than what we - // are willing to scan during encode. This keeps the encode - // logic linear in the size of the input rather than quadratic. - for i := 0; i < len(scan.table); i++ { - h := scan.table[i] - if h == 0 { - continue - } - - size := 0 - for { - size++ - if size == maxChainLength { - scan.next[h] = 0 - break - } - h = scan.next[h] - - if h == 0 { - break - } - } - cnt += size - } - - return -} - -func (idx *deltaIndex) copyEntries(scanner *deltaIndexScanner) { - // Rebuild the entries list from the scanner, positioning all - // blocks in the same hash chain next to each other. We can - // then later discard the next list, along with the scanner. - // - next := 1 - for i := 0; i < len(idx.table); i++ { - h := idx.table[i] - if h == 0 { - continue - } - - idx.table[i] = next - for { - idx.entries[next] = scanner.entries[h] - next++ - h = scanner.next[h] - - if h == 0 { - break - } - } - } -} - -type deltaIndexScanner struct { - table []int - entries []int - next []int - mask int - count int -} - -func newDeltaIndexScanner(buf []byte, size int) *deltaIndexScanner { - size -= size % blksz - worstCaseBlockCnt := size / blksz - if worstCaseBlockCnt < 1 { - return new(deltaIndexScanner) - } - - tableSize := tableSize(worstCaseBlockCnt) - scanner := &deltaIndexScanner{ - table: make([]int, tableSize), - mask: tableSize - 1, - entries: make([]int, worstCaseBlockCnt+1), - next: make([]int, worstCaseBlockCnt+1), - } - - scanner.scan(buf, size) - return scanner -} - -// slightly modified version of JGit's DeltaIndexScanner. We store the offset on the entries -// instead of the entries and the key, so we avoid operations to retrieve the offset later, as -// we don't use the key. -// See: https://github.com/eclipse/jgit/blob/005e5feb4ecd08c4e4d141a38b9e7942accb3212/org.eclipse.jgit/src/org/eclipse/jgit/internal/storage/pack/DeltaIndexScanner.java -func (s *deltaIndexScanner) scan(buf []byte, end int) { - lastHash := 0 - ptr := end - blksz - - for { - key := hashBlock(buf, ptr) - tIdx := key & s.mask - head := s.table[tIdx] - if head != 0 && lastHash == key { - s.entries[head] = ptr - } else { - s.count++ - eIdx := s.count - s.entries[eIdx] = ptr - s.next[eIdx] = head - s.table[tIdx] = eIdx - } - - lastHash = key - ptr -= blksz - - if 0 > ptr { - break - } - } -} - -func tableSize(worstCaseBlockCnt int) int { - shift := 32 - leadingZeros(uint32(worstCaseBlockCnt)) - sz := 1 << uint(shift-1) - if sz < worstCaseBlockCnt { - sz <<= 1 - } - return sz -} - -// use https://golang.org/pkg/math/bits/#LeadingZeros32 in the future -func leadingZeros(x uint32) (n int) { - if x >= 1<<16 { - x >>= 16 - n = 16 - } - if x >= 1<<8 { - x >>= 8 - n += 8 - } - n += int(len8tab[x]) - return 32 - n -} - -var len8tab = [256]uint8{ - 0x00, 0x01, 0x02, 0x02, 0x03, 0x03, 0x03, 0x03, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, - 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05, - 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, - 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, - 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, - 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, - 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, - 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, - 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, - 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, - 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, - 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, - 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, - 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, - 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, - 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, -} - -func hashBlock(raw []byte, ptr int) int { - // The first 4 steps collapse out into a 4 byte big-endian decode, - // with a larger right shift as we combined shift lefts together. - // - hash := ((uint32(raw[ptr]) & 0xff) << 24) | - ((uint32(raw[ptr+1]) & 0xff) << 16) | - ((uint32(raw[ptr+2]) & 0xff) << 8) | - (uint32(raw[ptr+3]) & 0xff) - hash ^= T[hash>>31] - - hash = ((hash << 8) | (uint32(raw[ptr+4]) & 0xff)) ^ T[hash>>23] - hash = ((hash << 8) | (uint32(raw[ptr+5]) & 0xff)) ^ T[hash>>23] - hash = ((hash << 8) | (uint32(raw[ptr+6]) & 0xff)) ^ T[hash>>23] - hash = ((hash << 8) | (uint32(raw[ptr+7]) & 0xff)) ^ T[hash>>23] - - hash = ((hash << 8) | (uint32(raw[ptr+8]) & 0xff)) ^ T[hash>>23] - hash = ((hash << 8) | (uint32(raw[ptr+9]) & 0xff)) ^ T[hash>>23] - hash = ((hash << 8) | (uint32(raw[ptr+10]) & 0xff)) ^ T[hash>>23] - hash = ((hash << 8) | (uint32(raw[ptr+11]) & 0xff)) ^ T[hash>>23] - - hash = ((hash << 8) | (uint32(raw[ptr+12]) & 0xff)) ^ T[hash>>23] - hash = ((hash << 8) | (uint32(raw[ptr+13]) & 0xff)) ^ T[hash>>23] - hash = ((hash << 8) | (uint32(raw[ptr+14]) & 0xff)) ^ T[hash>>23] - hash = ((hash << 8) | (uint32(raw[ptr+15]) & 0xff)) ^ T[hash>>23] - - return int(hash) -} - -var T = []uint32{0x00000000, 0xd4c6b32d, 0x7d4bd577, - 0xa98d665a, 0x2e5119c3, 0xfa97aaee, 0x531accb4, 0x87dc7f99, - 0x5ca23386, 0x886480ab, 0x21e9e6f1, 0xf52f55dc, 0x72f32a45, - 0xa6359968, 0x0fb8ff32, 0xdb7e4c1f, 0x6d82d421, 0xb944670c, - 0x10c90156, 0xc40fb27b, 0x43d3cde2, 0x97157ecf, 0x3e981895, - 0xea5eabb8, 0x3120e7a7, 0xe5e6548a, 0x4c6b32d0, 0x98ad81fd, - 0x1f71fe64, 0xcbb74d49, 0x623a2b13, 0xb6fc983e, 0x0fc31b6f, - 0xdb05a842, 0x7288ce18, 0xa64e7d35, 0x219202ac, 0xf554b181, - 0x5cd9d7db, 0x881f64f6, 0x536128e9, 0x87a79bc4, 0x2e2afd9e, - 0xfaec4eb3, 0x7d30312a, 0xa9f68207, 0x007be45d, 0xd4bd5770, - 0x6241cf4e, 0xb6877c63, 0x1f0a1a39, 0xcbcca914, 0x4c10d68d, - 0x98d665a0, 0x315b03fa, 0xe59db0d7, 0x3ee3fcc8, 0xea254fe5, - 0x43a829bf, 0x976e9a92, 0x10b2e50b, 0xc4745626, 0x6df9307c, - 0xb93f8351, 0x1f8636de, 0xcb4085f3, 0x62cde3a9, 0xb60b5084, - 0x31d72f1d, 0xe5119c30, 0x4c9cfa6a, 0x985a4947, 0x43240558, - 0x97e2b675, 0x3e6fd02f, 0xeaa96302, 0x6d751c9b, 0xb9b3afb6, - 0x103ec9ec, 0xc4f87ac1, 0x7204e2ff, 0xa6c251d2, 0x0f4f3788, - 0xdb8984a5, 0x5c55fb3c, 0x88934811, 0x211e2e4b, 0xf5d89d66, - 0x2ea6d179, 0xfa606254, 0x53ed040e, 0x872bb723, 0x00f7c8ba, - 0xd4317b97, 0x7dbc1dcd, 0xa97aaee0, 0x10452db1, 0xc4839e9c, - 0x6d0ef8c6, 0xb9c84beb, 0x3e143472, 0xead2875f, 0x435fe105, - 0x97995228, 0x4ce71e37, 0x9821ad1a, 0x31accb40, 0xe56a786d, - 0x62b607f4, 0xb670b4d9, 0x1ffdd283, 0xcb3b61ae, 0x7dc7f990, - 0xa9014abd, 0x008c2ce7, 0xd44a9fca, 0x5396e053, 0x8750537e, - 0x2edd3524, 0xfa1b8609, 0x2165ca16, 0xf5a3793b, 0x5c2e1f61, - 0x88e8ac4c, 0x0f34d3d5, 0xdbf260f8, 0x727f06a2, 0xa6b9b58f, - 0x3f0c6dbc, 0xebcade91, 0x4247b8cb, 0x96810be6, 0x115d747f, - 0xc59bc752, 0x6c16a108, 0xb8d01225, 0x63ae5e3a, 0xb768ed17, - 0x1ee58b4d, 0xca233860, 0x4dff47f9, 0x9939f4d4, 0x30b4928e, - 0xe47221a3, 0x528eb99d, 0x86480ab0, 0x2fc56cea, 0xfb03dfc7, - 0x7cdfa05e, 0xa8191373, 0x01947529, 0xd552c604, 0x0e2c8a1b, - 0xdaea3936, 0x73675f6c, 0xa7a1ec41, 0x207d93d8, 0xf4bb20f5, - 0x5d3646af, 0x89f0f582, 0x30cf76d3, 0xe409c5fe, 0x4d84a3a4, - 0x99421089, 0x1e9e6f10, 0xca58dc3d, 0x63d5ba67, 0xb713094a, - 0x6c6d4555, 0xb8abf678, 0x11269022, 0xc5e0230f, 0x423c5c96, - 0x96faefbb, 0x3f7789e1, 0xebb13acc, 0x5d4da2f2, 0x898b11df, - 0x20067785, 0xf4c0c4a8, 0x731cbb31, 0xa7da081c, 0x0e576e46, - 0xda91dd6b, 0x01ef9174, 0xd5292259, 0x7ca44403, 0xa862f72e, - 0x2fbe88b7, 0xfb783b9a, 0x52f55dc0, 0x8633eeed, 0x208a5b62, - 0xf44ce84f, 0x5dc18e15, 0x89073d38, 0x0edb42a1, 0xda1df18c, - 0x739097d6, 0xa75624fb, 0x7c2868e4, 0xa8eedbc9, 0x0163bd93, - 0xd5a50ebe, 0x52797127, 0x86bfc20a, 0x2f32a450, 0xfbf4177d, - 0x4d088f43, 0x99ce3c6e, 0x30435a34, 0xe485e919, 0x63599680, - 0xb79f25ad, 0x1e1243f7, 0xcad4f0da, 0x11aabcc5, 0xc56c0fe8, - 0x6ce169b2, 0xb827da9f, 0x3ffba506, 0xeb3d162b, 0x42b07071, - 0x9676c35c, 0x2f49400d, 0xfb8ff320, 0x5202957a, 0x86c42657, - 0x011859ce, 0xd5deeae3, 0x7c538cb9, 0xa8953f94, 0x73eb738b, - 0xa72dc0a6, 0x0ea0a6fc, 0xda6615d1, 0x5dba6a48, 0x897cd965, - 0x20f1bf3f, 0xf4370c12, 0x42cb942c, 0x960d2701, 0x3f80415b, - 0xeb46f276, 0x6c9a8def, 0xb85c3ec2, 0x11d15898, 0xc517ebb5, - 0x1e69a7aa, 0xcaaf1487, 0x632272dd, 0xb7e4c1f0, 0x3038be69, - 0xe4fe0d44, 0x4d736b1e, 0x99b5d833, -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/delta_selector.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/delta_selector.go deleted file mode 100644 index 4b60ff39..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/delta_selector.go +++ /dev/null @@ -1,369 +0,0 @@ -package packfile - -import ( - "sort" - "sync" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/plumbing/storer" -) - -const ( - // deltas based on deltas, how many steps we can do. - // 50 is the default value used in JGit - maxDepth = int64(50) -) - -// applyDelta is the set of object types that we should apply deltas -var applyDelta = map[plumbing.ObjectType]bool{ - plumbing.BlobObject: true, - plumbing.TreeObject: true, -} - -type deltaSelector struct { - storer storer.EncodedObjectStorer -} - -func newDeltaSelector(s storer.EncodedObjectStorer) *deltaSelector { - return &deltaSelector{s} -} - -// ObjectsToPack creates a list of ObjectToPack from the hashes -// provided, creating deltas if it's suitable, using an specific -// internal logic. `packWindow` specifies the size of the sliding -// window used to compare objects for delta compression; 0 turns off -// delta compression entirely. -func (dw *deltaSelector) ObjectsToPack( - hashes []plumbing.Hash, - packWindow uint, -) ([]*ObjectToPack, error) { - otp, err := dw.objectsToPack(hashes, packWindow) - if err != nil { - return nil, err - } - - if packWindow == 0 { - return otp, nil - } - - dw.sort(otp) - - var objectGroups [][]*ObjectToPack - var prev *ObjectToPack - i := -1 - for _, obj := range otp { - if prev == nil || prev.Type() != obj.Type() { - objectGroups = append(objectGroups, []*ObjectToPack{obj}) - i++ - prev = obj - } else { - objectGroups[i] = append(objectGroups[i], obj) - } - } - - var wg sync.WaitGroup - var once sync.Once - for _, objs := range objectGroups { - objs := objs - wg.Add(1) - go func() { - if walkErr := dw.walk(objs, packWindow); walkErr != nil { - once.Do(func() { - err = walkErr - }) - } - wg.Done() - }() - } - wg.Wait() - - if err != nil { - return nil, err - } - - return otp, nil -} - -func (dw *deltaSelector) objectsToPack( - hashes []plumbing.Hash, - packWindow uint, -) ([]*ObjectToPack, error) { - var objectsToPack []*ObjectToPack - for _, h := range hashes { - var o plumbing.EncodedObject - var err error - if packWindow == 0 { - o, err = dw.encodedObject(h) - } else { - o, err = dw.encodedDeltaObject(h) - } - if err != nil { - return nil, err - } - - otp := newObjectToPack(o) - if _, ok := o.(plumbing.DeltaObject); ok { - otp.CleanOriginal() - } - - objectsToPack = append(objectsToPack, otp) - } - - if packWindow == 0 { - return objectsToPack, nil - } - - if err := dw.fixAndBreakChains(objectsToPack); err != nil { - return nil, err - } - - return objectsToPack, nil -} - -func (dw *deltaSelector) encodedDeltaObject(h plumbing.Hash) (plumbing.EncodedObject, error) { - edos, ok := dw.storer.(storer.DeltaObjectStorer) - if !ok { - return dw.encodedObject(h) - } - - return edos.DeltaObject(plumbing.AnyObject, h) -} - -func (dw *deltaSelector) encodedObject(h plumbing.Hash) (plumbing.EncodedObject, error) { - return dw.storer.EncodedObject(plumbing.AnyObject, h) -} - -func (dw *deltaSelector) fixAndBreakChains(objectsToPack []*ObjectToPack) error { - m := make(map[plumbing.Hash]*ObjectToPack, len(objectsToPack)) - for _, otp := range objectsToPack { - m[otp.Hash()] = otp - } - - for _, otp := range objectsToPack { - if err := dw.fixAndBreakChainsOne(m, otp); err != nil { - return err - } - } - - return nil -} - -func (dw *deltaSelector) fixAndBreakChainsOne(objectsToPack map[plumbing.Hash]*ObjectToPack, otp *ObjectToPack) error { - if !otp.Object.Type().IsDelta() { - return nil - } - - // Initial ObjectToPack instances might have a delta assigned to Object - // but no actual base initially. Once Base is assigned to a delta, it means - // we already fixed it. - if otp.Base != nil { - return nil - } - - do, ok := otp.Object.(plumbing.DeltaObject) - if !ok { - // if this is not a DeltaObject, then we cannot retrieve its base, - // so we have to break the delta chain here. - return dw.undeltify(otp) - } - - base, ok := objectsToPack[do.BaseHash()] - if !ok { - // The base of the delta is not in our list of objects to pack, so - // we break the chain. - return dw.undeltify(otp) - } - - if err := dw.fixAndBreakChainsOne(objectsToPack, base); err != nil { - return err - } - - otp.SetDelta(base, otp.Object) - return nil -} - -func (dw *deltaSelector) restoreOriginal(otp *ObjectToPack) error { - if otp.Original != nil { - return nil - } - - if !otp.Object.Type().IsDelta() { - return nil - } - - obj, err := dw.encodedObject(otp.Hash()) - if err != nil { - return err - } - - otp.SetOriginal(obj) - - return nil -} - -// undeltify undeltifies an *ObjectToPack by retrieving the original object from -// the storer and resetting it. -func (dw *deltaSelector) undeltify(otp *ObjectToPack) error { - if err := dw.restoreOriginal(otp); err != nil { - return err - } - - otp.Object = otp.Original - otp.Depth = 0 - return nil -} - -func (dw *deltaSelector) sort(objectsToPack []*ObjectToPack) { - sort.Sort(byTypeAndSize(objectsToPack)) -} - -func (dw *deltaSelector) walk( - objectsToPack []*ObjectToPack, - packWindow uint, -) error { - indexMap := make(map[plumbing.Hash]*deltaIndex) - for i := 0; i < len(objectsToPack); i++ { - // Clean up the index map and reconstructed delta objects for anything - // outside our pack window, to save memory. - if i > int(packWindow) { - obj := objectsToPack[i-int(packWindow)] - - delete(indexMap, obj.Hash()) - - if obj.IsDelta() { - obj.SaveOriginalMetadata() - obj.CleanOriginal() - } - } - - target := objectsToPack[i] - - // If we already have a delta, we don't try to find a new one for this - // object. This happens when a delta is set to be reused from an existing - // packfile. - if target.IsDelta() { - continue - } - - // We only want to create deltas from specific types. - if !applyDelta[target.Type()] { - continue - } - - for j := i - 1; j >= 0 && i-j < int(packWindow); j-- { - base := objectsToPack[j] - // Objects must use only the same type as their delta base. - // Since objectsToPack is sorted by type and size, once we find - // a different type, we know we won't find more of them. - if base.Type() != target.Type() { - break - } - - if err := dw.tryToDeltify(indexMap, base, target); err != nil { - return err - } - } - } - - return nil -} - -func (dw *deltaSelector) tryToDeltify(indexMap map[plumbing.Hash]*deltaIndex, base, target *ObjectToPack) error { - // Original object might not be present if we're reusing a delta, so we - // ensure it is restored. - if err := dw.restoreOriginal(target); err != nil { - return err - } - - if err := dw.restoreOriginal(base); err != nil { - return err - } - - // If the sizes are radically different, this is a bad pairing. - if target.Size() < base.Size()>>4 { - return nil - } - - msz := dw.deltaSizeLimit( - target.Object.Size(), - base.Depth, - target.Depth, - target.IsDelta(), - ) - - // Nearly impossible to fit useful delta. - if msz <= 8 { - return nil - } - - // If we have to insert a lot to make this work, find another. - if base.Size()-target.Size() > msz { - return nil - } - - if _, ok := indexMap[base.Hash()]; !ok { - indexMap[base.Hash()] = new(deltaIndex) - } - - // Now we can generate the delta using originals - delta, err := getDelta(indexMap[base.Hash()], base.Original, target.Original) - if err != nil { - return err - } - - // if delta better than target - if delta.Size() < msz { - target.SetDelta(base, delta) - } - - return nil -} - -func (dw *deltaSelector) deltaSizeLimit(targetSize int64, baseDepth int, - targetDepth int, targetDelta bool) int64 { - if !targetDelta { - // Any delta should be no more than 50% of the original size - // (for text files deflate of whole form should shrink 50%). - n := targetSize >> 1 - - // Evenly distribute delta size limits over allowed depth. - // If src is non-delta (depth = 0), delta <= 50% of original. - // If src is almost at limit (9/10), delta <= 10% of original. - return n * (maxDepth - int64(baseDepth)) / maxDepth - } - - // With a delta base chosen any new delta must be "better". - // Retain the distribution described above. - d := int64(targetDepth) - n := targetSize - - // If target depth is bigger than maxDepth, this delta is not suitable to be used. - if d >= maxDepth { - return 0 - } - - // If src is whole (depth=0) and base is near limit (depth=9/10) - // any delta using src can be 10x larger and still be better. - // - // If src is near limit (depth=9/10) and base is whole (depth=0) - // a new delta dependent on src must be 1/10th the size. - return n * (maxDepth - int64(baseDepth)) / (maxDepth - d) -} - -type byTypeAndSize []*ObjectToPack - -func (a byTypeAndSize) Len() int { return len(a) } - -func (a byTypeAndSize) Swap(i, j int) { a[i], a[j] = a[j], a[i] } - -func (a byTypeAndSize) Less(i, j int) bool { - if a[i].Type() < a[j].Type() { - return false - } - - if a[i].Type() > a[j].Type() { - return true - } - - return a[i].Size() > a[j].Size() -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/diff_delta.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/diff_delta.go deleted file mode 100644 index 1951b34e..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/diff_delta.go +++ /dev/null @@ -1,204 +0,0 @@ -package packfile - -import ( - "bytes" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/utils/ioutil" -) - -// See https://github.com/jelmer/dulwich/blob/master/dulwich/pack.py and -// https://github.com/tarruda/node-git-core/blob/master/src/js/delta.js -// for more info - -const ( - // Standard chunk size used to generate fingerprints - s = 16 - - // https://github.com/git/git/blob/f7466e94375b3be27f229c78873f0acf8301c0a5/diff-delta.c#L428 - // Max size of a copy operation (64KB) - maxCopySize = 64 * 1024 -) - -// GetDelta returns an EncodedObject of type OFSDeltaObject. Base and Target object, -// will be loaded into memory to be able to create the delta object. -// To generate target again, you will need the obtained object and "base" one. -// Error will be returned if base or target object cannot be read. -func GetDelta(base, target plumbing.EncodedObject) (plumbing.EncodedObject, error) { - return getDelta(new(deltaIndex), base, target) -} - -func getDelta(index *deltaIndex, base, target plumbing.EncodedObject) (o plumbing.EncodedObject, err error) { - br, err := base.Reader() - if err != nil { - return nil, err - } - - defer ioutil.CheckClose(br, &err) - - tr, err := target.Reader() - if err != nil { - return nil, err - } - - defer ioutil.CheckClose(tr, &err) - - bb := bufPool.Get().(*bytes.Buffer) - defer bufPool.Put(bb) - bb.Reset() - - _, err = bb.ReadFrom(br) - if err != nil { - return nil, err - } - - tb := bufPool.Get().(*bytes.Buffer) - defer bufPool.Put(tb) - tb.Reset() - - _, err = tb.ReadFrom(tr) - if err != nil { - return nil, err - } - - db := diffDelta(index, bb.Bytes(), tb.Bytes()) - delta := &plumbing.MemoryObject{} - _, err = delta.Write(db) - if err != nil { - return nil, err - } - - delta.SetSize(int64(len(db))) - delta.SetType(plumbing.OFSDeltaObject) - - return delta, nil -} - -// DiffDelta returns the delta that transforms src into tgt. -func DiffDelta(src, tgt []byte) []byte { - return diffDelta(new(deltaIndex), src, tgt) -} - -func diffDelta(index *deltaIndex, src []byte, tgt []byte) []byte { - buf := bufPool.Get().(*bytes.Buffer) - defer bufPool.Put(buf) - buf.Reset() - buf.Write(deltaEncodeSize(len(src))) - buf.Write(deltaEncodeSize(len(tgt))) - - if len(index.entries) == 0 { - index.init(src) - } - - ibuf := bufPool.Get().(*bytes.Buffer) - defer bufPool.Put(ibuf) - ibuf.Reset() - for i := 0; i < len(tgt); i++ { - offset, l := index.findMatch(src, tgt, i) - - if l == 0 { - // couldn't find a match, just write the current byte and continue - ibuf.WriteByte(tgt[i]) - } else if l < 0 { - // src is less than blksz, copy the rest of the target to avoid - // calls to findMatch - for ; i < len(tgt); i++ { - ibuf.WriteByte(tgt[i]) - } - } else if l < s { - // remaining target is less than blksz, copy what's left of it - // and avoid calls to findMatch - for j := i; j < i+l; j++ { - ibuf.WriteByte(tgt[j]) - } - i += l - 1 - } else { - encodeInsertOperation(ibuf, buf) - - rl := l - aOffset := offset - for rl > 0 { - if rl < maxCopySize { - buf.Write(encodeCopyOperation(aOffset, rl)) - break - } - - buf.Write(encodeCopyOperation(aOffset, maxCopySize)) - rl -= maxCopySize - aOffset += maxCopySize - } - - i += l - 1 - } - } - - encodeInsertOperation(ibuf, buf) - - // buf.Bytes() is only valid until the next modifying operation on the buffer. Copy it. - return append([]byte{}, buf.Bytes()...) -} - -func encodeInsertOperation(ibuf, buf *bytes.Buffer) { - if ibuf.Len() == 0 { - return - } - - b := ibuf.Bytes() - s := ibuf.Len() - o := 0 - for { - if s <= 127 { - break - } - buf.WriteByte(byte(127)) - buf.Write(b[o : o+127]) - s -= 127 - o += 127 - } - buf.WriteByte(byte(s)) - buf.Write(b[o : o+s]) - - ibuf.Reset() -} - -func deltaEncodeSize(size int) []byte { - var ret []byte - c := size & 0x7f - size >>= 7 - for { - if size == 0 { - break - } - - ret = append(ret, byte(c|0x80)) - c = size & 0x7f - size >>= 7 - } - ret = append(ret, byte(c)) - - return ret -} - -func encodeCopyOperation(offset, length int) []byte { - code := 0x80 - var opcodes []byte - - var i uint - for i = 0; i < 4; i++ { - f := 0xff << (i * 8) - if offset&f != 0 { - opcodes = append(opcodes, byte(offset&f>>(i*8))) - code |= 0x01 << i - } - } - - for i = 0; i < 3; i++ { - f := 0xff << (i * 8) - if length&f != 0 { - opcodes = append(opcodes, byte(length&f>>(i*8))) - code |= 0x10 << i - } - } - - return append([]byte{byte(code)}, opcodes...) -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/doc.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/doc.go deleted file mode 100644 index 2882a7f3..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/doc.go +++ /dev/null @@ -1,39 +0,0 @@ -// Package packfile implements encoding and decoding of packfile format. -// -// == pack-*.pack files have the following format: -// -// - A header appears at the beginning and consists of the following: -// -// 4-byte signature: -// The signature is: {'P', 'A', 'C', 'K'} -// -// 4-byte version number (network byte order): -// GIT currently accepts version number 2 or 3 but -// generates version 2 only. -// -// 4-byte number of objects contained in the pack (network byte order) -// -// Observation: we cannot have more than 4G versions ;-) and -// more than 4G objects in a pack. -// -// - The header is followed by number of object entries, each of -// which looks like this: -// -// (undeltified representation) -// n-byte type and length (3-bit type, (n-1)*7+4-bit length) -// compressed data -// -// (deltified representation) -// n-byte type and length (3-bit type, (n-1)*7+4-bit length) -// 20-byte base object name -// compressed delta data -// -// Observation: length of each object is encoded in a variable -// length format and is not constrained to 32-bit or anything. -// -// - The trailer records 20-byte SHA1 checksum of all of the above. -// -// -// Source: -// https://www.kernel.org/pub/software/scm/git/docs/v1.7.5/technical/pack-protocol.txt -package packfile diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/encoder.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/encoder.go deleted file mode 100644 index 5501f886..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/encoder.go +++ /dev/null @@ -1,225 +0,0 @@ -package packfile - -import ( - "compress/zlib" - "crypto/sha1" - "fmt" - "io" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/plumbing/storer" - "github.com/go-git/go-git/v5/utils/binary" - "github.com/go-git/go-git/v5/utils/ioutil" -) - -// Encoder gets the data from the storage and write it into the writer in PACK -// format -type Encoder struct { - selector *deltaSelector - w *offsetWriter - zw *zlib.Writer - hasher plumbing.Hasher - - useRefDeltas bool -} - -// NewEncoder creates a new packfile encoder using a specific Writer and -// EncodedObjectStorer. By default deltas used to generate the packfile will be -// OFSDeltaObject. To use Reference deltas, set useRefDeltas to true. -func NewEncoder(w io.Writer, s storer.EncodedObjectStorer, useRefDeltas bool) *Encoder { - h := plumbing.Hasher{ - Hash: sha1.New(), - } - mw := io.MultiWriter(w, h) - ow := newOffsetWriter(mw) - zw := zlib.NewWriter(mw) - return &Encoder{ - selector: newDeltaSelector(s), - w: ow, - zw: zw, - hasher: h, - useRefDeltas: useRefDeltas, - } -} - -// Encode creates a packfile containing all the objects referenced in -// hashes and writes it to the writer in the Encoder. `packWindow` -// specifies the size of the sliding window used to compare objects -// for delta compression; 0 turns off delta compression entirely. -func (e *Encoder) Encode( - hashes []plumbing.Hash, - packWindow uint, -) (plumbing.Hash, error) { - objects, err := e.selector.ObjectsToPack(hashes, packWindow) - if err != nil { - return plumbing.ZeroHash, err - } - - return e.encode(objects) -} - -func (e *Encoder) encode(objects []*ObjectToPack) (plumbing.Hash, error) { - if err := e.head(len(objects)); err != nil { - return plumbing.ZeroHash, err - } - - for _, o := range objects { - if err := e.entry(o); err != nil { - return plumbing.ZeroHash, err - } - } - - return e.footer() -} - -func (e *Encoder) head(numEntries int) error { - return binary.Write( - e.w, - signature, - int32(VersionSupported), - int32(numEntries), - ) -} - -func (e *Encoder) entry(o *ObjectToPack) (err error) { - if o.WantWrite() { - // A cycle exists in this delta chain. This should only occur if a - // selected object representation disappeared during writing - // (for example due to a concurrent repack) and a different base - // was chosen, forcing a cycle. Select something other than a - // delta, and write this object. - e.selector.restoreOriginal(o) - o.BackToOriginal() - } - - if o.IsWritten() { - return nil - } - - o.MarkWantWrite() - - if err := e.writeBaseIfDelta(o); err != nil { - return err - } - - // We need to check if we already write that object due a cyclic delta chain - if o.IsWritten() { - return nil - } - - o.Offset = e.w.Offset() - - if o.IsDelta() { - if err := e.writeDeltaHeader(o); err != nil { - return err - } - } else { - if err := e.entryHead(o.Type(), o.Size()); err != nil { - return err - } - } - - e.zw.Reset(e.w) - - defer ioutil.CheckClose(e.zw, &err) - - or, err := o.Object.Reader() - if err != nil { - return err - } - - defer ioutil.CheckClose(or, &err) - - _, err = io.Copy(e.zw, or) - if err != nil { - return err - } - - return nil -} - -func (e *Encoder) writeBaseIfDelta(o *ObjectToPack) error { - if o.IsDelta() && !o.Base.IsWritten() { - // We must write base first - return e.entry(o.Base) - } - - return nil -} - -func (e *Encoder) writeDeltaHeader(o *ObjectToPack) error { - // Write offset deltas by default - t := plumbing.OFSDeltaObject - if e.useRefDeltas { - t = plumbing.REFDeltaObject - } - - if err := e.entryHead(t, o.Object.Size()); err != nil { - return err - } - - if e.useRefDeltas { - return e.writeRefDeltaHeader(o.Base.Hash()) - } else { - return e.writeOfsDeltaHeader(o) - } -} - -func (e *Encoder) writeRefDeltaHeader(base plumbing.Hash) error { - return binary.Write(e.w, base) -} - -func (e *Encoder) writeOfsDeltaHeader(o *ObjectToPack) error { - // for OFS_DELTA, offset of the base is interpreted as negative offset - // relative to the type-byte of the header of the ofs-delta entry. - relativeOffset := o.Offset - o.Base.Offset - if relativeOffset <= 0 { - return fmt.Errorf("bad offset for OFS_DELTA entry: %d", relativeOffset) - } - - return binary.WriteVariableWidthInt(e.w, relativeOffset) -} - -func (e *Encoder) entryHead(typeNum plumbing.ObjectType, size int64) error { - t := int64(typeNum) - header := []byte{} - c := (t << firstLengthBits) | (size & maskFirstLength) - size >>= firstLengthBits - for { - if size == 0 { - break - } - header = append(header, byte(c|maskContinue)) - c = size & int64(maskLength) - size >>= lengthBits - } - - header = append(header, byte(c)) - _, err := e.w.Write(header) - - return err -} - -func (e *Encoder) footer() (plumbing.Hash, error) { - h := e.hasher.Sum() - return h, binary.Write(e.w, h) -} - -type offsetWriter struct { - w io.Writer - offset int64 -} - -func newOffsetWriter(w io.Writer) *offsetWriter { - return &offsetWriter{w: w} -} - -func (ow *offsetWriter) Write(p []byte) (n int, err error) { - n, err = ow.w.Write(p) - ow.offset += int64(n) - return n, err -} - -func (ow *offsetWriter) Offset() int64 { - return ow.offset -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/error.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/error.go deleted file mode 100644 index c0b91633..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/error.go +++ /dev/null @@ -1,30 +0,0 @@ -package packfile - -import "fmt" - -// Error specifies errors returned during packfile parsing. -type Error struct { - reason, details string -} - -// NewError returns a new error. -func NewError(reason string) *Error { - return &Error{reason: reason} -} - -// Error returns a text representation of the error. -func (e *Error) Error() string { - if e.details == "" { - return e.reason - } - - return fmt.Sprintf("%s: %s", e.reason, e.details) -} - -// AddDetails adds details to an error, with additional text. -func (e *Error) AddDetails(format string, args ...interface{}) *Error { - return &Error{ - reason: e.reason, - details: fmt.Sprintf(format, args...), - } -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/fsobject.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/fsobject.go deleted file mode 100644 index c5edaf52..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/fsobject.go +++ /dev/null @@ -1,116 +0,0 @@ -package packfile - -import ( - "io" - - billy "github.com/go-git/go-billy/v5" - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/plumbing/cache" - "github.com/go-git/go-git/v5/plumbing/format/idxfile" -) - -// FSObject is an object from the packfile on the filesystem. -type FSObject struct { - hash plumbing.Hash - h *ObjectHeader - offset int64 - size int64 - typ plumbing.ObjectType - index idxfile.Index - fs billy.Filesystem - path string - cache cache.Object -} - -// NewFSObject creates a new filesystem object. -func NewFSObject( - hash plumbing.Hash, - finalType plumbing.ObjectType, - offset int64, - contentSize int64, - index idxfile.Index, - fs billy.Filesystem, - path string, - cache cache.Object, -) *FSObject { - return &FSObject{ - hash: hash, - offset: offset, - size: contentSize, - typ: finalType, - index: index, - fs: fs, - path: path, - cache: cache, - } -} - -// Reader implements the plumbing.EncodedObject interface. -func (o *FSObject) Reader() (io.ReadCloser, error) { - obj, ok := o.cache.Get(o.hash) - if ok && obj != o { - reader, err := obj.Reader() - if err != nil { - return nil, err - } - - return reader, nil - } - - f, err := o.fs.Open(o.path) - if err != nil { - return nil, err - } - - p := NewPackfileWithCache(o.index, nil, f, o.cache) - r, err := p.getObjectContent(o.offset) - if err != nil { - _ = f.Close() - return nil, err - } - - if err := f.Close(); err != nil { - return nil, err - } - - return r, nil -} - -// SetSize implements the plumbing.EncodedObject interface. This method -// is a noop. -func (o *FSObject) SetSize(int64) {} - -// SetType implements the plumbing.EncodedObject interface. This method is -// a noop. -func (o *FSObject) SetType(plumbing.ObjectType) {} - -// Hash implements the plumbing.EncodedObject interface. -func (o *FSObject) Hash() plumbing.Hash { return o.hash } - -// Size implements the plumbing.EncodedObject interface. -func (o *FSObject) Size() int64 { return o.size } - -// Type implements the plumbing.EncodedObject interface. -func (o *FSObject) Type() plumbing.ObjectType { - return o.typ -} - -// Writer implements the plumbing.EncodedObject interface. This method always -// returns a nil writer. -func (o *FSObject) Writer() (io.WriteCloser, error) { - return nil, nil -} - -type objectReader struct { - io.ReadCloser - f billy.File -} - -func (r *objectReader) Close() error { - if err := r.ReadCloser.Close(); err != nil { - _ = r.f.Close() - return err - } - - return r.f.Close() -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/object_pack.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/object_pack.go deleted file mode 100644 index 8ce29ef8..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/object_pack.go +++ /dev/null @@ -1,164 +0,0 @@ -package packfile - -import ( - "github.com/go-git/go-git/v5/plumbing" -) - -// ObjectToPack is a representation of an object that is going to be into a -// pack file. -type ObjectToPack struct { - // The main object to pack, it could be any object, including deltas - Object plumbing.EncodedObject - // Base is the object that a delta is based on (it could be also another delta). - // If the main object is not a delta, Base will be null - Base *ObjectToPack - // Original is the object that we can generate applying the delta to - // Base, or the same object as Object in the case of a non-delta - // object. - Original plumbing.EncodedObject - // Depth is the amount of deltas needed to resolve to obtain Original - // (delta based on delta based on ...) - Depth int - - // offset in pack when object has been already written, or 0 if it - // has not been written yet - Offset int64 - - // Information from the original object - resolvedOriginal bool - originalType plumbing.ObjectType - originalSize int64 - originalHash plumbing.Hash -} - -// newObjectToPack creates a correct ObjectToPack based on a non-delta object -func newObjectToPack(o plumbing.EncodedObject) *ObjectToPack { - return &ObjectToPack{ - Object: o, - Original: o, - } -} - -// newDeltaObjectToPack creates a correct ObjectToPack for a delta object, based on -// his base (could be another delta), the delta target (in this case called original), -// and the delta Object itself -func newDeltaObjectToPack(base *ObjectToPack, original, delta plumbing.EncodedObject) *ObjectToPack { - return &ObjectToPack{ - Object: delta, - Base: base, - Original: original, - Depth: base.Depth + 1, - } -} - -// BackToOriginal converts that ObjectToPack to a non-deltified object if it was one -func (o *ObjectToPack) BackToOriginal() { - if o.IsDelta() && o.Original != nil { - o.Object = o.Original - o.Base = nil - o.Depth = 0 - } -} - -// IsWritten returns if that ObjectToPack was -// already written into the packfile or not -func (o *ObjectToPack) IsWritten() bool { - return o.Offset > 1 -} - -// MarkWantWrite marks this ObjectToPack as WantWrite -// to avoid delta chain loops -func (o *ObjectToPack) MarkWantWrite() { - o.Offset = 1 -} - -// WantWrite checks if this ObjectToPack was marked as WantWrite before -func (o *ObjectToPack) WantWrite() bool { - return o.Offset == 1 -} - -// SetOriginal sets both Original and saves size, type and hash. If object -// is nil Original is set but previous resolved values are kept -func (o *ObjectToPack) SetOriginal(obj plumbing.EncodedObject) { - o.Original = obj - o.SaveOriginalMetadata() -} - -// SaveOriginalMetadata saves size, type and hash of Original object -func (o *ObjectToPack) SaveOriginalMetadata() { - if o.Original != nil { - o.originalSize = o.Original.Size() - o.originalType = o.Original.Type() - o.originalHash = o.Original.Hash() - o.resolvedOriginal = true - } -} - -// CleanOriginal sets Original to nil -func (o *ObjectToPack) CleanOriginal() { - o.Original = nil -} - -func (o *ObjectToPack) Type() plumbing.ObjectType { - if o.Original != nil { - return o.Original.Type() - } - - if o.resolvedOriginal { - return o.originalType - } - - if o.Base != nil { - return o.Base.Type() - } - - if o.Object != nil { - return o.Object.Type() - } - - panic("cannot get type") -} - -func (o *ObjectToPack) Hash() plumbing.Hash { - if o.Original != nil { - return o.Original.Hash() - } - - if o.resolvedOriginal { - return o.originalHash - } - - do, ok := o.Object.(plumbing.DeltaObject) - if ok { - return do.ActualHash() - } - - panic("cannot get hash") -} - -func (o *ObjectToPack) Size() int64 { - if o.Original != nil { - return o.Original.Size() - } - - if o.resolvedOriginal { - return o.originalSize - } - - do, ok := o.Object.(plumbing.DeltaObject) - if ok { - return do.ActualSize() - } - - panic("cannot get ObjectToPack size") -} - -func (o *ObjectToPack) IsDelta() bool { - return o.Base != nil -} - -func (o *ObjectToPack) SetDelta(base *ObjectToPack, delta plumbing.EncodedObject) { - o.Object = delta - o.Base = base - o.Depth = base.Depth + 1 -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/packfile.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/packfile.go deleted file mode 100644 index ddd7f62f..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/packfile.go +++ /dev/null @@ -1,565 +0,0 @@ -package packfile - -import ( - "bytes" - "io" - "os" - - billy "github.com/go-git/go-billy/v5" - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/plumbing/cache" - "github.com/go-git/go-git/v5/plumbing/format/idxfile" - "github.com/go-git/go-git/v5/plumbing/storer" - "github.com/go-git/go-git/v5/utils/ioutil" -) - -var ( - // ErrInvalidObject is returned by Decode when an invalid object is - // found in the packfile. - ErrInvalidObject = NewError("invalid git object") - // ErrZLib is returned by Decode when there was an error unzipping - // the packfile contents. - ErrZLib = NewError("zlib reading error") -) - -// When reading small objects from packfile it is beneficial to do so at -// once to exploit the buffered I/O. In many cases the objects are so small -// that they were already loaded to memory when the object header was -// loaded from the packfile. Wrapping in FSObject would cause this buffered -// data to be thrown away and then re-read later, with the additional -// seeking causing reloads from disk. Objects smaller than this threshold -// are now always read into memory and stored in cache instead of being -// wrapped in FSObject. -const smallObjectThreshold = 16 * 1024 - -// Packfile allows retrieving information from inside a packfile. -type Packfile struct { - idxfile.Index - fs billy.Filesystem - file billy.File - s *Scanner - deltaBaseCache cache.Object - offsetToType map[int64]plumbing.ObjectType -} - -// NewPackfileWithCache creates a new Packfile with the given object cache. -// If the filesystem is provided, the packfile will return FSObjects, otherwise -// it will return MemoryObjects. -func NewPackfileWithCache( - index idxfile.Index, - fs billy.Filesystem, - file billy.File, - cache cache.Object, -) *Packfile { - s := NewScanner(file) - return &Packfile{ - index, - fs, - file, - s, - cache, - make(map[int64]plumbing.ObjectType), - } -} - -// NewPackfile returns a packfile representation for the given packfile file -// and packfile idx. -// If the filesystem is provided, the packfile will return FSObjects, otherwise -// it will return MemoryObjects. -func NewPackfile(index idxfile.Index, fs billy.Filesystem, file billy.File) *Packfile { - return NewPackfileWithCache(index, fs, file, cache.NewObjectLRUDefault()) -} - -// Get retrieves the encoded object in the packfile with the given hash. -func (p *Packfile) Get(h plumbing.Hash) (plumbing.EncodedObject, error) { - offset, err := p.FindOffset(h) - if err != nil { - return nil, err - } - - return p.objectAtOffset(offset, h) -} - -// GetByOffset retrieves the encoded object from the packfile at the given -// offset. -func (p *Packfile) GetByOffset(o int64) (plumbing.EncodedObject, error) { - hash, err := p.FindHash(o) - if err != nil { - return nil, err - } - - return p.objectAtOffset(o, hash) -} - -// GetSizeByOffset retrieves the size of the encoded object from the -// packfile with the given offset. -func (p *Packfile) GetSizeByOffset(o int64) (size int64, err error) { - if _, err := p.s.SeekFromStart(o); err != nil { - if err == io.EOF || isInvalid(err) { - return 0, plumbing.ErrObjectNotFound - } - - return 0, err - } - - h, err := p.nextObjectHeader() - if err != nil { - return 0, err - } - return p.getObjectSize(h) -} - -func (p *Packfile) objectHeaderAtOffset(offset int64) (*ObjectHeader, error) { - h, err := p.s.SeekObjectHeader(offset) - p.s.pendingObject = nil - return h, err -} - -func (p *Packfile) nextObjectHeader() (*ObjectHeader, error) { - h, err := p.s.NextObjectHeader() - p.s.pendingObject = nil - return h, err -} - -func (p *Packfile) getDeltaObjectSize(buf *bytes.Buffer) int64 { - delta := buf.Bytes() - _, delta = decodeLEB128(delta) // skip src size - sz, _ := decodeLEB128(delta) - return int64(sz) -} - -func (p *Packfile) getObjectSize(h *ObjectHeader) (int64, error) { - switch h.Type { - case plumbing.CommitObject, plumbing.TreeObject, plumbing.BlobObject, plumbing.TagObject: - return h.Length, nil - case plumbing.REFDeltaObject, plumbing.OFSDeltaObject: - buf := bufPool.Get().(*bytes.Buffer) - defer bufPool.Put(buf) - buf.Reset() - - if _, _, err := p.s.NextObject(buf); err != nil { - return 0, err - } - - return p.getDeltaObjectSize(buf), nil - default: - return 0, ErrInvalidObject.AddDetails("type %q", h.Type) - } -} - -func (p *Packfile) getObjectType(h *ObjectHeader) (typ plumbing.ObjectType, err error) { - switch h.Type { - case plumbing.CommitObject, plumbing.TreeObject, plumbing.BlobObject, plumbing.TagObject: - return h.Type, nil - case plumbing.REFDeltaObject, plumbing.OFSDeltaObject: - var offset int64 - if h.Type == plumbing.REFDeltaObject { - offset, err = p.FindOffset(h.Reference) - if err != nil { - return - } - } else { - offset = h.OffsetReference - } - - if baseType, ok := p.offsetToType[offset]; ok { - typ = baseType - } else { - h, err = p.objectHeaderAtOffset(offset) - if err != nil { - return - } - - typ, err = p.getObjectType(h) - if err != nil { - return - } - } - default: - err = ErrInvalidObject.AddDetails("type %q", h.Type) - } - - p.offsetToType[h.Offset] = typ - - return -} - -func (p *Packfile) objectAtOffset(offset int64, hash plumbing.Hash) (plumbing.EncodedObject, error) { - if obj, ok := p.cacheGet(hash); ok { - return obj, nil - } - - h, err := p.objectHeaderAtOffset(offset) - if err != nil { - if err == io.EOF || isInvalid(err) { - return nil, plumbing.ErrObjectNotFound - } - return nil, err - } - - return p.getNextObject(h, hash) -} - -func (p *Packfile) getNextObject(h *ObjectHeader, hash plumbing.Hash) (plumbing.EncodedObject, error) { - var err error - - // If we have no filesystem, we will return a MemoryObject instead - // of an FSObject. - if p.fs == nil { - return p.getNextMemoryObject(h) - } - - // If the object is small enough then read it completely into memory now since - // it is already read from disk into buffer anyway. For delta objects we want - // to perform the optimization too, but we have to be careful about applying - // small deltas on big objects. - var size int64 - if h.Length <= smallObjectThreshold { - if h.Type != plumbing.OFSDeltaObject && h.Type != plumbing.REFDeltaObject { - return p.getNextMemoryObject(h) - } - - // For delta objects we read the delta data and apply the small object - // optimization only if the expanded version of the object still meets - // the small object threshold condition. - buf := bufPool.Get().(*bytes.Buffer) - defer bufPool.Put(buf) - buf.Reset() - if _, _, err := p.s.NextObject(buf); err != nil { - return nil, err - } - - size = p.getDeltaObjectSize(buf) - if size <= smallObjectThreshold { - var obj = new(plumbing.MemoryObject) - obj.SetSize(size) - if h.Type == plumbing.REFDeltaObject { - err = p.fillREFDeltaObjectContentWithBuffer(obj, h.Reference, buf) - } else { - err = p.fillOFSDeltaObjectContentWithBuffer(obj, h.OffsetReference, buf) - } - return obj, err - } - } else { - size, err = p.getObjectSize(h) - if err != nil { - return nil, err - } - } - - typ, err := p.getObjectType(h) - if err != nil { - return nil, err - } - - p.offsetToType[h.Offset] = typ - - return NewFSObject( - hash, - typ, - h.Offset, - size, - p.Index, - p.fs, - p.file.Name(), - p.deltaBaseCache, - ), nil -} - -func (p *Packfile) getObjectContent(offset int64) (io.ReadCloser, error) { - h, err := p.objectHeaderAtOffset(offset) - if err != nil { - return nil, err - } - - // getObjectContent is called from FSObject, so we have to explicitly - // get memory object here to avoid recursive cycle - obj, err := p.getNextMemoryObject(h) - if err != nil { - return nil, err - } - - return obj.Reader() -} - -func (p *Packfile) getNextMemoryObject(h *ObjectHeader) (plumbing.EncodedObject, error) { - var obj = new(plumbing.MemoryObject) - obj.SetSize(h.Length) - obj.SetType(h.Type) - - var err error - switch h.Type { - case plumbing.CommitObject, plumbing.TreeObject, plumbing.BlobObject, plumbing.TagObject: - err = p.fillRegularObjectContent(obj) - case plumbing.REFDeltaObject: - err = p.fillREFDeltaObjectContent(obj, h.Reference) - case plumbing.OFSDeltaObject: - err = p.fillOFSDeltaObjectContent(obj, h.OffsetReference) - default: - err = ErrInvalidObject.AddDetails("type %q", h.Type) - } - - if err != nil { - return nil, err - } - - p.offsetToType[h.Offset] = obj.Type() - - return obj, nil -} - -func (p *Packfile) fillRegularObjectContent(obj plumbing.EncodedObject) (err error) { - w, err := obj.Writer() - if err != nil { - return err - } - - defer ioutil.CheckClose(w, &err) - - _, _, err = p.s.NextObject(w) - p.cachePut(obj) - - return err -} - -func (p *Packfile) fillREFDeltaObjectContent(obj plumbing.EncodedObject, ref plumbing.Hash) error { - buf := bufPool.Get().(*bytes.Buffer) - defer bufPool.Put(buf) - buf.Reset() - _, _, err := p.s.NextObject(buf) - if err != nil { - return err - } - - return p.fillREFDeltaObjectContentWithBuffer(obj, ref, buf) -} - -func (p *Packfile) fillREFDeltaObjectContentWithBuffer(obj plumbing.EncodedObject, ref plumbing.Hash, buf *bytes.Buffer) error { - var err error - - base, ok := p.cacheGet(ref) - if !ok { - base, err = p.Get(ref) - if err != nil { - return err - } - } - - obj.SetType(base.Type()) - err = ApplyDelta(obj, base, buf.Bytes()) - p.cachePut(obj) - - return err -} - -func (p *Packfile) fillOFSDeltaObjectContent(obj plumbing.EncodedObject, offset int64) error { - buf := bufPool.Get().(*bytes.Buffer) - defer bufPool.Put(buf) - buf.Reset() - _, _, err := p.s.NextObject(buf) - if err != nil { - return err - } - - return p.fillOFSDeltaObjectContentWithBuffer(obj, offset, buf) -} - -func (p *Packfile) fillOFSDeltaObjectContentWithBuffer(obj plumbing.EncodedObject, offset int64, buf *bytes.Buffer) error { - hash, err := p.FindHash(offset) - if err != nil { - return err - } - - base, err := p.objectAtOffset(offset, hash) - if err != nil { - return err - } - - obj.SetType(base.Type()) - err = ApplyDelta(obj, base, buf.Bytes()) - p.cachePut(obj) - - return err -} - -func (p *Packfile) cacheGet(h plumbing.Hash) (plumbing.EncodedObject, bool) { - if p.deltaBaseCache == nil { - return nil, false - } - - return p.deltaBaseCache.Get(h) -} - -func (p *Packfile) cachePut(obj plumbing.EncodedObject) { - if p.deltaBaseCache == nil { - return - } - - p.deltaBaseCache.Put(obj) -} - -// GetAll returns an iterator with all encoded objects in the packfile. -// The iterator returned is not thread-safe, it should be used in the same -// thread as the Packfile instance. -func (p *Packfile) GetAll() (storer.EncodedObjectIter, error) { - return p.GetByType(plumbing.AnyObject) -} - -// GetByType returns all the objects of the given type. -func (p *Packfile) GetByType(typ plumbing.ObjectType) (storer.EncodedObjectIter, error) { - switch typ { - case plumbing.AnyObject, - plumbing.BlobObject, - plumbing.TreeObject, - plumbing.CommitObject, - plumbing.TagObject: - entries, err := p.EntriesByOffset() - if err != nil { - return nil, err - } - - return &objectIter{ - // Easiest way to provide an object decoder is just to pass a Packfile - // instance. To not mess with the seeks, it's a new instance with a - // different scanner but the same cache and offset to hash map for - // reusing as much cache as possible. - p: p, - iter: entries, - typ: typ, - }, nil - default: - return nil, plumbing.ErrInvalidType - } -} - -// ID returns the ID of the packfile, which is the checksum at the end of it. -func (p *Packfile) ID() (plumbing.Hash, error) { - prev, err := p.file.Seek(-20, io.SeekEnd) - if err != nil { - return plumbing.ZeroHash, err - } - - var hash plumbing.Hash - if _, err := io.ReadFull(p.file, hash[:]); err != nil { - return plumbing.ZeroHash, err - } - - if _, err := p.file.Seek(prev, io.SeekStart); err != nil { - return plumbing.ZeroHash, err - } - - return hash, nil -} - -// Scanner returns the packfile's Scanner -func (p *Packfile) Scanner() *Scanner { - return p.s -} - -// Close the packfile and its resources. -func (p *Packfile) Close() error { - closer, ok := p.file.(io.Closer) - if !ok { - return nil - } - - return closer.Close() -} - -type objectIter struct { - p *Packfile - typ plumbing.ObjectType - iter idxfile.EntryIter -} - -func (i *objectIter) Next() (plumbing.EncodedObject, error) { - for { - e, err := i.iter.Next() - if err != nil { - return nil, err - } - - if i.typ != plumbing.AnyObject { - if typ, ok := i.p.offsetToType[int64(e.Offset)]; ok { - if typ != i.typ { - continue - } - } else if obj, ok := i.p.cacheGet(e.Hash); ok { - if obj.Type() != i.typ { - i.p.offsetToType[int64(e.Offset)] = obj.Type() - continue - } - return obj, nil - } else { - h, err := i.p.objectHeaderAtOffset(int64(e.Offset)) - if err != nil { - return nil, err - } - - if h.Type == plumbing.REFDeltaObject || h.Type == plumbing.OFSDeltaObject { - typ, err := i.p.getObjectType(h) - if err != nil { - return nil, err - } - if typ != i.typ { - i.p.offsetToType[int64(e.Offset)] = typ - continue - } - // getObjectType will seek in the file so we cannot use getNextObject safely - return i.p.objectAtOffset(int64(e.Offset), e.Hash) - } else { - if h.Type != i.typ { - i.p.offsetToType[int64(e.Offset)] = h.Type - continue - } - return i.p.getNextObject(h, e.Hash) - } - } - } - - obj, err := i.p.objectAtOffset(int64(e.Offset), e.Hash) - if err != nil { - return nil, err - } - - return obj, nil - } -} - -func (i *objectIter) ForEach(f func(plumbing.EncodedObject) error) error { - for { - o, err := i.Next() - if err != nil { - if err == io.EOF { - return nil - } - return err - } - - if err := f(o); err != nil { - return err - } - } -} - -func (i *objectIter) Close() { - i.iter.Close() -} - -// isInvalid checks whether an error is an os.PathError with an os.ErrInvalid -// error inside. It also checks for the windows error, which is different from -// os.ErrInvalid. -func isInvalid(err error) bool { - pe, ok := err.(*os.PathError) - if !ok { - return false - } - - errstr := pe.Err.Error() - return errstr == errInvalidUnix || errstr == errInvalidWindows -} - -// errInvalidWindows is the Windows equivalent to os.ErrInvalid -const errInvalidWindows = "The parameter is incorrect." - -var errInvalidUnix = os.ErrInvalid.Error() diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/parser.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/parser.go deleted file mode 100644 index 4b5a5708..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/parser.go +++ /dev/null @@ -1,495 +0,0 @@ -package packfile - -import ( - "bytes" - "errors" - "io" - stdioutil "io/ioutil" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/plumbing/cache" - "github.com/go-git/go-git/v5/plumbing/storer" - "github.com/go-git/go-git/v5/utils/ioutil" -) - -var ( - // ErrReferenceDeltaNotFound is returned when the reference delta is not - // found. - ErrReferenceDeltaNotFound = errors.New("reference delta not found") - - // ErrNotSeekableSource is returned when the source for the parser is not - // seekable and a storage was not provided, so it can't be parsed. - ErrNotSeekableSource = errors.New("parser source is not seekable and storage was not provided") - - // ErrDeltaNotCached is returned when the delta could not be found in cache. - ErrDeltaNotCached = errors.New("delta could not be found in cache") -) - -// Observer interface is implemented by index encoders. -type Observer interface { - // OnHeader is called when a new packfile is opened. - OnHeader(count uint32) error - // OnInflatedObjectHeader is called for each object header read. - OnInflatedObjectHeader(t plumbing.ObjectType, objSize int64, pos int64) error - // OnInflatedObjectContent is called for each decoded object. - OnInflatedObjectContent(h plumbing.Hash, pos int64, crc uint32, content []byte) error - // OnFooter is called when decoding is done. - OnFooter(h plumbing.Hash) error -} - -// Parser decodes a packfile and calls any observer associated to it. Is used -// to generate indexes. -type Parser struct { - storage storer.EncodedObjectStorer - scanner *Scanner - count uint32 - oi []*objectInfo - oiByHash map[plumbing.Hash]*objectInfo - oiByOffset map[int64]*objectInfo - hashOffset map[plumbing.Hash]int64 - checksum plumbing.Hash - - cache *cache.BufferLRU - // delta content by offset, only used if source is not seekable - deltas map[int64][]byte - - ob []Observer -} - -// NewParser creates a new Parser. The Scanner source must be seekable. -// If it's not, NewParserWithStorage should be used instead. -func NewParser(scanner *Scanner, ob ...Observer) (*Parser, error) { - return NewParserWithStorage(scanner, nil, ob...) -} - -// NewParserWithStorage creates a new Parser. The scanner source must either -// be seekable or a storage must be provided. -func NewParserWithStorage( - scanner *Scanner, - storage storer.EncodedObjectStorer, - ob ...Observer, -) (*Parser, error) { - if !scanner.IsSeekable && storage == nil { - return nil, ErrNotSeekableSource - } - - var deltas map[int64][]byte - if !scanner.IsSeekable { - deltas = make(map[int64][]byte) - } - - return &Parser{ - storage: storage, - scanner: scanner, - ob: ob, - count: 0, - cache: cache.NewBufferLRUDefault(), - deltas: deltas, - }, nil -} - -func (p *Parser) forEachObserver(f func(o Observer) error) error { - for _, o := range p.ob { - if err := f(o); err != nil { - return err - } - } - return nil -} - -func (p *Parser) onHeader(count uint32) error { - return p.forEachObserver(func(o Observer) error { - return o.OnHeader(count) - }) -} - -func (p *Parser) onInflatedObjectHeader( - t plumbing.ObjectType, - objSize int64, - pos int64, -) error { - return p.forEachObserver(func(o Observer) error { - return o.OnInflatedObjectHeader(t, objSize, pos) - }) -} - -func (p *Parser) onInflatedObjectContent( - h plumbing.Hash, - pos int64, - crc uint32, - content []byte, -) error { - return p.forEachObserver(func(o Observer) error { - return o.OnInflatedObjectContent(h, pos, crc, content) - }) -} - -func (p *Parser) onFooter(h plumbing.Hash) error { - return p.forEachObserver(func(o Observer) error { - return o.OnFooter(h) - }) -} - -// Parse start decoding phase of the packfile. -func (p *Parser) Parse() (plumbing.Hash, error) { - if err := p.init(); err != nil { - return plumbing.ZeroHash, err - } - - if err := p.indexObjects(); err != nil { - return plumbing.ZeroHash, err - } - - var err error - p.checksum, err = p.scanner.Checksum() - if err != nil && err != io.EOF { - return plumbing.ZeroHash, err - } - - if err := p.resolveDeltas(); err != nil { - return plumbing.ZeroHash, err - } - - if err := p.onFooter(p.checksum); err != nil { - return plumbing.ZeroHash, err - } - - return p.checksum, nil -} - -func (p *Parser) init() error { - _, c, err := p.scanner.Header() - if err != nil { - return err - } - - if err := p.onHeader(c); err != nil { - return err - } - - p.count = c - p.oiByHash = make(map[plumbing.Hash]*objectInfo, p.count) - p.oiByOffset = make(map[int64]*objectInfo, p.count) - p.oi = make([]*objectInfo, p.count) - - return nil -} - -func (p *Parser) indexObjects() error { - buf := new(bytes.Buffer) - - for i := uint32(0); i < p.count; i++ { - buf.Reset() - - oh, err := p.scanner.NextObjectHeader() - if err != nil { - return err - } - - delta := false - var ota *objectInfo - switch t := oh.Type; t { - case plumbing.OFSDeltaObject: - delta = true - - parent, ok := p.oiByOffset[oh.OffsetReference] - if !ok { - return plumbing.ErrObjectNotFound - } - - ota = newDeltaObject(oh.Offset, oh.Length, t, parent) - parent.Children = append(parent.Children, ota) - case plumbing.REFDeltaObject: - delta = true - parent, ok := p.oiByHash[oh.Reference] - if !ok { - // can't find referenced object in this pack file - // this must be a "thin" pack. - parent = &objectInfo{ //Placeholder parent - SHA1: oh.Reference, - ExternalRef: true, // mark as an external reference that must be resolved - Type: plumbing.AnyObject, - DiskType: plumbing.AnyObject, - } - p.oiByHash[oh.Reference] = parent - } - ota = newDeltaObject(oh.Offset, oh.Length, t, parent) - parent.Children = append(parent.Children, ota) - - default: - ota = newBaseObject(oh.Offset, oh.Length, t) - } - - _, crc, err := p.scanner.NextObject(buf) - if err != nil { - return err - } - - ota.Crc32 = crc - ota.Length = oh.Length - - data := buf.Bytes() - if !delta { - sha1, err := getSHA1(ota.Type, data) - if err != nil { - return err - } - - ota.SHA1 = sha1 - p.oiByHash[ota.SHA1] = ota - } - - if p.storage != nil && !delta { - obj := new(plumbing.MemoryObject) - obj.SetSize(oh.Length) - obj.SetType(oh.Type) - if _, err := obj.Write(data); err != nil { - return err - } - - if _, err := p.storage.SetEncodedObject(obj); err != nil { - return err - } - } - - if delta && !p.scanner.IsSeekable { - p.deltas[oh.Offset] = make([]byte, len(data)) - copy(p.deltas[oh.Offset], data) - } - - p.oiByOffset[oh.Offset] = ota - p.oi[i] = ota - } - - return nil -} - -func (p *Parser) resolveDeltas() error { - buf := &bytes.Buffer{} - for _, obj := range p.oi { - buf.Reset() - err := p.get(obj, buf) - if err != nil { - return err - } - content := buf.Bytes() - - if err := p.onInflatedObjectHeader(obj.Type, obj.Length, obj.Offset); err != nil { - return err - } - - if err := p.onInflatedObjectContent(obj.SHA1, obj.Offset, obj.Crc32, content); err != nil { - return err - } - - if !obj.IsDelta() && len(obj.Children) > 0 { - for _, child := range obj.Children { - if err := p.resolveObject(stdioutil.Discard, child, content); err != nil { - return err - } - } - - // Remove the delta from the cache. - if obj.DiskType.IsDelta() && !p.scanner.IsSeekable { - delete(p.deltas, obj.Offset) - } - } - } - - return nil -} - -func (p *Parser) get(o *objectInfo, buf *bytes.Buffer) (err error) { - if !o.ExternalRef { // skip cache check for placeholder parents - b, ok := p.cache.Get(o.Offset) - if ok { - _, err := buf.Write(b) - return err - } - } - - // If it's not on the cache and is not a delta we can try to find it in the - // storage, if there's one. External refs must enter here. - if p.storage != nil && !o.Type.IsDelta() { - var e plumbing.EncodedObject - e, err = p.storage.EncodedObject(plumbing.AnyObject, o.SHA1) - if err != nil { - return err - } - o.Type = e.Type() - - var r io.ReadCloser - r, err = e.Reader() - if err != nil { - return err - } - - defer ioutil.CheckClose(r, &err) - - _, err = buf.ReadFrom(io.LimitReader(r, e.Size())) - return err - } - - if o.ExternalRef { - // we were not able to resolve a ref in a thin pack - return ErrReferenceDeltaNotFound - } - - if o.DiskType.IsDelta() { - b := bufPool.Get().(*bytes.Buffer) - defer bufPool.Put(b) - b.Reset() - err := p.get(o.Parent, b) - if err != nil { - return err - } - base := b.Bytes() - - err = p.resolveObject(buf, o, base) - if err != nil { - return err - } - } else { - err := p.readData(buf, o) - if err != nil { - return err - } - } - - if len(o.Children) > 0 { - data := make([]byte, buf.Len()) - copy(data, buf.Bytes()) - p.cache.Put(o.Offset, data) - } - return nil -} - -func (p *Parser) resolveObject( - w io.Writer, - o *objectInfo, - base []byte, -) error { - if !o.DiskType.IsDelta() { - return nil - } - buf := bufPool.Get().(*bytes.Buffer) - defer bufPool.Put(buf) - buf.Reset() - err := p.readData(buf, o) - if err != nil { - return err - } - data := buf.Bytes() - - data, err = applyPatchBase(o, data, base) - if err != nil { - return err - } - - if p.storage != nil { - obj := new(plumbing.MemoryObject) - obj.SetSize(o.Size()) - obj.SetType(o.Type) - if _, err := obj.Write(data); err != nil { - return err - } - - if _, err := p.storage.SetEncodedObject(obj); err != nil { - return err - } - } - _, err = w.Write(data) - return err -} - -func (p *Parser) readData(w io.Writer, o *objectInfo) error { - if !p.scanner.IsSeekable && o.DiskType.IsDelta() { - data, ok := p.deltas[o.Offset] - if !ok { - return ErrDeltaNotCached - } - _, err := w.Write(data) - return err - } - - if _, err := p.scanner.SeekObjectHeader(o.Offset); err != nil { - return err - } - - if _, _, err := p.scanner.NextObject(w); err != nil { - return err - } - return nil -} - -func applyPatchBase(ota *objectInfo, data, base []byte) ([]byte, error) { - patched, err := PatchDelta(base, data) - if err != nil { - return nil, err - } - - if ota.SHA1 == plumbing.ZeroHash { - ota.Type = ota.Parent.Type - sha1, err := getSHA1(ota.Type, patched) - if err != nil { - return nil, err - } - - ota.SHA1 = sha1 - ota.Length = int64(len(patched)) - } - - return patched, nil -} - -func getSHA1(t plumbing.ObjectType, data []byte) (plumbing.Hash, error) { - hasher := plumbing.NewHasher(t, int64(len(data))) - if _, err := hasher.Write(data); err != nil { - return plumbing.ZeroHash, err - } - - return hasher.Sum(), nil -} - -type objectInfo struct { - Offset int64 - Length int64 - Type plumbing.ObjectType - DiskType plumbing.ObjectType - ExternalRef bool // indicates this is an external reference in a thin pack file - - Crc32 uint32 - - Parent *objectInfo - Children []*objectInfo - SHA1 plumbing.Hash -} - -func newBaseObject(offset, length int64, t plumbing.ObjectType) *objectInfo { - return newDeltaObject(offset, length, t, nil) -} - -func newDeltaObject( - offset, length int64, - t plumbing.ObjectType, - parent *objectInfo, -) *objectInfo { - obj := &objectInfo{ - Offset: offset, - Length: length, - Type: t, - DiskType: t, - Crc32: 0, - Parent: parent, - } - - return obj -} - -func (o *objectInfo) IsDelta() bool { - return o.Type.IsDelta() -} - -func (o *objectInfo) Size() int64 { - return o.Length -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/patch_delta.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/patch_delta.go deleted file mode 100644 index 9e90f30a..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/patch_delta.go +++ /dev/null @@ -1,252 +0,0 @@ -package packfile - -import ( - "bytes" - "errors" - "io" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/utils/ioutil" -) - -// See https://github.com/git/git/blob/49fa3dc76179e04b0833542fa52d0f287a4955ac/delta.h -// https://github.com/git/git/blob/c2c5f6b1e479f2c38e0e01345350620944e3527f/patch-delta.c, -// and https://github.com/tarruda/node-git-core/blob/master/src/js/delta.js -// for details about the delta format. - -const deltaSizeMin = 4 - -// ApplyDelta writes to target the result of applying the modification deltas in delta to base. -func ApplyDelta(target, base plumbing.EncodedObject, delta []byte) (err error) { - r, err := base.Reader() - if err != nil { - return err - } - - defer ioutil.CheckClose(r, &err) - - w, err := target.Writer() - if err != nil { - return err - } - - defer ioutil.CheckClose(w, &err) - - buf := bufPool.Get().(*bytes.Buffer) - defer bufPool.Put(buf) - buf.Reset() - _, err = buf.ReadFrom(r) - if err != nil { - return err - } - src := buf.Bytes() - - dst := bufPool.Get().(*bytes.Buffer) - defer bufPool.Put(dst) - dst.Reset() - err = patchDelta(dst, src, delta) - if err != nil { - return err - } - - target.SetSize(int64(dst.Len())) - - b := byteSlicePool.Get().([]byte) - _, err = io.CopyBuffer(w, dst, b) - byteSlicePool.Put(b) - return err -} - -var ( - ErrInvalidDelta = errors.New("invalid delta") - ErrDeltaCmd = errors.New("wrong delta command") -) - -// PatchDelta returns the result of applying the modification deltas in delta to src. -// An error will be returned if delta is corrupted (ErrDeltaLen) or an action command -// is not copy from source or copy from delta (ErrDeltaCmd). -func PatchDelta(src, delta []byte) ([]byte, error) { - b := &bytes.Buffer{} - if err := patchDelta(b, src, delta); err != nil { - return nil, err - } - return b.Bytes(), nil -} - -func patchDelta(dst *bytes.Buffer, src, delta []byte) error { - if len(delta) < deltaSizeMin { - return ErrInvalidDelta - } - - srcSz, delta := decodeLEB128(delta) - if srcSz != uint(len(src)) { - return ErrInvalidDelta - } - - targetSz, delta := decodeLEB128(delta) - remainingTargetSz := targetSz - - var cmd byte - dst.Grow(int(targetSz)) - for { - if len(delta) == 0 { - return ErrInvalidDelta - } - - cmd = delta[0] - delta = delta[1:] - if isCopyFromSrc(cmd) { - var offset, sz uint - var err error - offset, delta, err = decodeOffset(cmd, delta) - if err != nil { - return err - } - - sz, delta, err = decodeSize(cmd, delta) - if err != nil { - return err - } - - if invalidSize(sz, targetSz) || - invalidOffsetSize(offset, sz, srcSz) { - break - } - dst.Write(src[offset : offset+sz]) - remainingTargetSz -= sz - } else if isCopyFromDelta(cmd) { - sz := uint(cmd) // cmd is the size itself - if invalidSize(sz, targetSz) { - return ErrInvalidDelta - } - - if uint(len(delta)) < sz { - return ErrInvalidDelta - } - - dst.Write(delta[0:sz]) - remainingTargetSz -= sz - delta = delta[sz:] - } else { - return ErrDeltaCmd - } - - if remainingTargetSz <= 0 { - break - } - } - - return nil -} - -// Decodes a number encoded as an unsigned LEB128 at the start of some -// binary data and returns the decoded number and the rest of the -// stream. -// -// This must be called twice on the delta data buffer, first to get the -// expected source buffer size, and again to get the target buffer size. -func decodeLEB128(input []byte) (uint, []byte) { - var num, sz uint - var b byte - for { - b = input[sz] - num |= (uint(b) & payload) << (sz * 7) // concats 7 bits chunks - sz++ - - if uint(b)&continuation == 0 || sz == uint(len(input)) { - break - } - } - - return num, input[sz:] -} - -const ( - payload = 0x7f // 0111 1111 - continuation = 0x80 // 1000 0000 -) - -func isCopyFromSrc(cmd byte) bool { - return (cmd & 0x80) != 0 -} - -func isCopyFromDelta(cmd byte) bool { - return (cmd&0x80) == 0 && cmd != 0 -} - -func decodeOffset(cmd byte, delta []byte) (uint, []byte, error) { - var offset uint - if (cmd & 0x01) != 0 { - if len(delta) == 0 { - return 0, nil, ErrInvalidDelta - } - offset = uint(delta[0]) - delta = delta[1:] - } - if (cmd & 0x02) != 0 { - if len(delta) == 0 { - return 0, nil, ErrInvalidDelta - } - offset |= uint(delta[0]) << 8 - delta = delta[1:] - } - if (cmd & 0x04) != 0 { - if len(delta) == 0 { - return 0, nil, ErrInvalidDelta - } - offset |= uint(delta[0]) << 16 - delta = delta[1:] - } - if (cmd & 0x08) != 0 { - if len(delta) == 0 { - return 0, nil, ErrInvalidDelta - } - offset |= uint(delta[0]) << 24 - delta = delta[1:] - } - - return offset, delta, nil -} - -func decodeSize(cmd byte, delta []byte) (uint, []byte, error) { - var sz uint - if (cmd & 0x10) != 0 { - if len(delta) == 0 { - return 0, nil, ErrInvalidDelta - } - sz = uint(delta[0]) - delta = delta[1:] - } - if (cmd & 0x20) != 0 { - if len(delta) == 0 { - return 0, nil, ErrInvalidDelta - } - sz |= uint(delta[0]) << 8 - delta = delta[1:] - } - if (cmd & 0x40) != 0 { - if len(delta) == 0 { - return 0, nil, ErrInvalidDelta - } - sz |= uint(delta[0]) << 16 - delta = delta[1:] - } - if sz == 0 { - sz = 0x10000 - } - - return sz, delta, nil -} - -func invalidSize(sz, targetSz uint) bool { - return sz > targetSz -} - -func invalidOffsetSize(offset, sz, srcSz uint) bool { - return sumOverflows(offset, sz) || - offset+sz > srcSz -} - -func sumOverflows(a, b uint) bool { - return a+b < a -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/scanner.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/scanner.go deleted file mode 100644 index 6e6a6878..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/packfile/scanner.go +++ /dev/null @@ -1,466 +0,0 @@ -package packfile - -import ( - "bufio" - "bytes" - "compress/zlib" - "fmt" - "hash" - "hash/crc32" - "io" - stdioutil "io/ioutil" - "sync" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/utils/binary" - "github.com/go-git/go-git/v5/utils/ioutil" -) - -var ( - // ErrEmptyPackfile is returned by ReadHeader when no data is found in the packfile - ErrEmptyPackfile = NewError("empty packfile") - // ErrBadSignature is returned by ReadHeader when the signature in the packfile is incorrect. - ErrBadSignature = NewError("malformed pack file signature") - // ErrUnsupportedVersion is returned by ReadHeader when the packfile version is - // different than VersionSupported. - ErrUnsupportedVersion = NewError("unsupported packfile version") - // ErrSeekNotSupported returned if seek is not support - ErrSeekNotSupported = NewError("not seek support") -) - -// ObjectHeader contains the information related to the object, this information -// is collected from the previous bytes to the content of the object. -type ObjectHeader struct { - Type plumbing.ObjectType - Offset int64 - Length int64 - Reference plumbing.Hash - OffsetReference int64 -} - -type Scanner struct { - r *scannerReader - crc hash.Hash32 - - // pendingObject is used to detect if an object has been read, or still - // is waiting to be read - pendingObject *ObjectHeader - version, objects uint32 - - // lsSeekable says if this scanner can do Seek or not, to have a Scanner - // seekable a r implementing io.Seeker is required - IsSeekable bool -} - -// NewScanner returns a new Scanner based on a reader, if the given reader -// implements io.ReadSeeker the Scanner will be also Seekable -func NewScanner(r io.Reader) *Scanner { - _, ok := r.(io.ReadSeeker) - - crc := crc32.NewIEEE() - return &Scanner{ - r: newScannerReader(r, crc), - crc: crc, - IsSeekable: ok, - } -} - -func (s *Scanner) Reset(r io.Reader) { - _, ok := r.(io.ReadSeeker) - - s.r.Reset(r) - s.crc.Reset() - s.IsSeekable = ok - s.pendingObject = nil - s.version = 0 - s.objects = 0 -} - -// Header reads the whole packfile header (signature, version and object count). -// It returns the version and the object count and performs checks on the -// validity of the signature and the version fields. -func (s *Scanner) Header() (version, objects uint32, err error) { - if s.version != 0 { - return s.version, s.objects, nil - } - - sig, err := s.readSignature() - if err != nil { - if err == io.EOF { - err = ErrEmptyPackfile - } - - return - } - - if !s.isValidSignature(sig) { - err = ErrBadSignature - return - } - - version, err = s.readVersion() - s.version = version - if err != nil { - return - } - - if !s.isSupportedVersion(version) { - err = ErrUnsupportedVersion.AddDetails("%d", version) - return - } - - objects, err = s.readCount() - s.objects = objects - return -} - -// readSignature reads an returns the signature field in the packfile. -func (s *Scanner) readSignature() ([]byte, error) { - var sig = make([]byte, 4) - if _, err := io.ReadFull(s.r, sig); err != nil { - return []byte{}, err - } - - return sig, nil -} - -// isValidSignature returns if sig is a valid packfile signature. -func (s *Scanner) isValidSignature(sig []byte) bool { - return bytes.Equal(sig, signature) -} - -// readVersion reads and returns the version field of a packfile. -func (s *Scanner) readVersion() (uint32, error) { - return binary.ReadUint32(s.r) -} - -// isSupportedVersion returns whether version v is supported by the parser. -// The current supported version is VersionSupported, defined above. -func (s *Scanner) isSupportedVersion(v uint32) bool { - return v == VersionSupported -} - -// readCount reads and returns the count of objects field of a packfile. -func (s *Scanner) readCount() (uint32, error) { - return binary.ReadUint32(s.r) -} - -// SeekObjectHeader seeks to specified offset and returns the ObjectHeader -// for the next object in the reader -func (s *Scanner) SeekObjectHeader(offset int64) (*ObjectHeader, error) { - // if seeking we assume that you are not interested in the header - if s.version == 0 { - s.version = VersionSupported - } - - if _, err := s.r.Seek(offset, io.SeekStart); err != nil { - return nil, err - } - - h, err := s.nextObjectHeader() - if err != nil { - return nil, err - } - - h.Offset = offset - return h, nil -} - -// NextObjectHeader returns the ObjectHeader for the next object in the reader -func (s *Scanner) NextObjectHeader() (*ObjectHeader, error) { - if err := s.doPending(); err != nil { - return nil, err - } - - offset, err := s.r.Seek(0, io.SeekCurrent) - if err != nil { - return nil, err - } - - h, err := s.nextObjectHeader() - if err != nil { - return nil, err - } - - h.Offset = offset - return h, nil -} - -// nextObjectHeader returns the ObjectHeader for the next object in the reader -// without the Offset field -func (s *Scanner) nextObjectHeader() (*ObjectHeader, error) { - s.r.Flush() - s.crc.Reset() - - h := &ObjectHeader{} - s.pendingObject = h - - var err error - h.Offset, err = s.r.Seek(0, io.SeekCurrent) - if err != nil { - return nil, err - } - - h.Type, h.Length, err = s.readObjectTypeAndLength() - if err != nil { - return nil, err - } - - switch h.Type { - case plumbing.OFSDeltaObject: - no, err := binary.ReadVariableWidthInt(s.r) - if err != nil { - return nil, err - } - - h.OffsetReference = h.Offset - no - case plumbing.REFDeltaObject: - var err error - h.Reference, err = binary.ReadHash(s.r) - if err != nil { - return nil, err - } - } - - return h, nil -} - -func (s *Scanner) doPending() error { - if s.version == 0 { - var err error - s.version, s.objects, err = s.Header() - if err != nil { - return err - } - } - - return s.discardObjectIfNeeded() -} - -func (s *Scanner) discardObjectIfNeeded() error { - if s.pendingObject == nil { - return nil - } - - h := s.pendingObject - n, _, err := s.NextObject(stdioutil.Discard) - if err != nil { - return err - } - - if n != h.Length { - return fmt.Errorf( - "error discarding object, discarded %d, expected %d", - n, h.Length, - ) - } - - return nil -} - -// ReadObjectTypeAndLength reads and returns the object type and the -// length field from an object entry in a packfile. -func (s *Scanner) readObjectTypeAndLength() (plumbing.ObjectType, int64, error) { - t, c, err := s.readType() - if err != nil { - return t, 0, err - } - - l, err := s.readLength(c) - - return t, l, err -} - -func (s *Scanner) readType() (plumbing.ObjectType, byte, error) { - var c byte - var err error - if c, err = s.r.ReadByte(); err != nil { - return plumbing.ObjectType(0), 0, err - } - - typ := parseType(c) - - return typ, c, nil -} - -func parseType(b byte) plumbing.ObjectType { - return plumbing.ObjectType((b & maskType) >> firstLengthBits) -} - -// the length is codified in the last 4 bits of the first byte and in -// the last 7 bits of subsequent bytes. Last byte has a 0 MSB. -func (s *Scanner) readLength(first byte) (int64, error) { - length := int64(first & maskFirstLength) - - c := first - shift := firstLengthBits - var err error - for c&maskContinue > 0 { - if c, err = s.r.ReadByte(); err != nil { - return 0, err - } - - length += int64(c&maskLength) << shift - shift += lengthBits - } - - return length, nil -} - -// NextObject writes the content of the next object into the reader, returns -// the number of bytes written, the CRC32 of the content and an error, if any -func (s *Scanner) NextObject(w io.Writer) (written int64, crc32 uint32, err error) { - s.pendingObject = nil - written, err = s.copyObject(w) - - s.r.Flush() - crc32 = s.crc.Sum32() - s.crc.Reset() - - return -} - -// ReadRegularObject reads and write a non-deltified object -// from it zlib stream in an object entry in the packfile. -func (s *Scanner) copyObject(w io.Writer) (n int64, err error) { - zr := zlibReaderPool.Get().(io.ReadCloser) - defer zlibReaderPool.Put(zr) - - if err = zr.(zlib.Resetter).Reset(s.r, nil); err != nil { - return 0, fmt.Errorf("zlib reset error: %s", err) - } - - defer ioutil.CheckClose(zr, &err) - buf := byteSlicePool.Get().([]byte) - n, err = io.CopyBuffer(w, zr, buf) - byteSlicePool.Put(buf) - return -} - -var byteSlicePool = sync.Pool{ - New: func() interface{} { - return make([]byte, 32*1024) - }, -} - -// SeekFromStart sets a new offset from start, returns the old position before -// the change. -func (s *Scanner) SeekFromStart(offset int64) (previous int64, err error) { - // if seeking we assume that you are not interested in the header - if s.version == 0 { - s.version = VersionSupported - } - - previous, err = s.r.Seek(0, io.SeekCurrent) - if err != nil { - return -1, err - } - - _, err = s.r.Seek(offset, io.SeekStart) - return previous, err -} - -// Checksum returns the checksum of the packfile -func (s *Scanner) Checksum() (plumbing.Hash, error) { - err := s.discardObjectIfNeeded() - if err != nil { - return plumbing.ZeroHash, err - } - - return binary.ReadHash(s.r) -} - -// Close reads the reader until io.EOF -func (s *Scanner) Close() error { - buf := byteSlicePool.Get().([]byte) - _, err := io.CopyBuffer(stdioutil.Discard, s.r, buf) - byteSlicePool.Put(buf) - return err -} - -// Flush is a no-op (deprecated) -func (s *Scanner) Flush() error { - return nil -} - -// scannerReader has the following characteristics: -// - Provides an io.SeekReader impl for bufio.Reader, when the underlying -// reader supports it. -// - Keeps track of the current read position, for when the underlying reader -// isn't an io.SeekReader, but we still want to know the current offset. -// - Writes to the hash writer what it reads, with the aid of a smaller buffer. -// The buffer helps avoid a performance penality for performing small writes -// to the crc32 hash writer. -type scannerReader struct { - reader io.Reader - crc io.Writer - rbuf *bufio.Reader - wbuf *bufio.Writer - offset int64 -} - -func newScannerReader(r io.Reader, h io.Writer) *scannerReader { - sr := &scannerReader{ - rbuf: bufio.NewReader(nil), - wbuf: bufio.NewWriterSize(nil, 64), - crc: h, - } - sr.Reset(r) - - return sr -} - -func (r *scannerReader) Reset(reader io.Reader) { - r.reader = reader - r.rbuf.Reset(r.reader) - r.wbuf.Reset(r.crc) - - r.offset = 0 - if seeker, ok := r.reader.(io.ReadSeeker); ok { - r.offset, _ = seeker.Seek(0, io.SeekCurrent) - } -} - -func (r *scannerReader) Read(p []byte) (n int, err error) { - n, err = r.rbuf.Read(p) - - r.offset += int64(n) - if _, err := r.wbuf.Write(p[:n]); err != nil { - return n, err - } - return -} - -func (r *scannerReader) ReadByte() (b byte, err error) { - b, err = r.rbuf.ReadByte() - if err == nil { - r.offset++ - return b, r.wbuf.WriteByte(b) - } - return -} - -func (r *scannerReader) Flush() error { - return r.wbuf.Flush() -} - -// Seek seeks to a location. If the underlying reader is not an io.ReadSeeker, -// then only whence=io.SeekCurrent is supported, any other operation fails. -func (r *scannerReader) Seek(offset int64, whence int) (int64, error) { - var err error - - if seeker, ok := r.reader.(io.ReadSeeker); !ok { - if whence != io.SeekCurrent || offset != 0 { - return -1, ErrSeekNotSupported - } - } else { - if whence == io.SeekCurrent && offset == 0 { - return r.offset, nil - } - - r.offset, err = seeker.Seek(offset, whence) - r.rbuf.Reset(r.reader) - } - - return r.offset, err -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/pktline/encoder.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/pktline/encoder.go deleted file mode 100644 index 6d409795..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/pktline/encoder.go +++ /dev/null @@ -1,122 +0,0 @@ -// Package pktline implements reading payloads form pkt-lines and encoding -// pkt-lines from payloads. -package pktline - -import ( - "bytes" - "errors" - "fmt" - "io" -) - -// An Encoder writes pkt-lines to an output stream. -type Encoder struct { - w io.Writer -} - -const ( - // MaxPayloadSize is the maximum payload size of a pkt-line in bytes. - MaxPayloadSize = 65516 - - // For compatibility with canonical Git implementation, accept longer pkt-lines - OversizePayloadMax = 65520 -) - -var ( - // FlushPkt are the contents of a flush-pkt pkt-line. - FlushPkt = []byte{'0', '0', '0', '0'} - // Flush is the payload to use with the Encode method to encode a flush-pkt. - Flush = []byte{} - // FlushString is the payload to use with the EncodeString method to encode a flush-pkt. - FlushString = "" - // ErrPayloadTooLong is returned by the Encode methods when any of the - // provided payloads is bigger than MaxPayloadSize. - ErrPayloadTooLong = errors.New("payload is too long") -) - -// NewEncoder returns a new encoder that writes to w. -func NewEncoder(w io.Writer) *Encoder { - return &Encoder{ - w: w, - } -} - -// Flush encodes a flush-pkt to the output stream. -func (e *Encoder) Flush() error { - _, err := e.w.Write(FlushPkt) - return err -} - -// Encode encodes a pkt-line with the payload specified and write it to -// the output stream. If several payloads are specified, each of them -// will get streamed in their own pkt-lines. -func (e *Encoder) Encode(payloads ...[]byte) error { - for _, p := range payloads { - if err := e.encodeLine(p); err != nil { - return err - } - } - - return nil -} - -func (e *Encoder) encodeLine(p []byte) error { - if len(p) > MaxPayloadSize { - return ErrPayloadTooLong - } - - if bytes.Equal(p, Flush) { - return e.Flush() - } - - n := len(p) + 4 - if _, err := e.w.Write(asciiHex16(n)); err != nil { - return err - } - _, err := e.w.Write(p) - return err -} - -// Returns the hexadecimal ascii representation of the 16 less -// significant bits of n. The length of the returned slice will always -// be 4. Example: if n is 1234 (0x4d2), the return value will be -// []byte{'0', '4', 'd', '2'}. -func asciiHex16(n int) []byte { - var ret [4]byte - ret[0] = byteToASCIIHex(byte(n & 0xf000 >> 12)) - ret[1] = byteToASCIIHex(byte(n & 0x0f00 >> 8)) - ret[2] = byteToASCIIHex(byte(n & 0x00f0 >> 4)) - ret[3] = byteToASCIIHex(byte(n & 0x000f)) - - return ret[:] -} - -// turns a byte into its hexadecimal ascii representation. Example: -// from 11 (0xb) to 'b'. -func byteToASCIIHex(n byte) byte { - if n < 10 { - return '0' + n - } - - return 'a' - 10 + n -} - -// EncodeString works similarly as Encode but payloads are specified as strings. -func (e *Encoder) EncodeString(payloads ...string) error { - for _, p := range payloads { - if err := e.Encode([]byte(p)); err != nil { - return err - } - } - - return nil -} - -// Encodef encodes a single pkt-line with the payload formatted as -// the format specifier. The rest of the arguments will be used in -// the format string. -func (e *Encoder) Encodef(format string, a ...interface{}) error { - return e.EncodeString( - fmt.Sprintf(format, a...), - ) -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/format/pktline/scanner.go b/vendor/github.com/go-git/go-git/v5/plumbing/format/pktline/scanner.go deleted file mode 100644 index 99aab46e..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/format/pktline/scanner.go +++ /dev/null @@ -1,134 +0,0 @@ -package pktline - -import ( - "errors" - "io" -) - -const ( - lenSize = 4 -) - -// ErrInvalidPktLen is returned by Err() when an invalid pkt-len is found. -var ErrInvalidPktLen = errors.New("invalid pkt-len found") - -// Scanner provides a convenient interface for reading the payloads of a -// series of pkt-lines. It takes an io.Reader providing the source, -// which then can be tokenized through repeated calls to the Scan -// method. -// -// After each Scan call, the Bytes method will return the payload of the -// corresponding pkt-line on a shared buffer, which will be 65516 bytes -// or smaller. Flush pkt-lines are represented by empty byte slices. -// -// Scanning stops at EOF or the first I/O error. -type Scanner struct { - r io.Reader // The reader provided by the client - err error // Sticky error - payload []byte // Last pkt-payload - len [lenSize]byte // Last pkt-len -} - -// NewScanner returns a new Scanner to read from r. -func NewScanner(r io.Reader) *Scanner { - return &Scanner{ - r: r, - } -} - -// Err returns the first error encountered by the Scanner. -func (s *Scanner) Err() error { - return s.err -} - -// Scan advances the Scanner to the next pkt-line, whose payload will -// then be available through the Bytes method. Scanning stops at EOF -// or the first I/O error. After Scan returns false, the Err method -// will return any error that occurred during scanning, except that if -// it was io.EOF, Err will return nil. -func (s *Scanner) Scan() bool { - var l int - l, s.err = s.readPayloadLen() - if s.err == io.EOF { - s.err = nil - return false - } - if s.err != nil { - return false - } - - if cap(s.payload) < l { - s.payload = make([]byte, 0, l) - } - - if _, s.err = io.ReadFull(s.r, s.payload[:l]); s.err != nil { - return false - } - s.payload = s.payload[:l] - - return true -} - -// Bytes returns the most recent payload generated by a call to Scan. -// The underlying array may point to data that will be overwritten by a -// subsequent call to Scan. It does no allocation. -func (s *Scanner) Bytes() []byte { - return s.payload -} - -// Method readPayloadLen returns the payload length by reading the -// pkt-len and subtracting the pkt-len size. -func (s *Scanner) readPayloadLen() (int, error) { - if _, err := io.ReadFull(s.r, s.len[:]); err != nil { - if err == io.ErrUnexpectedEOF { - return 0, ErrInvalidPktLen - } - - return 0, err - } - - n, err := hexDecode(s.len) - if err != nil { - return 0, err - } - - switch { - case n == 0: - return 0, nil - case n <= lenSize: - return 0, ErrInvalidPktLen - case n > OversizePayloadMax+lenSize: - return 0, ErrInvalidPktLen - default: - return n - lenSize, nil - } -} - -// Turns the hexadecimal representation of a number in a byte slice into -// a number. This function substitute strconv.ParseUint(string(buf), 16, -// 16) and/or hex.Decode, to avoid generating new strings, thus helping the -// GC. -func hexDecode(buf [lenSize]byte) (int, error) { - var ret int - for i := 0; i < lenSize; i++ { - n, err := asciiHexToByte(buf[i]) - if err != nil { - return 0, ErrInvalidPktLen - } - ret = 16*ret + int(n) - } - return ret, nil -} - -// turns the hexadecimal ascii representation of a byte into its -// numerical value. Example: from 'b' to 11 (0xb). -func asciiHexToByte(b byte) (byte, error) { - switch { - case b >= '0' && b <= '9': - return b - '0', nil - case b >= 'a' && b <= 'f': - return b - 'a' + 10, nil - default: - return 0, ErrInvalidPktLen - } -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/hash.go b/vendor/github.com/go-git/go-git/v5/plumbing/hash.go deleted file mode 100644 index afc602a9..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/hash.go +++ /dev/null @@ -1,83 +0,0 @@ -package plumbing - -import ( - "bytes" - "crypto/sha1" - "encoding/hex" - "hash" - "sort" - "strconv" -) - -// Hash SHA1 hashed content -type Hash [20]byte - -// ZeroHash is Hash with value zero -var ZeroHash Hash - -// ComputeHash compute the hash for a given ObjectType and content -func ComputeHash(t ObjectType, content []byte) Hash { - h := NewHasher(t, int64(len(content))) - h.Write(content) - return h.Sum() -} - -// NewHash return a new Hash from a hexadecimal hash representation -func NewHash(s string) Hash { - b, _ := hex.DecodeString(s) - - var h Hash - copy(h[:], b) - - return h -} - -func (h Hash) IsZero() bool { - var empty Hash - return h == empty -} - -func (h Hash) String() string { - return hex.EncodeToString(h[:]) -} - -type Hasher struct { - hash.Hash -} - -func NewHasher(t ObjectType, size int64) Hasher { - h := Hasher{sha1.New()} - h.Write(t.Bytes()) - h.Write([]byte(" ")) - h.Write([]byte(strconv.FormatInt(size, 10))) - h.Write([]byte{0}) - return h -} - -func (h Hasher) Sum() (hash Hash) { - copy(hash[:], h.Hash.Sum(nil)) - return -} - -// HashesSort sorts a slice of Hashes in increasing order. -func HashesSort(a []Hash) { - sort.Sort(HashSlice(a)) -} - -// HashSlice attaches the methods of sort.Interface to []Hash, sorting in -// increasing order. -type HashSlice []Hash - -func (p HashSlice) Len() int { return len(p) } -func (p HashSlice) Less(i, j int) bool { return bytes.Compare(p[i][:], p[j][:]) < 0 } -func (p HashSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] } - -// IsHash returns true if the given string is a valid hash. -func IsHash(s string) bool { - if len(s) != 40 { - return false - } - - _, err := hex.DecodeString(s) - return err == nil -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/memory.go b/vendor/github.com/go-git/go-git/v5/plumbing/memory.go deleted file mode 100644 index 21337cc0..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/memory.go +++ /dev/null @@ -1,72 +0,0 @@ -package plumbing - -import ( - "bytes" - "io" -) - -// MemoryObject on memory Object implementation -type MemoryObject struct { - t ObjectType - h Hash - cont []byte - sz int64 -} - -// Hash returns the object Hash, the hash is calculated on-the-fly the first -// time it's called, in all subsequent calls the same Hash is returned even -// if the type or the content have changed. The Hash is only generated if the -// size of the content is exactly the object size. -func (o *MemoryObject) Hash() Hash { - if o.h == ZeroHash && int64(len(o.cont)) == o.sz { - o.h = ComputeHash(o.t, o.cont) - } - - return o.h -} - -// Type return the ObjectType -func (o *MemoryObject) Type() ObjectType { return o.t } - -// SetType sets the ObjectType -func (o *MemoryObject) SetType(t ObjectType) { o.t = t } - -// Size return the size of the object -func (o *MemoryObject) Size() int64 { return o.sz } - -// SetSize set the object size, a content of the given size should be written -// afterwards -func (o *MemoryObject) SetSize(s int64) { o.sz = s } - -// Reader returns an io.ReadCloser used to read the object's content. -// -// For a MemoryObject, this reader is seekable. -func (o *MemoryObject) Reader() (io.ReadCloser, error) { - return nopCloser{bytes.NewReader(o.cont)}, nil -} - -// Writer returns a ObjectWriter used to write the object's content. -func (o *MemoryObject) Writer() (io.WriteCloser, error) { - return o, nil -} - -func (o *MemoryObject) Write(p []byte) (n int, err error) { - o.cont = append(o.cont, p...) - o.sz = int64(len(o.cont)) - - return len(p), nil -} - -// Close releases any resources consumed by the object when it is acting as a -// ObjectWriter. -func (o *MemoryObject) Close() error { return nil } - -// nopCloser exposes the extra methods of bytes.Reader while nopping Close(). -// -// This allows clients to attempt seeking in a cached Blob's Reader. -type nopCloser struct { - *bytes.Reader -} - -// Close does nothing. -func (nc nopCloser) Close() error { return nil } diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/object.go b/vendor/github.com/go-git/go-git/v5/plumbing/object.go deleted file mode 100644 index 2655dee4..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/object.go +++ /dev/null @@ -1,111 +0,0 @@ -// package plumbing implement the core interfaces and structs used by go-git -package plumbing - -import ( - "errors" - "io" -) - -var ( - ErrObjectNotFound = errors.New("object not found") - // ErrInvalidType is returned when an invalid object type is provided. - ErrInvalidType = errors.New("invalid object type") -) - -// Object is a generic representation of any git object -type EncodedObject interface { - Hash() Hash - Type() ObjectType - SetType(ObjectType) - Size() int64 - SetSize(int64) - Reader() (io.ReadCloser, error) - Writer() (io.WriteCloser, error) -} - -// DeltaObject is an EncodedObject representing a delta. -type DeltaObject interface { - EncodedObject - // BaseHash returns the hash of the object used as base for this delta. - BaseHash() Hash - // ActualHash returns the hash of the object after applying the delta. - ActualHash() Hash - // Size returns the size of the object after applying the delta. - ActualSize() int64 -} - -// ObjectType internal object type -// Integer values from 0 to 7 map to those exposed by git. -// AnyObject is used to represent any from 0 to 7. -type ObjectType int8 - -const ( - InvalidObject ObjectType = 0 - CommitObject ObjectType = 1 - TreeObject ObjectType = 2 - BlobObject ObjectType = 3 - TagObject ObjectType = 4 - // 5 reserved for future expansion - OFSDeltaObject ObjectType = 6 - REFDeltaObject ObjectType = 7 - - AnyObject ObjectType = -127 -) - -func (t ObjectType) String() string { - switch t { - case CommitObject: - return "commit" - case TreeObject: - return "tree" - case BlobObject: - return "blob" - case TagObject: - return "tag" - case OFSDeltaObject: - return "ofs-delta" - case REFDeltaObject: - return "ref-delta" - case AnyObject: - return "any" - default: - return "unknown" - } -} - -func (t ObjectType) Bytes() []byte { - return []byte(t.String()) -} - -// Valid returns true if t is a valid ObjectType. -func (t ObjectType) Valid() bool { - return t >= CommitObject && t <= REFDeltaObject -} - -// IsDelta returns true for any ObjectTyoe that represents a delta (i.e. -// REFDeltaObject or OFSDeltaObject). -func (t ObjectType) IsDelta() bool { - return t == REFDeltaObject || t == OFSDeltaObject -} - -// ParseObjectType parses a string representation of ObjectType. It returns an -// error on parse failure. -func ParseObjectType(value string) (typ ObjectType, err error) { - switch value { - case "commit": - typ = CommitObject - case "tree": - typ = TreeObject - case "blob": - typ = BlobObject - case "tag": - typ = TagObject - case "ofs-delta": - typ = OFSDeltaObject - case "ref-delta": - typ = REFDeltaObject - default: - err = ErrInvalidType - } - return -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/object/blob.go b/vendor/github.com/go-git/go-git/v5/plumbing/object/blob.go deleted file mode 100644 index 8fb7576f..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/object/blob.go +++ /dev/null @@ -1,144 +0,0 @@ -package object - -import ( - "io" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/plumbing/storer" - "github.com/go-git/go-git/v5/utils/ioutil" -) - -// Blob is used to store arbitrary data - it is generally a file. -type Blob struct { - // Hash of the blob. - Hash plumbing.Hash - // Size of the (uncompressed) blob. - Size int64 - - obj plumbing.EncodedObject -} - -// GetBlob gets a blob from an object storer and decodes it. -func GetBlob(s storer.EncodedObjectStorer, h plumbing.Hash) (*Blob, error) { - o, err := s.EncodedObject(plumbing.BlobObject, h) - if err != nil { - return nil, err - } - - return DecodeBlob(o) -} - -// DecodeObject decodes an encoded object into a *Blob. -func DecodeBlob(o plumbing.EncodedObject) (*Blob, error) { - b := &Blob{} - if err := b.Decode(o); err != nil { - return nil, err - } - - return b, nil -} - -// ID returns the object ID of the blob. The returned value will always match -// the current value of Blob.Hash. -// -// ID is present to fulfill the Object interface. -func (b *Blob) ID() plumbing.Hash { - return b.Hash -} - -// Type returns the type of object. It always returns plumbing.BlobObject. -// -// Type is present to fulfill the Object interface. -func (b *Blob) Type() plumbing.ObjectType { - return plumbing.BlobObject -} - -// Decode transforms a plumbing.EncodedObject into a Blob struct. -func (b *Blob) Decode(o plumbing.EncodedObject) error { - if o.Type() != plumbing.BlobObject { - return ErrUnsupportedObject - } - - b.Hash = o.Hash() - b.Size = o.Size() - b.obj = o - - return nil -} - -// Encode transforms a Blob into a plumbing.EncodedObject. -func (b *Blob) Encode(o plumbing.EncodedObject) (err error) { - o.SetType(plumbing.BlobObject) - - w, err := o.Writer() - if err != nil { - return err - } - - defer ioutil.CheckClose(w, &err) - - r, err := b.Reader() - if err != nil { - return err - } - - defer ioutil.CheckClose(r, &err) - - _, err = io.Copy(w, r) - return err -} - -// Reader returns a reader allow the access to the content of the blob -func (b *Blob) Reader() (io.ReadCloser, error) { - return b.obj.Reader() -} - -// BlobIter provides an iterator for a set of blobs. -type BlobIter struct { - storer.EncodedObjectIter - s storer.EncodedObjectStorer -} - -// NewBlobIter takes a storer.EncodedObjectStorer and a -// storer.EncodedObjectIter and returns a *BlobIter that iterates over all -// blobs contained in the storer.EncodedObjectIter. -// -// Any non-blob object returned by the storer.EncodedObjectIter is skipped. -func NewBlobIter(s storer.EncodedObjectStorer, iter storer.EncodedObjectIter) *BlobIter { - return &BlobIter{iter, s} -} - -// Next moves the iterator to the next blob and returns a pointer to it. If -// there are no more blobs, it returns io.EOF. -func (iter *BlobIter) Next() (*Blob, error) { - for { - obj, err := iter.EncodedObjectIter.Next() - if err != nil { - return nil, err - } - - if obj.Type() != plumbing.BlobObject { - continue - } - - return DecodeBlob(obj) - } -} - -// ForEach call the cb function for each blob contained on this iter until -// an error happens or the end of the iter is reached. If ErrStop is sent -// the iteration is stop but no error is returned. The iterator is closed. -func (iter *BlobIter) ForEach(cb func(*Blob) error) error { - return iter.EncodedObjectIter.ForEach(func(obj plumbing.EncodedObject) error { - if obj.Type() != plumbing.BlobObject { - return nil - } - - b, err := DecodeBlob(obj) - if err != nil { - return err - } - - return cb(b) - }) -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/object/change.go b/vendor/github.com/go-git/go-git/v5/plumbing/object/change.go deleted file mode 100644 index 8b119bc9..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/object/change.go +++ /dev/null @@ -1,159 +0,0 @@ -package object - -import ( - "bytes" - "context" - "fmt" - "strings" - - "github.com/go-git/go-git/v5/utils/merkletrie" -) - -// Change values represent a detected change between two git trees. For -// modifications, From is the original status of the node and To is its -// final status. For insertions, From is the zero value and for -// deletions To is the zero value. -type Change struct { - From ChangeEntry - To ChangeEntry -} - -var empty ChangeEntry - -// Action returns the kind of action represented by the change, an -// insertion, a deletion or a modification. -func (c *Change) Action() (merkletrie.Action, error) { - if c.From == empty && c.To == empty { - return merkletrie.Action(0), - fmt.Errorf("malformed change: empty from and to") - } - - if c.From == empty { - return merkletrie.Insert, nil - } - - if c.To == empty { - return merkletrie.Delete, nil - } - - return merkletrie.Modify, nil -} - -// Files return the files before and after a change. -// For insertions from will be nil. For deletions to will be nil. -func (c *Change) Files() (from, to *File, err error) { - action, err := c.Action() - if err != nil { - return - } - - if action == merkletrie.Insert || action == merkletrie.Modify { - to, err = c.To.Tree.TreeEntryFile(&c.To.TreeEntry) - if !c.To.TreeEntry.Mode.IsFile() { - return nil, nil, nil - } - - if err != nil { - return - } - } - - if action == merkletrie.Delete || action == merkletrie.Modify { - from, err = c.From.Tree.TreeEntryFile(&c.From.TreeEntry) - if !c.From.TreeEntry.Mode.IsFile() { - return nil, nil, nil - } - - if err != nil { - return - } - } - - return -} - -func (c *Change) String() string { - action, err := c.Action() - if err != nil { - return "malformed change" - } - - return fmt.Sprintf("", action, c.name()) -} - -// Patch returns a Patch with all the file changes in chunks. This -// representation can be used to create several diff outputs. -func (c *Change) Patch() (*Patch, error) { - return c.PatchContext(context.Background()) -} - -// Patch returns a Patch with all the file changes in chunks. This -// representation can be used to create several diff outputs. -// If context expires, an non-nil error will be returned -// Provided context must be non-nil -func (c *Change) PatchContext(ctx context.Context) (*Patch, error) { - return getPatchContext(ctx, "", c) -} - -func (c *Change) name() string { - if c.From != empty { - return c.From.Name - } - - return c.To.Name -} - -// ChangeEntry values represent a node that has suffered a change. -type ChangeEntry struct { - // Full path of the node using "/" as separator. - Name string - // Parent tree of the node that has changed. - Tree *Tree - // The entry of the node. - TreeEntry TreeEntry -} - -// Changes represents a collection of changes between two git trees. -// Implements sort.Interface lexicographically over the path of the -// changed files. -type Changes []*Change - -func (c Changes) Len() int { - return len(c) -} - -func (c Changes) Swap(i, j int) { - c[i], c[j] = c[j], c[i] -} - -func (c Changes) Less(i, j int) bool { - return strings.Compare(c[i].name(), c[j].name()) < 0 -} - -func (c Changes) String() string { - var buffer bytes.Buffer - buffer.WriteString("[") - comma := "" - for _, v := range c { - buffer.WriteString(comma) - buffer.WriteString(v.String()) - comma = ", " - } - buffer.WriteString("]") - - return buffer.String() -} - -// Patch returns a Patch with all the changes in chunks. This -// representation can be used to create several diff outputs. -func (c Changes) Patch() (*Patch, error) { - return c.PatchContext(context.Background()) -} - -// Patch returns a Patch with all the changes in chunks. This -// representation can be used to create several diff outputs. -// If context expires, an non-nil error will be returned -// Provided context must be non-nil -func (c Changes) PatchContext(ctx context.Context) (*Patch, error) { - return getPatchContext(ctx, "", c...) -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/object/change_adaptor.go b/vendor/github.com/go-git/go-git/v5/plumbing/object/change_adaptor.go deleted file mode 100644 index f7011882..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/object/change_adaptor.go +++ /dev/null @@ -1,61 +0,0 @@ -package object - -import ( - "errors" - "fmt" - - "github.com/go-git/go-git/v5/utils/merkletrie" - "github.com/go-git/go-git/v5/utils/merkletrie/noder" -) - -// The following functions transform changes types form the merkletrie -// package to changes types from this package. - -func newChange(c merkletrie.Change) (*Change, error) { - ret := &Change{} - - var err error - if ret.From, err = newChangeEntry(c.From); err != nil { - return nil, fmt.Errorf("From field: %s", err) - } - - if ret.To, err = newChangeEntry(c.To); err != nil { - return nil, fmt.Errorf("To field: %s", err) - } - - return ret, nil -} - -func newChangeEntry(p noder.Path) (ChangeEntry, error) { - if p == nil { - return empty, nil - } - - asTreeNoder, ok := p.Last().(*treeNoder) - if !ok { - return ChangeEntry{}, errors.New("cannot transform non-TreeNoders") - } - - return ChangeEntry{ - Name: p.String(), - Tree: asTreeNoder.parent, - TreeEntry: TreeEntry{ - Name: asTreeNoder.name, - Mode: asTreeNoder.mode, - Hash: asTreeNoder.hash, - }, - }, nil -} - -func newChanges(src merkletrie.Changes) (Changes, error) { - ret := make(Changes, len(src)) - var err error - for i, e := range src { - ret[i], err = newChange(e) - if err != nil { - return nil, fmt.Errorf("change #%d: %s", i, err) - } - } - - return ret, nil -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/object/commit.go b/vendor/github.com/go-git/go-git/v5/plumbing/object/commit.go deleted file mode 100644 index 98664a1e..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/object/commit.go +++ /dev/null @@ -1,442 +0,0 @@ -package object - -import ( - "bufio" - "bytes" - "context" - "errors" - "fmt" - "io" - "strings" - - "golang.org/x/crypto/openpgp" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/plumbing/storer" - "github.com/go-git/go-git/v5/utils/ioutil" -) - -const ( - beginpgp string = "-----BEGIN PGP SIGNATURE-----" - endpgp string = "-----END PGP SIGNATURE-----" - headerpgp string = "gpgsig" -) - -// Hash represents the hash of an object -type Hash plumbing.Hash - -// Commit points to a single tree, marking it as what the project looked like -// at a certain point in time. It contains meta-information about that point -// in time, such as a timestamp, the author of the changes since the last -// commit, a pointer to the previous commit(s), etc. -// http://shafiulazam.com/gitbook/1_the_git_object_model.html -type Commit struct { - // Hash of the commit object. - Hash plumbing.Hash - // Author is the original author of the commit. - Author Signature - // Committer is the one performing the commit, might be different from - // Author. - Committer Signature - // PGPSignature is the PGP signature of the commit. - PGPSignature string - // Message is the commit message, contains arbitrary text. - Message string - // TreeHash is the hash of the root tree of the commit. - TreeHash plumbing.Hash - // ParentHashes are the hashes of the parent commits of the commit. - ParentHashes []plumbing.Hash - - s storer.EncodedObjectStorer -} - -// GetCommit gets a commit from an object storer and decodes it. -func GetCommit(s storer.EncodedObjectStorer, h plumbing.Hash) (*Commit, error) { - o, err := s.EncodedObject(plumbing.CommitObject, h) - if err != nil { - return nil, err - } - - return DecodeCommit(s, o) -} - -// DecodeCommit decodes an encoded object into a *Commit and associates it to -// the given object storer. -func DecodeCommit(s storer.EncodedObjectStorer, o plumbing.EncodedObject) (*Commit, error) { - c := &Commit{s: s} - if err := c.Decode(o); err != nil { - return nil, err - } - - return c, nil -} - -// Tree returns the Tree from the commit. -func (c *Commit) Tree() (*Tree, error) { - return GetTree(c.s, c.TreeHash) -} - -// PatchContext returns the Patch between the actual commit and the provided one. -// Error will be return if context expires. Provided context must be non-nil. -// -// NOTE: Since version 5.1.0 the renames are correctly handled, the settings -// used are the recommended options DefaultDiffTreeOptions. -func (c *Commit) PatchContext(ctx context.Context, to *Commit) (*Patch, error) { - fromTree, err := c.Tree() - if err != nil { - return nil, err - } - - var toTree *Tree - if to != nil { - toTree, err = to.Tree() - if err != nil { - return nil, err - } - } - - return fromTree.PatchContext(ctx, toTree) -} - -// Patch returns the Patch between the actual commit and the provided one. -// -// NOTE: Since version 5.1.0 the renames are correctly handled, the settings -// used are the recommended options DefaultDiffTreeOptions. -func (c *Commit) Patch(to *Commit) (*Patch, error) { - return c.PatchContext(context.Background(), to) -} - -// Parents return a CommitIter to the parent Commits. -func (c *Commit) Parents() CommitIter { - return NewCommitIter(c.s, - storer.NewEncodedObjectLookupIter(c.s, plumbing.CommitObject, c.ParentHashes), - ) -} - -// NumParents returns the number of parents in a commit. -func (c *Commit) NumParents() int { - return len(c.ParentHashes) -} - -var ErrParentNotFound = errors.New("commit parent not found") - -// Parent returns the ith parent of a commit. -func (c *Commit) Parent(i int) (*Commit, error) { - if len(c.ParentHashes) == 0 || i > len(c.ParentHashes)-1 { - return nil, ErrParentNotFound - } - - return GetCommit(c.s, c.ParentHashes[i]) -} - -// File returns the file with the specified "path" in the commit and a -// nil error if the file exists. If the file does not exist, it returns -// a nil file and the ErrFileNotFound error. -func (c *Commit) File(path string) (*File, error) { - tree, err := c.Tree() - if err != nil { - return nil, err - } - - return tree.File(path) -} - -// Files returns a FileIter allowing to iterate over the Tree -func (c *Commit) Files() (*FileIter, error) { - tree, err := c.Tree() - if err != nil { - return nil, err - } - - return tree.Files(), nil -} - -// ID returns the object ID of the commit. The returned value will always match -// the current value of Commit.Hash. -// -// ID is present to fulfill the Object interface. -func (c *Commit) ID() plumbing.Hash { - return c.Hash -} - -// Type returns the type of object. It always returns plumbing.CommitObject. -// -// Type is present to fulfill the Object interface. -func (c *Commit) Type() plumbing.ObjectType { - return plumbing.CommitObject -} - -// Decode transforms a plumbing.EncodedObject into a Commit struct. -func (c *Commit) Decode(o plumbing.EncodedObject) (err error) { - if o.Type() != plumbing.CommitObject { - return ErrUnsupportedObject - } - - c.Hash = o.Hash() - - reader, err := o.Reader() - if err != nil { - return err - } - defer ioutil.CheckClose(reader, &err) - - r := bufPool.Get().(*bufio.Reader) - defer bufPool.Put(r) - r.Reset(reader) - - var message bool - var pgpsig bool - var msgbuf bytes.Buffer - for { - line, err := r.ReadBytes('\n') - if err != nil && err != io.EOF { - return err - } - - if pgpsig { - if len(line) > 0 && line[0] == ' ' { - line = bytes.TrimLeft(line, " ") - c.PGPSignature += string(line) - continue - } else { - pgpsig = false - } - } - - if !message { - line = bytes.TrimSpace(line) - if len(line) == 0 { - message = true - continue - } - - split := bytes.SplitN(line, []byte{' '}, 2) - - var data []byte - if len(split) == 2 { - data = split[1] - } - - switch string(split[0]) { - case "tree": - c.TreeHash = plumbing.NewHash(string(data)) - case "parent": - c.ParentHashes = append(c.ParentHashes, plumbing.NewHash(string(data))) - case "author": - c.Author.Decode(data) - case "committer": - c.Committer.Decode(data) - case headerpgp: - c.PGPSignature += string(data) + "\n" - pgpsig = true - } - } else { - msgbuf.Write(line) - } - - if err == io.EOF { - break - } - } - c.Message = msgbuf.String() - return nil -} - -// Encode transforms a Commit into a plumbing.EncodedObject. -func (c *Commit) Encode(o plumbing.EncodedObject) error { - return c.encode(o, true) -} - -// EncodeWithoutSignature export a Commit into a plumbing.EncodedObject without the signature (correspond to the payload of the PGP signature). -func (c *Commit) EncodeWithoutSignature(o plumbing.EncodedObject) error { - return c.encode(o, false) -} - -func (c *Commit) encode(o plumbing.EncodedObject, includeSig bool) (err error) { - o.SetType(plumbing.CommitObject) - w, err := o.Writer() - if err != nil { - return err - } - - defer ioutil.CheckClose(w, &err) - - if _, err = fmt.Fprintf(w, "tree %s\n", c.TreeHash.String()); err != nil { - return err - } - - for _, parent := range c.ParentHashes { - if _, err = fmt.Fprintf(w, "parent %s\n", parent.String()); err != nil { - return err - } - } - - if _, err = fmt.Fprint(w, "author "); err != nil { - return err - } - - if err = c.Author.Encode(w); err != nil { - return err - } - - if _, err = fmt.Fprint(w, "\ncommitter "); err != nil { - return err - } - - if err = c.Committer.Encode(w); err != nil { - return err - } - - if c.PGPSignature != "" && includeSig { - if _, err = fmt.Fprint(w, "\n"+headerpgp+" "); err != nil { - return err - } - - // Split all the signature lines and re-write with a left padding and - // newline. Use join for this so it's clear that a newline should not be - // added after this section, as it will be added when the message is - // printed. - signature := strings.TrimSuffix(c.PGPSignature, "\n") - lines := strings.Split(signature, "\n") - if _, err = fmt.Fprint(w, strings.Join(lines, "\n ")); err != nil { - return err - } - } - - if _, err = fmt.Fprintf(w, "\n\n%s", c.Message); err != nil { - return err - } - - return err -} - -// Stats returns the stats of a commit. -func (c *Commit) Stats() (FileStats, error) { - return c.StatsContext(context.Background()) -} - -// StatsContext returns the stats of a commit. Error will be return if context -// expires. Provided context must be non-nil. -func (c *Commit) StatsContext(ctx context.Context) (FileStats, error) { - fromTree, err := c.Tree() - if err != nil { - return nil, err - } - - toTree := &Tree{} - if c.NumParents() != 0 { - firstParent, err := c.Parents().Next() - if err != nil { - return nil, err - } - - toTree, err = firstParent.Tree() - if err != nil { - return nil, err - } - } - - patch, err := toTree.PatchContext(ctx, fromTree) - if err != nil { - return nil, err - } - - return getFileStatsFromFilePatches(patch.FilePatches()), nil -} - -func (c *Commit) String() string { - return fmt.Sprintf( - "%s %s\nAuthor: %s\nDate: %s\n\n%s\n", - plumbing.CommitObject, c.Hash, c.Author.String(), - c.Author.When.Format(DateFormat), indent(c.Message), - ) -} - -// Verify performs PGP verification of the commit with a provided armored -// keyring and returns openpgp.Entity associated with verifying key on success. -func (c *Commit) Verify(armoredKeyRing string) (*openpgp.Entity, error) { - keyRingReader := strings.NewReader(armoredKeyRing) - keyring, err := openpgp.ReadArmoredKeyRing(keyRingReader) - if err != nil { - return nil, err - } - - // Extract signature. - signature := strings.NewReader(c.PGPSignature) - - encoded := &plumbing.MemoryObject{} - // Encode commit components, excluding signature and get a reader object. - if err := c.EncodeWithoutSignature(encoded); err != nil { - return nil, err - } - er, err := encoded.Reader() - if err != nil { - return nil, err - } - - return openpgp.CheckArmoredDetachedSignature(keyring, er, signature) -} - -func indent(t string) string { - var output []string - for _, line := range strings.Split(t, "\n") { - if len(line) != 0 { - line = " " + line - } - - output = append(output, line) - } - - return strings.Join(output, "\n") -} - -// CommitIter is a generic closable interface for iterating over commits. -type CommitIter interface { - Next() (*Commit, error) - ForEach(func(*Commit) error) error - Close() -} - -// storerCommitIter provides an iterator from commits in an EncodedObjectStorer. -type storerCommitIter struct { - storer.EncodedObjectIter - s storer.EncodedObjectStorer -} - -// NewCommitIter takes a storer.EncodedObjectStorer and a -// storer.EncodedObjectIter and returns a CommitIter that iterates over all -// commits contained in the storer.EncodedObjectIter. -// -// Any non-commit object returned by the storer.EncodedObjectIter is skipped. -func NewCommitIter(s storer.EncodedObjectStorer, iter storer.EncodedObjectIter) CommitIter { - return &storerCommitIter{iter, s} -} - -// Next moves the iterator to the next commit and returns a pointer to it. If -// there are no more commits, it returns io.EOF. -func (iter *storerCommitIter) Next() (*Commit, error) { - obj, err := iter.EncodedObjectIter.Next() - if err != nil { - return nil, err - } - - return DecodeCommit(iter.s, obj) -} - -// ForEach call the cb function for each commit contained on this iter until -// an error appends or the end of the iter is reached. If ErrStop is sent -// the iteration is stopped but no error is returned. The iterator is closed. -func (iter *storerCommitIter) ForEach(cb func(*Commit) error) error { - return iter.EncodedObjectIter.ForEach(func(obj plumbing.EncodedObject) error { - c, err := DecodeCommit(iter.s, obj) - if err != nil { - return err - } - - return cb(c) - }) -} - -func (iter *storerCommitIter) Close() { - iter.EncodedObjectIter.Close() -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/object/commit_walker.go b/vendor/github.com/go-git/go-git/v5/plumbing/object/commit_walker.go deleted file mode 100644 index a96b6a4c..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/object/commit_walker.go +++ /dev/null @@ -1,327 +0,0 @@ -package object - -import ( - "container/list" - "io" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/plumbing/storer" - "github.com/go-git/go-git/v5/storage" -) - -type commitPreIterator struct { - seenExternal map[plumbing.Hash]bool - seen map[plumbing.Hash]bool - stack []CommitIter - start *Commit -} - -// NewCommitPreorderIter returns a CommitIter that walks the commit history, -// starting at the given commit and visiting its parents in pre-order. -// The given callback will be called for each visited commit. Each commit will -// be visited only once. If the callback returns an error, walking will stop -// and will return the error. Other errors might be returned if the history -// cannot be traversed (e.g. missing objects). Ignore allows to skip some -// commits from being iterated. -func NewCommitPreorderIter( - c *Commit, - seenExternal map[plumbing.Hash]bool, - ignore []plumbing.Hash, -) CommitIter { - seen := make(map[plumbing.Hash]bool) - for _, h := range ignore { - seen[h] = true - } - - return &commitPreIterator{ - seenExternal: seenExternal, - seen: seen, - stack: make([]CommitIter, 0), - start: c, - } -} - -func (w *commitPreIterator) Next() (*Commit, error) { - var c *Commit - for { - if w.start != nil { - c = w.start - w.start = nil - } else { - current := len(w.stack) - 1 - if current < 0 { - return nil, io.EOF - } - - var err error - c, err = w.stack[current].Next() - if err == io.EOF { - w.stack = w.stack[:current] - continue - } - - if err != nil { - return nil, err - } - } - - if w.seen[c.Hash] || w.seenExternal[c.Hash] { - continue - } - - w.seen[c.Hash] = true - - if c.NumParents() > 0 { - w.stack = append(w.stack, filteredParentIter(c, w.seen)) - } - - return c, nil - } -} - -func filteredParentIter(c *Commit, seen map[plumbing.Hash]bool) CommitIter { - var hashes []plumbing.Hash - for _, h := range c.ParentHashes { - if !seen[h] { - hashes = append(hashes, h) - } - } - - return NewCommitIter(c.s, - storer.NewEncodedObjectLookupIter(c.s, plumbing.CommitObject, hashes), - ) -} - -func (w *commitPreIterator) ForEach(cb func(*Commit) error) error { - for { - c, err := w.Next() - if err == io.EOF { - break - } - if err != nil { - return err - } - - err = cb(c) - if err == storer.ErrStop { - break - } - if err != nil { - return err - } - } - - return nil -} - -func (w *commitPreIterator) Close() {} - -type commitPostIterator struct { - stack []*Commit - seen map[plumbing.Hash]bool -} - -// NewCommitPostorderIter returns a CommitIter that walks the commit -// history like WalkCommitHistory but in post-order. This means that after -// walking a merge commit, the merged commit will be walked before the base -// it was merged on. This can be useful if you wish to see the history in -// chronological order. Ignore allows to skip some commits from being iterated. -func NewCommitPostorderIter(c *Commit, ignore []plumbing.Hash) CommitIter { - seen := make(map[plumbing.Hash]bool) - for _, h := range ignore { - seen[h] = true - } - - return &commitPostIterator{ - stack: []*Commit{c}, - seen: seen, - } -} - -func (w *commitPostIterator) Next() (*Commit, error) { - for { - if len(w.stack) == 0 { - return nil, io.EOF - } - - c := w.stack[len(w.stack)-1] - w.stack = w.stack[:len(w.stack)-1] - - if w.seen[c.Hash] { - continue - } - - w.seen[c.Hash] = true - - return c, c.Parents().ForEach(func(p *Commit) error { - w.stack = append(w.stack, p) - return nil - }) - } -} - -func (w *commitPostIterator) ForEach(cb func(*Commit) error) error { - for { - c, err := w.Next() - if err == io.EOF { - break - } - if err != nil { - return err - } - - err = cb(c) - if err == storer.ErrStop { - break - } - if err != nil { - return err - } - } - - return nil -} - -func (w *commitPostIterator) Close() {} - -// commitAllIterator stands for commit iterator for all refs. -type commitAllIterator struct { - // currCommit points to the current commit. - currCommit *list.Element -} - -// NewCommitAllIter returns a new commit iterator for all refs. -// repoStorer is a repo Storer used to get commits and references. -// commitIterFunc is a commit iterator function, used to iterate through ref commits in chosen order -func NewCommitAllIter(repoStorer storage.Storer, commitIterFunc func(*Commit) CommitIter) (CommitIter, error) { - commitsPath := list.New() - commitsLookup := make(map[plumbing.Hash]*list.Element) - head, err := storer.ResolveReference(repoStorer, plumbing.HEAD) - if err == nil { - err = addReference(repoStorer, commitIterFunc, head, commitsPath, commitsLookup) - } - - if err != nil && err != plumbing.ErrReferenceNotFound { - return nil, err - } - - // add all references along with the HEAD - refIter, err := repoStorer.IterReferences() - if err != nil { - return nil, err - } - defer refIter.Close() - - for { - ref, err := refIter.Next() - if err == io.EOF { - break - } - - if err == plumbing.ErrReferenceNotFound { - continue - } - - if err != nil { - return nil, err - } - - if err = addReference(repoStorer, commitIterFunc, ref, commitsPath, commitsLookup); err != nil { - return nil, err - } - } - - return &commitAllIterator{commitsPath.Front()}, nil -} - -func addReference( - repoStorer storage.Storer, - commitIterFunc func(*Commit) CommitIter, - ref *plumbing.Reference, - commitsPath *list.List, - commitsLookup map[plumbing.Hash]*list.Element) error { - - _, exists := commitsLookup[ref.Hash()] - if exists { - // we already have it - skip the reference. - return nil - } - - refCommit, _ := GetCommit(repoStorer, ref.Hash()) - if refCommit == nil { - // if it's not a commit - skip it. - return nil - } - - var ( - refCommits []*Commit - parent *list.Element - ) - // collect all ref commits to add - commitIter := commitIterFunc(refCommit) - for c, e := commitIter.Next(); e == nil; { - parent, exists = commitsLookup[c.Hash] - if exists { - break - } - refCommits = append(refCommits, c) - c, e = commitIter.Next() - } - commitIter.Close() - - if parent == nil { - // common parent - not found - // add all commits to the path from this ref (maybe it's a HEAD and we don't have anything, yet) - for _, c := range refCommits { - parent = commitsPath.PushBack(c) - commitsLookup[c.Hash] = parent - } - } else { - // add ref's commits to the path in reverse order (from the latest) - for i := len(refCommits) - 1; i >= 0; i-- { - c := refCommits[i] - // insert before found common parent - parent = commitsPath.InsertBefore(c, parent) - commitsLookup[c.Hash] = parent - } - } - - return nil -} - -func (it *commitAllIterator) Next() (*Commit, error) { - if it.currCommit == nil { - return nil, io.EOF - } - - c := it.currCommit.Value.(*Commit) - it.currCommit = it.currCommit.Next() - - return c, nil -} - -func (it *commitAllIterator) ForEach(cb func(*Commit) error) error { - for { - c, err := it.Next() - if err == io.EOF { - break - } - if err != nil { - return err - } - - err = cb(c) - if err == storer.ErrStop { - break - } - if err != nil { - return err - } - } - - return nil -} - -func (it *commitAllIterator) Close() { - it.currCommit = nil -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/object/commit_walker_bfs.go b/vendor/github.com/go-git/go-git/v5/plumbing/object/commit_walker_bfs.go deleted file mode 100644 index 8047fa9b..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/object/commit_walker_bfs.go +++ /dev/null @@ -1,100 +0,0 @@ -package object - -import ( - "io" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/plumbing/storer" -) - -type bfsCommitIterator struct { - seenExternal map[plumbing.Hash]bool - seen map[plumbing.Hash]bool - queue []*Commit -} - -// NewCommitIterBSF returns a CommitIter that walks the commit history, -// starting at the given commit and visiting its parents in pre-order. -// The given callback will be called for each visited commit. Each commit will -// be visited only once. If the callback returns an error, walking will stop -// and will return the error. Other errors might be returned if the history -// cannot be traversed (e.g. missing objects). Ignore allows to skip some -// commits from being iterated. -func NewCommitIterBSF( - c *Commit, - seenExternal map[plumbing.Hash]bool, - ignore []plumbing.Hash, -) CommitIter { - seen := make(map[plumbing.Hash]bool) - for _, h := range ignore { - seen[h] = true - } - - return &bfsCommitIterator{ - seenExternal: seenExternal, - seen: seen, - queue: []*Commit{c}, - } -} - -func (w *bfsCommitIterator) appendHash(store storer.EncodedObjectStorer, h plumbing.Hash) error { - if w.seen[h] || w.seenExternal[h] { - return nil - } - c, err := GetCommit(store, h) - if err != nil { - return err - } - w.queue = append(w.queue, c) - return nil -} - -func (w *bfsCommitIterator) Next() (*Commit, error) { - var c *Commit - for { - if len(w.queue) == 0 { - return nil, io.EOF - } - c = w.queue[0] - w.queue = w.queue[1:] - - if w.seen[c.Hash] || w.seenExternal[c.Hash] { - continue - } - - w.seen[c.Hash] = true - - for _, h := range c.ParentHashes { - err := w.appendHash(c.s, h) - if err != nil { - return nil, err - } - } - - return c, nil - } -} - -func (w *bfsCommitIterator) ForEach(cb func(*Commit) error) error { - for { - c, err := w.Next() - if err == io.EOF { - break - } - if err != nil { - return err - } - - err = cb(c) - if err == storer.ErrStop { - break - } - if err != nil { - return err - } - } - - return nil -} - -func (w *bfsCommitIterator) Close() {} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/object/commit_walker_bfs_filtered.go b/vendor/github.com/go-git/go-git/v5/plumbing/object/commit_walker_bfs_filtered.go deleted file mode 100644 index 9d518133..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/object/commit_walker_bfs_filtered.go +++ /dev/null @@ -1,175 +0,0 @@ -package object - -import ( - "io" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/plumbing/storer" -) - -// NewFilterCommitIter returns a CommitIter that walks the commit history, -// starting at the passed commit and visiting its parents in Breadth-first order. -// The commits returned by the CommitIter will validate the passed CommitFilter. -// The history won't be transversed beyond a commit if isLimit is true for it. -// Each commit will be visited only once. -// If the commit history can not be traversed, or the Close() method is called, -// the CommitIter won't return more commits. -// If no isValid is passed, all ancestors of from commit will be valid. -// If no isLimit is limit, all ancestors of all commits will be visited. -func NewFilterCommitIter( - from *Commit, - isValid *CommitFilter, - isLimit *CommitFilter, -) CommitIter { - var validFilter CommitFilter - if isValid == nil { - validFilter = func(_ *Commit) bool { - return true - } - } else { - validFilter = *isValid - } - - var limitFilter CommitFilter - if isLimit == nil { - limitFilter = func(_ *Commit) bool { - return false - } - } else { - limitFilter = *isLimit - } - - return &filterCommitIter{ - isValid: validFilter, - isLimit: limitFilter, - visited: map[plumbing.Hash]struct{}{}, - queue: []*Commit{from}, - } -} - -// CommitFilter returns a boolean for the passed Commit -type CommitFilter func(*Commit) bool - -// filterCommitIter implements CommitIter -type filterCommitIter struct { - isValid CommitFilter - isLimit CommitFilter - visited map[plumbing.Hash]struct{} - queue []*Commit - lastErr error -} - -// Next returns the next commit of the CommitIter. -// It will return io.EOF if there are no more commits to visit, -// or an error if the history could not be traversed. -func (w *filterCommitIter) Next() (*Commit, error) { - var commit *Commit - var err error - for { - commit, err = w.popNewFromQueue() - if err != nil { - return nil, w.close(err) - } - - w.visited[commit.Hash] = struct{}{} - - if !w.isLimit(commit) { - err = w.addToQueue(commit.s, commit.ParentHashes...) - if err != nil { - return nil, w.close(err) - } - } - - if w.isValid(commit) { - return commit, nil - } - } -} - -// ForEach runs the passed callback over each Commit returned by the CommitIter -// until the callback returns an error or there is no more commits to traverse. -func (w *filterCommitIter) ForEach(cb func(*Commit) error) error { - for { - commit, err := w.Next() - if err == io.EOF { - break - } - - if err != nil { - return err - } - - if err := cb(commit); err == storer.ErrStop { - break - } else if err != nil { - return err - } - } - - return nil -} - -// Error returns the error that caused that the CommitIter is no longer returning commits -func (w *filterCommitIter) Error() error { - return w.lastErr -} - -// Close closes the CommitIter -func (w *filterCommitIter) Close() { - w.visited = map[plumbing.Hash]struct{}{} - w.queue = []*Commit{} - w.isLimit = nil - w.isValid = nil -} - -// close closes the CommitIter with an error -func (w *filterCommitIter) close(err error) error { - w.Close() - w.lastErr = err - return err -} - -// popNewFromQueue returns the first new commit from the internal fifo queue, -// or an io.EOF error if the queue is empty -func (w *filterCommitIter) popNewFromQueue() (*Commit, error) { - var first *Commit - for { - if len(w.queue) == 0 { - if w.lastErr != nil { - return nil, w.lastErr - } - - return nil, io.EOF - } - - first = w.queue[0] - w.queue = w.queue[1:] - if _, ok := w.visited[first.Hash]; ok { - continue - } - - return first, nil - } -} - -// addToQueue adds the passed commits to the internal fifo queue if they weren't seen -// or returns an error if the passed hashes could not be used to get valid commits -func (w *filterCommitIter) addToQueue( - store storer.EncodedObjectStorer, - hashes ...plumbing.Hash, -) error { - for _, hash := range hashes { - if _, ok := w.visited[hash]; ok { - continue - } - - commit, err := GetCommit(store, hash) - if err != nil { - return err - } - - w.queue = append(w.queue, commit) - } - - return nil -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/object/commit_walker_ctime.go b/vendor/github.com/go-git/go-git/v5/plumbing/object/commit_walker_ctime.go deleted file mode 100644 index fbddf1d2..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/object/commit_walker_ctime.go +++ /dev/null @@ -1,103 +0,0 @@ -package object - -import ( - "io" - - "github.com/emirpasic/gods/trees/binaryheap" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/plumbing/storer" -) - -type commitIteratorByCTime struct { - seenExternal map[plumbing.Hash]bool - seen map[plumbing.Hash]bool - heap *binaryheap.Heap -} - -// NewCommitIterCTime returns a CommitIter that walks the commit history, -// starting at the given commit and visiting its parents while preserving Committer Time order. -// this appears to be the closest order to `git log` -// The given callback will be called for each visited commit. Each commit will -// be visited only once. If the callback returns an error, walking will stop -// and will return the error. Other errors might be returned if the history -// cannot be traversed (e.g. missing objects). Ignore allows to skip some -// commits from being iterated. -func NewCommitIterCTime( - c *Commit, - seenExternal map[plumbing.Hash]bool, - ignore []plumbing.Hash, -) CommitIter { - seen := make(map[plumbing.Hash]bool) - for _, h := range ignore { - seen[h] = true - } - - heap := binaryheap.NewWith(func(a, b interface{}) int { - if a.(*Commit).Committer.When.Before(b.(*Commit).Committer.When) { - return 1 - } - return -1 - }) - heap.Push(c) - - return &commitIteratorByCTime{ - seenExternal: seenExternal, - seen: seen, - heap: heap, - } -} - -func (w *commitIteratorByCTime) Next() (*Commit, error) { - var c *Commit - for { - cIn, ok := w.heap.Pop() - if !ok { - return nil, io.EOF - } - c = cIn.(*Commit) - - if w.seen[c.Hash] || w.seenExternal[c.Hash] { - continue - } - - w.seen[c.Hash] = true - - for _, h := range c.ParentHashes { - if w.seen[h] || w.seenExternal[h] { - continue - } - pc, err := GetCommit(c.s, h) - if err != nil { - return nil, err - } - w.heap.Push(pc) - } - - return c, nil - } -} - -func (w *commitIteratorByCTime) ForEach(cb func(*Commit) error) error { - for { - c, err := w.Next() - if err == io.EOF { - break - } - if err != nil { - return err - } - - err = cb(c) - if err == storer.ErrStop { - break - } - if err != nil { - return err - } - } - - return nil -} - -func (w *commitIteratorByCTime) Close() {} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/object/commit_walker_limit.go b/vendor/github.com/go-git/go-git/v5/plumbing/object/commit_walker_limit.go deleted file mode 100644 index ac56a71c..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/object/commit_walker_limit.go +++ /dev/null @@ -1,65 +0,0 @@ -package object - -import ( - "io" - "time" - - "github.com/go-git/go-git/v5/plumbing/storer" -) - -type commitLimitIter struct { - sourceIter CommitIter - limitOptions LogLimitOptions -} - -type LogLimitOptions struct { - Since *time.Time - Until *time.Time -} - -func NewCommitLimitIterFromIter(commitIter CommitIter, limitOptions LogLimitOptions) CommitIter { - iterator := new(commitLimitIter) - iterator.sourceIter = commitIter - iterator.limitOptions = limitOptions - return iterator -} - -func (c *commitLimitIter) Next() (*Commit, error) { - for { - commit, err := c.sourceIter.Next() - if err != nil { - return nil, err - } - - if c.limitOptions.Since != nil && commit.Committer.When.Before(*c.limitOptions.Since) { - continue - } - if c.limitOptions.Until != nil && commit.Committer.When.After(*c.limitOptions.Until) { - continue - } - return commit, nil - } -} - -func (c *commitLimitIter) ForEach(cb func(*Commit) error) error { - for { - commit, nextErr := c.Next() - if nextErr == io.EOF { - break - } - if nextErr != nil { - return nextErr - } - err := cb(commit) - if err == storer.ErrStop { - return nil - } else if err != nil { - return err - } - } - return nil -} - -func (c *commitLimitIter) Close() { - c.sourceIter.Close() -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/object/commit_walker_path.go b/vendor/github.com/go-git/go-git/v5/plumbing/object/commit_walker_path.go deleted file mode 100644 index aa0ca15f..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/object/commit_walker_path.go +++ /dev/null @@ -1,160 +0,0 @@ -package object - -import ( - "io" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/plumbing/storer" -) - -type commitPathIter struct { - pathFilter func(string) bool - sourceIter CommitIter - currentCommit *Commit - checkParent bool -} - -// NewCommitPathIterFromIter returns a commit iterator which performs diffTree between -// successive trees returned from the commit iterator from the argument. The purpose of this is -// to find the commits that explain how the files that match the path came to be. -// If checkParent is true then the function double checks if potential parent (next commit in a path) -// is one of the parents in the tree (it's used by `git log --all`). -// pathFilter is a function that takes path of file as argument and returns true if we want it -func NewCommitPathIterFromIter(pathFilter func(string) bool, commitIter CommitIter, checkParent bool) CommitIter { - iterator := new(commitPathIter) - iterator.sourceIter = commitIter - iterator.pathFilter = pathFilter - iterator.checkParent = checkParent - return iterator -} - -// NewCommitFileIterFromIter is kept for compatibility, can be replaced with NewCommitPathIterFromIter -func NewCommitFileIterFromIter(fileName string, commitIter CommitIter, checkParent bool) CommitIter { - return NewCommitPathIterFromIter( - func(path string) bool { - return path == fileName - }, - commitIter, - checkParent, - ) -} - -func (c *commitPathIter) Next() (*Commit, error) { - if c.currentCommit == nil { - var err error - c.currentCommit, err = c.sourceIter.Next() - if err != nil { - return nil, err - } - } - commit, commitErr := c.getNextFileCommit() - - // Setting current-commit to nil to prevent unwanted states when errors are raised - if commitErr != nil { - c.currentCommit = nil - } - return commit, commitErr -} - -func (c *commitPathIter) getNextFileCommit() (*Commit, error) { - for { - // Parent-commit can be nil if the current-commit is the initial commit - parentCommit, parentCommitErr := c.sourceIter.Next() - if parentCommitErr != nil { - // If the parent-commit is beyond the initial commit, keep it nil - if parentCommitErr != io.EOF { - return nil, parentCommitErr - } - parentCommit = nil - } - - // Fetch the trees of the current and parent commits - currentTree, currTreeErr := c.currentCommit.Tree() - if currTreeErr != nil { - return nil, currTreeErr - } - - var parentTree *Tree - if parentCommit != nil { - var parentTreeErr error - parentTree, parentTreeErr = parentCommit.Tree() - if parentTreeErr != nil { - return nil, parentTreeErr - } - } - - // Find diff between current and parent trees - changes, diffErr := DiffTree(currentTree, parentTree) - if diffErr != nil { - return nil, diffErr - } - - found := c.hasFileChange(changes, parentCommit) - - // Storing the current-commit in-case a change is found, and - // Updating the current-commit for the next-iteration - prevCommit := c.currentCommit - c.currentCommit = parentCommit - - if found { - return prevCommit, nil - } - - // If not matches found and if parent-commit is beyond the initial commit, then return with EOF - if parentCommit == nil { - return nil, io.EOF - } - } -} - -func (c *commitPathIter) hasFileChange(changes Changes, parent *Commit) bool { - for _, change := range changes { - if !c.pathFilter(change.name()) { - continue - } - - // filename matches, now check if source iterator contains all commits (from all refs) - if c.checkParent { - if parent != nil && isParentHash(parent.Hash, c.currentCommit) { - return true - } - continue - } - - return true - } - - return false -} - -func isParentHash(hash plumbing.Hash, commit *Commit) bool { - for _, h := range commit.ParentHashes { - if h == hash { - return true - } - } - return false -} - -func (c *commitPathIter) ForEach(cb func(*Commit) error) error { - for { - commit, nextErr := c.Next() - if nextErr == io.EOF { - break - } - if nextErr != nil { - return nextErr - } - err := cb(commit) - if err == storer.ErrStop { - return nil - } else if err != nil { - return err - } - } - return nil -} - -func (c *commitPathIter) Close() { - c.sourceIter.Close() -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/object/common.go b/vendor/github.com/go-git/go-git/v5/plumbing/object/common.go deleted file mode 100644 index 3591f5f0..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/object/common.go +++ /dev/null @@ -1,12 +0,0 @@ -package object - -import ( - "bufio" - "sync" -) - -var bufPool = sync.Pool{ - New: func() interface{} { - return bufio.NewReader(nil) - }, -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/object/difftree.go b/vendor/github.com/go-git/go-git/v5/plumbing/object/difftree.go deleted file mode 100644 index 7c222270..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/object/difftree.go +++ /dev/null @@ -1,98 +0,0 @@ -package object - -import ( - "bytes" - "context" - - "github.com/go-git/go-git/v5/utils/merkletrie" - "github.com/go-git/go-git/v5/utils/merkletrie/noder" -) - -// DiffTree compares the content and mode of the blobs found via two -// tree objects. -// DiffTree does not perform rename detection, use DiffTreeWithOptions -// instead to detect renames. -func DiffTree(a, b *Tree) (Changes, error) { - return DiffTreeContext(context.Background(), a, b) -} - -// DiffTreeContext compares the content and mode of the blobs found via two -// tree objects. Provided context must be non-nil. -// An error will be returned if context expires. -func DiffTreeContext(ctx context.Context, a, b *Tree) (Changes, error) { - return DiffTreeWithOptions(ctx, a, b, nil) -} - -// DiffTreeOptions are the configurable options when performing a diff tree. -type DiffTreeOptions struct { - // DetectRenames is whether the diff tree will use rename detection. - DetectRenames bool - // RenameScore is the threshold to of similarity between files to consider - // that a pair of delete and insert are a rename. The number must be - // exactly between 0 and 100. - RenameScore uint - // RenameLimit is the maximum amount of files that can be compared when - // detecting renames. The number of comparisons that have to be performed - // is equal to the number of deleted files * the number of added files. - // That means, that if 100 files were deleted and 50 files were added, 5000 - // file comparisons may be needed. So, if the rename limit is 50, the number - // of both deleted and added needs to be equal or less than 50. - // A value of 0 means no limit. - RenameLimit uint - // OnlyExactRenames performs only detection of exact renames and will not perform - // any detection of renames based on file similarity. - OnlyExactRenames bool -} - -// DefaultDiffTreeOptions are the default and recommended options for the -// diff tree. -var DefaultDiffTreeOptions = &DiffTreeOptions{ - DetectRenames: true, - RenameScore: 60, - RenameLimit: 0, - OnlyExactRenames: false, -} - -// DiffTreeWithOptions compares the content and mode of the blobs found -// via two tree objects with the given options. The provided context -// must be non-nil. -// If no options are passed, no rename detection will be performed. The -// recommended options are DefaultDiffTreeOptions. -// An error will be returned if the context expires. -// This function will be deprecated and removed in v6 so the default -// behaviour of DiffTree is to detect renames. -func DiffTreeWithOptions( - ctx context.Context, - a, b *Tree, - opts *DiffTreeOptions, -) (Changes, error) { - from := NewTreeRootNode(a) - to := NewTreeRootNode(b) - - hashEqual := func(a, b noder.Hasher) bool { - return bytes.Equal(a.Hash(), b.Hash()) - } - - merkletrieChanges, err := merkletrie.DiffTreeContext(ctx, from, to, hashEqual) - if err != nil { - if err == merkletrie.ErrCanceled { - return nil, ErrCanceled - } - return nil, err - } - - changes, err := newChanges(merkletrieChanges) - if err != nil { - return nil, err - } - - if opts == nil { - opts = new(DiffTreeOptions) - } - - if opts.DetectRenames { - return DetectRenames(changes, opts) - } - - return changes, nil -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/object/file.go b/vendor/github.com/go-git/go-git/v5/plumbing/object/file.go deleted file mode 100644 index 6cc5367d..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/object/file.go +++ /dev/null @@ -1,137 +0,0 @@ -package object - -import ( - "bytes" - "io" - "strings" - - "github.com/go-git/go-git/v5/plumbing/filemode" - "github.com/go-git/go-git/v5/plumbing/storer" - "github.com/go-git/go-git/v5/utils/binary" - "github.com/go-git/go-git/v5/utils/ioutil" -) - -// File represents git file objects. -type File struct { - // Name is the path of the file. It might be relative to a tree, - // depending of the function that generates it. - Name string - // Mode is the file mode. - Mode filemode.FileMode - // Blob with the contents of the file. - Blob -} - -// NewFile returns a File based on the given blob object -func NewFile(name string, m filemode.FileMode, b *Blob) *File { - return &File{Name: name, Mode: m, Blob: *b} -} - -// Contents returns the contents of a file as a string. -func (f *File) Contents() (content string, err error) { - reader, err := f.Reader() - if err != nil { - return "", err - } - defer ioutil.CheckClose(reader, &err) - - buf := new(bytes.Buffer) - if _, err := buf.ReadFrom(reader); err != nil { - return "", err - } - - return buf.String(), nil -} - -// IsBinary returns if the file is binary or not -func (f *File) IsBinary() (bin bool, err error) { - reader, err := f.Reader() - if err != nil { - return false, err - } - defer ioutil.CheckClose(reader, &err) - - return binary.IsBinary(reader) -} - -// Lines returns a slice of lines from the contents of a file, stripping -// all end of line characters. If the last line is empty (does not end -// in an end of line), it is also stripped. -func (f *File) Lines() ([]string, error) { - content, err := f.Contents() - if err != nil { - return nil, err - } - - splits := strings.Split(content, "\n") - // remove the last line if it is empty - if splits[len(splits)-1] == "" { - return splits[:len(splits)-1], nil - } - - return splits, nil -} - -// FileIter provides an iterator for the files in a tree. -type FileIter struct { - s storer.EncodedObjectStorer - w TreeWalker -} - -// NewFileIter takes a storer.EncodedObjectStorer and a Tree and returns a -// *FileIter that iterates over all files contained in the tree, recursively. -func NewFileIter(s storer.EncodedObjectStorer, t *Tree) *FileIter { - return &FileIter{s: s, w: *NewTreeWalker(t, true, nil)} -} - -// Next moves the iterator to the next file and returns a pointer to it. If -// there are no more files, it returns io.EOF. -func (iter *FileIter) Next() (*File, error) { - for { - name, entry, err := iter.w.Next() - if err != nil { - return nil, err - } - - if entry.Mode == filemode.Dir || entry.Mode == filemode.Submodule { - continue - } - - blob, err := GetBlob(iter.s, entry.Hash) - if err != nil { - return nil, err - } - - return NewFile(name, entry.Mode, blob), nil - } -} - -// ForEach call the cb function for each file contained in this iter until -// an error happens or the end of the iter is reached. If plumbing.ErrStop is sent -// the iteration is stop but no error is returned. The iterator is closed. -func (iter *FileIter) ForEach(cb func(*File) error) error { - defer iter.Close() - - for { - f, err := iter.Next() - if err != nil { - if err == io.EOF { - return nil - } - - return err - } - - if err := cb(f); err != nil { - if err == storer.ErrStop { - return nil - } - - return err - } - } -} - -func (iter *FileIter) Close() { - iter.w.Close() -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/object/merge_base.go b/vendor/github.com/go-git/go-git/v5/plumbing/object/merge_base.go deleted file mode 100644 index b412361d..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/object/merge_base.go +++ /dev/null @@ -1,210 +0,0 @@ -package object - -import ( - "fmt" - "sort" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/plumbing/storer" -) - -// errIsReachable is thrown when first commit is an ancestor of the second -var errIsReachable = fmt.Errorf("first is reachable from second") - -// MergeBase mimics the behavior of `git merge-base actual other`, returning the -// best common ancestor between the actual and the passed one. -// The best common ancestors can not be reached from other common ancestors. -func (c *Commit) MergeBase(other *Commit) ([]*Commit, error) { - // use sortedByCommitDateDesc strategy - sorted := sortByCommitDateDesc(c, other) - newer := sorted[0] - older := sorted[1] - - newerHistory, err := ancestorsIndex(older, newer) - if err == errIsReachable { - return []*Commit{older}, nil - } - - if err != nil { - return nil, err - } - - var res []*Commit - inNewerHistory := isInIndexCommitFilter(newerHistory) - resIter := NewFilterCommitIter(older, &inNewerHistory, &inNewerHistory) - _ = resIter.ForEach(func(commit *Commit) error { - res = append(res, commit) - return nil - }) - - return Independents(res) -} - -// IsAncestor returns true if the actual commit is ancestor of the passed one. -// It returns an error if the history is not transversable -// It mimics the behavior of `git merge --is-ancestor actual other` -func (c *Commit) IsAncestor(other *Commit) (bool, error) { - found := false - iter := NewCommitPreorderIter(other, nil, nil) - err := iter.ForEach(func(comm *Commit) error { - if comm.Hash != c.Hash { - return nil - } - - found = true - return storer.ErrStop - }) - - return found, err -} - -// ancestorsIndex returns a map with the ancestors of the starting commit if the -// excluded one is not one of them. It returns errIsReachable if the excluded commit -// is ancestor of the starting, or another error if the history is not traversable. -func ancestorsIndex(excluded, starting *Commit) (map[plumbing.Hash]struct{}, error) { - if excluded.Hash.String() == starting.Hash.String() { - return nil, errIsReachable - } - - startingHistory := map[plumbing.Hash]struct{}{} - startingIter := NewCommitIterBSF(starting, nil, nil) - err := startingIter.ForEach(func(commit *Commit) error { - if commit.Hash == excluded.Hash { - return errIsReachable - } - - startingHistory[commit.Hash] = struct{}{} - return nil - }) - - if err != nil { - return nil, err - } - - return startingHistory, nil -} - -// Independents returns a subset of the passed commits, that are not reachable the others -// It mimics the behavior of `git merge-base --independent commit...`. -func Independents(commits []*Commit) ([]*Commit, error) { - // use sortedByCommitDateDesc strategy - candidates := sortByCommitDateDesc(commits...) - candidates = removeDuplicated(candidates) - - seen := map[plumbing.Hash]struct{}{} - var isLimit CommitFilter = func(commit *Commit) bool { - _, ok := seen[commit.Hash] - return ok - } - - if len(candidates) < 2 { - return candidates, nil - } - - pos := 0 - for { - from := candidates[pos] - others := remove(candidates, from) - fromHistoryIter := NewFilterCommitIter(from, nil, &isLimit) - err := fromHistoryIter.ForEach(func(fromAncestor *Commit) error { - for _, other := range others { - if fromAncestor.Hash == other.Hash { - candidates = remove(candidates, other) - others = remove(others, other) - } - } - - if len(candidates) == 1 { - return storer.ErrStop - } - - seen[fromAncestor.Hash] = struct{}{} - return nil - }) - - if err != nil { - return nil, err - } - - nextPos := indexOf(candidates, from) + 1 - if nextPos >= len(candidates) { - break - } - - pos = nextPos - } - - return candidates, nil -} - -// sortByCommitDateDesc returns the passed commits, sorted by `committer.When desc` -// -// Following this strategy, it is tried to reduce the time needed when walking -// the history from one commit to reach the others. It is assumed that ancestors -// use to be committed before its descendant; -// That way `Independents(A^, A)` will be processed as being `Independents(A, A^)`; -// so starting by `A` it will be reached `A^` way sooner than walking from `A^` -// to the initial commit, and then from `A` to `A^`. -func sortByCommitDateDesc(commits ...*Commit) []*Commit { - sorted := make([]*Commit, len(commits)) - copy(sorted, commits) - sort.Slice(sorted, func(i, j int) bool { - return sorted[i].Committer.When.After(sorted[j].Committer.When) - }) - - return sorted -} - -// indexOf returns the first position where target was found in the passed commits -func indexOf(commits []*Commit, target *Commit) int { - for i, commit := range commits { - if target.Hash == commit.Hash { - return i - } - } - - return -1 -} - -// remove returns the passed commits excluding the commit toDelete -func remove(commits []*Commit, toDelete *Commit) []*Commit { - res := make([]*Commit, len(commits)) - j := 0 - for _, commit := range commits { - if commit.Hash == toDelete.Hash { - continue - } - - res[j] = commit - j++ - } - - return res[:j] -} - -// removeDuplicated removes duplicated commits from the passed slice of commits -func removeDuplicated(commits []*Commit) []*Commit { - seen := make(map[plumbing.Hash]struct{}, len(commits)) - res := make([]*Commit, len(commits)) - j := 0 - for _, commit := range commits { - if _, ok := seen[commit.Hash]; ok { - continue - } - - seen[commit.Hash] = struct{}{} - res[j] = commit - j++ - } - - return res[:j] -} - -// isInIndexCommitFilter returns a commitFilter that returns true -// if the commit is in the passed index. -func isInIndexCommitFilter(index map[plumbing.Hash]struct{}) CommitFilter { - return func(c *Commit) bool { - _, ok := index[c.Hash] - return ok - } -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/object/object.go b/vendor/github.com/go-git/go-git/v5/plumbing/object/object.go deleted file mode 100644 index 13b1e91c..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/object/object.go +++ /dev/null @@ -1,239 +0,0 @@ -// Package object contains implementations of all Git objects and utility -// functions to work with them. -package object - -import ( - "bytes" - "errors" - "fmt" - "io" - "strconv" - "time" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/plumbing/storer" -) - -// ErrUnsupportedObject trigger when a non-supported object is being decoded. -var ErrUnsupportedObject = errors.New("unsupported object type") - -// Object is a generic representation of any git object. It is implemented by -// Commit, Tree, Blob, and Tag, and includes the functions that are common to -// them. -// -// Object is returned when an object can be of any type. It is frequently used -// with a type cast to acquire the specific type of object: -// -// func process(obj Object) { -// switch o := obj.(type) { -// case *Commit: -// // o is a Commit -// case *Tree: -// // o is a Tree -// case *Blob: -// // o is a Blob -// case *Tag: -// // o is a Tag -// } -// } -// -// This interface is intentionally different from plumbing.EncodedObject, which -// is a lower level interface used by storage implementations to read and write -// objects in its encoded form. -type Object interface { - ID() plumbing.Hash - Type() plumbing.ObjectType - Decode(plumbing.EncodedObject) error - Encode(plumbing.EncodedObject) error -} - -// GetObject gets an object from an object storer and decodes it. -func GetObject(s storer.EncodedObjectStorer, h plumbing.Hash) (Object, error) { - o, err := s.EncodedObject(plumbing.AnyObject, h) - if err != nil { - return nil, err - } - - return DecodeObject(s, o) -} - -// DecodeObject decodes an encoded object into an Object and associates it to -// the given object storer. -func DecodeObject(s storer.EncodedObjectStorer, o plumbing.EncodedObject) (Object, error) { - switch o.Type() { - case plumbing.CommitObject: - return DecodeCommit(s, o) - case plumbing.TreeObject: - return DecodeTree(s, o) - case plumbing.BlobObject: - return DecodeBlob(o) - case plumbing.TagObject: - return DecodeTag(s, o) - default: - return nil, plumbing.ErrInvalidType - } -} - -// DateFormat is the format being used in the original git implementation -const DateFormat = "Mon Jan 02 15:04:05 2006 -0700" - -// Signature is used to identify who and when created a commit or tag. -type Signature struct { - // Name represents a person name. It is an arbitrary string. - Name string - // Email is an email, but it cannot be assumed to be well-formed. - Email string - // When is the timestamp of the signature. - When time.Time -} - -// Decode decodes a byte slice into a signature -func (s *Signature) Decode(b []byte) { - open := bytes.LastIndexByte(b, '<') - close := bytes.LastIndexByte(b, '>') - if open == -1 || close == -1 { - return - } - - if close < open { - return - } - - s.Name = string(bytes.Trim(b[:open], " ")) - s.Email = string(b[open+1 : close]) - - hasTime := close+2 < len(b) - if hasTime { - s.decodeTimeAndTimeZone(b[close+2:]) - } -} - -// Encode encodes a Signature into a writer. -func (s *Signature) Encode(w io.Writer) error { - if _, err := fmt.Fprintf(w, "%s <%s> ", s.Name, s.Email); err != nil { - return err - } - if err := s.encodeTimeAndTimeZone(w); err != nil { - return err - } - return nil -} - -var timeZoneLength = 5 - -func (s *Signature) decodeTimeAndTimeZone(b []byte) { - space := bytes.IndexByte(b, ' ') - if space == -1 { - space = len(b) - } - - ts, err := strconv.ParseInt(string(b[:space]), 10, 64) - if err != nil { - return - } - - s.When = time.Unix(ts, 0).In(time.UTC) - var tzStart = space + 1 - if tzStart >= len(b) || tzStart+timeZoneLength > len(b) { - return - } - - timezone := string(b[tzStart : tzStart+timeZoneLength]) - tzhours, err1 := strconv.ParseInt(timezone[0:3], 10, 64) - tzmins, err2 := strconv.ParseInt(timezone[3:], 10, 64) - if err1 != nil || err2 != nil { - return - } - if tzhours < 0 { - tzmins *= -1 - } - - tz := time.FixedZone("", int(tzhours*60*60+tzmins*60)) - - s.When = s.When.In(tz) -} - -func (s *Signature) encodeTimeAndTimeZone(w io.Writer) error { - u := s.When.Unix() - if u < 0 { - u = 0 - } - _, err := fmt.Fprintf(w, "%d %s", u, s.When.Format("-0700")) - return err -} - -func (s *Signature) String() string { - return fmt.Sprintf("%s <%s>", s.Name, s.Email) -} - -// ObjectIter provides an iterator for a set of objects. -type ObjectIter struct { - storer.EncodedObjectIter - s storer.EncodedObjectStorer -} - -// NewObjectIter takes a storer.EncodedObjectStorer and a -// storer.EncodedObjectIter and returns an *ObjectIter that iterates over all -// objects contained in the storer.EncodedObjectIter. -func NewObjectIter(s storer.EncodedObjectStorer, iter storer.EncodedObjectIter) *ObjectIter { - return &ObjectIter{iter, s} -} - -// Next moves the iterator to the next object and returns a pointer to it. If -// there are no more objects, it returns io.EOF. -func (iter *ObjectIter) Next() (Object, error) { - for { - obj, err := iter.EncodedObjectIter.Next() - if err != nil { - return nil, err - } - - o, err := iter.toObject(obj) - if err == plumbing.ErrInvalidType { - continue - } - - if err != nil { - return nil, err - } - - return o, nil - } -} - -// ForEach call the cb function for each object contained on this iter until -// an error happens or the end of the iter is reached. If ErrStop is sent -// the iteration is stop but no error is returned. The iterator is closed. -func (iter *ObjectIter) ForEach(cb func(Object) error) error { - return iter.EncodedObjectIter.ForEach(func(obj plumbing.EncodedObject) error { - o, err := iter.toObject(obj) - if err == plumbing.ErrInvalidType { - return nil - } - - if err != nil { - return err - } - - return cb(o) - }) -} - -func (iter *ObjectIter) toObject(obj plumbing.EncodedObject) (Object, error) { - switch obj.Type() { - case plumbing.BlobObject: - blob := &Blob{} - return blob, blob.Decode(obj) - case plumbing.TreeObject: - tree := &Tree{s: iter.s} - return tree, tree.Decode(obj) - case plumbing.CommitObject: - commit := &Commit{} - return commit, commit.Decode(obj) - case plumbing.TagObject: - tag := &Tag{} - return tag, tag.Decode(obj) - default: - return nil, plumbing.ErrInvalidType - } -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/object/patch.go b/vendor/github.com/go-git/go-git/v5/plumbing/object/patch.go deleted file mode 100644 index 9b5f438c..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/object/patch.go +++ /dev/null @@ -1,346 +0,0 @@ -package object - -import ( - "bytes" - "context" - "errors" - "fmt" - "io" - "math" - "strings" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/plumbing/filemode" - fdiff "github.com/go-git/go-git/v5/plumbing/format/diff" - "github.com/go-git/go-git/v5/utils/diff" - - dmp "github.com/sergi/go-diff/diffmatchpatch" -) - -var ( - ErrCanceled = errors.New("operation canceled") -) - -func getPatch(message string, changes ...*Change) (*Patch, error) { - ctx := context.Background() - return getPatchContext(ctx, message, changes...) -} - -func getPatchContext(ctx context.Context, message string, changes ...*Change) (*Patch, error) { - var filePatches []fdiff.FilePatch - for _, c := range changes { - select { - case <-ctx.Done(): - return nil, ErrCanceled - default: - } - - fp, err := filePatchWithContext(ctx, c) - if err != nil { - return nil, err - } - - filePatches = append(filePatches, fp) - } - - return &Patch{message, filePatches}, nil -} - -func filePatchWithContext(ctx context.Context, c *Change) (fdiff.FilePatch, error) { - from, to, err := c.Files() - if err != nil { - return nil, err - } - fromContent, fIsBinary, err := fileContent(from) - if err != nil { - return nil, err - } - - toContent, tIsBinary, err := fileContent(to) - if err != nil { - return nil, err - } - - if fIsBinary || tIsBinary { - return &textFilePatch{from: c.From, to: c.To}, nil - } - - diffs := diff.Do(fromContent, toContent) - - var chunks []fdiff.Chunk - for _, d := range diffs { - select { - case <-ctx.Done(): - return nil, ErrCanceled - default: - } - - var op fdiff.Operation - switch d.Type { - case dmp.DiffEqual: - op = fdiff.Equal - case dmp.DiffDelete: - op = fdiff.Delete - case dmp.DiffInsert: - op = fdiff.Add - } - - chunks = append(chunks, &textChunk{d.Text, op}) - } - - return &textFilePatch{ - chunks: chunks, - from: c.From, - to: c.To, - }, nil - -} - -func filePatch(c *Change) (fdiff.FilePatch, error) { - return filePatchWithContext(context.Background(), c) -} - -func fileContent(f *File) (content string, isBinary bool, err error) { - if f == nil { - return - } - - isBinary, err = f.IsBinary() - if err != nil || isBinary { - return - } - - content, err = f.Contents() - - return -} - -// Patch is an implementation of fdiff.Patch interface -type Patch struct { - message string - filePatches []fdiff.FilePatch -} - -func (p *Patch) FilePatches() []fdiff.FilePatch { - return p.filePatches -} - -func (p *Patch) Message() string { - return p.message -} - -func (p *Patch) Encode(w io.Writer) error { - ue := fdiff.NewUnifiedEncoder(w, fdiff.DefaultContextLines) - - return ue.Encode(p) -} - -func (p *Patch) Stats() FileStats { - return getFileStatsFromFilePatches(p.FilePatches()) -} - -func (p *Patch) String() string { - buf := bytes.NewBuffer(nil) - err := p.Encode(buf) - if err != nil { - return fmt.Sprintf("malformed patch: %s", err.Error()) - } - - return buf.String() -} - -// changeEntryWrapper is an implementation of fdiff.File interface -type changeEntryWrapper struct { - ce ChangeEntry -} - -func (f *changeEntryWrapper) Hash() plumbing.Hash { - if !f.ce.TreeEntry.Mode.IsFile() { - return plumbing.ZeroHash - } - - return f.ce.TreeEntry.Hash -} - -func (f *changeEntryWrapper) Mode() filemode.FileMode { - return f.ce.TreeEntry.Mode -} -func (f *changeEntryWrapper) Path() string { - if !f.ce.TreeEntry.Mode.IsFile() { - return "" - } - - return f.ce.Name -} - -func (f *changeEntryWrapper) Empty() bool { - return !f.ce.TreeEntry.Mode.IsFile() -} - -// textFilePatch is an implementation of fdiff.FilePatch interface -type textFilePatch struct { - chunks []fdiff.Chunk - from, to ChangeEntry -} - -func (tf *textFilePatch) Files() (from fdiff.File, to fdiff.File) { - f := &changeEntryWrapper{tf.from} - t := &changeEntryWrapper{tf.to} - - if !f.Empty() { - from = f - } - - if !t.Empty() { - to = t - } - - return -} - -func (tf *textFilePatch) IsBinary() bool { - return len(tf.chunks) == 0 -} - -func (tf *textFilePatch) Chunks() []fdiff.Chunk { - return tf.chunks -} - -// textChunk is an implementation of fdiff.Chunk interface -type textChunk struct { - content string - op fdiff.Operation -} - -func (t *textChunk) Content() string { - return t.content -} - -func (t *textChunk) Type() fdiff.Operation { - return t.op -} - -// FileStat stores the status of changes in content of a file. -type FileStat struct { - Name string - Addition int - Deletion int -} - -func (fs FileStat) String() string { - return printStat([]FileStat{fs}) -} - -// FileStats is a collection of FileStat. -type FileStats []FileStat - -func (fileStats FileStats) String() string { - return printStat(fileStats) -} - -func printStat(fileStats []FileStat) string { - padLength := float64(len(" ")) - newlineLength := float64(len("\n")) - separatorLength := float64(len("|")) - // Soft line length limit. The text length calculation below excludes - // length of the change number. Adding that would take it closer to 80, - // but probably not more than 80, until it's a huge number. - lineLength := 72.0 - - // Get the longest filename and longest total change. - var longestLength float64 - var longestTotalChange float64 - for _, fs := range fileStats { - if int(longestLength) < len(fs.Name) { - longestLength = float64(len(fs.Name)) - } - totalChange := fs.Addition + fs.Deletion - if int(longestTotalChange) < totalChange { - longestTotalChange = float64(totalChange) - } - } - - // Parts of the output: - // |<+++/---> - // example: " main.go | 10 +++++++--- " - - // - leftTextLength := padLength + longestLength + padLength - - // <+++++/-----> - // Excluding number length here. - rightTextLength := padLength + padLength + newlineLength - - totalTextArea := leftTextLength + separatorLength + rightTextLength - heightOfHistogram := lineLength - totalTextArea - - // Scale the histogram. - var scaleFactor float64 - if longestTotalChange > heightOfHistogram { - // Scale down to heightOfHistogram. - scaleFactor = longestTotalChange / heightOfHistogram - } else { - scaleFactor = 1.0 - } - - finalOutput := "" - for _, fs := range fileStats { - addn := float64(fs.Addition) - deln := float64(fs.Deletion) - adds := strings.Repeat("+", int(math.Floor(addn/scaleFactor))) - dels := strings.Repeat("-", int(math.Floor(deln/scaleFactor))) - finalOutput += fmt.Sprintf(" %s | %d %s%s\n", fs.Name, (fs.Addition + fs.Deletion), adds, dels) - } - - return finalOutput -} - -func getFileStatsFromFilePatches(filePatches []fdiff.FilePatch) FileStats { - var fileStats FileStats - - for _, fp := range filePatches { - // ignore empty patches (binary files, submodule refs updates) - if len(fp.Chunks()) == 0 { - continue - } - - cs := FileStat{} - from, to := fp.Files() - if from == nil { - // New File is created. - cs.Name = to.Path() - } else if to == nil { - // File is deleted. - cs.Name = from.Path() - } else if from.Path() != to.Path() { - // File is renamed. Not supported. - // cs.Name = fmt.Sprintf("%s => %s", from.Path(), to.Path()) - } else { - cs.Name = from.Path() - } - - for _, chunk := range fp.Chunks() { - s := chunk.Content() - if len(s) == 0 { - continue - } - - switch chunk.Type() { - case fdiff.Add: - cs.Addition += strings.Count(s, "\n") - if s[len(s)-1] != '\n' { - cs.Addition++ - } - case fdiff.Delete: - cs.Deletion += strings.Count(s, "\n") - if s[len(s)-1] != '\n' { - cs.Deletion++ - } - } - } - - fileStats = append(fileStats, cs) - } - - return fileStats -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/object/rename.go b/vendor/github.com/go-git/go-git/v5/plumbing/object/rename.go deleted file mode 100644 index 7fed72c2..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/object/rename.go +++ /dev/null @@ -1,813 +0,0 @@ -package object - -import ( - "errors" - "io" - "sort" - "strings" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/plumbing/filemode" - "github.com/go-git/go-git/v5/utils/ioutil" - "github.com/go-git/go-git/v5/utils/merkletrie" -) - -// DetectRenames detects the renames in the given changes on two trees with -// the given options. It will return the given changes grouping additions and -// deletions into modifications when possible. -// If options is nil, the default diff tree options will be used. -func DetectRenames( - changes Changes, - opts *DiffTreeOptions, -) (Changes, error) { - if opts == nil { - opts = DefaultDiffTreeOptions - } - - detector := &renameDetector{ - renameScore: int(opts.RenameScore), - renameLimit: int(opts.RenameLimit), - onlyExact: opts.OnlyExactRenames, - } - - for _, c := range changes { - action, err := c.Action() - if err != nil { - return nil, err - } - - switch action { - case merkletrie.Insert: - detector.added = append(detector.added, c) - case merkletrie.Delete: - detector.deleted = append(detector.deleted, c) - default: - detector.modified = append(detector.modified, c) - } - } - - return detector.detect() -} - -// renameDetector will detect and resolve renames in a set of changes. -// see: https://github.com/eclipse/jgit/blob/master/org.eclipse.jgit/src/org/eclipse/jgit/diff/RenameDetector.java -type renameDetector struct { - added []*Change - deleted []*Change - modified []*Change - - renameScore int - renameLimit int - onlyExact bool -} - -// detectExactRenames detects matches files that were deleted with files that -// were added where the hash is the same on both. If there are multiple targets -// the one with the most similar path will be chosen as the rename and the -// rest as either deletions or additions. -func (d *renameDetector) detectExactRenames() { - added := groupChangesByHash(d.added) - deletes := groupChangesByHash(d.deleted) - var uniqueAdds []*Change - var nonUniqueAdds [][]*Change - var addedLeft []*Change - - for _, cs := range added { - if len(cs) == 1 { - uniqueAdds = append(uniqueAdds, cs[0]) - } else { - nonUniqueAdds = append(nonUniqueAdds, cs) - } - } - - for _, c := range uniqueAdds { - hash := changeHash(c) - deleted := deletes[hash] - - if len(deleted) == 1 { - if sameMode(c, deleted[0]) { - d.modified = append(d.modified, &Change{From: deleted[0].From, To: c.To}) - delete(deletes, hash) - } else { - addedLeft = append(addedLeft, c) - } - } else if len(deleted) > 1 { - bestMatch := bestNameMatch(c, deleted) - if bestMatch != nil && sameMode(c, bestMatch) { - d.modified = append(d.modified, &Change{From: bestMatch.From, To: c.To}) - delete(deletes, hash) - - var newDeletes = make([]*Change, 0, len(deleted)-1) - for _, d := range deleted { - if d != bestMatch { - newDeletes = append(newDeletes, d) - } - } - deletes[hash] = newDeletes - } - } else { - addedLeft = append(addedLeft, c) - } - } - - for _, added := range nonUniqueAdds { - hash := changeHash(added[0]) - deleted := deletes[hash] - - if len(deleted) == 1 { - deleted := deleted[0] - bestMatch := bestNameMatch(deleted, added) - if bestMatch != nil && sameMode(deleted, bestMatch) { - d.modified = append(d.modified, &Change{From: deleted.From, To: bestMatch.To}) - delete(deletes, hash) - - for _, c := range added { - if c != bestMatch { - addedLeft = append(addedLeft, c) - } - } - } else { - addedLeft = append(addedLeft, added...) - } - } else if len(deleted) > 1 { - maxSize := len(deleted) * len(added) - if d.renameLimit > 0 && d.renameLimit < maxSize { - maxSize = d.renameLimit - } - - matrix := make(similarityMatrix, 0, maxSize) - - for delIdx, del := range deleted { - deletedName := changeName(del) - - for addIdx, add := range added { - addedName := changeName(add) - - score := nameSimilarityScore(addedName, deletedName) - matrix = append(matrix, similarityPair{added: addIdx, deleted: delIdx, score: score}) - - if len(matrix) >= maxSize { - break - } - } - - if len(matrix) >= maxSize { - break - } - } - - sort.Stable(matrix) - - usedAdds := make(map[*Change]struct{}) - usedDeletes := make(map[*Change]struct{}) - for i := len(matrix) - 1; i >= 0; i-- { - del := deleted[matrix[i].deleted] - add := added[matrix[i].added] - - if add == nil || del == nil { - // it was already matched - continue - } - - usedAdds[add] = struct{}{} - usedDeletes[del] = struct{}{} - d.modified = append(d.modified, &Change{From: del.From, To: add.To}) - added[matrix[i].added] = nil - deleted[matrix[i].deleted] = nil - } - - for _, c := range added { - if _, ok := usedAdds[c]; !ok && c != nil { - addedLeft = append(addedLeft, c) - } - } - - var newDeletes = make([]*Change, 0, len(deleted)-len(usedDeletes)) - for _, c := range deleted { - if _, ok := usedDeletes[c]; !ok && c != nil { - newDeletes = append(newDeletes, c) - } - } - deletes[hash] = newDeletes - } else { - addedLeft = append(addedLeft, added...) - } - } - - d.added = addedLeft - d.deleted = nil - for _, dels := range deletes { - d.deleted = append(d.deleted, dels...) - } -} - -// detectContentRenames detects renames based on the similarity of the content -// in the files by building a matrix of pairs between sources and destinations -// and matching by the highest score. -// see: https://github.com/eclipse/jgit/blob/master/org.eclipse.jgit/src/org/eclipse/jgit/diff/SimilarityRenameDetector.java -func (d *renameDetector) detectContentRenames() error { - cnt := max(len(d.added), len(d.deleted)) - if d.renameLimit > 0 && cnt > d.renameLimit { - return nil - } - - srcs, dsts := d.deleted, d.added - matrix, err := buildSimilarityMatrix(srcs, dsts, d.renameScore) - if err != nil { - return err - } - renames := make([]*Change, 0, min(len(matrix), len(dsts))) - - // Match rename pairs on a first come, first serve basis until - // we have looked at everything that is above the minimum score. - for i := len(matrix) - 1; i >= 0; i-- { - pair := matrix[i] - src := srcs[pair.deleted] - dst := dsts[pair.added] - - if dst == nil || src == nil { - // It was already matched before - continue - } - - renames = append(renames, &Change{From: src.From, To: dst.To}) - - // Claim destination and source as matched - dsts[pair.added] = nil - srcs[pair.deleted] = nil - } - - d.modified = append(d.modified, renames...) - d.added = compactChanges(dsts) - d.deleted = compactChanges(srcs) - - return nil -} - -func (d *renameDetector) detect() (Changes, error) { - if len(d.added) > 0 && len(d.deleted) > 0 { - d.detectExactRenames() - - if !d.onlyExact { - if err := d.detectContentRenames(); err != nil { - return nil, err - } - } - } - - result := make(Changes, 0, len(d.added)+len(d.deleted)+len(d.modified)) - result = append(result, d.added...) - result = append(result, d.deleted...) - result = append(result, d.modified...) - - sort.Stable(result) - - return result, nil -} - -func bestNameMatch(change *Change, changes []*Change) *Change { - var best *Change - var bestScore int - - cname := changeName(change) - - for _, c := range changes { - score := nameSimilarityScore(cname, changeName(c)) - if score > bestScore { - bestScore = score - best = c - } - } - - return best -} - -func nameSimilarityScore(a, b string) int { - aDirLen := strings.LastIndexByte(a, '/') + 1 - bDirLen := strings.LastIndexByte(b, '/') + 1 - - dirMin := min(aDirLen, bDirLen) - dirMax := max(aDirLen, bDirLen) - - var dirScoreLtr, dirScoreRtl int - if dirMax == 0 { - dirScoreLtr = 100 - dirScoreRtl = 100 - } else { - var dirSim int - - for ; dirSim < dirMin; dirSim++ { - if a[dirSim] != b[dirSim] { - break - } - } - - dirScoreLtr = dirSim * 100 / dirMax - - if dirScoreLtr == 100 { - dirScoreRtl = 100 - } else { - for dirSim = 0; dirSim < dirMin; dirSim++ { - if a[aDirLen-1-dirSim] != b[bDirLen-1-dirSim] { - break - } - } - dirScoreRtl = dirSim * 100 / dirMax - } - } - - fileMin := min(len(a)-aDirLen, len(b)-bDirLen) - fileMax := max(len(a)-aDirLen, len(b)-bDirLen) - - fileSim := 0 - for ; fileSim < fileMin; fileSim++ { - if a[len(a)-1-fileSim] != b[len(b)-1-fileSim] { - break - } - } - fileScore := fileSim * 100 / fileMax - - return (((dirScoreLtr + dirScoreRtl) * 25) + (fileScore * 50)) / 100 -} - -func changeName(c *Change) string { - if c.To != empty { - return c.To.Name - } - return c.From.Name -} - -func changeHash(c *Change) plumbing.Hash { - if c.To != empty { - return c.To.TreeEntry.Hash - } - - return c.From.TreeEntry.Hash -} - -func changeMode(c *Change) filemode.FileMode { - if c.To != empty { - return c.To.TreeEntry.Mode - } - - return c.From.TreeEntry.Mode -} - -func sameMode(a, b *Change) bool { - return changeMode(a) == changeMode(b) -} - -func groupChangesByHash(changes []*Change) map[plumbing.Hash][]*Change { - var result = make(map[plumbing.Hash][]*Change) - for _, c := range changes { - hash := changeHash(c) - result[hash] = append(result[hash], c) - } - return result -} - -type similarityMatrix []similarityPair - -func (m similarityMatrix) Len() int { return len(m) } -func (m similarityMatrix) Swap(i, j int) { m[i], m[j] = m[j], m[i] } -func (m similarityMatrix) Less(i, j int) bool { - if m[i].score == m[j].score { - if m[i].added == m[j].added { - return m[i].deleted < m[j].deleted - } - return m[i].added < m[j].added - } - return m[i].score < m[j].score -} - -type similarityPair struct { - // index of the added file - added int - // index of the deleted file - deleted int - // similarity score - score int -} - -func max(a, b int) int { - if a > b { - return a - } - return b -} - -func min(a, b int) int { - if a < b { - return a - } - return b -} - -func buildSimilarityMatrix(srcs, dsts []*Change, renameScore int) (similarityMatrix, error) { - // Allocate for the worst-case scenario where every pair has a score - // that we need to consider. We might not need that many. - matrix := make(similarityMatrix, 0, len(srcs)*len(dsts)) - srcSizes := make([]int64, len(srcs)) - dstSizes := make([]int64, len(dsts)) - dstTooLarge := make(map[int]bool) - - // Consider each pair of files, if the score is above the minimum - // threshold we need to record that scoring in the matrix so we can - // later find the best matches. -outerLoop: - for srcIdx, src := range srcs { - if changeMode(src) != filemode.Regular { - continue - } - - // Declare the from file and the similarity index here to be able to - // reuse it inside the inner loop. The reason to not initialize them - // here is so we can skip the initialization in case they happen to - // not be needed later. They will be initialized inside the inner - // loop if and only if they're needed and reused in subsequent passes. - var from *File - var s *similarityIndex - var err error - for dstIdx, dst := range dsts { - if changeMode(dst) != filemode.Regular { - continue - } - - if dstTooLarge[dstIdx] { - continue - } - - var to *File - srcSize := srcSizes[srcIdx] - if srcSize == 0 { - from, _, err = src.Files() - if err != nil { - return nil, err - } - srcSize = from.Size + 1 - srcSizes[srcIdx] = srcSize - } - - dstSize := dstSizes[dstIdx] - if dstSize == 0 { - _, to, err = dst.Files() - if err != nil { - return nil, err - } - dstSize = to.Size + 1 - dstSizes[dstIdx] = dstSize - } - - min, max := srcSize, dstSize - if dstSize < srcSize { - min = dstSize - max = srcSize - } - - if int(min*100/max) < renameScore { - // File sizes are too different to be a match - continue - } - - if s == nil { - s, err = fileSimilarityIndex(from) - if err != nil { - if err == errIndexFull { - continue outerLoop - } - return nil, err - } - } - - if to == nil { - _, to, err = dst.Files() - if err != nil { - return nil, err - } - } - - di, err := fileSimilarityIndex(to) - if err != nil { - if err == errIndexFull { - dstTooLarge[dstIdx] = true - } - - return nil, err - } - - contentScore := s.score(di, 10000) - // The name score returns a value between 0 and 100, so we need to - // convert it to the same range as the content score. - nameScore := nameSimilarityScore(src.From.Name, dst.To.Name) * 100 - score := (contentScore*99 + nameScore*1) / 10000 - - if score < renameScore { - continue - } - - matrix = append(matrix, similarityPair{added: dstIdx, deleted: srcIdx, score: score}) - } - } - - sort.Stable(matrix) - - return matrix, nil -} - -func compactChanges(changes []*Change) []*Change { - var result []*Change - for _, c := range changes { - if c != nil { - result = append(result, c) - } - } - return result -} - -const ( - keyShift = 32 - maxCountValue = (1 << keyShift) - 1 -) - -var errIndexFull = errors.New("index is full") - -// similarityIndex is an index structure of lines/blocks in one file. -// This structure can be used to compute an approximation of the similarity -// between two files. -// To save space in memory, this index uses a space efficient encoding which -// will not exceed 1MiB per instance. The index starts out at a smaller size -// (closer to 2KiB), but may grow as more distinct blocks within the scanned -// file are discovered. -// see: https://github.com/eclipse/jgit/blob/master/org.eclipse.jgit/src/org/eclipse/jgit/diff/SimilarityIndex.java -type similarityIndex struct { - hashed uint64 - // number of non-zero entries in hashes - numHashes int - growAt int - hashes []keyCountPair - hashBits int -} - -func fileSimilarityIndex(f *File) (*similarityIndex, error) { - idx := newSimilarityIndex() - if err := idx.hash(f); err != nil { - return nil, err - } - - sort.Stable(keyCountPairs(idx.hashes)) - - return idx, nil -} - -func newSimilarityIndex() *similarityIndex { - return &similarityIndex{ - hashBits: 8, - hashes: make([]keyCountPair, 1<<8), - growAt: shouldGrowAt(8), - } -} - -func (i *similarityIndex) hash(f *File) error { - isBin, err := f.IsBinary() - if err != nil { - return err - } - - r, err := f.Reader() - if err != nil { - return err - } - - defer ioutil.CheckClose(r, &err) - - return i.hashContent(r, f.Size, isBin) -} - -func (i *similarityIndex) hashContent(r io.Reader, size int64, isBin bool) error { - var buf = make([]byte, 4096) - var ptr, cnt int - remaining := size - - for 0 < remaining { - hash := 5381 - var blockHashedCnt uint64 - - // Hash one line or block, whatever happens first - n := int64(0) - for { - if ptr == cnt { - ptr = 0 - var err error - cnt, err = io.ReadFull(r, buf) - if err != nil && err != io.ErrUnexpectedEOF { - return err - } - - if cnt == 0 { - return io.EOF - } - } - n++ - c := buf[ptr] & 0xff - ptr++ - - // Ignore CR in CRLF sequence if it's text - if !isBin && c == '\r' && ptr < cnt && buf[ptr] == '\n' { - continue - } - blockHashedCnt++ - - if c == '\n' { - break - } - - hash = (hash << 5) + hash + int(c) - - if n >= 64 || n >= remaining { - break - } - } - i.hashed += blockHashedCnt - if err := i.add(hash, blockHashedCnt); err != nil { - return err - } - remaining -= n - } - - return nil -} - -// score computes the similarity score between this index and another one. -// A region of a file is defined as a line in a text file or a fixed-size -// block in a binary file. To prepare an index, each region in the file is -// hashed; the values and counts of hashes are retained in a sorted table. -// Define the similarity fraction F as the count of matching regions between -// the two files divided between the maximum count of regions in either file. -// The similarity score is F multiplied by the maxScore constant, yielding a -// range [0, maxScore]. It is defined as maxScore for the degenerate case of -// two empty files. -// The similarity score is symmetrical; i.e. a.score(b) == b.score(a). -func (i *similarityIndex) score(other *similarityIndex, maxScore int) int { - var maxHashed = i.hashed - if maxHashed < other.hashed { - maxHashed = other.hashed - } - if maxHashed == 0 { - return maxScore - } - - return int(i.common(other) * uint64(maxScore) / maxHashed) -} - -func (i *similarityIndex) common(dst *similarityIndex) uint64 { - srcIdx, dstIdx := 0, 0 - if i.numHashes == 0 || dst.numHashes == 0 { - return 0 - } - - var common uint64 - srcKey, dstKey := i.hashes[srcIdx].key(), dst.hashes[dstIdx].key() - - for { - if srcKey == dstKey { - srcCnt, dstCnt := i.hashes[srcIdx].count(), dst.hashes[dstIdx].count() - if srcCnt < dstCnt { - common += srcCnt - } else { - common += dstCnt - } - - srcIdx++ - if srcIdx == len(i.hashes) { - break - } - srcKey = i.hashes[srcIdx].key() - - dstIdx++ - if dstIdx == len(dst.hashes) { - break - } - dstKey = dst.hashes[dstIdx].key() - } else if srcKey < dstKey { - // Region of src that is not in dst - srcIdx++ - if srcIdx == len(i.hashes) { - break - } - srcKey = i.hashes[srcIdx].key() - } else { - // Region of dst that is not in src - dstIdx++ - if dstIdx == len(dst.hashes) { - break - } - dstKey = dst.hashes[dstIdx].key() - } - } - - return common -} - -func (i *similarityIndex) add(key int, cnt uint64) error { - key = int(uint32(key) * 0x9e370001 >> 1) - - j := i.slot(key) - for { - v := i.hashes[j] - if v == 0 { - // It's an empty slot, so we can store it here. - if i.growAt <= i.numHashes { - if err := i.grow(); err != nil { - return err - } - j = i.slot(key) - continue - } - - var err error - i.hashes[j], err = newKeyCountPair(key, cnt) - if err != nil { - return err - } - i.numHashes++ - return nil - } else if v.key() == key { - // It's the same key, so increment the counter. - var err error - i.hashes[j], err = newKeyCountPair(key, v.count()+cnt) - if err != nil { - return err - } - return nil - } else if j+1 >= len(i.hashes) { - j = 0 - } else { - j++ - } - } -} - -type keyCountPair uint64 - -func newKeyCountPair(key int, cnt uint64) (keyCountPair, error) { - if cnt > maxCountValue { - return 0, errIndexFull - } - - return keyCountPair((uint64(key) << keyShift) | cnt), nil -} - -func (p keyCountPair) key() int { - return int(p >> keyShift) -} - -func (p keyCountPair) count() uint64 { - return uint64(p) & maxCountValue -} - -func (i *similarityIndex) slot(key int) int { - // We use 31 - hashBits because the upper bit was already forced - // to be 0 and we want the remaining high bits to be used as the - // table slot. - return int(uint32(key) >> uint(31-i.hashBits)) -} - -func shouldGrowAt(hashBits int) int { - return (1 << uint(hashBits)) * (hashBits - 3) / hashBits -} - -func (i *similarityIndex) grow() error { - if i.hashBits == 30 { - return errIndexFull - } - - old := i.hashes - - i.hashBits++ - i.growAt = shouldGrowAt(i.hashBits) - - // TODO(erizocosmico): find a way to check if it will OOM and return - // errIndexFull instead. - i.hashes = make([]keyCountPair, 1<= len(i.hashes) { - j = 0 - } - } - i.hashes[j] = v - } - } - - return nil -} - -type keyCountPairs []keyCountPair - -func (p keyCountPairs) Len() int { return len(p) } -func (p keyCountPairs) Swap(i, j int) { p[i], p[j] = p[j], p[i] } -func (p keyCountPairs) Less(i, j int) bool { return p[i] < p[j] } diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/object/tag.go b/vendor/github.com/go-git/go-git/v5/plumbing/object/tag.go deleted file mode 100644 index 46416580..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/object/tag.go +++ /dev/null @@ -1,357 +0,0 @@ -package object - -import ( - "bufio" - "bytes" - "fmt" - "io" - stdioutil "io/ioutil" - "strings" - - "golang.org/x/crypto/openpgp" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/plumbing/storer" - "github.com/go-git/go-git/v5/utils/ioutil" -) - -// Tag represents an annotated tag object. It points to a single git object of -// any type, but tags typically are applied to commit or blob objects. It -// provides a reference that associates the target with a tag name. It also -// contains meta-information about the tag, including the tagger, tag date and -// message. -// -// Note that this is not used for lightweight tags. -// -// https://git-scm.com/book/en/v2/Git-Internals-Git-References#Tags -type Tag struct { - // Hash of the tag. - Hash plumbing.Hash - // Name of the tag. - Name string - // Tagger is the one who created the tag. - Tagger Signature - // Message is an arbitrary text message. - Message string - // PGPSignature is the PGP signature of the tag. - PGPSignature string - // TargetType is the object type of the target. - TargetType plumbing.ObjectType - // Target is the hash of the target object. - Target plumbing.Hash - - s storer.EncodedObjectStorer -} - -// GetTag gets a tag from an object storer and decodes it. -func GetTag(s storer.EncodedObjectStorer, h plumbing.Hash) (*Tag, error) { - o, err := s.EncodedObject(plumbing.TagObject, h) - if err != nil { - return nil, err - } - - return DecodeTag(s, o) -} - -// DecodeTag decodes an encoded object into a *Commit and associates it to the -// given object storer. -func DecodeTag(s storer.EncodedObjectStorer, o plumbing.EncodedObject) (*Tag, error) { - t := &Tag{s: s} - if err := t.Decode(o); err != nil { - return nil, err - } - - return t, nil -} - -// ID returns the object ID of the tag, not the object that the tag references. -// The returned value will always match the current value of Tag.Hash. -// -// ID is present to fulfill the Object interface. -func (t *Tag) ID() plumbing.Hash { - return t.Hash -} - -// Type returns the type of object. It always returns plumbing.TagObject. -// -// Type is present to fulfill the Object interface. -func (t *Tag) Type() plumbing.ObjectType { - return plumbing.TagObject -} - -// Decode transforms a plumbing.EncodedObject into a Tag struct. -func (t *Tag) Decode(o plumbing.EncodedObject) (err error) { - if o.Type() != plumbing.TagObject { - return ErrUnsupportedObject - } - - t.Hash = o.Hash() - - reader, err := o.Reader() - if err != nil { - return err - } - defer ioutil.CheckClose(reader, &err) - - r := bufPool.Get().(*bufio.Reader) - defer bufPool.Put(r) - r.Reset(reader) - for { - var line []byte - line, err = r.ReadBytes('\n') - if err != nil && err != io.EOF { - return err - } - - line = bytes.TrimSpace(line) - if len(line) == 0 { - break // Start of message - } - - split := bytes.SplitN(line, []byte{' '}, 2) - switch string(split[0]) { - case "object": - t.Target = plumbing.NewHash(string(split[1])) - case "type": - t.TargetType, err = plumbing.ParseObjectType(string(split[1])) - if err != nil { - return err - } - case "tag": - t.Name = string(split[1]) - case "tagger": - t.Tagger.Decode(split[1]) - } - - if err == io.EOF { - return nil - } - } - - data, err := stdioutil.ReadAll(r) - if err != nil { - return err - } - - var pgpsig bool - // Check if data contains PGP signature. - if bytes.Contains(data, []byte(beginpgp)) { - // Split the lines at newline. - messageAndSig := bytes.Split(data, []byte("\n")) - - for _, l := range messageAndSig { - if pgpsig { - if bytes.Contains(l, []byte(endpgp)) { - t.PGPSignature += endpgp + "\n" - break - } else { - t.PGPSignature += string(l) + "\n" - } - continue - } - - // Check if it's the beginning of a PGP signature. - if bytes.Contains(l, []byte(beginpgp)) { - t.PGPSignature += beginpgp + "\n" - pgpsig = true - continue - } - - t.Message += string(l) + "\n" - } - } else { - t.Message = string(data) - } - - return nil -} - -// Encode transforms a Tag into a plumbing.EncodedObject. -func (t *Tag) Encode(o plumbing.EncodedObject) error { - return t.encode(o, true) -} - -// EncodeWithoutSignature export a Tag into a plumbing.EncodedObject without the signature (correspond to the payload of the PGP signature). -func (t *Tag) EncodeWithoutSignature(o plumbing.EncodedObject) error { - return t.encode(o, false) -} - -func (t *Tag) encode(o plumbing.EncodedObject, includeSig bool) (err error) { - o.SetType(plumbing.TagObject) - w, err := o.Writer() - if err != nil { - return err - } - defer ioutil.CheckClose(w, &err) - - if _, err = fmt.Fprintf(w, - "object %s\ntype %s\ntag %s\ntagger ", - t.Target.String(), t.TargetType.Bytes(), t.Name); err != nil { - return err - } - - if err = t.Tagger.Encode(w); err != nil { - return err - } - - if _, err = fmt.Fprint(w, "\n\n"); err != nil { - return err - } - - if _, err = fmt.Fprint(w, t.Message); err != nil { - return err - } - - // Note that this is highly sensitive to what it sent along in the message. - // Message *always* needs to end with a newline, or else the message and the - // signature will be concatenated into a corrupt object. Since this is a - // lower-level method, we assume you know what you are doing and have already - // done the needful on the message in the caller. - if includeSig { - if _, err = fmt.Fprint(w, t.PGPSignature); err != nil { - return err - } - } - - return err -} - -// Commit returns the commit pointed to by the tag. If the tag points to a -// different type of object ErrUnsupportedObject will be returned. -func (t *Tag) Commit() (*Commit, error) { - if t.TargetType != plumbing.CommitObject { - return nil, ErrUnsupportedObject - } - - o, err := t.s.EncodedObject(plumbing.CommitObject, t.Target) - if err != nil { - return nil, err - } - - return DecodeCommit(t.s, o) -} - -// Tree returns the tree pointed to by the tag. If the tag points to a commit -// object the tree of that commit will be returned. If the tag does not point -// to a commit or tree object ErrUnsupportedObject will be returned. -func (t *Tag) Tree() (*Tree, error) { - switch t.TargetType { - case plumbing.CommitObject: - c, err := t.Commit() - if err != nil { - return nil, err - } - - return c.Tree() - case plumbing.TreeObject: - return GetTree(t.s, t.Target) - default: - return nil, ErrUnsupportedObject - } -} - -// Blob returns the blob pointed to by the tag. If the tag points to a -// different type of object ErrUnsupportedObject will be returned. -func (t *Tag) Blob() (*Blob, error) { - if t.TargetType != plumbing.BlobObject { - return nil, ErrUnsupportedObject - } - - return GetBlob(t.s, t.Target) -} - -// Object returns the object pointed to by the tag. -func (t *Tag) Object() (Object, error) { - o, err := t.s.EncodedObject(t.TargetType, t.Target) - if err != nil { - return nil, err - } - - return DecodeObject(t.s, o) -} - -// String returns the meta information contained in the tag as a formatted -// string. -func (t *Tag) String() string { - obj, _ := t.Object() - - return fmt.Sprintf( - "%s %s\nTagger: %s\nDate: %s\n\n%s\n%s", - plumbing.TagObject, t.Name, t.Tagger.String(), t.Tagger.When.Format(DateFormat), - t.Message, objectAsString(obj), - ) -} - -// Verify performs PGP verification of the tag with a provided armored -// keyring and returns openpgp.Entity associated with verifying key on success. -func (t *Tag) Verify(armoredKeyRing string) (*openpgp.Entity, error) { - keyRingReader := strings.NewReader(armoredKeyRing) - keyring, err := openpgp.ReadArmoredKeyRing(keyRingReader) - if err != nil { - return nil, err - } - - // Extract signature. - signature := strings.NewReader(t.PGPSignature) - - encoded := &plumbing.MemoryObject{} - // Encode tag components, excluding signature and get a reader object. - if err := t.EncodeWithoutSignature(encoded); err != nil { - return nil, err - } - er, err := encoded.Reader() - if err != nil { - return nil, err - } - - return openpgp.CheckArmoredDetachedSignature(keyring, er, signature) -} - -// TagIter provides an iterator for a set of tags. -type TagIter struct { - storer.EncodedObjectIter - s storer.EncodedObjectStorer -} - -// NewTagIter takes a storer.EncodedObjectStorer and a -// storer.EncodedObjectIter and returns a *TagIter that iterates over all -// tags contained in the storer.EncodedObjectIter. -// -// Any non-tag object returned by the storer.EncodedObjectIter is skipped. -func NewTagIter(s storer.EncodedObjectStorer, iter storer.EncodedObjectIter) *TagIter { - return &TagIter{iter, s} -} - -// Next moves the iterator to the next tag and returns a pointer to it. If -// there are no more tags, it returns io.EOF. -func (iter *TagIter) Next() (*Tag, error) { - obj, err := iter.EncodedObjectIter.Next() - if err != nil { - return nil, err - } - - return DecodeTag(iter.s, obj) -} - -// ForEach call the cb function for each tag contained on this iter until -// an error happens or the end of the iter is reached. If ErrStop is sent -// the iteration is stop but no error is returned. The iterator is closed. -func (iter *TagIter) ForEach(cb func(*Tag) error) error { - return iter.EncodedObjectIter.ForEach(func(obj plumbing.EncodedObject) error { - t, err := DecodeTag(iter.s, obj) - if err != nil { - return err - } - - return cb(t) - }) -} - -func objectAsString(obj Object) string { - switch o := obj.(type) { - case *Commit: - return o.String() - default: - return "" - } -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/object/tree.go b/vendor/github.com/go-git/go-git/v5/plumbing/object/tree.go deleted file mode 100644 index 5e6378ca..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/object/tree.go +++ /dev/null @@ -1,525 +0,0 @@ -package object - -import ( - "bufio" - "context" - "errors" - "fmt" - "io" - "path" - "path/filepath" - "strings" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/plumbing/filemode" - "github.com/go-git/go-git/v5/plumbing/storer" - "github.com/go-git/go-git/v5/utils/ioutil" -) - -const ( - maxTreeDepth = 1024 - startingStackSize = 8 -) - -// New errors defined by this package. -var ( - ErrMaxTreeDepth = errors.New("maximum tree depth exceeded") - ErrFileNotFound = errors.New("file not found") - ErrDirectoryNotFound = errors.New("directory not found") - ErrEntryNotFound = errors.New("entry not found") -) - -// Tree is basically like a directory - it references a bunch of other trees -// and/or blobs (i.e. files and sub-directories) -type Tree struct { - Entries []TreeEntry - Hash plumbing.Hash - - s storer.EncodedObjectStorer - m map[string]*TreeEntry - t map[string]*Tree // tree path cache -} - -// GetTree gets a tree from an object storer and decodes it. -func GetTree(s storer.EncodedObjectStorer, h plumbing.Hash) (*Tree, error) { - o, err := s.EncodedObject(plumbing.TreeObject, h) - if err != nil { - return nil, err - } - - return DecodeTree(s, o) -} - -// DecodeTree decodes an encoded object into a *Tree and associates it to the -// given object storer. -func DecodeTree(s storer.EncodedObjectStorer, o plumbing.EncodedObject) (*Tree, error) { - t := &Tree{s: s} - if err := t.Decode(o); err != nil { - return nil, err - } - - return t, nil -} - -// TreeEntry represents a file -type TreeEntry struct { - Name string - Mode filemode.FileMode - Hash plumbing.Hash -} - -// File returns the hash of the file identified by the `path` argument. -// The path is interpreted as relative to the tree receiver. -func (t *Tree) File(path string) (*File, error) { - e, err := t.FindEntry(path) - if err != nil { - return nil, ErrFileNotFound - } - - blob, err := GetBlob(t.s, e.Hash) - if err != nil { - if err == plumbing.ErrObjectNotFound { - return nil, ErrFileNotFound - } - return nil, err - } - - return NewFile(path, e.Mode, blob), nil -} - -// Size returns the plaintext size of an object, without reading it -// into memory. -func (t *Tree) Size(path string) (int64, error) { - e, err := t.FindEntry(path) - if err != nil { - return 0, ErrEntryNotFound - } - - return t.s.EncodedObjectSize(e.Hash) -} - -// Tree returns the tree identified by the `path` argument. -// The path is interpreted as relative to the tree receiver. -func (t *Tree) Tree(path string) (*Tree, error) { - e, err := t.FindEntry(path) - if err != nil { - return nil, ErrDirectoryNotFound - } - - tree, err := GetTree(t.s, e.Hash) - if err == plumbing.ErrObjectNotFound { - return nil, ErrDirectoryNotFound - } - - return tree, err -} - -// TreeEntryFile returns the *File for a given *TreeEntry. -func (t *Tree) TreeEntryFile(e *TreeEntry) (*File, error) { - blob, err := GetBlob(t.s, e.Hash) - if err != nil { - return nil, err - } - - return NewFile(e.Name, e.Mode, blob), nil -} - -// FindEntry search a TreeEntry in this tree or any subtree. -func (t *Tree) FindEntry(path string) (*TreeEntry, error) { - if t.t == nil { - t.t = make(map[string]*Tree) - } - - pathParts := strings.Split(path, "/") - startingTree := t - pathCurrent := "" - - // search for the longest path in the tree path cache - for i := len(pathParts) - 1; i > 1; i-- { - path := filepath.Join(pathParts[:i]...) - - tree, ok := t.t[path] - if ok { - startingTree = tree - pathParts = pathParts[i:] - pathCurrent = path - - break - } - } - - var tree *Tree - var err error - for tree = startingTree; len(pathParts) > 1; pathParts = pathParts[1:] { - if tree, err = tree.dir(pathParts[0]); err != nil { - return nil, err - } - - pathCurrent = filepath.Join(pathCurrent, pathParts[0]) - t.t[pathCurrent] = tree - } - - return tree.entry(pathParts[0]) -} - -func (t *Tree) dir(baseName string) (*Tree, error) { - entry, err := t.entry(baseName) - if err != nil { - return nil, ErrDirectoryNotFound - } - - obj, err := t.s.EncodedObject(plumbing.TreeObject, entry.Hash) - if err != nil { - return nil, err - } - - tree := &Tree{s: t.s} - err = tree.Decode(obj) - - return tree, err -} - -func (t *Tree) entry(baseName string) (*TreeEntry, error) { - if t.m == nil { - t.buildMap() - } - - entry, ok := t.m[baseName] - if !ok { - return nil, ErrEntryNotFound - } - - return entry, nil -} - -// Files returns a FileIter allowing to iterate over the Tree -func (t *Tree) Files() *FileIter { - return NewFileIter(t.s, t) -} - -// ID returns the object ID of the tree. The returned value will always match -// the current value of Tree.Hash. -// -// ID is present to fulfill the Object interface. -func (t *Tree) ID() plumbing.Hash { - return t.Hash -} - -// Type returns the type of object. It always returns plumbing.TreeObject. -func (t *Tree) Type() plumbing.ObjectType { - return plumbing.TreeObject -} - -// Decode transform an plumbing.EncodedObject into a Tree struct -func (t *Tree) Decode(o plumbing.EncodedObject) (err error) { - if o.Type() != plumbing.TreeObject { - return ErrUnsupportedObject - } - - t.Hash = o.Hash() - if o.Size() == 0 { - return nil - } - - t.Entries = nil - t.m = nil - - reader, err := o.Reader() - if err != nil { - return err - } - defer ioutil.CheckClose(reader, &err) - - r := bufPool.Get().(*bufio.Reader) - defer bufPool.Put(r) - r.Reset(reader) - for { - str, err := r.ReadString(' ') - if err != nil { - if err == io.EOF { - break - } - - return err - } - str = str[:len(str)-1] // strip last byte (' ') - - mode, err := filemode.New(str) - if err != nil { - return err - } - - name, err := r.ReadString(0) - if err != nil && err != io.EOF { - return err - } - - var hash plumbing.Hash - if _, err = io.ReadFull(r, hash[:]); err != nil { - return err - } - - baseName := name[:len(name)-1] - t.Entries = append(t.Entries, TreeEntry{ - Hash: hash, - Mode: mode, - Name: baseName, - }) - } - - return nil -} - -// Encode transforms a Tree into a plumbing.EncodedObject. -func (t *Tree) Encode(o plumbing.EncodedObject) (err error) { - o.SetType(plumbing.TreeObject) - w, err := o.Writer() - if err != nil { - return err - } - - defer ioutil.CheckClose(w, &err) - for _, entry := range t.Entries { - if _, err = fmt.Fprintf(w, "%o %s", entry.Mode, entry.Name); err != nil { - return err - } - - if _, err = w.Write([]byte{0x00}); err != nil { - return err - } - - if _, err = w.Write(entry.Hash[:]); err != nil { - return err - } - } - - return err -} - -func (t *Tree) buildMap() { - t.m = make(map[string]*TreeEntry) - for i := 0; i < len(t.Entries); i++ { - t.m[t.Entries[i].Name] = &t.Entries[i] - } -} - -// Diff returns a list of changes between this tree and the provided one -func (t *Tree) Diff(to *Tree) (Changes, error) { - return t.DiffContext(context.Background(), to) -} - -// DiffContext returns a list of changes between this tree and the provided one -// Error will be returned if context expires. Provided context must be non nil. -// -// NOTE: Since version 5.1.0 the renames are correctly handled, the settings -// used are the recommended options DefaultDiffTreeOptions. -func (t *Tree) DiffContext(ctx context.Context, to *Tree) (Changes, error) { - return DiffTreeWithOptions(ctx, t, to, DefaultDiffTreeOptions) -} - -// Patch returns a slice of Patch objects with all the changes between trees -// in chunks. This representation can be used to create several diff outputs. -func (t *Tree) Patch(to *Tree) (*Patch, error) { - return t.PatchContext(context.Background(), to) -} - -// PatchContext returns a slice of Patch objects with all the changes between -// trees in chunks. This representation can be used to create several diff -// outputs. If context expires, an error will be returned. Provided context must -// be non-nil. -// -// NOTE: Since version 5.1.0 the renames are correctly handled, the settings -// used are the recommended options DefaultDiffTreeOptions. -func (t *Tree) PatchContext(ctx context.Context, to *Tree) (*Patch, error) { - changes, err := t.DiffContext(ctx, to) - if err != nil { - return nil, err - } - - return changes.PatchContext(ctx) -} - -// treeEntryIter facilitates iterating through the TreeEntry objects in a Tree. -type treeEntryIter struct { - t *Tree - pos int -} - -func (iter *treeEntryIter) Next() (TreeEntry, error) { - if iter.pos >= len(iter.t.Entries) { - return TreeEntry{}, io.EOF - } - iter.pos++ - return iter.t.Entries[iter.pos-1], nil -} - -// TreeWalker provides a means of walking through all of the entries in a Tree. -type TreeWalker struct { - stack []*treeEntryIter - base string - recursive bool - seen map[plumbing.Hash]bool - - s storer.EncodedObjectStorer - t *Tree -} - -// NewTreeWalker returns a new TreeWalker for the given tree. -// -// It is the caller's responsibility to call Close() when finished with the -// tree walker. -func NewTreeWalker(t *Tree, recursive bool, seen map[plumbing.Hash]bool) *TreeWalker { - stack := make([]*treeEntryIter, 0, startingStackSize) - stack = append(stack, &treeEntryIter{t, 0}) - - return &TreeWalker{ - stack: stack, - recursive: recursive, - seen: seen, - - s: t.s, - t: t, - } -} - -// Next returns the next object from the tree. Objects are returned in order -// and subtrees are included. After the last object has been returned further -// calls to Next() will return io.EOF. -// -// In the current implementation any objects which cannot be found in the -// underlying repository will be skipped automatically. It is possible that this -// may change in future versions. -func (w *TreeWalker) Next() (name string, entry TreeEntry, err error) { - var obj *Tree - for { - current := len(w.stack) - 1 - if current < 0 { - // Nothing left on the stack so we're finished - err = io.EOF - return - } - - if current > maxTreeDepth { - // We're probably following bad data or some self-referencing tree - err = ErrMaxTreeDepth - return - } - - entry, err = w.stack[current].Next() - if err == io.EOF { - // Finished with the current tree, move back up to the parent - w.stack = w.stack[:current] - w.base, _ = path.Split(w.base) - w.base = strings.TrimSuffix(w.base, "/") - continue - } - - if err != nil { - return - } - - if w.seen[entry.Hash] { - continue - } - - if entry.Mode == filemode.Dir { - obj, err = GetTree(w.s, entry.Hash) - } - - name = simpleJoin(w.base, entry.Name) - - if err != nil { - err = io.EOF - return - } - - break - } - - if !w.recursive { - return - } - - if obj != nil { - w.stack = append(w.stack, &treeEntryIter{obj, 0}) - w.base = simpleJoin(w.base, entry.Name) - } - - return -} - -// Tree returns the tree that the tree walker most recently operated on. -func (w *TreeWalker) Tree() *Tree { - current := len(w.stack) - 1 - if w.stack[current].pos == 0 { - current-- - } - - if current < 0 { - return nil - } - - return w.stack[current].t -} - -// Close releases any resources used by the TreeWalker. -func (w *TreeWalker) Close() { - w.stack = nil -} - -// TreeIter provides an iterator for a set of trees. -type TreeIter struct { - storer.EncodedObjectIter - s storer.EncodedObjectStorer -} - -// NewTreeIter takes a storer.EncodedObjectStorer and a -// storer.EncodedObjectIter and returns a *TreeIter that iterates over all -// tree contained in the storer.EncodedObjectIter. -// -// Any non-tree object returned by the storer.EncodedObjectIter is skipped. -func NewTreeIter(s storer.EncodedObjectStorer, iter storer.EncodedObjectIter) *TreeIter { - return &TreeIter{iter, s} -} - -// Next moves the iterator to the next tree and returns a pointer to it. If -// there are no more trees, it returns io.EOF. -func (iter *TreeIter) Next() (*Tree, error) { - for { - obj, err := iter.EncodedObjectIter.Next() - if err != nil { - return nil, err - } - - if obj.Type() != plumbing.TreeObject { - continue - } - - return DecodeTree(iter.s, obj) - } -} - -// ForEach call the cb function for each tree contained on this iter until -// an error happens or the end of the iter is reached. If ErrStop is sent -// the iteration is stop but no error is returned. The iterator is closed. -func (iter *TreeIter) ForEach(cb func(*Tree) error) error { - return iter.EncodedObjectIter.ForEach(func(obj plumbing.EncodedObject) error { - if obj.Type() != plumbing.TreeObject { - return nil - } - - t, err := DecodeTree(iter.s, obj) - if err != nil { - return err - } - - return cb(t) - }) -} - -func simpleJoin(parent, child string) string { - if len(parent) > 0 { - return parent + "/" + child - } - return child -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/object/treenoder.go b/vendor/github.com/go-git/go-git/v5/plumbing/object/treenoder.go deleted file mode 100644 index b4891b95..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/object/treenoder.go +++ /dev/null @@ -1,136 +0,0 @@ -package object - -import ( - "io" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/plumbing/filemode" - "github.com/go-git/go-git/v5/utils/merkletrie/noder" -) - -// A treenoder is a helper type that wraps git trees into merkletrie -// noders. -// -// As a merkletrie noder doesn't understand the concept of modes (e.g. -// file permissions), the treenoder includes the mode of the git tree in -// the hash, so changes in the modes will be detected as modifications -// to the file contents by the merkletrie difftree algorithm. This is -// consistent with how the "git diff-tree" command works. -type treeNoder struct { - parent *Tree // the root node is its own parent - name string // empty string for the root node - mode filemode.FileMode - hash plumbing.Hash - children []noder.Noder // memoized -} - -// NewTreeRootNode returns the root node of a Tree -func NewTreeRootNode(t *Tree) noder.Noder { - if t == nil { - return &treeNoder{} - } - - return &treeNoder{ - parent: t, - name: "", - mode: filemode.Dir, - hash: t.Hash, - } -} - -func (t *treeNoder) isRoot() bool { - return t.name == "" -} - -func (t *treeNoder) String() string { - return "treeNoder <" + t.name + ">" -} - -func (t *treeNoder) Hash() []byte { - if t.mode == filemode.Deprecated { - return append(t.hash[:], filemode.Regular.Bytes()...) - } - return append(t.hash[:], t.mode.Bytes()...) -} - -func (t *treeNoder) Name() string { - return t.name -} - -func (t *treeNoder) IsDir() bool { - return t.mode == filemode.Dir -} - -// Children will return the children of a treenoder as treenoders, -// building them from the children of the wrapped git tree. -func (t *treeNoder) Children() ([]noder.Noder, error) { - if t.mode != filemode.Dir { - return noder.NoChildren, nil - } - - // children are memoized for efficiency - if t.children != nil { - return t.children, nil - } - - // the parent of the returned children will be ourself as a tree if - // we are a not the root treenoder. The root is special as it - // is is own parent. - parent := t.parent - if !t.isRoot() { - var err error - if parent, err = t.parent.Tree(t.name); err != nil { - return nil, err - } - } - - return transformChildren(parent) -} - -// Returns the children of a tree as treenoders. -// Efficiency is key here. -func transformChildren(t *Tree) ([]noder.Noder, error) { - var err error - var e TreeEntry - - // there will be more tree entries than children in the tree, - // due to submodules and empty directories, but I think it is still - // worth it to pre-allocate the whole array now, even if sometimes - // is bigger than needed. - ret := make([]noder.Noder, 0, len(t.Entries)) - - walker := NewTreeWalker(t, false, nil) // don't recurse - // don't defer walker.Close() for efficiency reasons. - for { - _, e, err = walker.Next() - if err == io.EOF { - break - } - if err != nil { - walker.Close() - return nil, err - } - - ret = append(ret, &treeNoder{ - parent: t, - name: e.Name, - mode: e.Mode, - hash: e.Hash, - }) - } - walker.Close() - - return ret, nil -} - -// len(t.tree.Entries) != the number of elements walked by treewalker -// for some reason because of empty directories, submodules, etc, so we -// have to walk here. -func (t *treeNoder) NumChildren() (int, error) { - children, err := t.Children() - if err != nil { - return 0, err - } - - return len(children), nil -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/advrefs.go b/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/advrefs.go deleted file mode 100644 index 1bd724ca..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/advrefs.go +++ /dev/null @@ -1,211 +0,0 @@ -package packp - -import ( - "fmt" - "sort" - "strings" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/plumbing/protocol/packp/capability" - "github.com/go-git/go-git/v5/plumbing/storer" - "github.com/go-git/go-git/v5/storage/memory" -) - -// AdvRefs values represent the information transmitted on an -// advertised-refs message. Values from this type are not zero-value -// safe, use the New function instead. -type AdvRefs struct { - // Prefix stores prefix payloads. - // - // When using this message over (smart) HTTP, you have to add a pktline - // before the whole thing with the following payload: - // - // '# service=$servicename" LF - // - // Moreover, some (all) git HTTP smart servers will send a flush-pkt - // just after the first pkt-line. - // - // To accommodate both situations, the Prefix field allow you to store - // any data you want to send before the actual pktlines. It will also - // be filled up with whatever is found on the line. - Prefix [][]byte - // Head stores the resolved HEAD reference if present. - // This can be present with git-upload-pack, not with git-receive-pack. - Head *plumbing.Hash - // Capabilities are the capabilities. - Capabilities *capability.List - // References are the hash references. - References map[string]plumbing.Hash - // Peeled are the peeled hash references. - Peeled map[string]plumbing.Hash - // Shallows are the shallow object ids. - Shallows []plumbing.Hash -} - -// NewAdvRefs returns a pointer to a new AdvRefs value, ready to be used. -func NewAdvRefs() *AdvRefs { - return &AdvRefs{ - Prefix: [][]byte{}, - Capabilities: capability.NewList(), - References: make(map[string]plumbing.Hash), - Peeled: make(map[string]plumbing.Hash), - Shallows: []plumbing.Hash{}, - } -} - -func (a *AdvRefs) AddReference(r *plumbing.Reference) error { - switch r.Type() { - case plumbing.SymbolicReference: - v := fmt.Sprintf("%s:%s", r.Name().String(), r.Target().String()) - a.Capabilities.Add(capability.SymRef, v) - case plumbing.HashReference: - a.References[r.Name().String()] = r.Hash() - default: - return plumbing.ErrInvalidType - } - - return nil -} - -func (a *AdvRefs) AllReferences() (memory.ReferenceStorage, error) { - s := memory.ReferenceStorage{} - if err := a.addRefs(s); err != nil { - return s, plumbing.NewUnexpectedError(err) - } - - return s, nil -} - -func (a *AdvRefs) addRefs(s storer.ReferenceStorer) error { - for name, hash := range a.References { - ref := plumbing.NewReferenceFromStrings(name, hash.String()) - if err := s.SetReference(ref); err != nil { - return err - } - } - - if a.supportSymrefs() { - return a.addSymbolicRefs(s) - } - - return a.resolveHead(s) -} - -// If the server does not support symrefs capability, -// we need to guess the reference where HEAD is pointing to. -// -// Git versions prior to 1.8.4.3 has an special procedure to get -// the reference where is pointing to HEAD: -// - Check if a reference called master exists. If exists and it -// has the same hash as HEAD hash, we can say that HEAD is pointing to master -// - If master does not exists or does not have the same hash as HEAD, -// order references and check in that order if that reference has the same -// hash than HEAD. If yes, set HEAD pointing to that branch hash -// - If no reference is found, throw an error -func (a *AdvRefs) resolveHead(s storer.ReferenceStorer) error { - if a.Head == nil { - return nil - } - - ref, err := s.Reference(plumbing.Master) - - // check first if HEAD is pointing to master - if err == nil { - ok, err := a.createHeadIfCorrectReference(ref, s) - if err != nil { - return err - } - - if ok { - return nil - } - } - - if err != nil && err != plumbing.ErrReferenceNotFound { - return err - } - - // From here we are trying to guess the branch that HEAD is pointing - refIter, err := s.IterReferences() - if err != nil { - return err - } - - var refNames []string - err = refIter.ForEach(func(r *plumbing.Reference) error { - refNames = append(refNames, string(r.Name())) - return nil - }) - if err != nil { - return err - } - - sort.Strings(refNames) - - var headSet bool - for _, refName := range refNames { - ref, err := s.Reference(plumbing.ReferenceName(refName)) - if err != nil { - return err - } - ok, err := a.createHeadIfCorrectReference(ref, s) - if err != nil { - return err - } - if ok { - headSet = true - break - } - } - - if !headSet { - return plumbing.ErrReferenceNotFound - } - - return nil -} - -func (a *AdvRefs) createHeadIfCorrectReference( - reference *plumbing.Reference, - s storer.ReferenceStorer) (bool, error) { - if reference.Hash() == *a.Head { - headRef := plumbing.NewSymbolicReference(plumbing.HEAD, reference.Name()) - if err := s.SetReference(headRef); err != nil { - return false, err - } - - return true, nil - } - - return false, nil -} - -func (a *AdvRefs) addSymbolicRefs(s storer.ReferenceStorer) error { - for _, symref := range a.Capabilities.Get(capability.SymRef) { - chunks := strings.Split(symref, ":") - if len(chunks) != 2 { - err := fmt.Errorf("bad number of `:` in symref value (%q)", symref) - return plumbing.NewUnexpectedError(err) - } - name := plumbing.ReferenceName(chunks[0]) - target := plumbing.ReferenceName(chunks[1]) - ref := plumbing.NewSymbolicReference(name, target) - if err := s.SetReference(ref); err != nil { - return nil - } - } - - return nil -} - -func (a *AdvRefs) supportSymrefs() bool { - return a.Capabilities.Supports(capability.SymRef) -} - -// IsEmpty returns true if doesn't contain any reference. -func (a *AdvRefs) IsEmpty() bool { - return a.Head == nil && - len(a.References) == 0 && - len(a.Peeled) == 0 && - len(a.Shallows) == 0 -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/advrefs_decode.go b/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/advrefs_decode.go deleted file mode 100644 index 63bbe5ab..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/advrefs_decode.go +++ /dev/null @@ -1,288 +0,0 @@ -package packp - -import ( - "bytes" - "encoding/hex" - "errors" - "fmt" - "io" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/plumbing/format/pktline" -) - -// Decode reads the next advertised-refs message form its input and -// stores it in the AdvRefs. -func (a *AdvRefs) Decode(r io.Reader) error { - d := newAdvRefsDecoder(r) - return d.Decode(a) -} - -type advRefsDecoder struct { - s *pktline.Scanner // a pkt-line scanner from the input stream - line []byte // current pkt-line contents, use parser.nextLine() to make it advance - nLine int // current pkt-line number for debugging, begins at 1 - hash plumbing.Hash // last hash read - err error // sticky error, use the parser.error() method to fill this out - data *AdvRefs // parsed data is stored here -} - -var ( - // ErrEmptyAdvRefs is returned by Decode if it gets an empty advertised - // references message. - ErrEmptyAdvRefs = errors.New("empty advertised-ref message") - // ErrEmptyInput is returned by Decode if the input is empty. - ErrEmptyInput = errors.New("empty input") -) - -func newAdvRefsDecoder(r io.Reader) *advRefsDecoder { - return &advRefsDecoder{ - s: pktline.NewScanner(r), - } -} - -func (d *advRefsDecoder) Decode(v *AdvRefs) error { - d.data = v - - for state := decodePrefix; state != nil; { - state = state(d) - } - - return d.err -} - -type decoderStateFn func(*advRefsDecoder) decoderStateFn - -// fills out the parser sticky error -func (d *advRefsDecoder) error(format string, a ...interface{}) { - msg := fmt.Sprintf( - "pkt-line %d: %s", d.nLine, - fmt.Sprintf(format, a...), - ) - - d.err = NewErrUnexpectedData(msg, d.line) -} - -// Reads a new pkt-line from the scanner, makes its payload available as -// p.line and increments p.nLine. A successful invocation returns true, -// otherwise, false is returned and the sticky error is filled out -// accordingly. Trims eols at the end of the payloads. -func (d *advRefsDecoder) nextLine() bool { - d.nLine++ - - if !d.s.Scan() { - if d.err = d.s.Err(); d.err != nil { - return false - } - - if d.nLine == 1 { - d.err = ErrEmptyInput - return false - } - - d.error("EOF") - return false - } - - d.line = d.s.Bytes() - d.line = bytes.TrimSuffix(d.line, eol) - - return true -} - -// The HTTP smart prefix is often followed by a flush-pkt. -func decodePrefix(d *advRefsDecoder) decoderStateFn { - if ok := d.nextLine(); !ok { - return nil - } - - if !isPrefix(d.line) { - return decodeFirstHash - } - - tmp := make([]byte, len(d.line)) - copy(tmp, d.line) - d.data.Prefix = append(d.data.Prefix, tmp) - if ok := d.nextLine(); !ok { - return nil - } - - if !isFlush(d.line) { - return decodeFirstHash - } - - d.data.Prefix = append(d.data.Prefix, pktline.Flush) - if ok := d.nextLine(); !ok { - return nil - } - - return decodeFirstHash -} - -func isPrefix(payload []byte) bool { - return len(payload) > 0 && payload[0] == '#' -} - -// If the first hash is zero, then a no-refs is coming. Otherwise, a -// list-of-refs is coming, and the hash will be followed by the first -// advertised ref. -func decodeFirstHash(p *advRefsDecoder) decoderStateFn { - // If the repository is empty, we receive a flush here (HTTP). - if isFlush(p.line) { - p.err = ErrEmptyAdvRefs - return nil - } - - if len(p.line) < hashSize { - p.error("cannot read hash, pkt-line too short") - return nil - } - - if _, err := hex.Decode(p.hash[:], p.line[:hashSize]); err != nil { - p.error("invalid hash text: %s", err) - return nil - } - - p.line = p.line[hashSize:] - - if p.hash.IsZero() { - return decodeSkipNoRefs - } - - return decodeFirstRef -} - -// Skips SP "capabilities^{}" NUL -func decodeSkipNoRefs(p *advRefsDecoder) decoderStateFn { - if len(p.line) < len(noHeadMark) { - p.error("too short zero-id ref") - return nil - } - - if !bytes.HasPrefix(p.line, noHeadMark) { - p.error("malformed zero-id ref") - return nil - } - - p.line = p.line[len(noHeadMark):] - - return decodeCaps -} - -// decode the refname, expects SP refname NULL -func decodeFirstRef(l *advRefsDecoder) decoderStateFn { - if len(l.line) < 3 { - l.error("line too short after hash") - return nil - } - - if !bytes.HasPrefix(l.line, sp) { - l.error("no space after hash") - return nil - } - l.line = l.line[1:] - - chunks := bytes.SplitN(l.line, null, 2) - if len(chunks) < 2 { - l.error("NULL not found") - return nil - } - ref := chunks[0] - l.line = chunks[1] - - if bytes.Equal(ref, []byte(head)) { - l.data.Head = &l.hash - } else { - l.data.References[string(ref)] = l.hash - } - - return decodeCaps -} - -func decodeCaps(p *advRefsDecoder) decoderStateFn { - if err := p.data.Capabilities.Decode(p.line); err != nil { - p.error("invalid capabilities: %s", err) - return nil - } - - return decodeOtherRefs -} - -// The refs are either tips (obj-id SP refname) or a peeled (obj-id SP refname^{}). -// If there are no refs, then there might be a shallow or flush-ptk. -func decodeOtherRefs(p *advRefsDecoder) decoderStateFn { - if ok := p.nextLine(); !ok { - return nil - } - - if bytes.HasPrefix(p.line, shallow) { - return decodeShallow - } - - if len(p.line) == 0 { - return nil - } - - saveTo := p.data.References - if bytes.HasSuffix(p.line, peeled) { - p.line = bytes.TrimSuffix(p.line, peeled) - saveTo = p.data.Peeled - } - - ref, hash, err := readRef(p.line) - if err != nil { - p.error("%s", err) - return nil - } - saveTo[ref] = hash - - return decodeOtherRefs -} - -// Reads a ref-name -func readRef(data []byte) (string, plumbing.Hash, error) { - chunks := bytes.Split(data, sp) - switch { - case len(chunks) == 1: - return "", plumbing.ZeroHash, fmt.Errorf("malformed ref data: no space was found") - case len(chunks) > 2: - return "", plumbing.ZeroHash, fmt.Errorf("malformed ref data: more than one space found") - default: - return string(chunks[1]), plumbing.NewHash(string(chunks[0])), nil - } -} - -// Keeps reading shallows until a flush-pkt is found -func decodeShallow(p *advRefsDecoder) decoderStateFn { - if !bytes.HasPrefix(p.line, shallow) { - p.error("malformed shallow prefix, found %q... instead", p.line[:len(shallow)]) - return nil - } - p.line = bytes.TrimPrefix(p.line, shallow) - - if len(p.line) != hashSize { - p.error(fmt.Sprintf( - "malformed shallow hash: wrong length, expected 40 bytes, read %d bytes", - len(p.line))) - return nil - } - - text := p.line[:hashSize] - var h plumbing.Hash - if _, err := hex.Decode(h[:], text); err != nil { - p.error("invalid hash text: %s", err) - return nil - } - - p.data.Shallows = append(p.data.Shallows, h) - - if ok := p.nextLine(); !ok { - return nil - } - - if len(p.line) == 0 { - return nil // successful parse of the advertised-refs message - } - - return decodeShallow -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/advrefs_encode.go b/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/advrefs_encode.go deleted file mode 100644 index fb9bd883..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/advrefs_encode.go +++ /dev/null @@ -1,176 +0,0 @@ -package packp - -import ( - "bytes" - "fmt" - "io" - "sort" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/plumbing/format/pktline" - "github.com/go-git/go-git/v5/plumbing/protocol/packp/capability" -) - -// Encode writes the AdvRefs encoding to a writer. -// -// All the payloads will end with a newline character. Capabilities, -// references and shallows are written in alphabetical order, except for -// peeled references that always follow their corresponding references. -func (a *AdvRefs) Encode(w io.Writer) error { - e := newAdvRefsEncoder(w) - return e.Encode(a) -} - -type advRefsEncoder struct { - data *AdvRefs // data to encode - pe *pktline.Encoder // where to write the encoded data - firstRefName string // reference name to encode in the first pkt-line (HEAD if present) - firstRefHash plumbing.Hash // hash referenced to encode in the first pkt-line (HEAD if present) - sortedRefs []string // hash references to encode ordered by increasing order - err error // sticky error - -} - -func newAdvRefsEncoder(w io.Writer) *advRefsEncoder { - return &advRefsEncoder{ - pe: pktline.NewEncoder(w), - } -} - -func (e *advRefsEncoder) Encode(v *AdvRefs) error { - e.data = v - e.sortRefs() - e.setFirstRef() - - for state := encodePrefix; state != nil; { - state = state(e) - } - - return e.err -} - -func (e *advRefsEncoder) sortRefs() { - if len(e.data.References) > 0 { - refs := make([]string, 0, len(e.data.References)) - for refName := range e.data.References { - refs = append(refs, refName) - } - - sort.Strings(refs) - e.sortedRefs = refs - } -} - -func (e *advRefsEncoder) setFirstRef() { - if e.data.Head != nil { - e.firstRefName = head - e.firstRefHash = *e.data.Head - return - } - - if len(e.sortedRefs) > 0 { - refName := e.sortedRefs[0] - e.firstRefName = refName - e.firstRefHash = e.data.References[refName] - } -} - -type encoderStateFn func(*advRefsEncoder) encoderStateFn - -func encodePrefix(e *advRefsEncoder) encoderStateFn { - for _, p := range e.data.Prefix { - if bytes.Equal(p, pktline.Flush) { - if e.err = e.pe.Flush(); e.err != nil { - return nil - } - continue - } - if e.err = e.pe.Encodef("%s\n", string(p)); e.err != nil { - return nil - } - } - - return encodeFirstLine -} - -// Adds the first pkt-line payload: head hash, head ref and capabilities. -// If HEAD ref is not found, the first reference ordered in increasing order will be used. -// If there aren't HEAD neither refs, the first line will be "PKT-LINE(zero-id SP "capabilities^{}" NUL capability-list)". -// See: https://github.com/git/git/blob/master/Documentation/technical/pack-protocol.txt -// See: https://github.com/git/git/blob/master/Documentation/technical/protocol-common.txt -func encodeFirstLine(e *advRefsEncoder) encoderStateFn { - const formatFirstLine = "%s %s\x00%s\n" - var firstLine string - capabilities := formatCaps(e.data.Capabilities) - - if e.firstRefName == "" { - firstLine = fmt.Sprintf(formatFirstLine, plumbing.ZeroHash.String(), "capabilities^{}", capabilities) - } else { - firstLine = fmt.Sprintf(formatFirstLine, e.firstRefHash.String(), e.firstRefName, capabilities) - - } - - if e.err = e.pe.EncodeString(firstLine); e.err != nil { - return nil - } - - return encodeRefs -} - -func formatCaps(c *capability.List) string { - if c == nil { - return "" - } - - return c.String() -} - -// Adds the (sorted) refs: hash SP refname EOL -// and their peeled refs if any. -func encodeRefs(e *advRefsEncoder) encoderStateFn { - for _, r := range e.sortedRefs { - if r == e.firstRefName { - continue - } - - hash := e.data.References[r] - if e.err = e.pe.Encodef("%s %s\n", hash.String(), r); e.err != nil { - return nil - } - - if hash, ok := e.data.Peeled[r]; ok { - if e.err = e.pe.Encodef("%s %s^{}\n", hash.String(), r); e.err != nil { - return nil - } - } - } - - return encodeShallow -} - -// Adds the (sorted) shallows: "shallow" SP hash EOL -func encodeShallow(e *advRefsEncoder) encoderStateFn { - sorted := sortShallows(e.data.Shallows) - for _, hash := range sorted { - if e.err = e.pe.Encodef("shallow %s\n", hash); e.err != nil { - return nil - } - } - - return encodeFlush -} - -func sortShallows(c []plumbing.Hash) []string { - ret := []string{} - for _, h := range c { - ret = append(ret, h.String()) - } - sort.Strings(ret) - - return ret -} - -func encodeFlush(e *advRefsEncoder) encoderStateFn { - e.err = e.pe.Flush() - return nil -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/capability/capability.go b/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/capability/capability.go deleted file mode 100644 index 8d6a56f5..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/capability/capability.go +++ /dev/null @@ -1,259 +0,0 @@ -// Package capability defines the server and client capabilities. -package capability - -// Capability describes a server or client capability. -type Capability string - -func (n Capability) String() string { - return string(n) -} - -const ( - // MultiACK capability allows the server to return "ACK obj-id continue" as - // soon as it finds a commit that it can use as a common base, between the - // client's wants and the client's have set. - // - // By sending this early, the server can potentially head off the client - // from walking any further down that particular branch of the client's - // repository history. The client may still need to walk down other - // branches, sending have lines for those, until the server has a - // complete cut across the DAG, or the client has said "done". - // - // Without multi_ack, a client sends have lines in --date-order until - // the server has found a common base. That means the client will send - // have lines that are already known by the server to be common, because - // they overlap in time with another branch that the server hasn't found - // a common base on yet. - // - // For example suppose the client has commits in caps that the server - // doesn't and the server has commits in lower case that the client - // doesn't, as in the following diagram: - // - // +---- u ---------------------- x - // / +----- y - // / / - // a -- b -- c -- d -- E -- F - // \ - // +--- Q -- R -- S - // - // If the client wants x,y and starts out by saying have F,S, the server - // doesn't know what F,S is. Eventually the client says "have d" and - // the server sends "ACK d continue" to let the client know to stop - // walking down that line (so don't send c-b-a), but it's not done yet, - // it needs a base for x. The client keeps going with S-R-Q, until a - // gets reached, at which point the server has a clear base and it all - // ends. - // - // Without multi_ack the client would have sent that c-b-a chain anyway, - // interleaved with S-R-Q. - MultiACK Capability = "multi_ack" - // MultiACKDetailed is an extension of multi_ack that permits client to - // better understand the server's in-memory state. - MultiACKDetailed Capability = "multi_ack_detailed" - // NoDone should only be used with the smart HTTP protocol. If - // multi_ack_detailed and no-done are both present, then the sender is - // free to immediately send a pack following its first "ACK obj-id ready" - // message. - // - // Without no-done in the smart HTTP protocol, the server session would - // end and the client has to make another trip to send "done" before - // the server can send the pack. no-done removes the last round and - // thus slightly reduces latency. - NoDone Capability = "no-done" - // ThinPack is one with deltas which reference base objects not - // contained within the pack (but are known to exist at the receiving - // end). This can reduce the network traffic significantly, but it - // requires the receiving end to know how to "thicken" these packs by - // adding the missing bases to the pack. - // - // The upload-pack server advertises 'thin-pack' when it can generate - // and send a thin pack. A client requests the 'thin-pack' capability - // when it understands how to "thicken" it, notifying the server that - // it can receive such a pack. A client MUST NOT request the - // 'thin-pack' capability if it cannot turn a thin pack into a - // self-contained pack. - // - // Receive-pack, on the other hand, is assumed by default to be able to - // handle thin packs, but can ask the client not to use the feature by - // advertising the 'no-thin' capability. A client MUST NOT send a thin - // pack if the server advertises the 'no-thin' capability. - // - // The reasons for this asymmetry are historical. The receive-pack - // program did not exist until after the invention of thin packs, so - // historically the reference implementation of receive-pack always - // understood thin packs. Adding 'no-thin' later allowed receive-pack - // to disable the feature in a backwards-compatible manner. - ThinPack Capability = "thin-pack" - // Sideband means that server can send, and client understand multiplexed - // progress reports and error info interleaved with the packfile itself. - // - // These two options are mutually exclusive. A modern client always - // favors Sideband64k. - // - // Either mode indicates that the packfile data will be streamed broken - // up into packets of up to either 1000 bytes in the case of 'side_band', - // or 65520 bytes in the case of 'side_band_64k'. Each packet is made up - // of a leading 4-byte pkt-line length of how much data is in the packet, - // followed by a 1-byte stream code, followed by the actual data. - // - // The stream code can be one of: - // - // 1 - pack data - // 2 - progress messages - // 3 - fatal error message just before stream aborts - // - // The "side-band-64k" capability came about as a way for newer clients - // that can handle much larger packets to request packets that are - // actually crammed nearly full, while maintaining backward compatibility - // for the older clients. - // - // Further, with side-band and its up to 1000-byte messages, it's actually - // 999 bytes of payload and 1 byte for the stream code. With side-band-64k, - // same deal, you have up to 65519 bytes of data and 1 byte for the stream - // code. - // - // The client MUST send only maximum of one of "side-band" and "side- - // band-64k". Server MUST diagnose it as an error if client requests - // both. - Sideband Capability = "side-band" - Sideband64k Capability = "side-band-64k" - // OFSDelta server can send, and client understand PACKv2 with delta - // referring to its base by position in pack rather than by an obj-id. That - // is, they can send/read OBJ_OFS_DELTA (aka type 6) in a packfile. - OFSDelta Capability = "ofs-delta" - // Agent the server may optionally send this capability to notify the client - // that the server is running version `X`. The client may optionally return - // its own agent string by responding with an `agent=Y` capability (but it - // MUST NOT do so if the server did not mention the agent capability). The - // `X` and `Y` strings may contain any printable ASCII characters except - // space (i.e., the byte range 32 < x < 127), and are typically of the form - // "package/version" (e.g., "git/1.8.3.1"). The agent strings are purely - // informative for statistics and debugging purposes, and MUST NOT be used - // to programmatically assume the presence or absence of particular features. - Agent Capability = "agent" - // Shallow capability adds "deepen", "shallow" and "unshallow" commands to - // the fetch-pack/upload-pack protocol so clients can request shallow - // clones. - Shallow Capability = "shallow" - // DeepenSince adds "deepen-since" command to fetch-pack/upload-pack - // protocol so the client can request shallow clones that are cut at a - // specific time, instead of depth. Internally it's equivalent of doing - // "rev-list --max-age=" on the server side. "deepen-since" - // cannot be used with "deepen". - DeepenSince Capability = "deepen-since" - // DeepenNot adds "deepen-not" command to fetch-pack/upload-pack - // protocol so the client can request shallow clones that are cut at a - // specific revision, instead of depth. Internally it's equivalent of - // doing "rev-list --not " on the server side. "deepen-not" - // cannot be used with "deepen", but can be used with "deepen-since". - DeepenNot Capability = "deepen-not" - // DeepenRelative if this capability is requested by the client, the - // semantics of "deepen" command is changed. The "depth" argument is the - // depth from the current shallow boundary, instead of the depth from - // remote refs. - DeepenRelative Capability = "deepen-relative" - // NoProgress the client was started with "git clone -q" or something, and - // doesn't want that side band 2. Basically the client just says "I do not - // wish to receive stream 2 on sideband, so do not send it to me, and if - // you did, I will drop it on the floor anyway". However, the sideband - // channel 3 is still used for error responses. - NoProgress Capability = "no-progress" - // IncludeTag capability is about sending annotated tags if we are - // sending objects they point to. If we pack an object to the client, and - // a tag object points exactly at that object, we pack the tag object too. - // In general this allows a client to get all new annotated tags when it - // fetches a branch, in a single network connection. - // - // Clients MAY always send include-tag, hardcoding it into a request when - // the server advertises this capability. The decision for a client to - // request include-tag only has to do with the client's desires for tag - // data, whether or not a server had advertised objects in the - // refs/tags/* namespace. - // - // Servers MUST pack the tags if their referrant is packed and the client - // has requested include-tags. - // - // Clients MUST be prepared for the case where a server has ignored - // include-tag and has not actually sent tags in the pack. In such - // cases the client SHOULD issue a subsequent fetch to acquire the tags - // that include-tag would have otherwise given the client. - // - // The server SHOULD send include-tag, if it supports it, regardless - // of whether or not there are tags available. - IncludeTag Capability = "include-tag" - // ReportStatus the receive-pack process can receive a 'report-status' - // capability, which tells it that the client wants a report of what - // happened after a packfile upload and reference update. If the pushing - // client requests this capability, after unpacking and updating references - // the server will respond with whether the packfile unpacked successfully - // and if each reference was updated successfully. If any of those were not - // successful, it will send back an error message. See pack-protocol.txt - // for example messages. - ReportStatus Capability = "report-status" - // DeleteRefs If the server sends back this capability, it means that - // it is capable of accepting a zero-id value as the target - // value of a reference update. It is not sent back by the client, it - // simply informs the client that it can be sent zero-id values - // to delete references - DeleteRefs Capability = "delete-refs" - // Quiet If the receive-pack server advertises this capability, it is - // capable of silencing human-readable progress output which otherwise may - // be shown when processing the received pack. A send-pack client should - // respond with the 'quiet' capability to suppress server-side progress - // reporting if the local progress reporting is also being suppressed - // (e.g., via `push -q`, or if stderr does not go to a tty). - Quiet Capability = "quiet" - // Atomic If the server sends this capability it is capable of accepting - // atomic pushes. If the pushing client requests this capability, the server - // will update the refs in one atomic transaction. Either all refs are - // updated or none. - Atomic Capability = "atomic" - // PushOptions If the server sends this capability it is able to accept - // push options after the update commands have been sent, but before the - // packfile is streamed. If the pushing client requests this capability, - // the server will pass the options to the pre- and post- receive hooks - // that process this push request. - PushOptions Capability = "push-options" - // AllowTipSHA1InWant if the upload-pack server advertises this capability, - // fetch-pack may send "want" lines with SHA-1s that exist at the server but - // are not advertised by upload-pack. - AllowTipSHA1InWant Capability = "allow-tip-sha1-in-want" - // AllowReachableSHA1InWant if the upload-pack server advertises this - // capability, fetch-pack may send "want" lines with SHA-1s that exist at - // the server but are not advertised by upload-pack. - AllowReachableSHA1InWant Capability = "allow-reachable-sha1-in-want" - // PushCert the receive-pack server that advertises this capability is - // willing to accept a signed push certificate, and asks the to be - // included in the push certificate. A send-pack client MUST NOT - // send a push-cert packet unless the receive-pack server advertises - // this capability. - PushCert Capability = "push-cert" - // SymRef symbolic reference support for better negotiation. - SymRef Capability = "symref" - // ObjectFormat takes a hash algorithm as an argument, indicates that the - // server supports the given hash algorithms. - ObjectFormat Capability = "object-format" - // Filter if present, fetch-pack may send "filter" commands to request a - // partial clone or partial fetch and request that the server omit various objects from the packfile - Filter Capability = "filter" -) - -const DefaultAgent = "go-git/4.x" - -var known = map[Capability]bool{ - MultiACK: true, MultiACKDetailed: true, NoDone: true, ThinPack: true, - Sideband: true, Sideband64k: true, OFSDelta: true, Agent: true, - Shallow: true, DeepenSince: true, DeepenNot: true, DeepenRelative: true, - NoProgress: true, IncludeTag: true, ReportStatus: true, DeleteRefs: true, - Quiet: true, Atomic: true, PushOptions: true, AllowTipSHA1InWant: true, - AllowReachableSHA1InWant: true, PushCert: true, SymRef: true, - ObjectFormat: true, Filter: true, -} - -var requiresArgument = map[Capability]bool{ - Agent: true, PushCert: true, SymRef: true, ObjectFormat: true, -} - -var multipleArgument = map[Capability]bool{ - SymRef: true, -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/capability/list.go b/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/capability/list.go deleted file mode 100644 index f41ec799..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/capability/list.go +++ /dev/null @@ -1,193 +0,0 @@ -package capability - -import ( - "bytes" - "errors" - "fmt" - "strings" -) - -var ( - // ErrArgumentsRequired is returned if no arguments are giving with a - // capability that requires arguments - ErrArgumentsRequired = errors.New("arguments required") - // ErrArguments is returned if arguments are given with a capabilities that - // not supports arguments - ErrArguments = errors.New("arguments not allowed") - // ErrEmptyArgument is returned when an empty value is given - ErrEmptyArgument = errors.New("empty argument") - // ErrMultipleArguments multiple argument given to a capabilities that not - // support it - ErrMultipleArguments = errors.New("multiple arguments not allowed") -) - -// List represents a list of capabilities -type List struct { - m map[Capability]*entry - sort []string -} - -type entry struct { - Name Capability - Values []string -} - -// NewList returns a new List of capabilities -func NewList() *List { - return &List{ - m: make(map[Capability]*entry), - } -} - -// IsEmpty returns true if the List is empty -func (l *List) IsEmpty() bool { - return len(l.sort) == 0 -} - -// Decode decodes list of capabilities from raw into the list -func (l *List) Decode(raw []byte) error { - // git 1.x receive pack used to send a leading space on its - // git-receive-pack capabilities announcement. We just trim space to be - // tolerant to space changes in different versions. - raw = bytes.TrimSpace(raw) - - if len(raw) == 0 { - return nil - } - - for _, data := range bytes.Split(raw, []byte{' '}) { - pair := bytes.SplitN(data, []byte{'='}, 2) - - c := Capability(pair[0]) - if len(pair) == 1 { - if err := l.Add(c); err != nil { - return err - } - - continue - } - - if err := l.Add(c, string(pair[1])); err != nil { - return err - } - } - - return nil -} - -// Get returns the values for a capability -func (l *List) Get(capability Capability) []string { - if _, ok := l.m[capability]; !ok { - return nil - } - - return l.m[capability].Values -} - -// Set sets a capability removing the previous values -func (l *List) Set(capability Capability, values ...string) error { - delete(l.m, capability) - return l.Add(capability, values...) -} - -// Add adds a capability, values are optional -func (l *List) Add(c Capability, values ...string) error { - if err := l.validate(c, values); err != nil { - return err - } - - if !l.Supports(c) { - l.m[c] = &entry{Name: c} - l.sort = append(l.sort, c.String()) - } - - if len(values) == 0 { - return nil - } - - if known[c] && !multipleArgument[c] && len(l.m[c].Values) > 0 { - return ErrMultipleArguments - } - - l.m[c].Values = append(l.m[c].Values, values...) - return nil -} - -func (l *List) validateNoEmptyArgs(values []string) error { - for _, v := range values { - if v == "" { - return ErrEmptyArgument - } - } - return nil -} - -func (l *List) validate(c Capability, values []string) error { - if !known[c] { - return l.validateNoEmptyArgs(values) - } - if requiresArgument[c] && len(values) == 0 { - return ErrArgumentsRequired - } - - if !requiresArgument[c] && len(values) != 0 { - return ErrArguments - } - - if !multipleArgument[c] && len(values) > 1 { - return ErrMultipleArguments - } - return l.validateNoEmptyArgs(values) -} - -// Supports returns true if capability is present -func (l *List) Supports(capability Capability) bool { - _, ok := l.m[capability] - return ok -} - -// Delete deletes a capability from the List -func (l *List) Delete(capability Capability) { - if !l.Supports(capability) { - return - } - - delete(l.m, capability) - for i, c := range l.sort { - if c != string(capability) { - continue - } - - l.sort = append(l.sort[:i], l.sort[i+1:]...) - return - } -} - -// All returns a slice with all defined capabilities. -func (l *List) All() []Capability { - var cs []Capability - for _, key := range l.sort { - cs = append(cs, Capability(key)) - } - - return cs -} - -// String generates the capabilities strings, the capabilities are sorted in -// insertion order -func (l *List) String() string { - var o []string - for _, key := range l.sort { - cap := l.m[Capability(key)] - if len(cap.Values) == 0 { - o = append(o, key) - continue - } - - for _, value := range cap.Values { - o = append(o, fmt.Sprintf("%s=%s", key, value)) - } - } - - return strings.Join(o, " ") -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/common.go b/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/common.go deleted file mode 100644 index ab07ac8f..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/common.go +++ /dev/null @@ -1,70 +0,0 @@ -package packp - -import ( - "fmt" -) - -type stateFn func() stateFn - -const ( - // common - hashSize = 40 - - // advrefs - head = "HEAD" - noHead = "capabilities^{}" -) - -var ( - // common - sp = []byte(" ") - eol = []byte("\n") - eq = []byte{'='} - - // advertised-refs - null = []byte("\x00") - peeled = []byte("^{}") - noHeadMark = []byte(" capabilities^{}\x00") - - // upload-request - want = []byte("want ") - shallow = []byte("shallow ") - deepen = []byte("deepen") - deepenCommits = []byte("deepen ") - deepenSince = []byte("deepen-since ") - deepenReference = []byte("deepen-not ") - - // shallow-update - unshallow = []byte("unshallow ") - - // server-response - ack = []byte("ACK") - nak = []byte("NAK") - - // updreq - shallowNoSp = []byte("shallow") -) - -func isFlush(payload []byte) bool { - return len(payload) == 0 -} - -// ErrUnexpectedData represents an unexpected data decoding a message -type ErrUnexpectedData struct { - Msg string - Data []byte -} - -// NewErrUnexpectedData returns a new ErrUnexpectedData containing the data and -// the message given -func NewErrUnexpectedData(msg string, data []byte) error { - return &ErrUnexpectedData{Msg: msg, Data: data} -} - -func (err *ErrUnexpectedData) Error() string { - if len(err.Data) == 0 { - return err.Msg - } - - return fmt.Sprintf("%s (%s)", err.Msg, err.Data) -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/doc.go b/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/doc.go deleted file mode 100644 index 4950d1d6..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/doc.go +++ /dev/null @@ -1,724 +0,0 @@ -package packp - -/* - -A nice way to trace the real data transmitted and received by git, use: - -GIT_TRACE_PACKET=true git ls-remote http://github.com/src-d/go-git -GIT_TRACE_PACKET=true git clone http://github.com/src-d/go-git - -Here follows a copy of the current protocol specification at the time of -this writing. - -(Please notice that most http git servers will add a flush-pkt after the -first pkt-line when using HTTP smart.) - - -Documentation Common to Pack and Http Protocols -=============================================== - -ABNF Notation -------------- - -ABNF notation as described by RFC 5234 is used within the protocol documents, -except the following replacement core rules are used: ----- - HEXDIG = DIGIT / "a" / "b" / "c" / "d" / "e" / "f" ----- - -We also define the following common rules: ----- - NUL = %x00 - zero-id = 40*"0" - obj-id = 40*(HEXDIGIT) - - refname = "HEAD" - refname /= "refs/" ----- - -A refname is a hierarchical octet string beginning with "refs/" and -not violating the 'git-check-ref-format' command's validation rules. -More specifically, they: - -. They can include slash `/` for hierarchical (directory) - grouping, but no slash-separated component can begin with a - dot `.`. - -. They must contain at least one `/`. This enforces the presence of a - category like `heads/`, `tags/` etc. but the actual names are not - restricted. - -. They cannot have two consecutive dots `..` anywhere. - -. They cannot have ASCII control characters (i.e. bytes whose - values are lower than \040, or \177 `DEL`), space, tilde `~`, - caret `^`, colon `:`, question-mark `?`, asterisk `*`, - or open bracket `[` anywhere. - -. They cannot end with a slash `/` or a dot `.`. - -. They cannot end with the sequence `.lock`. - -. They cannot contain a sequence `@{`. - -. They cannot contain a `\\`. - - -pkt-line Format ---------------- - -Much (but not all) of the payload is described around pkt-lines. - -A pkt-line is a variable length binary string. The first four bytes -of the line, the pkt-len, indicates the total length of the line, -in hexadecimal. The pkt-len includes the 4 bytes used to contain -the length's hexadecimal representation. - -A pkt-line MAY contain binary data, so implementors MUST ensure -pkt-line parsing/formatting routines are 8-bit clean. - -A non-binary line SHOULD BE terminated by an LF, which if present -MUST be included in the total length. Receivers MUST treat pkt-lines -with non-binary data the same whether or not they contain the trailing -LF (stripping the LF if present, and not complaining when it is -missing). - -The maximum length of a pkt-line's data component is 65516 bytes. -Implementations MUST NOT send pkt-line whose length exceeds 65520 -(65516 bytes of payload + 4 bytes of length data). - -Implementations SHOULD NOT send an empty pkt-line ("0004"). - -A pkt-line with a length field of 0 ("0000"), called a flush-pkt, -is a special case and MUST be handled differently than an empty -pkt-line ("0004"). - ----- - pkt-line = data-pkt / flush-pkt - - data-pkt = pkt-len pkt-payload - pkt-len = 4*(HEXDIG) - pkt-payload = (pkt-len - 4)*(OCTET) - - flush-pkt = "0000" ----- - -Examples (as C-style strings): - ----- - pkt-line actual value - --------------------------------- - "0006a\n" "a\n" - "0005a" "a" - "000bfoobar\n" "foobar\n" - "0004" "" ----- - -Packfile transfer protocols -=========================== - -Git supports transferring data in packfiles over the ssh://, git://, http:// and -file:// transports. There exist two sets of protocols, one for pushing -data from a client to a server and another for fetching data from a -server to a client. The three transports (ssh, git, file) use the same -protocol to transfer data. http is documented in http-protocol.txt. - -The processes invoked in the canonical Git implementation are 'upload-pack' -on the server side and 'fetch-pack' on the client side for fetching data; -then 'receive-pack' on the server and 'send-pack' on the client for pushing -data. The protocol functions to have a server tell a client what is -currently on the server, then for the two to negotiate the smallest amount -of data to send in order to fully update one or the other. - -pkt-line Format ---------------- - -The descriptions below build on the pkt-line format described in -protocol-common.txt. When the grammar indicate `PKT-LINE(...)`, unless -otherwise noted the usual pkt-line LF rules apply: the sender SHOULD -include a LF, but the receiver MUST NOT complain if it is not present. - -Transports ----------- -There are three transports over which the packfile protocol is -initiated. The Git transport is a simple, unauthenticated server that -takes the command (almost always 'upload-pack', though Git -servers can be configured to be globally writable, in which 'receive- -pack' initiation is also allowed) with which the client wishes to -communicate and executes it and connects it to the requesting -process. - -In the SSH transport, the client just runs the 'upload-pack' -or 'receive-pack' process on the server over the SSH protocol and then -communicates with that invoked process over the SSH connection. - -The file:// transport runs the 'upload-pack' or 'receive-pack' -process locally and communicates with it over a pipe. - -Git Transport -------------- - -The Git transport starts off by sending the command and repository -on the wire using the pkt-line format, followed by a NUL byte and a -hostname parameter, terminated by a NUL byte. - - 0032git-upload-pack /project.git\0host=myserver.com\0 - --- - git-proto-request = request-command SP pathname NUL [ host-parameter NUL ] - request-command = "git-upload-pack" / "git-receive-pack" / - "git-upload-archive" ; case sensitive - pathname = *( %x01-ff ) ; exclude NUL - host-parameter = "host=" hostname [ ":" port ] --- - -Only host-parameter is allowed in the git-proto-request. Clients -MUST NOT attempt to send additional parameters. It is used for the -git-daemon name based virtual hosting. See --interpolated-path -option to git daemon, with the %H/%CH format characters. - -Basically what the Git client is doing to connect to an 'upload-pack' -process on the server side over the Git protocol is this: - - $ echo -e -n \ - "0039git-upload-pack /schacon/gitbook.git\0host=example.com\0" | - nc -v example.com 9418 - -If the server refuses the request for some reasons, it could abort -gracefully with an error message. - ----- - error-line = PKT-LINE("ERR" SP explanation-text) ----- - - -SSH Transport -------------- - -Initiating the upload-pack or receive-pack processes over SSH is -executing the binary on the server via SSH remote execution. -It is basically equivalent to running this: - - $ ssh git.example.com "git-upload-pack '/project.git'" - -For a server to support Git pushing and pulling for a given user over -SSH, that user needs to be able to execute one or both of those -commands via the SSH shell that they are provided on login. On some -systems, that shell access is limited to only being able to run those -two commands, or even just one of them. - -In an ssh:// format URI, it's absolute in the URI, so the '/' after -the host name (or port number) is sent as an argument, which is then -read by the remote git-upload-pack exactly as is, so it's effectively -an absolute path in the remote filesystem. - - git clone ssh://user@example.com/project.git - | - v - ssh user@example.com "git-upload-pack '/project.git'" - -In a "user@host:path" format URI, its relative to the user's home -directory, because the Git client will run: - - git clone user@example.com:project.git - | - v - ssh user@example.com "git-upload-pack 'project.git'" - -The exception is if a '~' is used, in which case -we execute it without the leading '/'. - - ssh://user@example.com/~alice/project.git, - | - v - ssh user@example.com "git-upload-pack '~alice/project.git'" - -A few things to remember here: - -- The "command name" is spelled with dash (e.g. git-upload-pack), but - this can be overridden by the client; - -- The repository path is always quoted with single quotes. - -Fetching Data From a Server ---------------------------- - -When one Git repository wants to get data that a second repository -has, the first can 'fetch' from the second. This operation determines -what data the server has that the client does not then streams that -data down to the client in packfile format. - - -Reference Discovery -------------------- - -When the client initially connects the server will immediately respond -with a listing of each reference it has (all branches and tags) along -with the object name that each reference currently points to. - - $ echo -e -n "0039git-upload-pack /schacon/gitbook.git\0host=example.com\0" | - nc -v example.com 9418 - 00887217a7c7e582c46cec22a130adf4b9d7d950fba0 HEAD\0multi_ack thin-pack - side-band side-band-64k ofs-delta shallow no-progress include-tag - 00441d3fcd5ced445d1abc402225c0b8a1299641f497 refs/heads/integration - 003f7217a7c7e582c46cec22a130adf4b9d7d950fba0 refs/heads/master - 003cb88d2441cac0977faf98efc80305012112238d9d refs/tags/v0.9 - 003c525128480b96c89e6418b1e40909bf6c5b2d580f refs/tags/v1.0 - 003fe92df48743b7bc7d26bcaabfddde0a1e20cae47c refs/tags/v1.0^{} - 0000 - -The returned response is a pkt-line stream describing each ref and -its current value. The stream MUST be sorted by name according to -the C locale ordering. - -If HEAD is a valid ref, HEAD MUST appear as the first advertised -ref. If HEAD is not a valid ref, HEAD MUST NOT appear in the -advertisement list at all, but other refs may still appear. - -The stream MUST include capability declarations behind a NUL on the -first ref. The peeled value of a ref (that is "ref^{}") MUST be -immediately after the ref itself, if presented. A conforming server -MUST peel the ref if it's an annotated tag. - ----- - advertised-refs = (no-refs / list-of-refs) - *shallow - flush-pkt - - no-refs = PKT-LINE(zero-id SP "capabilities^{}" - NUL capability-list) - - list-of-refs = first-ref *other-ref - first-ref = PKT-LINE(obj-id SP refname - NUL capability-list) - - other-ref = PKT-LINE(other-tip / other-peeled) - other-tip = obj-id SP refname - other-peeled = obj-id SP refname "^{}" - - shallow = PKT-LINE("shallow" SP obj-id) - - capability-list = capability *(SP capability) - capability = 1*(LC_ALPHA / DIGIT / "-" / "_") - LC_ALPHA = %x61-7A ----- - -Server and client MUST use lowercase for obj-id, both MUST treat obj-id -as case-insensitive. - -See protocol-capabilities.txt for a list of allowed server capabilities -and descriptions. - -Packfile Negotiation --------------------- -After reference and capabilities discovery, the client can decide to -terminate the connection by sending a flush-pkt, telling the server it can -now gracefully terminate, and disconnect, when it does not need any pack -data. This can happen with the ls-remote command, and also can happen when -the client already is up-to-date. - -Otherwise, it enters the negotiation phase, where the client and -server determine what the minimal packfile necessary for transport is, -by telling the server what objects it wants, its shallow objects -(if any), and the maximum commit depth it wants (if any). The client -will also send a list of the capabilities it wants to be in effect, -out of what the server said it could do with the first 'want' line. - ----- - upload-request = want-list - *shallow-line - *1depth-request - flush-pkt - - want-list = first-want - *additional-want - - shallow-line = PKT-LINE("shallow" SP obj-id) - - depth-request = PKT-LINE("deepen" SP depth) / - PKT-LINE("deepen-since" SP timestamp) / - PKT-LINE("deepen-not" SP ref) - - first-want = PKT-LINE("want" SP obj-id SP capability-list) - additional-want = PKT-LINE("want" SP obj-id) - - depth = 1*DIGIT ----- - -Clients MUST send all the obj-ids it wants from the reference -discovery phase as 'want' lines. Clients MUST send at least one -'want' command in the request body. Clients MUST NOT mention an -obj-id in a 'want' command which did not appear in the response -obtained through ref discovery. - -The client MUST write all obj-ids which it only has shallow copies -of (meaning that it does not have the parents of a commit) as -'shallow' lines so that the server is aware of the limitations of -the client's history. - -The client now sends the maximum commit history depth it wants for -this transaction, which is the number of commits it wants from the -tip of the history, if any, as a 'deepen' line. A depth of 0 is the -same as not making a depth request. The client does not want to receive -any commits beyond this depth, nor does it want objects needed only to -complete those commits. Commits whose parents are not received as a -result are defined as shallow and marked as such in the server. This -information is sent back to the client in the next step. - -Once all the 'want's and 'shallow's (and optional 'deepen') are -transferred, clients MUST send a flush-pkt, to tell the server side -that it is done sending the list. - -Otherwise, if the client sent a positive depth request, the server -will determine which commits will and will not be shallow and -send this information to the client. If the client did not request -a positive depth, this step is skipped. - ----- - shallow-update = *shallow-line - *unshallow-line - flush-pkt - - shallow-line = PKT-LINE("shallow" SP obj-id) - - unshallow-line = PKT-LINE("unshallow" SP obj-id) ----- - -If the client has requested a positive depth, the server will compute -the set of commits which are no deeper than the desired depth. The set -of commits start at the client's wants. - -The server writes 'shallow' lines for each -commit whose parents will not be sent as a result. The server writes -an 'unshallow' line for each commit which the client has indicated is -shallow, but is no longer shallow at the currently requested depth -(that is, its parents will now be sent). The server MUST NOT mark -as unshallow anything which the client has not indicated was shallow. - -Now the client will send a list of the obj-ids it has using 'have' -lines, so the server can make a packfile that only contains the objects -that the client needs. In multi_ack mode, the canonical implementation -will send up to 32 of these at a time, then will send a flush-pkt. The -canonical implementation will skip ahead and send the next 32 immediately, -so that there is always a block of 32 "in-flight on the wire" at a time. - ----- - upload-haves = have-list - compute-end - - have-list = *have-line - have-line = PKT-LINE("have" SP obj-id) - compute-end = flush-pkt / PKT-LINE("done") ----- - -If the server reads 'have' lines, it then will respond by ACKing any -of the obj-ids the client said it had that the server also has. The -server will ACK obj-ids differently depending on which ack mode is -chosen by the client. - -In multi_ack mode: - - * the server will respond with 'ACK obj-id continue' for any common - commits. - - * once the server has found an acceptable common base commit and is - ready to make a packfile, it will blindly ACK all 'have' obj-ids - back to the client. - - * the server will then send a 'NAK' and then wait for another response - from the client - either a 'done' or another list of 'have' lines. - -In multi_ack_detailed mode: - - * the server will differentiate the ACKs where it is signaling - that it is ready to send data with 'ACK obj-id ready' lines, and - signals the identified common commits with 'ACK obj-id common' lines. - -Without either multi_ack or multi_ack_detailed: - - * upload-pack sends "ACK obj-id" on the first common object it finds. - After that it says nothing until the client gives it a "done". - - * upload-pack sends "NAK" on a flush-pkt if no common object - has been found yet. If one has been found, and thus an ACK - was already sent, it's silent on the flush-pkt. - -After the client has gotten enough ACK responses that it can determine -that the server has enough information to send an efficient packfile -(in the canonical implementation, this is determined when it has received -enough ACKs that it can color everything left in the --date-order queue -as common with the server, or the --date-order queue is empty), or the -client determines that it wants to give up (in the canonical implementation, -this is determined when the client sends 256 'have' lines without getting -any of them ACKed by the server - meaning there is nothing in common and -the server should just send all of its objects), then the client will send -a 'done' command. The 'done' command signals to the server that the client -is ready to receive its packfile data. - -However, the 256 limit *only* turns on in the canonical client -implementation if we have received at least one "ACK %s continue" -during a prior round. This helps to ensure that at least one common -ancestor is found before we give up entirely. - -Once the 'done' line is read from the client, the server will either -send a final 'ACK obj-id' or it will send a 'NAK'. 'obj-id' is the object -name of the last commit determined to be common. The server only sends -ACK after 'done' if there is at least one common base and multi_ack or -multi_ack_detailed is enabled. The server always sends NAK after 'done' -if there is no common base found. - -Then the server will start sending its packfile data. - ----- - server-response = *ack_multi ack / nak - ack_multi = PKT-LINE("ACK" SP obj-id ack_status) - ack_status = "continue" / "common" / "ready" - ack = PKT-LINE("ACK" SP obj-id) - nak = PKT-LINE("NAK") ----- - -A simple clone may look like this (with no 'have' lines): - ----- - C: 0054want 74730d410fcb6603ace96f1dc55ea6196122532d multi_ack \ - side-band-64k ofs-delta\n - C: 0032want 7d1665144a3a975c05f1f43902ddaf084e784dbe\n - C: 0032want 5a3f6be755bbb7deae50065988cbfa1ffa9ab68a\n - C: 0032want 7e47fe2bd8d01d481f44d7af0531bd93d3b21c01\n - C: 0032want 74730d410fcb6603ace96f1dc55ea6196122532d\n - C: 0000 - C: 0009done\n - - S: 0008NAK\n - S: [PACKFILE] ----- - -An incremental update (fetch) response might look like this: - ----- - C: 0054want 74730d410fcb6603ace96f1dc55ea6196122532d multi_ack \ - side-band-64k ofs-delta\n - C: 0032want 7d1665144a3a975c05f1f43902ddaf084e784dbe\n - C: 0032want 5a3f6be755bbb7deae50065988cbfa1ffa9ab68a\n - C: 0000 - C: 0032have 7e47fe2bd8d01d481f44d7af0531bd93d3b21c01\n - C: [30 more have lines] - C: 0032have 74730d410fcb6603ace96f1dc55ea6196122532d\n - C: 0000 - - S: 003aACK 7e47fe2bd8d01d481f44d7af0531bd93d3b21c01 continue\n - S: 003aACK 74730d410fcb6603ace96f1dc55ea6196122532d continue\n - S: 0008NAK\n - - C: 0009done\n - - S: 0031ACK 74730d410fcb6603ace96f1dc55ea6196122532d\n - S: [PACKFILE] ----- - - -Packfile Data -------------- - -Now that the client and server have finished negotiation about what -the minimal amount of data that needs to be sent to the client is, the server -will construct and send the required data in packfile format. - -See pack-format.txt for what the packfile itself actually looks like. - -If 'side-band' or 'side-band-64k' capabilities have been specified by -the client, the server will send the packfile data multiplexed. - -Each packet starting with the packet-line length of the amount of data -that follows, followed by a single byte specifying the sideband the -following data is coming in on. - -In 'side-band' mode, it will send up to 999 data bytes plus 1 control -code, for a total of up to 1000 bytes in a pkt-line. In 'side-band-64k' -mode it will send up to 65519 data bytes plus 1 control code, for a -total of up to 65520 bytes in a pkt-line. - -The sideband byte will be a '1', '2' or a '3'. Sideband '1' will contain -packfile data, sideband '2' will be used for progress information that the -client will generally print to stderr and sideband '3' is used for error -information. - -If no 'side-band' capability was specified, the server will stream the -entire packfile without multiplexing. - - -Pushing Data To a Server ------------------------- - -Pushing data to a server will invoke the 'receive-pack' process on the -server, which will allow the client to tell it which references it should -update and then send all the data the server will need for those new -references to be complete. Once all the data is received and validated, -the server will then update its references to what the client specified. - -Authentication --------------- - -The protocol itself contains no authentication mechanisms. That is to be -handled by the transport, such as SSH, before the 'receive-pack' process is -invoked. If 'receive-pack' is configured over the Git transport, those -repositories will be writable by anyone who can access that port (9418) as -that transport is unauthenticated. - -Reference Discovery -------------------- - -The reference discovery phase is done nearly the same way as it is in the -fetching protocol. Each reference obj-id and name on the server is sent -in packet-line format to the client, followed by a flush-pkt. The only -real difference is that the capability listing is different - the only -possible values are 'report-status', 'delete-refs', 'ofs-delta' and -'push-options'. - -Reference Update Request and Packfile Transfer ----------------------------------------------- - -Once the client knows what references the server is at, it can send a -list of reference update requests. For each reference on the server -that it wants to update, it sends a line listing the obj-id currently on -the server, the obj-id the client would like to update it to and the name -of the reference. - -This list is followed by a flush-pkt. Then the push options are transmitted -one per packet followed by another flush-pkt. After that the packfile that -should contain all the objects that the server will need to complete the new -references will be sent. - ----- - update-request = *shallow ( command-list | push-cert ) [packfile] - - shallow = PKT-LINE("shallow" SP obj-id) - - command-list = PKT-LINE(command NUL capability-list) - *PKT-LINE(command) - flush-pkt - - command = create / delete / update - create = zero-id SP new-id SP name - delete = old-id SP zero-id SP name - update = old-id SP new-id SP name - - old-id = obj-id - new-id = obj-id - - push-cert = PKT-LINE("push-cert" NUL capability-list LF) - PKT-LINE("certificate version 0.1" LF) - PKT-LINE("pusher" SP ident LF) - PKT-LINE("pushee" SP url LF) - PKT-LINE("nonce" SP nonce LF) - PKT-LINE(LF) - *PKT-LINE(command LF) - *PKT-LINE(gpg-signature-lines LF) - PKT-LINE("push-cert-end" LF) - - packfile = "PACK" 28*(OCTET) ----- - -If the receiving end does not support delete-refs, the sending end MUST -NOT ask for delete command. - -If the receiving end does not support push-cert, the sending end -MUST NOT send a push-cert command. When a push-cert command is -sent, command-list MUST NOT be sent; the commands recorded in the -push certificate is used instead. - -The packfile MUST NOT be sent if the only command used is 'delete'. - -A packfile MUST be sent if either create or update command is used, -even if the server already has all the necessary objects. In this -case the client MUST send an empty packfile. The only time this -is likely to happen is if the client is creating -a new branch or a tag that points to an existing obj-id. - -The server will receive the packfile, unpack it, then validate each -reference that is being updated that it hasn't changed while the request -was being processed (the obj-id is still the same as the old-id), and -it will run any update hooks to make sure that the update is acceptable. -If all of that is fine, the server will then update the references. - -Push Certificate ----------------- - -A push certificate begins with a set of header lines. After the -header and an empty line, the protocol commands follow, one per -line. Note that the trailing LF in push-cert PKT-LINEs is _not_ -optional; it must be present. - -Currently, the following header fields are defined: - -`pusher` ident:: - Identify the GPG key in "Human Readable Name " - format. - -`pushee` url:: - The repository URL (anonymized, if the URL contains - authentication material) the user who ran `git push` - intended to push into. - -`nonce` nonce:: - The 'nonce' string the receiving repository asked the - pushing user to include in the certificate, to prevent - replay attacks. - -The GPG signature lines are a detached signature for the contents -recorded in the push certificate before the signature block begins. -The detached signature is used to certify that the commands were -given by the pusher, who must be the signer. - -Report Status -------------- - -After receiving the pack data from the sender, the receiver sends a -report if 'report-status' capability is in effect. -It is a short listing of what happened in that update. It will first -list the status of the packfile unpacking as either 'unpack ok' or -'unpack [error]'. Then it will list the status for each of the references -that it tried to update. Each line is either 'ok [refname]' if the -update was successful, or 'ng [refname] [error]' if the update was not. - ----- - report-status = unpack-status - 1*(command-status) - flush-pkt - - unpack-status = PKT-LINE("unpack" SP unpack-result) - unpack-result = "ok" / error-msg - - command-status = command-ok / command-fail - command-ok = PKT-LINE("ok" SP refname) - command-fail = PKT-LINE("ng" SP refname SP error-msg) - - error-msg = 1*(OCTECT) ; where not "ok" ----- - -Updates can be unsuccessful for a number of reasons. The reference can have -changed since the reference discovery phase was originally sent, meaning -someone pushed in the meantime. The reference being pushed could be a -non-fast-forward reference and the update hooks or configuration could be -set to not allow that, etc. Also, some references can be updated while others -can be rejected. - -An example client/server communication might look like this: - ----- - S: 007c74730d410fcb6603ace96f1dc55ea6196122532d refs/heads/local\0report-status delete-refs ofs-delta\n - S: 003e7d1665144a3a975c05f1f43902ddaf084e784dbe refs/heads/debug\n - S: 003f74730d410fcb6603ace96f1dc55ea6196122532d refs/heads/master\n - S: 003f74730d410fcb6603ace96f1dc55ea6196122532d refs/heads/team\n - S: 0000 - - C: 003e7d1665144a3a975c05f1f43902ddaf084e784dbe 74730d410fcb6603ace96f1dc55ea6196122532d refs/heads/debug\n - C: 003e74730d410fcb6603ace96f1dc55ea6196122532d 5a3f6be755bbb7deae50065988cbfa1ffa9ab68a refs/heads/master\n - C: 0000 - C: [PACKDATA] - - S: 000eunpack ok\n - S: 0018ok refs/heads/debug\n - S: 002ang refs/heads/master non-fast-forward\n ----- -*/ diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/report_status.go b/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/report_status.go deleted file mode 100644 index e2a0a108..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/report_status.go +++ /dev/null @@ -1,165 +0,0 @@ -package packp - -import ( - "bytes" - "fmt" - "io" - "strings" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/plumbing/format/pktline" -) - -const ( - ok = "ok" -) - -// ReportStatus is a report status message, as used in the git-receive-pack -// process whenever the 'report-status' capability is negotiated. -type ReportStatus struct { - UnpackStatus string - CommandStatuses []*CommandStatus -} - -// NewReportStatus creates a new ReportStatus message. -func NewReportStatus() *ReportStatus { - return &ReportStatus{} -} - -// Error returns the first error if any. -func (s *ReportStatus) Error() error { - if s.UnpackStatus != ok { - return fmt.Errorf("unpack error: %s", s.UnpackStatus) - } - - for _, s := range s.CommandStatuses { - if err := s.Error(); err != nil { - return err - } - } - - return nil -} - -// Encode writes the report status to a writer. -func (s *ReportStatus) Encode(w io.Writer) error { - e := pktline.NewEncoder(w) - if err := e.Encodef("unpack %s\n", s.UnpackStatus); err != nil { - return err - } - - for _, cs := range s.CommandStatuses { - if err := cs.encode(w); err != nil { - return err - } - } - - return e.Flush() -} - -// Decode reads from the given reader and decodes a report-status message. It -// does not read more input than what is needed to fill the report status. -func (s *ReportStatus) Decode(r io.Reader) error { - scan := pktline.NewScanner(r) - if err := s.scanFirstLine(scan); err != nil { - return err - } - - if err := s.decodeReportStatus(scan.Bytes()); err != nil { - return err - } - - flushed := false - for scan.Scan() { - b := scan.Bytes() - if isFlush(b) { - flushed = true - break - } - - if err := s.decodeCommandStatus(b); err != nil { - return err - } - } - - if !flushed { - return fmt.Errorf("missing flush") - } - - return scan.Err() -} - -func (s *ReportStatus) scanFirstLine(scan *pktline.Scanner) error { - if scan.Scan() { - return nil - } - - if scan.Err() != nil { - return scan.Err() - } - - return io.ErrUnexpectedEOF -} - -func (s *ReportStatus) decodeReportStatus(b []byte) error { - if isFlush(b) { - return fmt.Errorf("premature flush") - } - - b = bytes.TrimSuffix(b, eol) - - line := string(b) - fields := strings.SplitN(line, " ", 2) - if len(fields) != 2 || fields[0] != "unpack" { - return fmt.Errorf("malformed unpack status: %s", line) - } - - s.UnpackStatus = fields[1] - return nil -} - -func (s *ReportStatus) decodeCommandStatus(b []byte) error { - b = bytes.TrimSuffix(b, eol) - - line := string(b) - fields := strings.SplitN(line, " ", 3) - status := ok - if len(fields) == 3 && fields[0] == "ng" { - status = fields[2] - } else if len(fields) != 2 || fields[0] != "ok" { - return fmt.Errorf("malformed command status: %s", line) - } - - cs := &CommandStatus{ - ReferenceName: plumbing.ReferenceName(fields[1]), - Status: status, - } - s.CommandStatuses = append(s.CommandStatuses, cs) - return nil -} - -// CommandStatus is the status of a reference in a report status. -// See ReportStatus struct. -type CommandStatus struct { - ReferenceName plumbing.ReferenceName - Status string -} - -// Error returns the error, if any. -func (s *CommandStatus) Error() error { - if s.Status == ok { - return nil - } - - return fmt.Errorf("command error on %s: %s", - s.ReferenceName.String(), s.Status) -} - -func (s *CommandStatus) encode(w io.Writer) error { - e := pktline.NewEncoder(w) - if s.Error() == nil { - return e.Encodef("ok %s\n", s.ReferenceName.String()) - } - - return e.Encodef("ng %s %s\n", s.ReferenceName.String(), s.Status) -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/shallowupd.go b/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/shallowupd.go deleted file mode 100644 index fe4fe688..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/shallowupd.go +++ /dev/null @@ -1,92 +0,0 @@ -package packp - -import ( - "bytes" - "fmt" - "io" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/plumbing/format/pktline" -) - -const ( - shallowLineLen = 48 - unshallowLineLen = 50 -) - -type ShallowUpdate struct { - Shallows []plumbing.Hash - Unshallows []plumbing.Hash -} - -func (r *ShallowUpdate) Decode(reader io.Reader) error { - s := pktline.NewScanner(reader) - - for s.Scan() { - line := s.Bytes() - line = bytes.TrimSpace(line) - - var err error - switch { - case bytes.HasPrefix(line, shallow): - err = r.decodeShallowLine(line) - case bytes.HasPrefix(line, unshallow): - err = r.decodeUnshallowLine(line) - case bytes.Equal(line, pktline.Flush): - return nil - } - - if err != nil { - return err - } - } - - return s.Err() -} - -func (r *ShallowUpdate) decodeShallowLine(line []byte) error { - hash, err := r.decodeLine(line, shallow, shallowLineLen) - if err != nil { - return err - } - - r.Shallows = append(r.Shallows, hash) - return nil -} - -func (r *ShallowUpdate) decodeUnshallowLine(line []byte) error { - hash, err := r.decodeLine(line, unshallow, unshallowLineLen) - if err != nil { - return err - } - - r.Unshallows = append(r.Unshallows, hash) - return nil -} - -func (r *ShallowUpdate) decodeLine(line, prefix []byte, expLen int) (plumbing.Hash, error) { - if len(line) != expLen { - return plumbing.ZeroHash, fmt.Errorf("malformed %s%q", prefix, line) - } - - raw := string(line[expLen-40 : expLen]) - return plumbing.NewHash(raw), nil -} - -func (r *ShallowUpdate) Encode(w io.Writer) error { - e := pktline.NewEncoder(w) - - for _, h := range r.Shallows { - if err := e.Encodef("%s%s\n", shallow, h.String()); err != nil { - return err - } - } - - for _, h := range r.Unshallows { - if err := e.Encodef("%s%s\n", unshallow, h.String()); err != nil { - return err - } - } - - return e.Flush() -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/sideband/common.go b/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/sideband/common.go deleted file mode 100644 index de500128..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/sideband/common.go +++ /dev/null @@ -1,33 +0,0 @@ -package sideband - -// Type sideband type "side-band" or "side-band-64k" -type Type int8 - -const ( - // Sideband legacy sideband type up to 1000-byte messages - Sideband Type = iota - // Sideband64k sideband type up to 65519-byte messages - Sideband64k Type = iota - - // MaxPackedSize for Sideband type - MaxPackedSize = 1000 - // MaxPackedSize64k for Sideband64k type - MaxPackedSize64k = 65520 -) - -// Channel sideband channel -type Channel byte - -// WithPayload encode the payload as a message -func (ch Channel) WithPayload(payload []byte) []byte { - return append([]byte{byte(ch)}, payload...) -} - -const ( - // PackData packfile content - PackData Channel = 1 - // ProgressMessage progress messages - ProgressMessage Channel = 2 - // ErrorMessage fatal error message just before stream aborts - ErrorMessage Channel = 3 -) diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/sideband/demux.go b/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/sideband/demux.go deleted file mode 100644 index 0116f962..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/sideband/demux.go +++ /dev/null @@ -1,148 +0,0 @@ -package sideband - -import ( - "errors" - "fmt" - "io" - - "github.com/go-git/go-git/v5/plumbing/format/pktline" -) - -// ErrMaxPackedExceeded returned by Read, if the maximum packed size is exceeded -var ErrMaxPackedExceeded = errors.New("max. packed size exceeded") - -// Progress where the progress information is stored -type Progress interface { - io.Writer -} - -// Demuxer demultiplexes the progress reports and error info interleaved with the -// packfile itself. -// -// A sideband has three different channels the main one, called PackData, contains -// the packfile data; the ErrorMessage channel, that contains server errors; and -// the last one, ProgressMessage channel, containing information about the ongoing -// task happening in the server (optional, can be suppressed sending NoProgress -// or Quiet capabilities to the server) -// -// In order to demultiplex the data stream, method `Read` should be called to -// retrieve the PackData channel, the incoming data from the ProgressMessage is -// written at `Progress` (if any), if any message is retrieved from the -// ErrorMessage channel an error is returned and we can assume that the -// connection has been closed. -type Demuxer struct { - t Type - r io.Reader - s *pktline.Scanner - - max int - pending []byte - - // Progress is where the progress messages are stored - Progress Progress -} - -// NewDemuxer returns a new Demuxer for the given t and read from r -func NewDemuxer(t Type, r io.Reader) *Demuxer { - max := MaxPackedSize64k - if t == Sideband { - max = MaxPackedSize - } - - return &Demuxer{ - t: t, - r: r, - max: max, - s: pktline.NewScanner(r), - } -} - -// Read reads up to len(p) bytes from the PackData channel into p, an error can -// be return if an error happens when reading or if a message is sent in the -// ErrorMessage channel. -// -// When a ProgressMessage is read, is not copy to b, instead of this is written -// to the Progress -func (d *Demuxer) Read(b []byte) (n int, err error) { - var read, req int - - req = len(b) - for read < req { - n, err := d.doRead(b[read:req]) - read += n - - if err != nil { - return read, err - } - } - - return read, nil -} - -func (d *Demuxer) doRead(b []byte) (int, error) { - read, err := d.nextPackData() - size := len(read) - wanted := len(b) - - if size > wanted { - d.pending = read[wanted:] - } - - if wanted > size { - wanted = size - } - - size = copy(b, read[:wanted]) - return size, err -} - -func (d *Demuxer) nextPackData() ([]byte, error) { - content := d.getPending() - if len(content) != 0 { - return content, nil - } - - if !d.s.Scan() { - if err := d.s.Err(); err != nil { - return nil, err - } - - return nil, io.EOF - } - - content = d.s.Bytes() - - size := len(content) - if size == 0 { - return nil, nil - } else if size > d.max { - return nil, ErrMaxPackedExceeded - } - - switch Channel(content[0]) { - case PackData: - return content[1:], nil - case ProgressMessage: - if d.Progress != nil { - _, err := d.Progress.Write(content[1:]) - return nil, err - } - case ErrorMessage: - return nil, fmt.Errorf("unexpected error: %s", content[1:]) - default: - return nil, fmt.Errorf("unknown channel %s", content) - } - - return nil, nil -} - -func (d *Demuxer) getPending() (b []byte) { - if len(d.pending) == 0 { - return nil - } - - content := d.pending - d.pending = nil - - return content -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/sideband/doc.go b/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/sideband/doc.go deleted file mode 100644 index c5d24295..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/sideband/doc.go +++ /dev/null @@ -1,31 +0,0 @@ -// Package sideband implements a sideband mutiplex/demultiplexer -package sideband - -// If 'side-band' or 'side-band-64k' capabilities have been specified by -// the client, the server will send the packfile data multiplexed. -// -// Either mode indicates that the packfile data will be streamed broken -// up into packets of up to either 1000 bytes in the case of 'side_band', -// or 65520 bytes in the case of 'side_band_64k'. Each packet is made up -// of a leading 4-byte pkt-line length of how much data is in the packet, -// followed by a 1-byte stream code, followed by the actual data. -// -// The stream code can be one of: -// -// 1 - pack data -// 2 - progress messages -// 3 - fatal error message just before stream aborts -// -// The "side-band-64k" capability came about as a way for newer clients -// that can handle much larger packets to request packets that are -// actually crammed nearly full, while maintaining backward compatibility -// for the older clients. -// -// Further, with side-band and its up to 1000-byte messages, it's actually -// 999 bytes of payload and 1 byte for the stream code. With side-band-64k, -// same deal, you have up to 65519 bytes of data and 1 byte for the stream -// code. -// -// The client MUST send only maximum of one of "side-band" and "side- -// band-64k". Server MUST diagnose it as an error if client requests -// both. diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/sideband/muxer.go b/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/sideband/muxer.go deleted file mode 100644 index d51ac826..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/sideband/muxer.go +++ /dev/null @@ -1,65 +0,0 @@ -package sideband - -import ( - "io" - - "github.com/go-git/go-git/v5/plumbing/format/pktline" -) - -// Muxer multiplex the packfile along with the progress messages and the error -// information. The multiplex is perform using pktline format. -type Muxer struct { - max int - e *pktline.Encoder -} - -const chLen = 1 - -// NewMuxer returns a new Muxer for the given t that writes on w. -// -// If t is equal to `Sideband` the max pack size is set to MaxPackedSize, in any -// other value is given, max pack is set to MaxPackedSize64k, that is the -// maximum length of a line in pktline format. -func NewMuxer(t Type, w io.Writer) *Muxer { - max := MaxPackedSize64k - if t == Sideband { - max = MaxPackedSize - } - - return &Muxer{ - max: max - chLen, - e: pktline.NewEncoder(w), - } -} - -// Write writes p in the PackData channel -func (m *Muxer) Write(p []byte) (int, error) { - return m.WriteChannel(PackData, p) -} - -// WriteChannel writes p in the given channel. This method can be used with any -// channel, but is recommend use it only for the ProgressMessage and -// ErrorMessage channels and use Write for the PackData channel -func (m *Muxer) WriteChannel(t Channel, p []byte) (int, error) { - wrote := 0 - size := len(p) - for wrote < size { - n, err := m.doWrite(t, p[wrote:]) - wrote += n - - if err != nil { - return wrote, err - } - } - - return wrote, nil -} - -func (m *Muxer) doWrite(ch Channel, p []byte) (int, error) { - sz := len(p) - if sz > m.max { - sz = m.max - } - - return sz, m.e.Encode(ch.WithPayload(p[:sz])) -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/srvresp.go b/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/srvresp.go deleted file mode 100644 index b3a7ee80..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/srvresp.go +++ /dev/null @@ -1,127 +0,0 @@ -package packp - -import ( - "bufio" - "bytes" - "errors" - "fmt" - "io" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/plumbing/format/pktline" -) - -const ackLineLen = 44 - -// ServerResponse object acknowledgement from upload-pack service -type ServerResponse struct { - ACKs []plumbing.Hash -} - -// Decode decodes the response into the struct, isMultiACK should be true, if -// the request was done with multi_ack or multi_ack_detailed capabilities. -func (r *ServerResponse) Decode(reader *bufio.Reader, isMultiACK bool) error { - // TODO: implement support for multi_ack or multi_ack_detailed responses - if isMultiACK { - return errors.New("multi_ack and multi_ack_detailed are not supported") - } - - s := pktline.NewScanner(reader) - - for s.Scan() { - line := s.Bytes() - - if err := r.decodeLine(line); err != nil { - return err - } - - // we need to detect when the end of a response header and the beginning - // of a packfile header happened, some requests to the git daemon - // produces a duplicate ACK header even when multi_ack is not supported. - stop, err := r.stopReading(reader) - if err != nil { - return err - } - - if stop { - break - } - } - - return s.Err() -} - -// stopReading detects when a valid command such as ACK or NAK is found to be -// read in the buffer without moving the read pointer. -func (r *ServerResponse) stopReading(reader *bufio.Reader) (bool, error) { - ahead, err := reader.Peek(7) - if err == io.EOF { - return true, nil - } - - if err != nil { - return false, err - } - - if len(ahead) > 4 && r.isValidCommand(ahead[0:3]) { - return false, nil - } - - if len(ahead) == 7 && r.isValidCommand(ahead[4:]) { - return false, nil - } - - return true, nil -} - -func (r *ServerResponse) isValidCommand(b []byte) bool { - commands := [][]byte{ack, nak} - for _, c := range commands { - if bytes.Equal(b, c) { - return true - } - } - - return false -} - -func (r *ServerResponse) decodeLine(line []byte) error { - if len(line) == 0 { - return fmt.Errorf("unexpected flush") - } - - if bytes.Equal(line[0:3], ack) { - return r.decodeACKLine(line) - } - - if bytes.Equal(line[0:3], nak) { - return nil - } - - return fmt.Errorf("unexpected content %q", string(line)) -} - -func (r *ServerResponse) decodeACKLine(line []byte) error { - if len(line) < ackLineLen { - return fmt.Errorf("malformed ACK %q", line) - } - - sp := bytes.Index(line, []byte(" ")) - h := plumbing.NewHash(string(line[sp+1 : sp+41])) - r.ACKs = append(r.ACKs, h) - return nil -} - -// Encode encodes the ServerResponse into a writer. -func (r *ServerResponse) Encode(w io.Writer) error { - if len(r.ACKs) > 1 { - return errors.New("multi_ack and multi_ack_detailed are not supported") - } - - e := pktline.NewEncoder(w) - if len(r.ACKs) == 0 { - return e.Encodef("%s\n", nak) - } - - return e.Encodef("%s %s\n", ack, r.ACKs[0].String()) -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/ulreq.go b/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/ulreq.go deleted file mode 100644 index ddec06e9..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/ulreq.go +++ /dev/null @@ -1,168 +0,0 @@ -package packp - -import ( - "fmt" - "time" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/plumbing/protocol/packp/capability" -) - -// UploadRequest values represent the information transmitted on a -// upload-request message. Values from this type are not zero-value -// safe, use the New function instead. -// This is a low level type, use UploadPackRequest instead. -type UploadRequest struct { - Capabilities *capability.List - Wants []plumbing.Hash - Shallows []plumbing.Hash - Depth Depth -} - -// Depth values stores the desired depth of the requested packfile: see -// DepthCommit, DepthSince and DepthReference. -type Depth interface { - isDepth() - IsZero() bool -} - -// DepthCommits values stores the maximum number of requested commits in -// the packfile. Zero means infinite. A negative value will have -// undefined consequences. -type DepthCommits int - -func (d DepthCommits) isDepth() {} - -func (d DepthCommits) IsZero() bool { - return d == 0 -} - -// DepthSince values requests only commits newer than the specified time. -type DepthSince time.Time - -func (d DepthSince) isDepth() {} - -func (d DepthSince) IsZero() bool { - return time.Time(d).IsZero() -} - -// DepthReference requests only commits not to found in the specified reference. -type DepthReference string - -func (d DepthReference) isDepth() {} - -func (d DepthReference) IsZero() bool { - return string(d) == "" -} - -// NewUploadRequest returns a pointer to a new UploadRequest value, ready to be -// used. It has no capabilities, wants or shallows and an infinite depth. Please -// note that to encode an upload-request it has to have at least one wanted hash. -func NewUploadRequest() *UploadRequest { - return &UploadRequest{ - Capabilities: capability.NewList(), - Wants: []plumbing.Hash{}, - Shallows: []plumbing.Hash{}, - Depth: DepthCommits(0), - } -} - -// NewUploadRequestFromCapabilities returns a pointer to a new UploadRequest -// value, the request capabilities are filled with the most optimal ones, based -// on the adv value (advertised capabilities), the UploadRequest generated it -// has no wants or shallows and an infinite depth. -func NewUploadRequestFromCapabilities(adv *capability.List) *UploadRequest { - r := NewUploadRequest() - - if adv.Supports(capability.MultiACKDetailed) { - r.Capabilities.Set(capability.MultiACKDetailed) - } else if adv.Supports(capability.MultiACK) { - r.Capabilities.Set(capability.MultiACK) - } - - if adv.Supports(capability.Sideband64k) { - r.Capabilities.Set(capability.Sideband64k) - } else if adv.Supports(capability.Sideband) { - r.Capabilities.Set(capability.Sideband) - } - - if adv.Supports(capability.ThinPack) { - r.Capabilities.Set(capability.ThinPack) - } - - if adv.Supports(capability.OFSDelta) { - r.Capabilities.Set(capability.OFSDelta) - } - - if adv.Supports(capability.Agent) { - r.Capabilities.Set(capability.Agent, capability.DefaultAgent) - } - - return r -} - -// Validate validates the content of UploadRequest, following the next rules: -// - Wants MUST have at least one reference -// - capability.Shallow MUST be present if Shallows is not empty -// - is a non-zero DepthCommits is given capability.Shallow MUST be present -// - is a DepthSince is given capability.Shallow MUST be present -// - is a DepthReference is given capability.DeepenNot MUST be present -// - MUST contain only maximum of one of capability.Sideband and capability.Sideband64k -// - MUST contain only maximum of one of capability.MultiACK and capability.MultiACKDetailed -func (req *UploadRequest) Validate() error { - if len(req.Wants) == 0 { - return fmt.Errorf("want can't be empty") - } - - if err := req.validateRequiredCapabilities(); err != nil { - return err - } - - if err := req.validateConflictCapabilities(); err != nil { - return err - } - - return nil -} - -func (req *UploadRequest) validateRequiredCapabilities() error { - msg := "missing capability %s" - - if len(req.Shallows) != 0 && !req.Capabilities.Supports(capability.Shallow) { - return fmt.Errorf(msg, capability.Shallow) - } - - switch req.Depth.(type) { - case DepthCommits: - if req.Depth != DepthCommits(0) { - if !req.Capabilities.Supports(capability.Shallow) { - return fmt.Errorf(msg, capability.Shallow) - } - } - case DepthSince: - if !req.Capabilities.Supports(capability.DeepenSince) { - return fmt.Errorf(msg, capability.DeepenSince) - } - case DepthReference: - if !req.Capabilities.Supports(capability.DeepenNot) { - return fmt.Errorf(msg, capability.DeepenNot) - } - } - - return nil -} - -func (req *UploadRequest) validateConflictCapabilities() error { - msg := "capabilities %s and %s are mutually exclusive" - if req.Capabilities.Supports(capability.Sideband) && - req.Capabilities.Supports(capability.Sideband64k) { - return fmt.Errorf(msg, capability.Sideband, capability.Sideband64k) - } - - if req.Capabilities.Supports(capability.MultiACK) && - req.Capabilities.Supports(capability.MultiACKDetailed) { - return fmt.Errorf(msg, capability.MultiACK, capability.MultiACKDetailed) - } - - return nil -} diff --git a/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/ulreq_decode.go b/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/ulreq_decode.go deleted file mode 100644 index 895a3bf6..00000000 --- a/vendor/github.com/go-git/go-git/v5/plumbing/protocol/packp/ulreq_decode.go +++ /dev/null @@ -1,257 +0,0 @@ -package packp - -import ( - "bytes" - "encoding/hex" - "fmt" - "io" - "strconv" - "time" - - "github.com/go-git/go-git/v5/plumbing" - "github.com/go-git/go-git/v5/plumbing/format/pktline" -) - -// Decode reads the next upload-request form its input and -// stores it in the UploadRequest. -func (req *UploadRequest) Decode(r io.Reader) error { - d := newUlReqDecoder(r) - return d.Decode(req) -} - -type ulReqDecoder struct { - s *pktline.Scanner // a pkt-line scanner from the input stream - line []byte // current pkt-line contents, use parser.nextLine() to make it advance - nLine int // current pkt-line number for debugging, begins at 1 - err error // sticky error, use the parser.error() method to fill this out - data *UploadRequest // parsed data is stored here -} - -func newUlReqDecoder(r io.Reader) *ulReqDecoder { - return &ulReqDecoder{ - s: pktline.NewScanner(r), - } -} - -func (d *ulReqDecoder) Decode(v *UploadRequest) error { - d.data = v - - for state := d.decodeFirstWant; state != nil; { - state = state() - } - - return d.err -} - -// fills out the parser stiky error -func (d *ulReqDecoder) error(format string, a ...interface{}) { - msg := fmt.Sprintf( - "pkt-line %d: %s", d.nLine, - fmt.Sprintf(format, a...), - ) - - d.err = NewErrUnexpectedData(msg, d.line) -} - -// Reads a new pkt-line from the scanner, makes its payload available as -// p.line and increments p.nLine. A successful invocation returns true, -// otherwise, false is returned and the sticky error is filled out -// accordingly. Trims eols at the end of the payloads. -func (d *ulReqDecoder) nextLine() bool { - d.nLine++ - - if !d.s.Scan() { - if d.err = d.s.Err(); d.err != nil { - return false - } - - d.error("EOF") - return false - } - - d.line = d.s.Bytes() - d.line = bytes.TrimSuffix(d.line, eol) - - return true -} - -// Expected format: want [ capabilities] -func (d *ulReqDecoder) decodeFirstWant() stateFn { - if ok := d.nextLine(); !ok { - return nil - } - - if !bytes.HasPrefix(d.line, want) { - d.error("missing 'want ' prefix") - return nil - } - d.line = bytes.TrimPrefix(d.line, want) - - hash, ok := d.readHash() - if !ok { - return nil - } - d.data.Wants = append(d.data.Wants, hash) - - return d.decodeCaps -} - -func (d *ulReqDecoder) readHash() (plumbing.Hash, bool) { - if len(d.line) < hashSize { - d.err = fmt.Errorf("malformed hash: %v", d.line) - return plumbing.ZeroHash, false - } - - var hash plumbing.Hash - if _, err := hex.Decode(hash[:], d.line[:hashSize]); err != nil { - d.error("invalid hash text: %s", err) - return plumbing.ZeroHash, false - } - d.line = d.line[hashSize:] - - return hash, true -} - -// Expected format: sp cap1 sp cap2 sp cap3... -func (d *ulReqDecoder) decodeCaps() stateFn { - d.line = bytes.TrimPrefix(d.line, sp) - if err := d.data.Capabilities.Decode(d.line); err != nil { - d.error("invalid capabilities: %s", err) - } - - return d.decodeOtherWants -} - -// Expected format: want -func (d *ulReqDecoder) decodeOtherWants() stateFn { - if ok := d.nextLine(); !ok { - return nil - } - - if bytes.HasPrefix(d.line, shallow) { - return d.decodeShallow - } - - if bytes.HasPrefix(d.line, deepen) { - return d.decodeDeepen - } - - if len(d.line) == 0 { - return nil - } - - if !bytes.HasPrefix(d.line, want) { - d.error("unexpected payload while expecting a want: %q", d.line) - return nil - } - d.line = bytes.TrimPrefix(d.line, want) - - hash, ok := d.readHash() - if !ok { - return nil - } - d.data.Wants = append(d.data.Wants, hash) - - return d.decodeOtherWants -} - -// Expected format: shallow -func (d *ulReqDecoder) decodeShallow() stateFn { - if bytes.HasPrefix(d.line, deepen) { - return d.decodeDeepen - } - - if len(d.line) == 0 { - return nil - } - - if !bytes.HasPrefix(d.line, shallow) { - d.error("unexpected payload while expecting a shallow: %q", d.line) - return nil - } - d.line = bytes.TrimPrefix(d.line, shallow) - - hash, ok := d.readHash() - if !ok { - return nil - } - d.data.Shallows = append(d.data.Shallows, hash) - - if ok := d.nextLine(); !ok { - return nil - } - - return d.decodeShallow -} - -// Expected format: deepen / deepen-since