diff --git a/go.mod b/go.mod index adc5c908d1b4..e32ae15e4430 100644 --- a/go.mod +++ b/go.mod @@ -15,9 +15,9 @@ require ( github.com/gofrs/uuid v4.4.0+incompatible github.com/golang-jwt/jwt/v4 v4.5.0 github.com/google/go-cmp v0.5.9 - github.com/google/uuid v1.3.1 - github.com/hashicorp/go-azure-helpers v0.65.1 - github.com/hashicorp/go-azure-sdk v0.20240117.1163544 + github.com/google/uuid v1.4.0 + github.com/hashicorp/go-azure-helpers v0.65.0 + github.com/hashicorp/go-azure-sdk v0.20231215.1114251 github.com/hashicorp/go-hclog v1.5.0 github.com/hashicorp/go-multierror v1.1.1 github.com/hashicorp/go-uuid v1.0.3 @@ -28,7 +28,7 @@ require ( github.com/mitchellh/mapstructure v1.5.0 github.com/rickb777/date v1.12.5-0.20200422084442-6300e543c4d9 github.com/sergi/go-diff v1.2.0 - github.com/tombuildsstuff/giovanni v0.20.0 + github.com/tombuildsstuff/giovanni v0.22.0 github.com/tombuildsstuff/kermit v0.20230703.1101016 golang.org/x/crypto v0.17.0 golang.org/x/tools v0.13.0 diff --git a/go.sum b/go.sum index bfa7370f84ee..ea594ff45e8d 100644 --- a/go.sum +++ b/go.sum @@ -1,36 +1,23 @@ dario.cat/mergo v1.0.0 h1:AGCNq9Evsj31mOgNPcLyXc+4PNABt905YmuqPYYpBWk= dario.cat/mergo v1.0.0/go.mod h1:uNxQE+84aUszobStD9th8a29P2fMDhsBdgRYvZOxGmk= -github.com/Azure/azure-sdk-for-go v45.0.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= -github.com/Azure/azure-sdk-for-go v56.0.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= github.com/Azure/azure-sdk-for-go v66.0.0+incompatible h1:bmmC38SlE8/E81nNADlgmVGurPWMHDX2YNXVQMrBpEE= github.com/Azure/azure-sdk-for-go v66.0.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= github.com/Azure/go-autorest v14.2.0+incompatible h1:V5VMDjClD3GiElqLWO7mz2MxNAK/vTfRHdAubSIPRgs= github.com/Azure/go-autorest v14.2.0+incompatible/go.mod h1:r+4oMnoxhatjLLJ6zxSWATqVooLgysK6ZNox3g/xq24= -github.com/Azure/go-autorest/autorest v0.11.3/go.mod h1:JFgpikqFJ/MleTTxwepExTKnFUKKszPS8UavbQYUMuw= -github.com/Azure/go-autorest/autorest v0.11.19/go.mod h1:dSiJPy22c3u0OtOKDNttNgqpNFY/GeWa7GH/Pz56QRA= github.com/Azure/go-autorest/autorest v0.11.29 h1:I4+HL/JDvErx2LjyzaVxllw2lRDB5/BT2Bm4g20iqYw= github.com/Azure/go-autorest/autorest v0.11.29/go.mod h1:ZtEzC4Jy2JDrZLxvWs8LrBWEBycl1hbT1eknI8MtfAs= -github.com/Azure/go-autorest/autorest/adal v0.9.0/go.mod h1:/c022QCutn2P7uY+/oQWWNcK9YU+MH96NgK+jErpbcg= -github.com/Azure/go-autorest/autorest/adal v0.9.5/go.mod h1:B7KF7jKIeC9Mct5spmyCB/A8CG/sEz1vwIRGv/bbw7A= -github.com/Azure/go-autorest/autorest/adal v0.9.13/go.mod h1:W/MM4U6nLxnIskrw4UwWzlHfGjwUS50aOsc/I3yuU8M= -github.com/Azure/go-autorest/autorest/adal v0.9.14/go.mod h1:W/MM4U6nLxnIskrw4UwWzlHfGjwUS50aOsc/I3yuU8M= github.com/Azure/go-autorest/autorest/adal v0.9.22/go.mod h1:XuAbAEUv2Tta//+voMI038TrJBqjKam0me7qR+L8Cmk= github.com/Azure/go-autorest/autorest/adal v0.9.23 h1:Yepx8CvFxwNKpH6ja7RZ+sKX+DWYNldbLiALMC3BTz8= github.com/Azure/go-autorest/autorest/adal v0.9.23/go.mod h1:5pcMqFkdPhviJdlEy3kC/v1ZLnQl0MH6XA5YCcMhy4c= -github.com/Azure/go-autorest/autorest/azure/cli v0.4.0/go.mod h1:JljT387FplPzBA31vUcvsetLKF3pec5bdAxjVU4kI2s= -github.com/Azure/go-autorest/autorest/azure/cli v0.4.2/go.mod h1:7qkJkT+j6b+hIpzMOwPChJhTqS8VbsqqgULzMNRugoM= github.com/Azure/go-autorest/autorest/date v0.3.0 h1:7gUk1U5M/CQbp9WoqinNzJar+8KY+LPI6wiWrP/myHw= github.com/Azure/go-autorest/autorest/date v0.3.0/go.mod h1:BI0uouVdmngYNUzGWeSYnokU+TrmwEsOqdt8Y6sso74= -github.com/Azure/go-autorest/autorest/mocks v0.4.0/go.mod h1:LTp+uSrOhSkaKrUy935gNZuuIPPVsHlr9DSOxSayd+k= github.com/Azure/go-autorest/autorest/mocks v0.4.1/go.mod h1:LTp+uSrOhSkaKrUy935gNZuuIPPVsHlr9DSOxSayd+k= github.com/Azure/go-autorest/autorest/mocks v0.4.2 h1:PGN4EDXnuQbojHbU0UWoNvmu9AGVwYHG9/fkDYhtAfw= github.com/Azure/go-autorest/autorest/mocks v0.4.2/go.mod h1:Vy7OitM9Kei0i1Oj+LvyAWMXJHeKH1MVlzFugfVrmyU= github.com/Azure/go-autorest/autorest/to v0.4.0 h1:oXVqrxakqqV1UZdSazDOPOLvOIz+XA683u8EctwboHk= github.com/Azure/go-autorest/autorest/to v0.4.0/go.mod h1:fE8iZBn7LQR7zH/9XU2NcPR4o9jEImooCeWJcYV/zLE= -github.com/Azure/go-autorest/autorest/validation v0.3.0/go.mod h1:yhLgjC0Wda5DYXl6JAsWyUe4KVNffhoDhG0zVzUMo3E= github.com/Azure/go-autorest/autorest/validation v0.3.1 h1:AgyqjAd94fwNAoTjl/WQXg4VvFeRFpO+UhNyRXqF1ac= github.com/Azure/go-autorest/autorest/validation v0.3.1/go.mod h1:yhLgjC0Wda5DYXl6JAsWyUe4KVNffhoDhG0zVzUMo3E= -github.com/Azure/go-autorest/logger v0.2.0/go.mod h1:T9E3cAhj2VqvPOtCYAvby9aBXkZmbF5NWuPV8+WeEW8= github.com/Azure/go-autorest/logger v0.2.1 h1:IG7i4p/mDa2Ce4TRyAO8IHnVhAVF3RFU+ZtXWSmf4Tg= github.com/Azure/go-autorest/logger v0.2.1/go.mod h1:T9E3cAhj2VqvPOtCYAvby9aBXkZmbF5NWuPV8+WeEW8= github.com/Azure/go-autorest/tracing v0.6.0 h1:TYi4+3m5t6K48TGI9AUdb+IzbnSxvnvUMfuitfgcfuo= @@ -66,16 +53,11 @@ github.com/dave/jennifer v1.6.0/go.mod h1:AxTG893FiZKqxy3FP1kL80VMshSMuz2G+Egvsz github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 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/dimchansky/utfbom v1.1.0/go.mod h1:rO41eb7gLfo8SF1jd9F8HplJm1Fewwi4mQvIirEdv+8= -github.com/dimchansky/utfbom v1.1.1/go.mod h1:SxdoEBH5qIqFocHMyGOXVAybYJdr71b1Q/j0mACtrfE= github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc= github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ= github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk= github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= -github.com/form3tech-oss/jwt-go v3.2.2+incompatible/go.mod h1:pbq4aXjuKjdthFRnoDwaVPLA+WlJuPGy+QneDUgJi2k= -github.com/form3tech-oss/jwt-go v3.2.3+incompatible/go.mod h1:pbq4aXjuKjdthFRnoDwaVPLA+WlJuPGy+QneDUgJi2k= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 h1:+zs/tPmkDkHx3U66DAb0lQFJrpS6731Oaa12ikc+DiI= github.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376/go.mod h1:an3vInlBmSxCcxctByoQdvwPiA7DTK7jaaFDBTtu0ic= @@ -103,19 +85,17 @@ github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMyw github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= -github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= -github.com/google/uuid v1.3.1 h1:KjJaJ9iWZ3jOFZIf1Lqf4laDRCasjl0BCmnEGxkdLb4= -github.com/google/uuid v1.3.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.4.0 h1:MtMxsa51/r9yyhkyLsVeVt0B+BGQZzpQiTQ4eHZ8bc4= +github.com/google/uuid v1.4.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= github.com/hashicorp/errwrap v0.0.0-20180715044906-d6c0cd880357/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= -github.com/hashicorp/go-azure-helpers v0.12.0/go.mod h1:Zc3v4DNeX6PDdy7NljlYpnrdac1++qNW0I4U+ofGwpg= -github.com/hashicorp/go-azure-helpers v0.65.1 h1:MLfd6MqCthMbop4N7OKsF8qn61Pe3Vyw30LjEEJkW5Q= -github.com/hashicorp/go-azure-helpers v0.65.1/go.mod h1:kJxXrFtJKJdOEqvad8pllAe7dhP4DbN8J6sqFZe47+4= -github.com/hashicorp/go-azure-sdk v0.20240117.1163544 h1:af8d6M+NESF60ZOT6RAPU5KqndAWIhAeiDM8RB6qvdM= -github.com/hashicorp/go-azure-sdk v0.20240117.1163544/go.mod h1:txHCdAIIyuDyQdPHgztJAoboIYO4ObG4Vwla/ekMylE= +github.com/hashicorp/go-azure-helpers v0.65.0 h1:aOZV7HcxvqAlnaWJ/Fhfu321dXLs++TyBIVelWOb/8w= +github.com/hashicorp/go-azure-helpers v0.65.0/go.mod h1:ELmZ65vzHJNTk6ml4jsPD+xq2gZb7t78D35s+XN02Kk= +github.com/hashicorp/go-azure-sdk v0.20231215.1114251 h1:SxPZYo5UrS1HcGOkTvz9k+ymHn4EFB3I1gbBiU3DksI= +github.com/hashicorp/go-azure-sdk v0.20231215.1114251/go.mod h1:69DSA+VMovHYJyQkRuUP3BCgwlEFrKvzeIHKi9m5xzY= github.com/hashicorp/go-checkpoint v0.5.0 h1:MFYpPZCnQqQTE18jFwSII6eUQrD/oxMFp3mlgcqk5mU= github.com/hashicorp/go-checkpoint v0.5.0/go.mod h1:7nfLNL10NsxqO4iWuW6tWW0HjZuDrwkBuEQsVcpCOgg= github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= @@ -127,7 +107,6 @@ github.com/hashicorp/go-hclog v0.9.2/go.mod h1:5CU+agLiy3J7N7QjHK5d05KxGsuXiQLrj github.com/hashicorp/go-hclog v1.5.0 h1:bI2ocEMgcVlz55Oj1xZNBsVi900c7II+fWDyV9o+13c= github.com/hashicorp/go-hclog v1.5.0/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M= github.com/hashicorp/go-multierror v0.0.0-20180717150148-3d5d8f294aa0/go.mod h1:JMRHfdO9jKNzS/+BTlxCjKNQHg/jZAft8U7LloJvN7I= -github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= github.com/hashicorp/go-plugin v1.5.1 h1:oGm7cWBaYIp3lJpx1RUEfLWophprE2EV/KUeqBYo+6k= @@ -196,7 +175,6 @@ github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D github.com/mattn/goveralls v0.0.2/go.mod h1:8d1ZMHsd7fW6IRPKQh46F2WRpyib5/X4FOpevwGNQEw= github.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw= github.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s= -github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/mitchellh/go-testing-interface v1.14.1 h1:jrgshOhYAUVNMAJiKbEu7EqAwgJJ2JqpQmpLJOu07cU= github.com/mitchellh/go-testing-interface v1.14.1/go.mod h1:gfgS7OtZj6MA4U1UrDRp04twqAjfvlZyCfX3sDjEym8= github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= @@ -238,10 +216,11 @@ github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8= github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/tombuildsstuff/giovanni v0.20.0 h1:IM/I/iNWMXnPYwcSq8uxV7TKDlv7Nejq0bRK9i6O/C0= -github.com/tombuildsstuff/giovanni v0.20.0/go.mod h1:66KVLYma2whJhEdxPSPL3GQHkulhK+C5CluKfHGfPF4= +github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/tombuildsstuff/giovanni v0.22.0 h1:21dYqBedy7XBnFRxv+rBLEEnLDtYi4ySsLYvD+w59Xc= +github.com/tombuildsstuff/giovanni v0.22.0/go.mod h1:wqkwY/Le3urqxFiUEcwi0n8sIDCcxGKNlvAxdAoiKN4= github.com/tombuildsstuff/kermit v0.20230703.1101016 h1:8GJ4BFlmpPiWFYFGpVNZl0H4/+FPm9kfueC4DNRBmpQ= github.com/tombuildsstuff/kermit v0.20230703.1101016/go.mod h1:YleYDYRKTGy5ihWHG9u3CwyVTr0l8dOLkYtVEPjnzGI= github.com/vmihailenco/msgpack v3.3.3+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= @@ -261,9 +240,6 @@ github.com/zclconf/go-cty v1.14.0/go.mod h1:VvMs5i0vgZdhYawQNq5kePSpLAoz8u1xvZgr golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20190426145343-a29dc8fdc734/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-20201002170205-7f63de1d35b0/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.3.1-0.20221117191849-2c476679df9a/go.mod h1:hebNnKkNXi2UzZN1eVRvBB7co0a+JxK6XbPiWVs/3J4= diff --git a/internal/common/client_options.go b/internal/common/client_options.go index 6eba6eeaedcc..9d60a1e1e42f 100644 --- a/internal/common/client_options.go +++ b/internal/common/client_options.go @@ -61,7 +61,7 @@ type ClientOptions struct { KeyVaultAuthorizer autorest.Authorizer ManagedHSMAuthorizer autorest.Authorizer ResourceManagerAuthorizer autorest.Authorizer - StorageAuthorizer autorest.Authorizer + StorageAuthorizer auth.Authorizer SynapseAuthorizer autorest.Authorizer } diff --git a/internal/services/legacy/virtual_machine_resource.go b/internal/services/legacy/virtual_machine_resource.go index e1d7d72e3e37..e1e8bdf457e6 100644 --- a/internal/services/legacy/virtual_machine_resource.go +++ b/internal/services/legacy/virtual_machine_resource.go @@ -192,7 +192,7 @@ func resourceVirtualMachine() *pluginsdk.Resource { DiffSuppressFunc: suppress.CaseDifference, }, - //lintignore:S018 + // lintignore:S018 "storage_image_reference": { Type: pluginsdk.TypeSet, Optional: true, @@ -434,7 +434,7 @@ func resourceVirtualMachine() *pluginsdk.Resource { }, }, - //lintignore:S018 + // lintignore:S018 "os_profile": { Type: pluginsdk.TypeSet, Optional: true, @@ -470,7 +470,7 @@ func resourceVirtualMachine() *pluginsdk.Resource { Set: resourceVirtualMachineStorageOsProfileHash, }, - //lintignore:S018 + // lintignore:S018 "os_profile_windows_config": { Type: pluginsdk.TypeSet, Optional: true, @@ -555,7 +555,7 @@ func resourceVirtualMachine() *pluginsdk.Resource { ConflictsWith: []string{"os_profile_linux_config"}, }, - //lintignore:S018 + // lintignore:S018 "os_profile_linux_config": { Type: pluginsdk.TypeSet, Optional: true, @@ -1032,18 +1032,20 @@ func resourceVirtualMachineDeleteVhd(ctx context.Context, storageClient *intStor return fmt.Errorf("`vhd.URI` was nil`") } + domainSuffix := storageClient.Environment.StorageEndpointSuffix + uri := *vhd.URI - id, err := blobs.ParseResourceID(uri) + id, err := blobs.ParseBlobID(uri, domainSuffix) if err != nil { return fmt.Errorf("parsing %q: %s", uri, err) } - account, err := storageClient.FindAccount(ctx, id.AccountName) + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Blob %q (Container %q): %s", id.AccountName, id.BlobName, id.ContainerName, err) + return fmt.Errorf("retrieving Account %q for Blob %q (Container %q): %s", id.AccountId.AccountName, id.BlobName, id.ContainerName, err) } if account == nil { - return fmt.Errorf("Unable to locate Storage Account %q (Disk %q)!", id.AccountName, uri) + return fmt.Errorf("Unable to locate Storage Account %q (Disk %q)!", id.AccountId.AccountName, uri) } if err != nil { @@ -1058,8 +1060,8 @@ func resourceVirtualMachineDeleteVhd(ctx context.Context, storageClient *intStor input := blobs.DeleteInput{ DeleteSnapshots: false, } - if _, err := blobsClient.Delete(ctx, id.AccountName, id.ContainerName, id.BlobName, input); err != nil { - return fmt.Errorf("deleting Blob %q (Container %q / Account %q / Resource Group %q): %s", id.BlobName, id.ContainerName, id.AccountName, account.ResourceGroup, err) + if _, err := blobsClient.Delete(ctx, id.ContainerName, id.BlobName, input); err != nil { + return fmt.Errorf("deleting Blob %q (Container %q / Account %q / Resource Group %q): %s", id.BlobName, id.ContainerName, id.AccountId.AccountName, account.ResourceGroup, err) } return nil diff --git a/internal/services/legacy/virtual_machine_resource_test.go b/internal/services/legacy/virtual_machine_resource_test.go index 656633a55ee0..17a984839a2f 100644 --- a/internal/services/legacy/virtual_machine_resource_test.go +++ b/internal/services/legacy/virtual_machine_resource_test.go @@ -8,6 +8,7 @@ import ( "fmt" "testing" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" @@ -255,9 +256,9 @@ func (VirtualMachineResource) unmanagedDiskExistsInContainer(blobName string, sh } input := blobs.GetPropertiesInput{} - props, err := client.GetProperties(ctx, accountName, containerName, blobName, input) + props, err := client.GetProperties(ctx, containerName, blobName, input) if err != nil { - if utils.ResponseWasNotFound(props.Response) { + if response.WasNotFound(props.HttpResponse.Response) { if !shouldExist { return nil } diff --git a/internal/services/storage/blobs.go b/internal/services/storage/blobs.go index 116c69ad9445..b6b75ff82e21 100644 --- a/internal/services/storage/blobs.go +++ b/internal/services/storage/blobs.go @@ -96,7 +96,7 @@ func (sbu BlobUpload) copy(ctx context.Context) error { CopySource: sbu.SourceUri, MetaData: sbu.MetaData, } - if err := sbu.Client.CopyAndWait(ctx, sbu.AccountName, sbu.ContainerName, sbu.BlobName, input, pollingInterval); err != nil { + if err := sbu.Client.CopyAndWait(ctx, sbu.ContainerName, sbu.BlobName, input); err != nil { return fmt.Errorf("copy/waiting: %s", err) } @@ -108,7 +108,7 @@ func (sbu BlobUpload) createEmptyAppendBlob(ctx context.Context) error { ContentType: utils.String(sbu.ContentType), MetaData: sbu.MetaData, } - if _, err := sbu.Client.PutAppendBlob(ctx, sbu.AccountName, sbu.ContainerName, sbu.BlobName, input); err != nil { + if _, err := sbu.Client.PutAppendBlob(ctx, sbu.ContainerName, sbu.BlobName, input); err != nil { return fmt.Errorf("PutAppendBlob: %s", err) } @@ -124,7 +124,7 @@ func (sbu BlobUpload) createEmptyBlockBlob(ctx context.Context) error { ContentType: utils.String(sbu.ContentType), MetaData: sbu.MetaData, } - if _, err := sbu.Client.PutBlockBlob(ctx, sbu.AccountName, sbu.ContainerName, sbu.BlobName, input); err != nil { + if _, err := sbu.Client.PutBlockBlob(ctx, sbu.ContainerName, sbu.BlobName, input); err != nil { return fmt.Errorf("PutBlockBlob: %s", err) } @@ -161,7 +161,7 @@ func (sbu BlobUpload) uploadBlockBlob(ctx context.Context) error { if sbu.ContentMD5 != "" { input.ContentMD5 = utils.String(sbu.ContentMD5) } - if err := sbu.Client.PutBlockBlobFromFile(ctx, sbu.AccountName, sbu.ContainerName, sbu.BlobName, file, input); err != nil { + if err := sbu.Client.PutBlockBlobFromFile(ctx, sbu.ContainerName, sbu.BlobName, file, input); err != nil { return fmt.Errorf("PutBlockBlobFromFile: %s", err) } @@ -178,7 +178,7 @@ func (sbu BlobUpload) createEmptyPageBlob(ctx context.Context) error { ContentType: utils.String(sbu.ContentType), MetaData: sbu.MetaData, } - if _, err := sbu.Client.PutPageBlob(ctx, sbu.AccountName, sbu.ContainerName, sbu.BlobName, input); err != nil { + if _, err := sbu.Client.PutPageBlob(ctx, sbu.ContainerName, sbu.BlobName, input); err != nil { return fmt.Errorf("PutPageBlob: %s", err) } @@ -228,7 +228,7 @@ func (sbu BlobUpload) uploadPageBlob(ctx context.Context) error { ContentType: utils.String(sbu.ContentType), MetaData: sbu.MetaData, } - if _, err := sbu.Client.PutPageBlob(ctx, sbu.AccountName, sbu.ContainerName, sbu.BlobName, input); err != nil { + if _, err := sbu.Client.PutPageBlob(ctx, sbu.ContainerName, sbu.BlobName, input); err != nil { return fmt.Errorf("PutPageBlob: %s", err) } @@ -373,7 +373,7 @@ func (sbu BlobUpload) blobPageUploadWorker(ctx context.Context, uploadCtx blobPa Content: chunk, } - if _, err := sbu.Client.PutPageUpdate(ctx, sbu.AccountName, sbu.ContainerName, sbu.BlobName, input); err != nil { + if _, err := sbu.Client.PutPageUpdate(ctx, sbu.ContainerName, sbu.BlobName, input); err != nil { uploadCtx.errors <- fmt.Errorf("writing page at offset %d for file %q: %s", page.offset, sbu.Source, err) uploadCtx.wg.Done() continue diff --git a/internal/services/storage/client/client.go b/internal/services/storage/client/client.go index 199f0dbbfc56..82b3cab100ab 100644 --- a/internal/services/storage/client/client.go +++ b/internal/services/storage/client/client.go @@ -14,6 +14,7 @@ import ( "github.com/hashicorp/go-azure-sdk/resource-manager/storagesync/2020-03-01/cloudendpointresource" "github.com/hashicorp/go-azure-sdk/resource-manager/storagesync/2020-03-01/storagesyncservicesresource" "github.com/hashicorp/go-azure-sdk/resource-manager/storagesync/2020-03-01/syncgroupresource" + "github.com/hashicorp/go-azure-sdk/sdk/auth" "github.com/hashicorp/go-azure-sdk/sdk/client/resourcemanager" "github.com/hashicorp/terraform-provider-azurerm/internal/common" "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/shim" @@ -32,8 +33,6 @@ import ( type Client struct { AccountsClient *storage.AccountsClient - FileSystemsClient *filesystems.Client - ADLSGen2PathsClient *paths.Client BlobServicesClient *storage.BlobServicesClient BlobInventoryPoliciesClient *storage.BlobInventoryPoliciesClient EncryptionScopesClient *storage.EncryptionScopesClient @@ -47,19 +46,13 @@ type Client struct { ResourceManager *storage_v2023_01_01.Client resourceManagerAuthorizer autorest.Authorizer - storageAdAuth *autorest.Authorizer + storageAdAuth *auth.Authorizer } func NewClient(o *common.ClientOptions) (*Client, error) { accountsClient := storage.NewAccountsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&accountsClient.Client, o.ResourceManagerAuthorizer) - fileSystemsClient := filesystems.NewWithEnvironment(o.AzureEnvironment) - o.ConfigureClient(&fileSystemsClient.Client, o.StorageAuthorizer) - - adlsGen2PathsClient := paths.NewWithEnvironment(o.AzureEnvironment) - o.ConfigureClient(&adlsGen2PathsClient.Client, o.StorageAuthorizer) - blobServicesClient := storage.NewBlobServicesClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&blobServicesClient.Client, o.ResourceManagerAuthorizer) @@ -100,8 +93,6 @@ func NewClient(o *common.ClientOptions) (*Client, error) { // (which should fix #2977) when the storage clients have been moved in here client := Client{ AccountsClient: &accountsClient, - FileSystemsClient: &fileSystemsClient, - ADLSGen2PathsClient: &adlsGen2PathsClient, BlobServicesClient: &blobServicesClient, BlobInventoryPoliciesClient: &blobInventoryPoliciesClient, EncryptionScopesClient: &encryptionScopesClient, @@ -125,9 +116,12 @@ func NewClient(o *common.ClientOptions) (*Client, error) { func (client Client) AccountsDataPlaneClient(ctx context.Context, account accountDetails) (*accounts.Client, error) { if client.storageAdAuth != nil { - accountsClient := accounts.NewWithEnvironment(client.Environment) - accountsClient.Client.Authorizer = *client.storageAdAuth - return &accountsClient, nil + accountsClient, err := accounts.NewWithBaseUri(*account.Properties.PrimaryEndpoints.Blob) + if err != nil { + return nil, fmt.Errorf("creating Accounts Client: %+v", err) + } + accountsClient.Client.WithAuthorizer(*client.storageAdAuth) + return accountsClient, nil } accountKey, err := account.AccountKey(ctx, client) @@ -135,21 +129,27 @@ func (client Client) AccountsDataPlaneClient(ctx context.Context, account accoun return nil, fmt.Errorf("retrieving Account Key: %s", err) } - storageAuth, err := autorest.NewSharedKeyAuthorizer(account.name, *accountKey, autorest.SharedKey) + storageAuth, err := auth.NewSharedKeyAuthorizer(account.name, *accountKey, auth.SharedKey) if err != nil { return nil, fmt.Errorf("building Authorizer: %+v", err) } - accountsClient := accounts.NewWithEnvironment(client.Environment) - accountsClient.Client.Authorizer = storageAuth - return &accountsClient, nil + accountsClient, err := accounts.NewWithBaseUri(*account.Properties.PrimaryEndpoints.Blob) + if err != nil { + return nil, fmt.Errorf("creating Accounts Client: %+v", err) + } + accountsClient.Client.WithAuthorizer(storageAuth) + return accountsClient, nil } func (client Client) BlobsClient(ctx context.Context, account accountDetails) (*blobs.Client, error) { if client.storageAdAuth != nil { - blobsClient := blobs.NewWithEnvironment(client.Environment) - blobsClient.Client.Authorizer = *client.storageAdAuth - return &blobsClient, nil + blobsClient, err := blobs.NewWithBaseUri(*account.Properties.PrimaryEndpoints.Blob) + if err != nil { + return nil, fmt.Errorf("creating Blobs Client: %+v", err) + } + blobsClient.Client.WithAuthorizer(*client.storageAdAuth) + return blobsClient, nil } accountKey, err := account.AccountKey(ctx, client) @@ -157,21 +157,27 @@ func (client Client) BlobsClient(ctx context.Context, account accountDetails) (* return nil, fmt.Errorf("retrieving Account Key: %s", err) } - storageAuth, err := autorest.NewSharedKeyAuthorizer(account.name, *accountKey, autorest.SharedKey) + storageAuth, err := auth.NewSharedKeyAuthorizer(account.name, *accountKey, auth.SharedKey) if err != nil { return nil, fmt.Errorf("building Authorizer: %+v", err) } - blobsClient := blobs.NewWithEnvironment(client.Environment) - blobsClient.Client.Authorizer = storageAuth - return &blobsClient, nil + blobsClient, err := blobs.NewWithBaseUri(*account.Properties.PrimaryEndpoints.Blob) + if err != nil { + return nil, fmt.Errorf("creating Blobs Client: %+v", err) + } + blobsClient.Client.WithAuthorizer(storageAuth) + return blobsClient, nil } func (client Client) ContainersClient(ctx context.Context, account accountDetails) (shim.StorageContainerWrapper, error) { if client.storageAdAuth != nil { - containersClient := containers.NewWithEnvironment(client.Environment) - containersClient.Client.Authorizer = *client.storageAdAuth - shim := shim.NewDataPlaneStorageContainerWrapper(&containersClient) + containersClient, err := containers.NewWithBaseUri(*account.Properties.PrimaryEndpoints.Blob) + if err != nil { + return nil, fmt.Errorf("creating Containers Client: %+v", err) + } + containersClient.Client.WithAuthorizer(*client.storageAdAuth) + shim := shim.NewDataPlaneStorageContainerWrapper(containersClient) return shim, nil } @@ -180,15 +186,18 @@ func (client Client) ContainersClient(ctx context.Context, account accountDetail return nil, fmt.Errorf("retrieving Account Key: %s", err) } - storageAuth, err := autorest.NewSharedKeyAuthorizer(account.name, *accountKey, autorest.SharedKey) + storageAuth, err := auth.NewSharedKeyAuthorizer(account.name, *accountKey, auth.SharedKey) if err != nil { return nil, fmt.Errorf("building Authorizer: %+v", err) } - containersClient := containers.NewWithEnvironment(client.Environment) - containersClient.Client.Authorizer = storageAuth + containersClient, err := containers.NewWithBaseUri(*account.Properties.PrimaryEndpoints.Blob) + if err != nil { + return nil, fmt.Errorf("creating Containers Client: %+v", err) + } + containersClient.Client.WithAuthorizer(storageAuth) - shim := shim.NewDataPlaneStorageContainerWrapper(&containersClient) + shim := shim.NewDataPlaneStorageContainerWrapper(containersClient) return shim, nil } @@ -200,14 +209,17 @@ func (client Client) FileShareDirectoriesClient(ctx context.Context, account acc return nil, fmt.Errorf("retrieving Account Key: %s", err) } - storageAuth, err := autorest.NewSharedKeyAuthorizer(account.name, *accountKey, autorest.SharedKeyLite) + storageAuth, err := auth.NewSharedKeyAuthorizer(account.name, *accountKey, auth.SharedKey) if err != nil { return nil, fmt.Errorf("building Authorizer: %+v", err) } - directoriesClient := directories.NewWithEnvironment(client.Environment) - directoriesClient.Client.Authorizer = storageAuth - return &directoriesClient, nil + directoriesClient, err := directories.NewWithBaseUri(*account.Properties.PrimaryEndpoints.File) + if err != nil { + return nil, fmt.Errorf("creating Directories Client: %+v", err) + } + directoriesClient.Client.WithAuthorizer(storageAuth) + return directoriesClient, nil } func (client Client) FileShareFilesClient(ctx context.Context, account accountDetails) (*files.Client, error) { @@ -218,14 +230,17 @@ func (client Client) FileShareFilesClient(ctx context.Context, account accountDe return nil, fmt.Errorf("retrieving Account Key: %s", err) } - storageAuth, err := autorest.NewSharedKeyAuthorizer(account.name, *accountKey, autorest.SharedKeyLite) + storageAuth, err := auth.NewSharedKeyAuthorizer(account.name, *accountKey, auth.SharedKey) if err != nil { return nil, fmt.Errorf("building Authorizer: %+v", err) } - filesClient := files.NewWithEnvironment(client.Environment) - filesClient.Client.Authorizer = storageAuth - return &filesClient, nil + filesClient, err := files.NewWithBaseUri(*account.Properties.PrimaryEndpoints.File) + if err != nil { + return nil, fmt.Errorf("creating Files Client: %+v", err) + } + filesClient.Client.WithAuthorizer(storageAuth) + return filesClient, nil } func (client Client) FileSharesClient(ctx context.Context, account accountDetails) (shim.StorageShareWrapper, error) { @@ -236,22 +251,84 @@ func (client Client) FileSharesClient(ctx context.Context, account accountDetail return nil, fmt.Errorf("retrieving Account Key: %s", err) } - storageAuth, err := autorest.NewSharedKeyAuthorizer(account.name, *accountKey, autorest.SharedKeyLite) + storageAuth, err := auth.NewSharedKeyAuthorizer(account.name, *accountKey, auth.SharedKey) if err != nil { return nil, fmt.Errorf("building Authorizer: %+v", err) } - sharesClient := shares.NewWithEnvironment(client.Environment) - sharesClient.Client.Authorizer = storageAuth - shim := shim.NewDataPlaneStorageShareWrapper(&sharesClient) + sharesClient, err := shares.NewWithBaseUri(*account.Properties.PrimaryEndpoints.File) + if err != nil { + return nil, fmt.Errorf("creating Shares Client: %+v", err) + } + sharesClient.Client.WithAuthorizer(storageAuth) + shim := shim.NewDataPlaneStorageShareWrapper(sharesClient) return shim, nil } +func (client Client) FileSystemsClient(ctx context.Context, account accountDetails) (*filesystems.Client, error) { + if client.storageAdAuth != nil { + filesystemsClient, err := filesystems.NewWithBaseUri(*account.Properties.PrimaryEndpoints.Dfs) + if err != nil { + return nil, fmt.Errorf("creating Filesystems Client: %+v", err) + } + filesystemsClient.Client.WithAuthorizer(*client.storageAdAuth) + return filesystemsClient, nil + } + + accountKey, err := account.AccountKey(ctx, client) + if err != nil { + return nil, fmt.Errorf("retrieving Account Key: %s", err) + } + + storageAuth, err := auth.NewSharedKeyAuthorizer(account.name, *accountKey, auth.SharedKey) + if err != nil { + return nil, fmt.Errorf("building Authorizer: %+v", err) + } + + filesystemsClient, err := filesystems.NewWithBaseUri(*account.Properties.PrimaryEndpoints.Dfs) + if err != nil { + return nil, fmt.Errorf("creating Filesystems Client: %+v", err) + } + filesystemsClient.Client.WithAuthorizer(storageAuth) + return filesystemsClient, nil +} + +func (client Client) PathsClient(ctx context.Context, account accountDetails) (*paths.Client, error) { + if client.storageAdAuth != nil { + pathsClient, err := paths.NewWithBaseUri(*account.Properties.PrimaryEndpoints.Dfs) + if err != nil { + return nil, fmt.Errorf("creating Filesystems Client: %+v", err) + } + pathsClient.Client.WithAuthorizer(*client.storageAdAuth) + return pathsClient, nil + } + + accountKey, err := account.AccountKey(ctx, client) + if err != nil { + return nil, fmt.Errorf("retrieving Account Key: %s", err) + } + + storageAuth, err := auth.NewSharedKeyAuthorizer(account.name, *accountKey, auth.SharedKey) + if err != nil { + return nil, fmt.Errorf("building Authorizer: %+v", err) + } + + pathsClient, err := paths.NewWithBaseUri(*account.Properties.PrimaryEndpoints.Dfs) + if err != nil { + return nil, fmt.Errorf("creating Filesystems Client: %+v", err) + } + pathsClient.Client.WithAuthorizer(storageAuth) + return pathsClient, nil +} + func (client Client) QueuesClient(ctx context.Context, account accountDetails) (shim.StorageQueuesWrapper, error) { if client.storageAdAuth != nil { - queueClient := queues.NewWithEnvironment(client.Environment) - queueClient.Client.Authorizer = *client.storageAdAuth - return shim.NewDataPlaneStorageQueueWrapper(&queueClient), nil + queueClient, err := queues.NewWithBaseUri(*account.Properties.PrimaryEndpoints.Queue) + if err != nil { + return nil, fmt.Errorf("creating Queues Client: %+v", err) + } + queueClient.Client.WithAuthorizer(*client.storageAdAuth) + return shim.NewDataPlaneStorageQueueWrapper(queueClient), nil } accountKey, err := account.AccountKey(ctx, client) @@ -259,14 +336,17 @@ func (client Client) QueuesClient(ctx context.Context, account accountDetails) ( return nil, fmt.Errorf("retrieving Account Key: %s", err) } - storageAuth, err := autorest.NewSharedKeyAuthorizer(account.name, *accountKey, autorest.SharedKeyLite) + storageAuth, err := auth.NewSharedKeyAuthorizer(account.name, *accountKey, auth.SharedKey) if err != nil { return nil, fmt.Errorf("building Authorizer: %+v", err) } - queuesClient := queues.NewWithEnvironment(client.Environment) - queuesClient.Client.Authorizer = storageAuth - return shim.NewDataPlaneStorageQueueWrapper(&queuesClient), nil + queuesClient, err := queues.NewWithBaseUri(*account.Properties.PrimaryEndpoints.Queue) + if err != nil { + return nil, fmt.Errorf("creating Queues Client: %+v", err) + } + queuesClient.Client.WithAuthorizer(storageAuth) + return shim.NewDataPlaneStorageQueueWrapper(queuesClient), nil } func (client Client) TableEntityClient(ctx context.Context, account accountDetails) (*entities.Client, error) { @@ -277,14 +357,17 @@ func (client Client) TableEntityClient(ctx context.Context, account accountDetai return nil, fmt.Errorf("retrieving Account Key: %s", err) } - storageAuth, err := autorest.NewSharedKeyAuthorizer(account.name, *accountKey, autorest.SharedKeyLiteForTable) + storageAuth, err := auth.NewSharedKeyAuthorizer(account.name, *accountKey, auth.SharedKeyTable) if err != nil { return nil, fmt.Errorf("building Authorizer: %+v", err) } - entitiesClient := entities.NewWithEnvironment(client.Environment) - entitiesClient.Client.Authorizer = storageAuth - return &entitiesClient, nil + entitiesClient, err := entities.NewWithBaseUri(*account.Properties.PrimaryEndpoints.Table) + if err != nil { + return nil, fmt.Errorf("creating Queues Client: %+v", err) + } + entitiesClient.Client.WithAuthorizer(storageAuth) + return entitiesClient, nil } func (client Client) TablesClient(ctx context.Context, account accountDetails) (shim.StorageTableWrapper, error) { @@ -295,13 +378,16 @@ func (client Client) TablesClient(ctx context.Context, account accountDetails) ( return nil, fmt.Errorf("retrieving Account Key: %s", err) } - storageAuth, err := autorest.NewSharedKeyAuthorizer(account.name, *accountKey, autorest.SharedKeyLiteForTable) + storageAuth, err := auth.NewSharedKeyAuthorizer(account.name, *accountKey, auth.SharedKeyTable) if err != nil { return nil, fmt.Errorf("building Authorizer: %+v", err) } - tablesClient := tables.NewWithEnvironment(client.Environment) - tablesClient.Client.Authorizer = storageAuth - shim := shim.NewDataPlaneStorageTableWrapper(&tablesClient) + tablesClient, err := tables.NewWithBaseUri(*account.Properties.PrimaryEndpoints.Table) + if err != nil { + return nil, fmt.Errorf("creating Queues Client: %+v", err) + } + tablesClient.Client.WithAuthorizer(storageAuth) + shim := shim.NewDataPlaneStorageTableWrapper(tablesClient) return shim, nil } diff --git a/internal/services/storage/migration/share.go b/internal/services/storage/migration/share.go index 6e48a71d3ae9..142df6d06499 100644 --- a/internal/services/storage/migration/share.go +++ b/internal/services/storage/migration/share.go @@ -12,6 +12,7 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" + "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts" "github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares" ) @@ -60,10 +61,26 @@ func (s ShareV1ToV2) UpgradeFunc() pluginsdk.StateUpgraderFunc { shareName := parsedId[0] accountName := parsedId[2] - environment := meta.(*clients.Client).Account.AzureEnvironment - client := shares.NewWithEnvironment(environment) + storageClient := meta.(*clients.Client).Storage + account, err := storageClient.FindAccount(ctx, accountName) + if err != nil { + return rawState, fmt.Errorf("retrieving Account %q for Share: %s", accountName, err) + } + if account == nil { + return rawState, fmt.Errorf("Unable to locate Storage Account %q!", accountName) + } + + domainSuffix, ok := meta.(*clients.Client).Account.Environment.Storage.DomainSuffix() + if !ok { + return rawState, fmt.Errorf("retrieving domain suffix for Storage Accounts") + } + + accountId, err := accounts.ParseAccountID(account.ID, *domainSuffix) + if err != nil { + return rawState, fmt.Errorf("parsing account ID %s: %+v", account.ID, err) + } - newResourceId := client.GetResourceID(accountName, shareName) + newResourceId := shares.NewShareID(*accountId, shareName) log.Printf("[DEBUG] Updating Resource ID from %q to %q", id, newResourceId) rawState["id"] = newResourceId diff --git a/internal/services/storage/parse/storage_container_data_plane.go b/internal/services/storage/parse/storage_container_data_plane.go deleted file mode 100644 index 47dc25a7ec8c..000000000000 --- a/internal/services/storage/parse/storage_container_data_plane.go +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) HashiCorp, Inc. -// SPDX-License-Identifier: MPL-2.0 - -package parse - -import ( - "fmt" - "net/url" - "strings" - - "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" - "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers" -) - -var _ resourceids.Id = StorageContainerDataPlaneId{} - -type StorageContainerDataPlaneId struct { - AccountName string - DomainSuffix string - Name string -} - -func (id StorageContainerDataPlaneId) String() string { - components := []string{ - fmt.Sprintf("Account Name %q", id.AccountName), - fmt.Sprintf("Domain Suffix %q", id.DomainSuffix), - fmt.Sprintf("Name %q", id.Name), - } - return fmt.Sprintf("Storage Container %s", strings.Join(components, " / ")) -} - -func (id StorageContainerDataPlaneId) ID() string { - return fmt.Sprintf("https://%s.blob.%s/%s", id.AccountName, id.DomainSuffix, id.Name) -} - -func NewStorageContainerDataPlaneId(accountName, domainSuffix, name string) StorageContainerDataPlaneId { - return StorageContainerDataPlaneId{ - AccountName: accountName, - DomainSuffix: domainSuffix, - Name: name, - } -} - -func StorageContainerDataPlaneID(id string) (*StorageContainerDataPlaneId, error) { - parsed, err := containers.ParseResourceID(id) - if err != nil { - return nil, err - } - - uri, err := url.Parse(id) - if err != nil { - return nil, err - } - - host := uri.Host - hostSegments := strings.Split(host, ".") - if len(hostSegments) == 0 { - return nil, fmt.Errorf("expected multiple host segments but got 0") - } - domainNameSuffix := strings.TrimPrefix(host, fmt.Sprintf("%s.blob.", hostSegments[0])) - - return &StorageContainerDataPlaneId{ - AccountName: parsed.AccountName, - DomainSuffix: domainNameSuffix, - Name: parsed.ContainerName, - }, nil -} diff --git a/internal/services/storage/parse/storage_queue_data_plane.go b/internal/services/storage/parse/storage_queue_data_plane.go index 3fd6770ec093..bed659c8b9db 100644 --- a/internal/services/storage/parse/storage_queue_data_plane.go +++ b/internal/services/storage/parse/storage_queue_data_plane.go @@ -41,8 +41,8 @@ func NewStorageQueueDataPlaneId(accountName, domainSuffix, name string) StorageQ } } -func StorageQueueDataPlaneID(id string) (*StorageQueueDataPlaneId, error) { - parsed, err := queues.ParseResourceID(id) +func StorageQueueDataPlaneID(id, domainSuffix string) (*StorageQueueDataPlaneId, error) { + parsed, err := queues.ParseQueueID(id, domainSuffix) if err != nil { return nil, err } @@ -60,7 +60,7 @@ func StorageQueueDataPlaneID(id string) (*StorageQueueDataPlaneId, error) { domainNameSuffix := strings.TrimPrefix(host, fmt.Sprintf("%s.queue.", hostSegments[0])) return &StorageQueueDataPlaneId{ - AccountName: parsed.AccountName, + AccountName: parsed.AccountId.AccountName, DomainSuffix: domainNameSuffix, Name: parsed.QueueName, }, nil diff --git a/internal/services/storage/parse/storage_share_data_plane.go b/internal/services/storage/parse/storage_share_data_plane.go index 321fff4a7a8f..6ca3deb0bc95 100644 --- a/internal/services/storage/parse/storage_share_data_plane.go +++ b/internal/services/storage/parse/storage_share_data_plane.go @@ -42,8 +42,8 @@ func NewStorageShareDataPlaneId(accountName, domainSuffix, name string) StorageS } } -func StorageShareDataPlaneID(id string) (*StorageShareDataPlaneId, error) { - parsed, err := shares.ParseResourceID(id) +func StorageShareDataPlaneID(id, domainSuffix string) (*StorageShareDataPlaneId, error) { + parsed, err := shares.ParseShareID(id, domainSuffix) if err != nil { return nil, err } @@ -61,7 +61,7 @@ func StorageShareDataPlaneID(id string) (*StorageShareDataPlaneId, error) { domainNameSuffix := strings.TrimPrefix(host, fmt.Sprintf("%s.file.", hostSegments[0])) return &StorageShareDataPlaneId{ - AccountName: parsed.AccountName, + AccountName: parsed.AccountId.AccountName, DomainSuffix: domainNameSuffix, Name: parsed.ShareName, }, nil diff --git a/internal/services/storage/parse/storage_table_data_plane.go b/internal/services/storage/parse/storage_table_data_plane.go index bf668f89f317..494febad8e0e 100644 --- a/internal/services/storage/parse/storage_table_data_plane.go +++ b/internal/services/storage/parse/storage_table_data_plane.go @@ -42,13 +42,13 @@ func NewStorageTableDataPlaneId(accountName, domainSuffix, name string) StorageT } } -func StorageTableDataPlaneID(input string) (*StorageTableDataPlaneId, error) { - parsed, err := tables.ParseResourceID(input) +func StorageTableDataPlaneID(id, domainSuffix string) (*StorageTableDataPlaneId, error) { + parsed, err := tables.ParseTableID(id, domainSuffix) if err != nil { return nil, err } - uri, err := url.Parse(input) + uri, err := url.Parse(id) if err != nil { return nil, err } @@ -61,7 +61,7 @@ func StorageTableDataPlaneID(input string) (*StorageTableDataPlaneId, error) { domainNameSuffix := strings.TrimPrefix(host, fmt.Sprintf("%s.table.", hostSegments[0])) return &StorageTableDataPlaneId{ - AccountName: parsed.AccountName, + AccountName: parsed.AccountId.AccountName, DomainSuffix: domainNameSuffix, Name: parsed.TableName, }, nil diff --git a/internal/services/storage/shim/containers.go b/internal/services/storage/shim/containers.go index 55156bb5d9f3..ec59b31153bb 100644 --- a/internal/services/storage/shim/containers.go +++ b/internal/services/storage/shim/containers.go @@ -10,12 +10,12 @@ import ( ) type StorageContainerWrapper interface { - Create(ctx context.Context, resourceGroup, accountName, containerName string, input containers.CreateInput) error - Delete(ctx context.Context, resourceGroup, accountName, containerName string) error - Exists(ctx context.Context, resourceGroup, accountName, containerName string) (*bool, error) - Get(ctx context.Context, resourceGroup, accountName, containerName string) (*StorageContainerProperties, error) - UpdateAccessLevel(ctx context.Context, resourceGroup, accountName, containerName string, level containers.AccessLevel) error - UpdateMetaData(ctx context.Context, resourceGroup, accountName, containerName string, metadata map[string]string) error + Create(ctx context.Context, resourceGroup, containerName string, input containers.CreateInput) error + Delete(ctx context.Context, resourceGroup, containerName string) error + Exists(ctx context.Context, resourceGroup, containerName string) (*bool, error) + Get(ctx context.Context, resourceGroup, containerName string) (*StorageContainerProperties, error) + UpdateAccessLevel(ctx context.Context, resourceGroup, containerName string, level containers.AccessLevel) error + UpdateMetaData(ctx context.Context, resourceGroup, containerName string, metadata map[string]string) error } type StorageContainerProperties struct { diff --git a/internal/services/storage/shim/containers_data_plane.go b/internal/services/storage/shim/containers_data_plane.go index 2310188f5230..9449198dda6d 100644 --- a/internal/services/storage/shim/containers_data_plane.go +++ b/internal/services/storage/shim/containers_data_plane.go @@ -9,8 +9,8 @@ import ( "strings" "time" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" - "github.com/hashicorp/terraform-provider-azurerm/utils" "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers" ) @@ -24,19 +24,19 @@ func NewDataPlaneStorageContainerWrapper(client *containers.Client) StorageConta } } -func (w DataPlaneStorageContainerWrapper) Create(ctx context.Context, _, accountName, containerName string, input containers.CreateInput) error { +func (w DataPlaneStorageContainerWrapper) Create(ctx context.Context, _, containerName string, input containers.CreateInput) error { timeout, ok := ctx.Deadline() if !ok { return fmt.Errorf("context is missing a timeout") } - if resp, err := w.client.Create(ctx, accountName, containerName, input); err != nil { + if resp, err := w.client.Create(ctx, containerName, input); err != nil { // If we fail due to previous delete still in progress, then we can retry - if utils.ResponseWasConflict(resp.Response) && strings.Contains(err.Error(), "ContainerBeingDeleted") { + if response.WasConflict(resp.HttpResponse.Response) && strings.Contains(err.Error(), "ContainerBeingDeleted") { stateConf := &pluginsdk.StateChangeConf{ Pending: []string{"waitingOnDelete"}, Target: []string{"succeeded"}, - Refresh: w.createRefreshFunc(ctx, accountName, containerName, input), + Refresh: w.createRefreshFunc(ctx, containerName, input), PollInterval: 10 * time.Second, NotFoundChecks: 180, Timeout: time.Until(timeout), @@ -52,31 +52,31 @@ func (w DataPlaneStorageContainerWrapper) Create(ctx context.Context, _, account return nil } -func (w DataPlaneStorageContainerWrapper) Delete(ctx context.Context, _, accountName, containerName string) error { - resp, err := w.client.Delete(ctx, accountName, containerName) - if utils.ResponseWasNotFound(resp) { +func (w DataPlaneStorageContainerWrapper) Delete(ctx context.Context, _, containerName string) error { + resp, err := w.client.Delete(ctx, containerName) + if response.WasNotFound(resp.HttpResponse.Response) { return nil } return err } -func (w DataPlaneStorageContainerWrapper) Exists(ctx context.Context, _, accountName, containerName string) (*bool, error) { - existing, err := w.client.GetProperties(ctx, accountName, containerName) +func (w DataPlaneStorageContainerWrapper) Exists(ctx context.Context, _, containerName string) (*bool, error) { + existing, err := w.client.GetProperties(ctx, containerName, containers.GetPropertiesInput{}) if err != nil { - if !utils.ResponseWasNotFound(existing.Response) { + if !response.WasNotFound(existing.HttpResponse.Response) { return nil, err } } - exists := !utils.ResponseWasNotFound(existing.Response) + exists := !response.WasNotFound(existing.HttpResponse.Response) return &exists, nil } -func (w DataPlaneStorageContainerWrapper) Get(ctx context.Context, _, accountName, containerName string) (*StorageContainerProperties, error) { - props, err := w.client.GetProperties(ctx, accountName, containerName) +func (w DataPlaneStorageContainerWrapper) Get(ctx context.Context, _, containerName string) (*StorageContainerProperties, error) { + props, err := w.client.GetProperties(ctx, containerName, containers.GetPropertiesInput{}) if err != nil { - if utils.ResponseWasNotFound(props.Response) { + if response.WasNotFound(props.HttpResponse.Response) { return nil, nil } @@ -84,32 +84,38 @@ func (w DataPlaneStorageContainerWrapper) Get(ctx context.Context, _, accountNam } return &StorageContainerProperties{ - AccessLevel: props.AccessLevel, - MetaData: props.MetaData, - HasImmutabilityPolicy: props.HasImmutabilityPolicy, - HasLegalHold: props.HasLegalHold, + AccessLevel: props.Model.AccessLevel, + MetaData: props.Model.MetaData, + HasImmutabilityPolicy: props.Model.HasImmutabilityPolicy, + HasLegalHold: props.Model.HasLegalHold, }, nil } -func (w DataPlaneStorageContainerWrapper) UpdateAccessLevel(ctx context.Context, _, accountName, containerName string, level containers.AccessLevel) error { - _, err := w.client.SetAccessControl(ctx, accountName, containerName, level) +func (w DataPlaneStorageContainerWrapper) UpdateAccessLevel(ctx context.Context, _, containerName string, level containers.AccessLevel) error { + acInput := containers.SetAccessControlInput{ + AccessLevel: level, + } + _, err := w.client.SetAccessControl(ctx, containerName, acInput) return err } -func (w DataPlaneStorageContainerWrapper) UpdateMetaData(ctx context.Context, _, accountName, containerName string, metaData map[string]string) error { - _, err := w.client.SetMetaData(ctx, accountName, containerName, metaData) +func (w DataPlaneStorageContainerWrapper) UpdateMetaData(ctx context.Context, _, containerName string, metaData map[string]string) error { + metadataInput := containers.SetMetaDataInput{ + MetaData: metaData, + } + _, err := w.client.SetMetaData(ctx, containerName, metadataInput) return err } -func (w DataPlaneStorageContainerWrapper) createRefreshFunc(ctx context.Context, accountName string, containerName string, input containers.CreateInput) pluginsdk.StateRefreshFunc { +func (w DataPlaneStorageContainerWrapper) createRefreshFunc(ctx context.Context, containerName string, input containers.CreateInput) pluginsdk.StateRefreshFunc { return func() (interface{}, string, error) { - resp, err := w.client.Create(ctx, accountName, containerName, input) + resp, err := w.client.Create(ctx, containerName, input) if err != nil { - if !utils.ResponseWasConflict(resp.Response) { + if !response.WasConflict(resp.HttpResponse.Response) { return nil, "", err } - if utils.ResponseWasConflict(resp.Response) && strings.Contains(err.Error(), "ContainerBeingDeleted") { + if response.WasConflict(resp.HttpResponse.Response) && strings.Contains(err.Error(), "ContainerBeingDeleted") { return nil, "waitingOnDelete", nil } } diff --git a/internal/services/storage/shim/queues.go b/internal/services/storage/shim/queues.go index d145093014b0..ec03e82ce852 100644 --- a/internal/services/storage/shim/queues.go +++ b/internal/services/storage/shim/queues.go @@ -10,13 +10,13 @@ import ( ) type StorageQueuesWrapper interface { - Create(ctx context.Context, resourceGroup, accountName, queueName string, metaData map[string]string) error - Delete(ctx context.Context, resourceGroup, accountName, queueName string) error - Exists(ctx context.Context, resourceGroup, accountName, queueName string) (*bool, error) - Get(ctx context.Context, resourceGroup, accountName, queueName string) (*StorageQueueProperties, error) - GetServiceProperties(ctx context.Context, resourceGroup, accountName string) (*queues.StorageServiceProperties, error) - UpdateMetaData(ctx context.Context, resourceGroup, accountName, queueName string, metaData map[string]string) error - UpdateServiceProperties(ctx context.Context, resourceGroup, accountName string, properties queues.StorageServiceProperties) error + Create(ctx context.Context, resourceGroup, queueName string, metaData map[string]string) error + Delete(ctx context.Context, resourceGroup, queueName string) error + Exists(ctx context.Context, resourceGroup, queueName string) (*bool, error) + Get(ctx context.Context, resourceGroup, queueName string) (*StorageQueueProperties, error) + GetServiceProperties(ctx context.Context) (*queues.StorageServiceProperties, error) + UpdateMetaData(ctx context.Context, resourceGroup, queueName string, metaData map[string]string) error + UpdateServiceProperties(ctx context.Context, resourceGroup string, properties queues.StorageServiceProperties) error } type StorageQueueProperties struct { diff --git a/internal/services/storage/shim/queues_data_plane.go b/internal/services/storage/shim/queues_data_plane.go index 3052f205761a..cee5e8d61ad0 100644 --- a/internal/services/storage/shim/queues_data_plane.go +++ b/internal/services/storage/shim/queues_data_plane.go @@ -6,6 +6,7 @@ package shim import ( "context" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/terraform-provider-azurerm/utils" "github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues" ) @@ -20,20 +21,23 @@ func NewDataPlaneStorageQueueWrapper(client *queues.Client) StorageQueuesWrapper } } -func (w DataPlaneStorageQueueWrapper) Create(ctx context.Context, _, accountName, queueName string, metaData map[string]string) error { - _, err := w.client.Create(ctx, accountName, queueName, metaData) +func (w DataPlaneStorageQueueWrapper) Create(ctx context.Context, _, queueName string, metaData map[string]string) error { + input := queues.CreateInput{ + MetaData: metaData, + } + _, err := w.client.Create(ctx, queueName, input) return err } -func (w DataPlaneStorageQueueWrapper) Delete(ctx context.Context, _, accountName, queueName string) error { - _, err := w.client.Delete(ctx, accountName, queueName) +func (w DataPlaneStorageQueueWrapper) Delete(ctx context.Context, _, queueName string) error { + _, err := w.client.Delete(ctx, queueName) return err } -func (w DataPlaneStorageQueueWrapper) Exists(ctx context.Context, _, accountName, queueName string) (*bool, error) { - existing, err := w.client.GetMetaData(ctx, accountName, queueName) +func (w DataPlaneStorageQueueWrapper) Exists(ctx context.Context, _, queueName string) (*bool, error) { + existing, err := w.client.GetMetaData(ctx, queueName) if err != nil { - if utils.ResponseWasNotFound(existing.Response) { + if response.WasNotFound(existing.HttpResponse.Response) { return utils.Bool(false), nil } return nil, err @@ -42,10 +46,10 @@ func (w DataPlaneStorageQueueWrapper) Exists(ctx context.Context, _, accountName return utils.Bool(true), nil } -func (w DataPlaneStorageQueueWrapper) Get(ctx context.Context, _, accountName, queueName string) (*StorageQueueProperties, error) { - props, err := w.client.GetMetaData(ctx, accountName, queueName) +func (w DataPlaneStorageQueueWrapper) Get(ctx context.Context, _, queueName string) (*StorageQueueProperties, error) { + props, err := w.client.GetMetaData(ctx, queueName) if err != nil { - if utils.ResponseWasNotFound(props.Response) { + if response.WasNotFound(props.HttpResponse.Response) { return nil, nil } return nil, err @@ -56,10 +60,10 @@ func (w DataPlaneStorageQueueWrapper) Get(ctx context.Context, _, accountName, q }, nil } -func (w DataPlaneStorageQueueWrapper) GetServiceProperties(ctx context.Context, resourceGroup, accountName string) (*queues.StorageServiceProperties, error) { - serviceProps, err := w.client.GetServiceProperties(ctx, accountName) +func (w DataPlaneStorageQueueWrapper) GetServiceProperties(ctx context.Context) (*queues.StorageServiceProperties, error) { + serviceProps, err := w.client.GetServiceProperties(ctx) if err != nil { - if utils.ResponseWasNotFound(serviceProps.Response) { + if response.WasNotFound(serviceProps.HttpResponse.Response) { return nil, nil } return nil, err @@ -68,12 +72,18 @@ func (w DataPlaneStorageQueueWrapper) GetServiceProperties(ctx context.Context, return &serviceProps.StorageServiceProperties, nil } -func (w DataPlaneStorageQueueWrapper) UpdateMetaData(ctx context.Context, _, accountName, queueName string, metaData map[string]string) error { - _, err := w.client.SetMetaData(ctx, accountName, queueName, metaData) +func (w DataPlaneStorageQueueWrapper) UpdateMetaData(ctx context.Context, _, queueName string, metaData map[string]string) error { + input := queues.SetMetaDataInput{ + MetaData: metaData, + } + _, err := w.client.SetMetaData(ctx, queueName, input) return err } -func (w DataPlaneStorageQueueWrapper) UpdateServiceProperties(ctx context.Context, _, accountName string, properties queues.StorageServiceProperties) error { - _, err := w.client.SetServiceProperties(ctx, accountName, properties) +func (w DataPlaneStorageQueueWrapper) UpdateServiceProperties(ctx context.Context, _ string, properties queues.StorageServiceProperties) error { + input := queues.SetStorageServicePropertiesInput{ + Properties: properties, + } + _, err := w.client.SetServiceProperties(ctx, input) return err } diff --git a/internal/services/storage/shim/shares.go b/internal/services/storage/shim/shares.go index 702e34b492b2..eb3b54c1d2f7 100644 --- a/internal/services/storage/shim/shares.go +++ b/internal/services/storage/shim/shares.go @@ -10,14 +10,14 @@ import ( ) type StorageShareWrapper interface { - Create(ctx context.Context, resourceGroup, accountName, shareName string, input shares.CreateInput) error - Delete(ctx context.Context, resourceGroup, accountName, shareName string) error - Exists(ctx context.Context, resourceGroup, accountName, shareName string) (*bool, error) - Get(ctx context.Context, resourceGroup, accountName, shareName string) (*StorageShareProperties, error) - UpdateACLs(ctx context.Context, resourceGroup, accountName, shareName string, acls []shares.SignedIdentifier) error - UpdateMetaData(ctx context.Context, resourceGroup, accountName, shareName string, metaData map[string]string) error - UpdateQuota(ctx context.Context, resourceGroup, accountName, shareName string, quotaGB int) error - UpdateTier(ctx context.Context, resourceGroup, accountName, shareName string, tier shares.AccessTier) error + Create(ctx context.Context, resourceGroup, shareName string, input shares.CreateInput) error + Delete(ctx context.Context, resourceGroup, shareName string) error + Exists(ctx context.Context, resourceGroup, shareName string) (*bool, error) + Get(ctx context.Context, resourceGroup, shareName string) (*StorageShareProperties, error) + UpdateACLs(ctx context.Context, resourceGroup, shareName string, acls []shares.SignedIdentifier) error + UpdateMetaData(ctx context.Context, resourceGroup, shareName string, metaData map[string]string) error + UpdateQuota(ctx context.Context, resourceGroup, shareName string, quotaGB int) error + UpdateTier(ctx context.Context, resourceGroup, shareName string, tier shares.AccessTier) error } type StorageShareProperties struct { diff --git a/internal/services/storage/shim/shares_data_plane.go b/internal/services/storage/shim/shares_data_plane.go index ae88b650cd55..51be297be5ee 100644 --- a/internal/services/storage/shim/shares_data_plane.go +++ b/internal/services/storage/shim/shares_data_plane.go @@ -9,6 +9,7 @@ import ( "strings" "time" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" "github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares" @@ -24,23 +25,23 @@ func NewDataPlaneStorageShareWrapper(client *shares.Client) StorageShareWrapper } } -func (w DataPlaneStorageShareWrapper) Create(ctx context.Context, _, accountName, shareName string, input shares.CreateInput) error { +func (w DataPlaneStorageShareWrapper) Create(ctx context.Context, _, shareName string, input shares.CreateInput) error { timeout, ok := ctx.Deadline() if !ok { return fmt.Errorf("context is missing a timeout") } - resp, err := w.client.Create(ctx, accountName, shareName, input) + resp, err := w.client.Create(ctx, shareName, input) if err == nil { return nil } // If we fail due to previous delete still in progress, then we can retry - if utils.ResponseWasConflict(resp) && strings.Contains(err.Error(), "ShareBeingDeleted") { + if response.WasConflict(resp.HttpResponse.Response) && strings.Contains(err.Error(), "ShareBeingDeleted") { stateConf := &pluginsdk.StateChangeConf{ Pending: []string{"waitingOnDelete"}, Target: []string{"succeeded"}, - Refresh: w.createRefreshFunc(ctx, accountName, shareName, input), + Refresh: w.createRefreshFunc(ctx, shareName, input), PollInterval: 10 * time.Second, NotFoundChecks: 180, Timeout: time.Until(timeout), @@ -54,16 +55,18 @@ func (w DataPlaneStorageShareWrapper) Create(ctx context.Context, _, accountName return err } -func (w DataPlaneStorageShareWrapper) Delete(ctx context.Context, _, accountName, shareName string) error { - deleteSnapshots := true - _, err := w.client.Delete(ctx, accountName, shareName, deleteSnapshots) +func (w DataPlaneStorageShareWrapper) Delete(ctx context.Context, _, shareName string) error { + input := shares.DeleteInput{ + DeleteSnapshots: true, + } + _, err := w.client.Delete(ctx, shareName, input) return err } -func (w DataPlaneStorageShareWrapper) Exists(ctx context.Context, _, accountName, shareName string) (*bool, error) { - existing, err := w.client.GetProperties(ctx, accountName, shareName) +func (w DataPlaneStorageShareWrapper) Exists(ctx context.Context, _, shareName string) (*bool, error) { + existing, err := w.client.GetProperties(ctx, shareName) if err != nil { - if utils.ResponseWasNotFound(existing.Response) { + if response.WasNotFound(existing.HttpResponse.Response) { return nil, nil } @@ -73,17 +76,17 @@ func (w DataPlaneStorageShareWrapper) Exists(ctx context.Context, _, accountName return utils.Bool(true), nil } -func (w DataPlaneStorageShareWrapper) Get(ctx context.Context, _, accountName, shareName string) (*StorageShareProperties, error) { - props, err := w.client.GetProperties(ctx, accountName, shareName) +func (w DataPlaneStorageShareWrapper) Get(ctx context.Context, _, shareName string) (*StorageShareProperties, error) { + props, err := w.client.GetProperties(ctx, shareName) if err != nil { - if utils.ResponseWasNotFound(props.Response) { + if response.WasNotFound(props.HttpResponse.Response) { return nil, nil } return nil, err } - acls, err := w.client.GetACL(ctx, accountName, shareName) + acls, err := w.client.GetACL(ctx, shareName) if err != nil { return nil, err } @@ -97,40 +100,46 @@ func (w DataPlaneStorageShareWrapper) Get(ctx context.Context, _, accountName, s }, nil } -func (w DataPlaneStorageShareWrapper) UpdateACLs(ctx context.Context, _, accountName, shareName string, acls []shares.SignedIdentifier) error { - _, err := w.client.SetACL(ctx, accountName, shareName, acls) +func (w DataPlaneStorageShareWrapper) UpdateACLs(ctx context.Context, _, shareName string, acls []shares.SignedIdentifier) error { + input := shares.SetAclInput{ + SignedIdentifiers: acls, + } + _, err := w.client.SetACL(ctx, shareName, input) return err } -func (w DataPlaneStorageShareWrapper) UpdateMetaData(ctx context.Context, _, accountName, shareName string, metaData map[string]string) error { - _, err := w.client.SetMetaData(ctx, accountName, shareName, metaData) +func (w DataPlaneStorageShareWrapper) UpdateMetaData(ctx context.Context, _, shareName string, metaData map[string]string) error { + input := shares.SetMetaDataInput{ + MetaData: metaData, + } + _, err := w.client.SetMetaData(ctx, shareName, input) return err } -func (w DataPlaneStorageShareWrapper) UpdateQuota(ctx context.Context, _, accountName, shareName string, quotaGB int) error { - _, err := w.client.SetProperties(ctx, accountName, shareName, shares.ShareProperties{ +func (w DataPlaneStorageShareWrapper) UpdateQuota(ctx context.Context, _, shareName string, quotaGB int) error { + _, err := w.client.SetProperties(ctx, shareName, shares.ShareProperties{ QuotaInGb: "aGB, }) return err } -func (w DataPlaneStorageShareWrapper) UpdateTier(ctx context.Context, _, accountname, shareName string, tier shares.AccessTier) error { +func (w DataPlaneStorageShareWrapper) UpdateTier(ctx context.Context, _, shareName string, tier shares.AccessTier) error { props := shares.ShareProperties{ AccessTier: &tier, } - _, err := w.client.SetProperties(ctx, accountname, shareName, props) + _, err := w.client.SetProperties(ctx, shareName, props) return err } -func (w DataPlaneStorageShareWrapper) createRefreshFunc(ctx context.Context, accountName string, shareName string, input shares.CreateInput) pluginsdk.StateRefreshFunc { +func (w DataPlaneStorageShareWrapper) createRefreshFunc(ctx context.Context, shareName string, input shares.CreateInput) pluginsdk.StateRefreshFunc { return func() (interface{}, string, error) { - resp, err := w.client.Create(ctx, accountName, shareName, input) + resp, err := w.client.Create(ctx, shareName, input) if err != nil { - if !utils.ResponseWasConflict(resp) { + if !response.WasConflict(resp.HttpResponse.Response) { return nil, "", err } - if utils.ResponseWasConflict(resp) && strings.Contains(err.Error(), "ShareBeingDeleted") { + if response.WasConflict(resp.HttpResponse.Response) && strings.Contains(err.Error(), "ShareBeingDeleted") { return nil, "waitingOnDelete", nil } } diff --git a/internal/services/storage/shim/tables.go b/internal/services/storage/shim/tables.go index f928d83fcea0..b27a140e2452 100644 --- a/internal/services/storage/shim/tables.go +++ b/internal/services/storage/shim/tables.go @@ -10,9 +10,9 @@ import ( ) type StorageTableWrapper interface { - Create(ctx context.Context, resourceGroup string, accountName string, tableName string) error - Delete(ctx context.Context, resourceGroup string, accountName string, tableName string) error - Exists(ctx context.Context, resourceGroup string, accountName string, tableName string) (*bool, error) - GetACLs(ctx context.Context, resourceGroup string, accountName string, tableName string) (*[]tables.SignedIdentifier, error) - UpdateACLs(ctx context.Context, resourceGroup string, accountName string, tableName string, acls []tables.SignedIdentifier) error + Create(ctx context.Context, resourceGroup string, tableName string) error + Delete(ctx context.Context, resourceGroup string, tableName string) error + Exists(ctx context.Context, resourceGroup string, tableName string) (*bool, error) + GetACLs(ctx context.Context, resourceGroup string, tableName string) (*[]tables.SignedIdentifier, error) + UpdateACLs(ctx context.Context, resourceGroup string, tableName string, acls []tables.SignedIdentifier) error } diff --git a/internal/services/storage/shim/tables_data_plane.go b/internal/services/storage/shim/tables_data_plane.go index f8a998f06069..ebd57d45f401 100644 --- a/internal/services/storage/shim/tables_data_plane.go +++ b/internal/services/storage/shim/tables_data_plane.go @@ -6,6 +6,7 @@ package shim import ( "context" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/terraform-provider-azurerm/utils" "github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables" ) @@ -20,20 +21,20 @@ func NewDataPlaneStorageTableWrapper(client *tables.Client) StorageTableWrapper } } -func (w DataPlaneStorageTableWrapper) Create(ctx context.Context, _, accountName, tableName string) error { - _, err := w.client.Create(ctx, accountName, tableName) +func (w DataPlaneStorageTableWrapper) Create(ctx context.Context, _, tableName string) error { + _, err := w.client.Create(ctx, tableName) return err } -func (w DataPlaneStorageTableWrapper) Delete(ctx context.Context, _, accountName, tableName string) error { - _, err := w.client.Delete(ctx, accountName, tableName) +func (w DataPlaneStorageTableWrapper) Delete(ctx context.Context, _, tableName string) error { + _, err := w.client.Delete(ctx, tableName) return err } -func (w DataPlaneStorageTableWrapper) Exists(ctx context.Context, _, accountName, tableName string) (*bool, error) { - existing, err := w.client.Exists(ctx, accountName, tableName) +func (w DataPlaneStorageTableWrapper) Exists(ctx context.Context, _, tableName string) (*bool, error) { + existing, err := w.client.Exists(ctx, tableName) if err != nil { - if utils.ResponseWasNotFound(existing) { + if response.WasNotFound(existing.HttpResponse.Response) { return nil, nil } @@ -43,8 +44,8 @@ func (w DataPlaneStorageTableWrapper) Exists(ctx context.Context, _, accountName return utils.Bool(true), nil } -func (w DataPlaneStorageTableWrapper) GetACLs(ctx context.Context, _, accountName, tableName string) (*[]tables.SignedIdentifier, error) { - acls, err := w.client.GetACL(ctx, accountName, tableName) +func (w DataPlaneStorageTableWrapper) GetACLs(ctx context.Context, _, tableName string) (*[]tables.SignedIdentifier, error) { + acls, err := w.client.GetACL(ctx, tableName) if err != nil { return nil, err } @@ -52,7 +53,7 @@ func (w DataPlaneStorageTableWrapper) GetACLs(ctx context.Context, _, accountNam return &acls.SignedIdentifiers, nil } -func (w DataPlaneStorageTableWrapper) UpdateACLs(ctx context.Context, _, accountName, tableName string, acls []tables.SignedIdentifier) error { - _, err := w.client.SetACL(ctx, accountName, tableName, acls) +func (w DataPlaneStorageTableWrapper) UpdateACLs(ctx context.Context, _, tableName string, acls []tables.SignedIdentifier) error { + _, err := w.client.SetACL(ctx, tableName, acls) return err } diff --git a/internal/services/storage/storage_account_resource.go b/internal/services/storage/storage_account_resource.go index 69d3d2e1f812..c25ce3406a9c 100644 --- a/internal/services/storage/storage_account_resource.go +++ b/internal/services/storage/storage_account_resource.go @@ -1565,7 +1565,7 @@ func resourceStorageAccountCreate(d *pluginsdk.ResourceData, meta interface{}) e return fmt.Errorf("expanding `queue_properties`: %+v", err) } - if err = queueClient.UpdateServiceProperties(ctx, id.ResourceGroupName, id.StorageAccountName, queueProperties); err != nil { + if err = queueClient.UpdateServiceProperties(ctx, id.ResourceGroupName, queueProperties); err != nil { return fmt.Errorf("updating Queue Properties: %+v", err) } } @@ -2029,7 +2029,7 @@ func resourceStorageAccountUpdate(d *pluginsdk.ResourceData, meta interface{}) e return fmt.Errorf("expanding `queue_properties` for %s: %+v", *id, err) } - if err = queueClient.UpdateServiceProperties(ctx, account.ResourceGroup, id.StorageAccountName, queueProperties); err != nil { + if err = queueClient.UpdateServiceProperties(ctx, account.ResourceGroup, queueProperties); err != nil { return fmt.Errorf("updating Queue Properties for %s: %+v", *id, err) } } @@ -2358,7 +2358,7 @@ func resourceStorageAccountRead(d *pluginsdk.ResourceData, meta interface{}) err return fmt.Errorf("building Queues Client: %s", err) } - queueProps, err := queueClient.GetServiceProperties(ctx, id.ResourceGroupName, id.StorageAccountName) + queueProps, err := queueClient.GetServiceProperties(ctx) if err != nil { return fmt.Errorf("retrieving queue properties for %s: %+v", *id, err) } @@ -3683,7 +3683,7 @@ func flattenedSharePropertiesSMB(input *storage.SmbSetting) []interface{} { } func flattenStaticWebsiteProperties(input accounts.GetServicePropertiesResult) []interface{} { - if storageServiceProps := input.StorageServiceProperties; storageServiceProps != nil { + if storageServiceProps := input.Model; storageServiceProps != nil { if staticWebsite := storageServiceProps.StaticWebsite; staticWebsite != nil { if !staticWebsite.Enabled { return []interface{}{} diff --git a/internal/services/storage/storage_blob_data_source.go b/internal/services/storage/storage_blob_data_source.go index cbe1c2a1b655..3469001a9080 100644 --- a/internal/services/storage/storage_blob_data_source.go +++ b/internal/services/storage/storage_blob_data_source.go @@ -9,10 +9,11 @@ import ( "strings" "time" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" - "github.com/hashicorp/terraform-provider-azurerm/utils" + "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts" "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs" ) @@ -76,6 +77,11 @@ func dataSourceStorageBlobRead(d *pluginsdk.ResourceData, meta interface{}) erro ctx, cancel := timeouts.ForCreate(meta.(*clients.Client).StopContext, d) defer cancel() + domainSuffix, ok := meta.(*clients.Client).Account.Environment.Storage.DomainSuffix() + if !ok { + return fmt.Errorf("retrieving domain suffix for Storage Accounts") + } + accountName := d.Get("storage_account_name").(string) containerName := d.Get("storage_container_name").(string) name := d.Get("name").(string) @@ -88,18 +94,23 @@ func dataSourceStorageBlobRead(d *pluginsdk.ResourceData, meta interface{}) erro return fmt.Errorf("Unable to locate Storage Account %q!", accountName) } + accountId, err := accounts.ParseAccountID(account.ID, *domainSuffix) + if err != nil { + return fmt.Errorf("parsing account ID %s: %+v", account.ID, err) + } + blobsClient, err := storageClient.BlobsClient(ctx, *account) if err != nil { return fmt.Errorf("building Blobs Client: %s", err) } - id := blobsClient.GetResourceID(accountName, containerName, name) + id := blobs.NewBlobID(*accountId, containerName, name) log.Printf("[INFO] Retrieving Storage Blob %q (Container %q / Account %q).", name, containerName, accountName) input := blobs.GetPropertiesInput{} - props, err := blobsClient.GetProperties(ctx, accountName, containerName, name, input) + props, err := blobsClient.GetProperties(ctx, containerName, name, input) if err != nil { - if utils.ResponseWasNotFound(props.Response) { + if response.WasNotFound(props.HttpResponse.Response) { return fmt.Errorf("the Blob %q was not found in Container %q / Account %q", name, containerName, accountName) } @@ -125,7 +136,7 @@ func dataSourceStorageBlobRead(d *pluginsdk.ResourceData, meta interface{}) erro d.Set("type", strings.TrimSuffix(string(props.BlobType), "Blob")) - d.SetId(id) + d.SetId(id.ID()) d.Set("url", id) diff --git a/internal/services/storage/storage_blob_resource.go b/internal/services/storage/storage_blob_resource.go index d2c5b1c227ab..a536877679ff 100644 --- a/internal/services/storage/storage_blob_resource.go +++ b/internal/services/storage/storage_blob_resource.go @@ -10,6 +10,7 @@ import ( "strings" "time" + "github.com/hashicorp/go-azure-helpers/lang/response" "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/migration" @@ -18,6 +19,7 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" "github.com/hashicorp/terraform-provider-azurerm/utils" + "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts" "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs" ) @@ -33,10 +35,10 @@ func resourceStorageBlob() *pluginsdk.Resource { 0: migration.BlobV0ToV1{}, }), - Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { - _, err := blobs.ParseResourceID(id) - return err - }), + // Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { + // _, err := blobs.ParseResourceID(id) + // return err + // }), Timeouts: &pluginsdk.ResourceTimeout{ Create: pluginsdk.DefaultTimeout(30 * time.Minute), @@ -173,12 +175,17 @@ func resourceStorageBlobCreate(d *pluginsdk.ResourceData, meta interface{}) erro containerName := d.Get("storage_container_name").(string) name := d.Get("name").(string) + domainSuffix, ok := meta.(*clients.Client).Account.Environment.Storage.DomainSuffix() + if !ok { + return fmt.Errorf("retrieving domain suffix for Storage Accounts") + } + account, err := storageClient.FindAccount(ctx, accountName) if err != nil { return fmt.Errorf("retrieving Account %q for Blob %q (Container %q): %s", accountName, name, containerName, err) } if account == nil { - return fmt.Errorf("Unable to locate Storage Account %q!", accountName) + return fmt.Errorf("locating Storage Account %q", accountName) } blobsClient, err := storageClient.BlobsClient(ctx, *account) @@ -186,17 +193,21 @@ func resourceStorageBlobCreate(d *pluginsdk.ResourceData, meta interface{}) erro return fmt.Errorf("building Blobs Client: %s", err) } - id := blobsClient.GetResourceID(accountName, containerName, name) + accountId, err := accounts.ParseAccountID(account.ID, *domainSuffix) + if err != nil { + return fmt.Errorf("parsing account ID %s: %+v", account.ID, err) + } + id := blobs.NewBlobID(*accountId, containerName, name) if d.IsNewResource() { input := blobs.GetPropertiesInput{} - props, err := blobsClient.GetProperties(ctx, accountName, containerName, name, input) + props, err := blobsClient.GetProperties(ctx, containerName, name, input) if err != nil { - if !utils.ResponseWasNotFound(props.Response) { + if !response.WasNotFound(props.HttpResponse.Response) { return fmt.Errorf("checking if Blob %q exists (Container %q / Account %q / Resource Group %q): %s", name, containerName, accountName, account.ResourceGroup, err) } } - if !utils.ResponseWasNotFound(props.Response) { - return tf.ImportAsExistsError("azurerm_storage_blob", id) + if !response.WasNotFound(props.HttpResponse.Response) { + return tf.ImportAsExistsError("azurerm_storage_blob", id.ID()) } } @@ -234,7 +245,7 @@ func resourceStorageBlobCreate(d *pluginsdk.ResourceData, meta interface{}) erro } log.Printf("[DEBUG] Created Blob %q in Container %q within Storage Account %q.", name, containerName, accountName) - d.SetId(id) + d.SetId(id.ID()) return resourceStorageBlobUpdate(d, meta) } @@ -244,17 +255,22 @@ func resourceStorageBlobUpdate(d *pluginsdk.ResourceData, meta interface{}) erro ctx, cancel := timeouts.ForUpdate(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := blobs.ParseResourceID(d.Id()) + domainSuffix, ok := meta.(*clients.Client).Account.Environment.Storage.DomainSuffix() + if !ok { + return fmt.Errorf("retrieving domain suffix for Storage Accounts") + } + + id, err := blobs.ParseBlobID(d.Id(), *domainSuffix) if err != nil { return fmt.Errorf("parsing %q: %s", d.Id(), err) } - account, err := storageClient.FindAccount(ctx, id.AccountName) + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Blob %q (Container %q): %s", id.AccountName, id.BlobName, id.ContainerName, err) + return fmt.Errorf("retrieving Account %q for Blob %q (Container %q): %s", id.AccountId.AccountName, id.BlobName, id.ContainerName, err) } if account == nil { - return fmt.Errorf("Unable to locate Storage Account %q!", id.AccountName) + return fmt.Errorf("locating Storage Account %q", id.AccountId.AccountName) } blobsClient, err := storageClient.BlobsClient(ctx, *account) @@ -264,18 +280,22 @@ func resourceStorageBlobUpdate(d *pluginsdk.ResourceData, meta interface{}) erro if d.HasChange("access_tier") { // this is only applicable for Gen2/BlobStorage accounts - log.Printf("[DEBUG] Updating Access Tier for Blob %q (Container %q / Account %q)...", id.BlobName, id.ContainerName, id.AccountName) + log.Printf("[DEBUG] Updating Access Tier for Blob %q (Container %q / Account %q)...", id.BlobName, id.ContainerName, id.AccountId.AccountName) accessTier := blobs.AccessTier(d.Get("access_tier").(string)) - if _, err := blobsClient.SetTier(ctx, id.AccountName, id.ContainerName, id.BlobName, accessTier); err != nil { - return fmt.Errorf("updating Access Tier for Blob %q (Container %q / Account %q): %s", id.BlobName, id.ContainerName, id.AccountName, err) + input := blobs.SetTierInput{ + Tier: accessTier, } - log.Printf("[DEBUG] Updated Access Tier for Blob %q (Container %q / Account %q).", id.BlobName, id.ContainerName, id.AccountName) + if _, err := blobsClient.SetTier(ctx, id.ContainerName, id.BlobName, input); err != nil { + return fmt.Errorf("updating Access Tier for Blob %q (Container %q / Account %q): %s", id.BlobName, id.ContainerName, id.AccountId.AccountName, err) + } + + log.Printf("[DEBUG] Updated Access Tier for Blob %q (Container %q / Account %q).", id.BlobName, id.ContainerName, id.AccountId.AccountName) } if d.HasChange("content_type") || d.HasChange("cache_control") { - log.Printf("[DEBUG] Updating Properties for Blob %q (Container %q / Account %q)...", id.BlobName, id.ContainerName, id.AccountName) + log.Printf("[DEBUG] Updating Properties for Blob %q (Container %q / Account %q)...", id.BlobName, id.ContainerName, id.AccountId.AccountName) input := blobs.SetPropertiesInput{ ContentType: utils.String(d.Get("content_type").(string)), CacheControl: utils.String(d.Get("cache_control").(string)), @@ -291,22 +311,22 @@ func resourceStorageBlobUpdate(d *pluginsdk.ResourceData, meta interface{}) erro input.ContentMD5 = utils.String(data) } - if _, err := blobsClient.SetProperties(ctx, id.AccountName, id.ContainerName, id.BlobName, input); err != nil { - return fmt.Errorf("updating Properties for Blob %q (Container %q / Account %q): %s", id.BlobName, id.ContainerName, id.AccountName, err) + if _, err := blobsClient.SetProperties(ctx, id.ContainerName, id.BlobName, input); err != nil { + return fmt.Errorf("updating Properties for Blob %q (Container %q / Account %q): %s", id.BlobName, id.ContainerName, id.AccountId.AccountName, err) } - log.Printf("[DEBUG] Updated Properties for Blob %q (Container %q / Account %q).", id.BlobName, id.ContainerName, id.AccountName) + log.Printf("[DEBUG] Updated Properties for Blob %q (Container %q / Account %q).", id.BlobName, id.ContainerName, id.AccountId.AccountName) } if d.HasChange("metadata") { - log.Printf("[DEBUG] Updating MetaData for Blob %q (Container %q / Account %q)...", id.BlobName, id.ContainerName, id.AccountName) + log.Printf("[DEBUG] Updating MetaData for Blob %q (Container %q / Account %q)...", id.BlobName, id.ContainerName, id.AccountId.AccountName) metaDataRaw := d.Get("metadata").(map[string]interface{}) input := blobs.SetMetaDataInput{ MetaData: ExpandMetaData(metaDataRaw), } - if _, err := blobsClient.SetMetaData(ctx, id.AccountName, id.ContainerName, id.BlobName, input); err != nil { - return fmt.Errorf("updating MetaData for Blob %q (Container %q / Account %q): %s", id.BlobName, id.ContainerName, id.AccountName, err) + if _, err := blobsClient.SetMetaData(ctx, id.ContainerName, id.BlobName, input); err != nil { + return fmt.Errorf("updating MetaData for Blob %q (Container %q / Account %q): %s", id.BlobName, id.ContainerName, id.AccountId.AccountName, err) } - log.Printf("[DEBUG] Updated MetaData for Blob %q (Container %q / Account %q).", id.BlobName, id.ContainerName, id.AccountName) + log.Printf("[DEBUG] Updated MetaData for Blob %q (Container %q / Account %q).", id.BlobName, id.ContainerName, id.AccountId.AccountName) } return resourceStorageBlobRead(d, meta) @@ -317,17 +337,22 @@ func resourceStorageBlobRead(d *pluginsdk.ResourceData, meta interface{}) error ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := blobs.ParseResourceID(d.Id()) + domainSuffix, ok := meta.(*clients.Client).Account.Environment.Storage.DomainSuffix() + if !ok { + return fmt.Errorf("retrieving domain suffix for Storage Accounts") + } + + id, err := blobs.ParseBlobID(d.Id(), *domainSuffix) if err != nil { return fmt.Errorf("parsing %q: %s", d.Id(), err) } - account, err := storageClient.FindAccount(ctx, id.AccountName) + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Blob %q (Container %q): %s", id.AccountName, id.BlobName, id.ContainerName, err) + return fmt.Errorf("retrieving Account %q for Blob %q (Container %q): %s", id.AccountId.AccountName, id.BlobName, id.ContainerName, err) } if account == nil { - log.Printf("[DEBUG] Unable to locate Account %q for Blob %q (Container %q) - assuming removed & removing from state!", id.AccountName, id.BlobName, id.ContainerName) + log.Printf("[DEBUG] Unable to locate Account %q for Blob %q (Container %q) - assuming removed & removing from state!", id.AccountId.AccountName, id.BlobName, id.ContainerName) d.SetId("") return nil } @@ -337,22 +362,22 @@ func resourceStorageBlobRead(d *pluginsdk.ResourceData, meta interface{}) error return fmt.Errorf("building Blobs Client: %s", err) } - log.Printf("[INFO] Retrieving Storage Blob %q (Container %q / Account %q).", id.BlobName, id.ContainerName, id.AccountName) + log.Printf("[INFO] Retrieving Storage Blob %q (Container %q / Account %q).", id.BlobName, id.ContainerName, id.AccountId.AccountName) input := blobs.GetPropertiesInput{} - props, err := blobsClient.GetProperties(ctx, id.AccountName, id.ContainerName, id.BlobName, input) + props, err := blobsClient.GetProperties(ctx, id.ContainerName, id.BlobName, input) if err != nil { - if utils.ResponseWasNotFound(props.Response) { - log.Printf("[INFO] Blob %q was not found in Container %q / Account %q - assuming removed & removing from state...", id.BlobName, id.ContainerName, id.AccountName) + if response.WasNotFound(props.HttpResponse.Response) { + log.Printf("[INFO] Blob %q was not found in Container %q / Account %q - assuming removed & removing from state...", id.BlobName, id.ContainerName, id.AccountId.AccountName) d.SetId("") return nil } - return fmt.Errorf("retrieving properties for Blob %q (Container %q / Account %q): %s", id.BlobName, id.ContainerName, id.AccountName, err) + return fmt.Errorf("retrieving properties for Blob %q (Container %q / Account %q): %s", id.BlobName, id.ContainerName, id.AccountId.AccountName, err) } d.Set("name", id.BlobName) d.Set("storage_container_name", id.ContainerName) - d.Set("storage_account_name", id.AccountName) + d.Set("storage_account_name", id.AccountId.AccountName) d.Set("access_tier", string(props.AccessTier)) d.Set("content_type", props.ContentType) @@ -388,17 +413,22 @@ func resourceStorageBlobDelete(d *pluginsdk.ResourceData, meta interface{}) erro ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := blobs.ParseResourceID(d.Id()) + domainSuffix, ok := meta.(*clients.Client).Account.Environment.Storage.DomainSuffix() + if !ok { + return fmt.Errorf("retrieving domain suffix for Storage Accounts") + } + + id, err := blobs.ParseBlobID(d.Id(), *domainSuffix) if err != nil { return fmt.Errorf("parsing %q: %s", d.Id(), err) } - account, err := storageClient.FindAccount(ctx, id.AccountName) + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Blob %q (Container %q): %s", id.AccountName, id.BlobName, id.ContainerName, err) + return fmt.Errorf("retrieving Account %q for Blob %q (Container %q): %s", id.AccountId.AccountName, id.BlobName, id.ContainerName, err) } if account == nil { - return fmt.Errorf("Unable to locate Storage Account %q!", id.AccountName) + return fmt.Errorf("locating Storage Account %q", id.AccountId.AccountName) } blobsClient, err := storageClient.BlobsClient(ctx, *account) @@ -406,12 +436,12 @@ func resourceStorageBlobDelete(d *pluginsdk.ResourceData, meta interface{}) erro return fmt.Errorf("building Blobs Client: %s", err) } - log.Printf("[INFO] Deleting Blob %q from Container %q / Storage Account %q", id.BlobName, id.ContainerName, id.AccountName) + log.Printf("[INFO] Deleting Blob %q from Container %q / Storage Account %q", id.BlobName, id.ContainerName, id.AccountId.AccountName) input := blobs.DeleteInput{ DeleteSnapshots: true, } - if _, err := blobsClient.Delete(ctx, id.AccountName, id.ContainerName, id.BlobName, input); err != nil { - return fmt.Errorf("deleting Blob %q (Container %q / Account %q): %s", id.BlobName, id.ContainerName, id.AccountName, err) + if _, err := blobsClient.Delete(ctx, id.ContainerName, id.BlobName, input); err != nil { + return fmt.Errorf("deleting Blob %q (Container %q / Account %q): %s", id.BlobName, id.ContainerName, id.AccountId.AccountName, err) } return nil diff --git a/internal/services/storage/storage_container_data_source.go b/internal/services/storage/storage_container_data_source.go index dc7a74da8ef0..2f93acbc9041 100644 --- a/internal/services/storage/storage_container_data_source.go +++ b/internal/services/storage/storage_container_data_source.go @@ -9,9 +9,10 @@ import ( "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" + "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts" + "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers" ) func dataSourceStorageContainer() *pluginsdk.Resource { @@ -64,6 +65,11 @@ func dataSourceStorageContainerRead(d *pluginsdk.ResourceData, meta interface{}) ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() + domainSuffix, ok := meta.(*clients.Client).Account.Environment.Storage.DomainSuffix() + if !ok { + return fmt.Errorf("retrieving domain suffix for Storage Accounts") + } + containerName := d.Get("name").(string) accountName := d.Get("storage_account_name").(string) @@ -75,15 +81,20 @@ func dataSourceStorageContainerRead(d *pluginsdk.ResourceData, meta interface{}) return fmt.Errorf("Unable to locate Account %q for Storage Container %q", accountName, containerName) } + accountId, err := accounts.ParseAccountID(account.ID, *domainSuffix) + if err != nil { + return fmt.Errorf("parsing account ID %s: %+v", account.ID, err) + } + client, err := storageClient.ContainersClient(ctx, *account) if err != nil { return fmt.Errorf("building Containers Client for Storage Account %q (Resource Group %q): %s", accountName, account.ResourceGroup, err) } - id := parse.NewStorageContainerDataPlaneId(accountName, storageClient.Environment.StorageEndpointSuffix, containerName).ID() + id := containers.NewContainerID(*accountId, containerName).ID() d.SetId(id) - props, err := client.Get(ctx, account.ResourceGroup, accountName, containerName) + props, err := client.Get(ctx, account.ResourceGroup, containerName) if err != nil { return fmt.Errorf("retrieving Container %q (Account %q / Resource Group %q): %s", containerName, accountName, account.ResourceGroup, err) } diff --git a/internal/services/storage/storage_container_resource.go b/internal/services/storage/storage_container_resource.go index c4dc99de623e..8339160ea7d1 100644 --- a/internal/services/storage/storage_container_resource.go +++ b/internal/services/storage/storage_container_resource.go @@ -12,11 +12,11 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/helpers/tf" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/migration" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" "github.com/hashicorp/terraform-provider-azurerm/internal/timeouts" + "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts" "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers" ) @@ -27,10 +27,10 @@ func resourceStorageContainer() *pluginsdk.Resource { Delete: resourceStorageContainerDelete, Update: resourceStorageContainerUpdate, - Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { - _, err := parse.StorageContainerDataPlaneID(id) - return err - }), + // Importer: pluginsdk.ImporterValidatingResourceId(func(id string) error { + // _, err := parse.StorageContainerDataPlaneID(id) + // return err + // }), SchemaVersion: 1, StateUpgraders: pluginsdk.StateUpgrades(map[int]pluginsdk.StateUpgrade{ @@ -96,6 +96,11 @@ func resourceStorageContainerCreate(d *pluginsdk.ResourceData, meta interface{}) ctx, cancel := timeouts.ForCreate(meta.(*clients.Client).StopContext, d) defer cancel() + domainSuffix, ok := meta.(*clients.Client).Account.Environment.Storage.DomainSuffix() + if !ok { + return fmt.Errorf("retrieving domain suffix for Storage Accounts") + } + containerName := d.Get("name").(string) accountName := d.Get("storage_account_name").(string) accessLevelRaw := d.Get("container_access_type").(string) @@ -117,8 +122,13 @@ func resourceStorageContainerCreate(d *pluginsdk.ResourceData, meta interface{}) return fmt.Errorf("building storage client: %+v", err) } - id := parse.NewStorageContainerDataPlaneId(accountName, storageClient.Environment.StorageEndpointSuffix, containerName).ID() - exists, err := client.Exists(ctx, account.ResourceGroup, accountName, containerName) + accountId, err := accounts.ParseAccountID(account.ID, *domainSuffix) + if err != nil { + return fmt.Errorf("parsing account ID %s: %+v", account.ID, err) + } + + id := containers.NewContainerID(*accountId, containerName).ID() + exists, err := client.Exists(ctx, account.ResourceGroup, containerName) if err != nil { return err } @@ -132,7 +142,7 @@ func resourceStorageContainerCreate(d *pluginsdk.ResourceData, meta interface{}) MetaData: metaData, } - if err := client.Create(ctx, account.ResourceGroup, accountName, containerName, input); err != nil { + if err := client.Create(ctx, account.ResourceGroup, containerName, input); err != nil { return fmt.Errorf("failed creating container: %+v", err) } @@ -145,45 +155,50 @@ func resourceStorageContainerUpdate(d *pluginsdk.ResourceData, meta interface{}) ctx, cancel := timeouts.ForUpdate(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.StorageContainerDataPlaneID(d.Id()) + domainSuffix, ok := meta.(*clients.Client).Account.Environment.Storage.DomainSuffix() + if !ok { + return fmt.Errorf("retrieving domain suffix for Storage Accounts") + } + + id, err := containers.ParseContainerID(d.Id(), *domainSuffix) if err != nil { return err } - account, err := storageClient.FindAccount(ctx, id.AccountName) + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Container %q: %s", id.AccountName, id.Name, err) + return fmt.Errorf("retrieving Account %q for Container %q: %s", id.AccountId.AccountName, id.ContainerName, err) } if account == nil { - return fmt.Errorf("Unable to locate Storage Account %q!", id.AccountName) + return fmt.Errorf("Unable to locate Storage Account %q!", id.AccountId.AccountName) } client, err := storageClient.ContainersClient(ctx, *account) if err != nil { - return fmt.Errorf("building Containers Client for Storage Account %q (Resource Group %q): %s", id.AccountName, account.ResourceGroup, err) + return fmt.Errorf("building Containers Client for Storage Account %q (Resource Group %q): %s", id.AccountId.AccountName, account.ResourceGroup, err) } if d.HasChange("container_access_type") { - log.Printf("[DEBUG] Updating the Access Control for Container %q (Storage Account %q / Resource Group %q)..", id.Name, id.AccountName, account.ResourceGroup) + log.Printf("[DEBUG] Updating the Access Control for Container %q (Storage Account %q / Resource Group %q)..", id.ContainerName, id.AccountId.AccountName, account.ResourceGroup) accessLevelRaw := d.Get("container_access_type").(string) accessLevel := expandStorageContainerAccessLevel(accessLevelRaw) - if err := client.UpdateAccessLevel(ctx, account.ResourceGroup, id.AccountName, id.Name, accessLevel); err != nil { - return fmt.Errorf("updating the Access Control for Container %q (Storage Account %q / Resource Group %q): %s", id.Name, id.AccountName, account.ResourceGroup, err) + if err := client.UpdateAccessLevel(ctx, account.ResourceGroup, id.ContainerName, accessLevel); err != nil { + return fmt.Errorf("updating the Access Control for Container %q (Storage Account %q / Resource Group %q): %s", id.ContainerName, id.AccountId.AccountName, account.ResourceGroup, err) } - log.Printf("[DEBUG] Updated the Access Control for Container %q (Storage Account %q / Resource Group %q)", id.Name, id.AccountName, account.ResourceGroup) + log.Printf("[DEBUG] Updated the Access Control for Container %q (Storage Account %q / Resource Group %q)", id.ContainerName, id.AccountId.AccountName, account.ResourceGroup) } if d.HasChange("metadata") { - log.Printf("[DEBUG] Updating the MetaData for Container %q (Storage Account %q / Resource Group %q)..", id.Name, id.AccountName, account.ResourceGroup) + log.Printf("[DEBUG] Updating the MetaData for Container %q (Storage Account %q / Resource Group %q)..", id.ContainerName, id.AccountId.AccountName, account.ResourceGroup) metaDataRaw := d.Get("metadata").(map[string]interface{}) metaData := ExpandMetaData(metaDataRaw) - if err := client.UpdateMetaData(ctx, account.ResourceGroup, id.AccountName, id.Name, metaData); err != nil { - return fmt.Errorf("updating the MetaData for Container %q (Storage Account %q / Resource Group %q): %s", id.Name, id.AccountName, account.ResourceGroup, err) + if err := client.UpdateMetaData(ctx, account.ResourceGroup, id.ContainerName, metaData); err != nil { + return fmt.Errorf("updating the MetaData for Container %q (Storage Account %q / Resource Group %q): %s", id.ContainerName, id.AccountId.AccountName, account.ResourceGroup, err) } - log.Printf("[DEBUG] Updated the MetaData for Container %q (Storage Account %q / Resource Group %q)", id.Name, id.AccountName, account.ResourceGroup) + log.Printf("[DEBUG] Updated the MetaData for Container %q (Storage Account %q / Resource Group %q)", id.ContainerName, id.AccountId.AccountName, account.ResourceGroup) } return resourceStorageContainerRead(d, meta) @@ -195,37 +210,42 @@ func resourceStorageContainerRead(d *pluginsdk.ResourceData, meta interface{}) e ctx, cancel := timeouts.ForRead(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.StorageContainerDataPlaneID(d.Id()) + domainSuffix, ok := meta.(*clients.Client).Account.Environment.Storage.DomainSuffix() + if !ok { + return fmt.Errorf("retrieving domain suffix for Storage Accounts") + } + + id, err := containers.ParseContainerID(d.Id(), *domainSuffix) if err != nil { return err } - account, err := storageClient.FindAccount(ctx, id.AccountName) + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Container %q: %s", id.AccountName, id.Name, err) + return fmt.Errorf("retrieving Account %q for Container %q: %s", id.AccountId.AccountName, id.ContainerName, err) } if account == nil { - log.Printf("[DEBUG] Unable to locate Account %q for Storage Container %q - assuming removed & removing from state", id.AccountName, id.Name) + log.Printf("[DEBUG] Unable to locate Account %q for Storage Container %q - assuming removed & removing from state", id.AccountId.AccountName, id.ContainerName) d.SetId("") return nil } client, err := storageClient.ContainersClient(ctx, *account) if err != nil { - return fmt.Errorf("building Containers Client for Storage Account %q (Resource Group %q): %s", id.AccountName, account.ResourceGroup, err) + return fmt.Errorf("building Containers Client for Storage Account %q (Resource Group %q): %s", id.AccountId.AccountName, account.ResourceGroup, err) } - props, err := client.Get(ctx, account.ResourceGroup, id.AccountName, id.Name) + props, err := client.Get(ctx, account.ResourceGroup, id.ContainerName) if err != nil { - return fmt.Errorf("retrieving Container %q (Account %q / Resource Group %q): %s", id.Name, id.AccountName, account.ResourceGroup, err) + return fmt.Errorf("retrieving Container %q (Account %q / Resource Group %q): %s", id.ContainerName, id.AccountId.AccountName, account.ResourceGroup, err) } if props == nil { - log.Printf("[DEBUG] Container %q was not found in Account %q / Resource Group %q - assuming removed & removing from state", id.Name, id.AccountName, account.ResourceGroup) + log.Printf("[DEBUG] Container %q was not found in Account %q / Resource Group %q - assuming removed & removing from state", id.ContainerName, id.AccountId.AccountName, account.ResourceGroup) d.SetId("") return nil } - d.Set("name", id.Name) - d.Set("storage_account_name", id.AccountName) + d.Set("name", id.ContainerName) + d.Set("storage_account_name", id.AccountId.AccountName) d.Set("container_access_type", flattenStorageContainerAccessLevel(props.AccessLevel)) @@ -236,7 +256,7 @@ func resourceStorageContainerRead(d *pluginsdk.ResourceData, meta interface{}) e d.Set("has_immutability_policy", props.HasImmutabilityPolicy) d.Set("has_legal_hold", props.HasLegalHold) - resourceManagerId := commonids.NewStorageContainerID(subscriptionId, account.ResourceGroup, id.AccountName, id.Name) + resourceManagerId := commonids.NewStorageContainerID(subscriptionId, account.ResourceGroup, id.AccountId.AccountName, id.ContainerName) d.Set("resource_manager_id", resourceManagerId.ID()) return nil @@ -247,25 +267,30 @@ func resourceStorageContainerDelete(d *pluginsdk.ResourceData, meta interface{}) ctx, cancel := timeouts.ForDelete(meta.(*clients.Client).StopContext, d) defer cancel() - id, err := parse.StorageContainerDataPlaneID(d.Id()) + domainSuffix, ok := meta.(*clients.Client).Account.Environment.Storage.DomainSuffix() + if !ok { + return fmt.Errorf("retrieving domain suffix for Storage Accounts") + } + + id, err := containers.ParseContainerID(d.Id(), *domainSuffix) if err != nil { return err } - account, err := storageClient.FindAccount(ctx, id.AccountName) + account, err := storageClient.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return fmt.Errorf("retrieving Account %q for Container %q: %s", id.AccountName, id.Name, err) + return fmt.Errorf("retrieving Account %q for Container %q: %s", id.AccountId.AccountName, id.ContainerName, err) } if account == nil { - return fmt.Errorf("Unable to locate Storage Account %q!", id.AccountName) + return fmt.Errorf("Unable to locate Storage Account %q!", id.AccountId.AccountName) } client, err := storageClient.ContainersClient(ctx, *account) if err != nil { - return fmt.Errorf("building Containers Client for Storage Account %q (Resource Group %q): %s", id.AccountName, account.ResourceGroup, err) + return fmt.Errorf("building Containers Client for Storage Account %q (Resource Group %q): %s", id.AccountId.AccountName, account.ResourceGroup, err) } - if err := client.Delete(ctx, account.ResourceGroup, id.AccountName, id.Name); err != nil { - return fmt.Errorf("deleting Container %q (Storage Account %q / Resource Group %q): %s", id.Name, id.AccountName, account.ResourceGroup, err) + if err := client.Delete(ctx, account.ResourceGroup, id.ContainerName); err != nil { + return fmt.Errorf("deleting Container %q (Storage Account %q / Resource Group %q): %s", id.ContainerName, id.AccountId.AccountName, account.ResourceGroup, err) } return nil diff --git a/internal/services/storage/storage_container_resource_test.go b/internal/services/storage/storage_container_resource_test.go index cf0a8c0ae07b..1ddd0491b177 100644 --- a/internal/services/storage/storage_container_resource_test.go +++ b/internal/services/storage/storage_container_resource_test.go @@ -12,10 +12,10 @@ import ( "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance" "github.com/hashicorp/terraform-provider-azurerm/internal/acceptance/check" "github.com/hashicorp/terraform-provider-azurerm/internal/clients" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/validate" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/utils" + "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers" ) type StorageContainerResource struct{} @@ -187,47 +187,59 @@ func TestAccStorageContainer_web(t *testing.T) { } func (r StorageContainerResource) Exists(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.StorageContainerDataPlaneID(state.ID) + domainSuffix, ok := client.Account.Environment.Storage.DomainSuffix() + if !ok { + return nil, fmt.Errorf("retrieving domain suffix for Storage Accounts") + } + + id, err := containers.ParseContainerID(state.ID, *domainSuffix) if err != nil { return nil, err } - account, err := client.Storage.FindAccount(ctx, id.AccountName) + + account, err := client.Storage.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return nil, fmt.Errorf("retrieving Account %q for Container %q: %+v", id.AccountName, id.Name, err) + return nil, fmt.Errorf("retrieving Account %q for Container %q: %+v", id.AccountId.AccountName, id.ContainerName, err) } if account == nil { - return nil, fmt.Errorf("unable to locate Storage Account %q", id.AccountName) + return nil, fmt.Errorf("unable to locate Storage Account %q", id.AccountId.AccountName) } containersClient, err := client.Storage.ContainersClient(ctx, *account) if err != nil { return nil, fmt.Errorf("building Containers Client: %+v", err) } - prop, err := containersClient.Get(ctx, account.ResourceGroup, id.AccountName, id.Name) + prop, err := containersClient.Get(ctx, account.ResourceGroup, id.ContainerName) if err != nil { - return nil, fmt.Errorf("retrieving Container %q (Account %q / Resource Group %q): %+v", id.Name, id.AccountName, account.ResourceGroup, err) + return nil, fmt.Errorf("retrieving Container %q (Account %q / Resource Group %q): %+v", id.ContainerName, id.AccountId.AccountName, account.ResourceGroup, err) } return utils.Bool(prop != nil), nil } func (r StorageContainerResource) Destroy(ctx context.Context, client *clients.Client, state *pluginsdk.InstanceState) (*bool, error) { - id, err := parse.StorageContainerDataPlaneID(state.ID) + domainSuffix, ok := client.Account.Environment.Storage.DomainSuffix() + if !ok { + return nil, fmt.Errorf("retrieving domain suffix for Storage Accounts") + } + + id, err := containers.ParseContainerID(state.ID, *domainSuffix) if err != nil { return nil, err } - account, err := client.Storage.FindAccount(ctx, id.AccountName) + + account, err := client.Storage.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return nil, fmt.Errorf("retrieving Account %q for Container %q: %+v", id.AccountName, id.Name, err) + return nil, fmt.Errorf("retrieving Account %q for Container %q: %+v", id.AccountId.AccountName, id.ContainerName, err) } if account == nil { - return nil, fmt.Errorf("unable to locate Storage Account %q", id.AccountName) + return nil, fmt.Errorf("unable to locate Storage Account %q", id.AccountId.AccountName) } containersClient, err := client.Storage.ContainersClient(ctx, *account) if err != nil { return nil, fmt.Errorf("building Containers Client: %+v", err) } - if err := containersClient.Delete(ctx, account.ResourceGroup, id.AccountName, id.Name); err != nil { - return nil, fmt.Errorf("deleting Container %q (Account %q / Resource Group %q): %+v", id.Name, id.AccountName, account.ResourceGroup, err) + if err := containersClient.Delete(ctx, account.ResourceGroup, id.ContainerName); err != nil { + return nil, fmt.Errorf("deleting Container %q (Account %q / Resource Group %q): %+v", id.ContainerName, id.AccountId.AccountName, account.ResourceGroup, err) } return utils.Bool(true), nil } diff --git a/internal/services/storage/storage_containers_data_source.go b/internal/services/storage/storage_containers_data_source.go index 40c5ec7ff49a..32688d6d3fff 100644 --- a/internal/services/storage/storage_containers_data_source.go +++ b/internal/services/storage/storage_containers_data_source.go @@ -12,9 +12,10 @@ import ( "github.com/hashicorp/go-azure-helpers/resourcemanager/commonids" "github.com/hashicorp/go-azure-sdk/resource-manager/storage/2023-01-01/blobcontainers" "github.com/hashicorp/terraform-provider-azurerm/internal/sdk" - "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/parse" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/pluginsdk" "github.com/hashicorp/terraform-provider-azurerm/internal/tf/validation" + "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts" + "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers" ) type storageContainersDataSource struct{} @@ -88,6 +89,11 @@ func (r storageContainersDataSource) Read() sdk.ResourceFunc { Func: func(ctx context.Context, metadata sdk.ResourceMetaData) error { client := metadata.Client.Storage.ResourceManager.BlobContainers + domainSuffix, ok := metadata.Client.Account.Environment.Storage.DomainSuffix() + if !ok { + return fmt.Errorf("retrieving domain suffix for Storage Accounts") + } + var plan storageContainersDataSourceModel if err := metadata.Decode(&plan); err != nil { return fmt.Errorf("decoding %+v", err) @@ -98,12 +104,17 @@ func (r storageContainersDataSource) Read() sdk.ResourceFunc { return err } + accountId, err := accounts.ParseAccountID(plan.StorageAccountId, *domainSuffix) + if err != nil { + return fmt.Errorf("parsing account ID %s: %+v", accountId.ID, err) + } + resp, err := client.ListCompleteMatchingPredicate(ctx, *id, blobcontainers.DefaultListOperationOptions(), blobcontainers.ListContainerItemOperationPredicate{}) if err != nil { return fmt.Errorf("retrieving %s: %+v", id, err) } - plan.Containers = flattenStorageContainersContainers(resp.Items, id.StorageAccountName, metadata.Client.Storage.Environment.StorageEndpointSuffix, plan.NamePrefix) + plan.Containers = flattenStorageContainersContainers(resp.Items, *accountId, plan.NamePrefix) if err := metadata.Encode(&plan); err != nil { return fmt.Errorf("encoding %s: %+v", id, err) @@ -116,7 +127,7 @@ func (r storageContainersDataSource) Read() sdk.ResourceFunc { } } -func flattenStorageContainersContainers(l []blobcontainers.ListContainerItem, accountName, endpointSuffix, prefix string) []containerModel { +func flattenStorageContainersContainers(l []blobcontainers.ListContainerItem, accountId accounts.AccountId, prefix string) []containerModel { var output []containerModel for _, item := range l { var name string @@ -136,7 +147,7 @@ func flattenStorageContainersContainers(l []blobcontainers.ListContainerItem, ac output = append(output, containerModel{ Name: name, ResourceManagerId: mgmtId, - DataPlaneId: parse.NewStorageContainerDataPlaneId(accountName, endpointSuffix, name).ID(), + DataPlaneId: containers.NewContainerID(accountId, name).ID(), }) } diff --git a/internal/services/storage/storage_data_lake_gen2_filesystem_resource.go b/internal/services/storage/storage_data_lake_gen2_filesystem_resource.go index 4998f22fc693..83215c0f9239 100644 --- a/internal/services/storage/storage_data_lake_gen2_filesystem_resource.go +++ b/internal/services/storage/storage_data_lake_gen2_filesystem_resource.go @@ -31,22 +31,23 @@ func resourceStorageDataLakeGen2FileSystem() *pluginsdk.Resource { Delete: resourceStorageDataLakeGen2FileSystemDelete, Importer: pluginsdk.ImporterValidatingResourceIdThen(func(id string) error { - _, err := filesystems.ParseResourceID(id) + _, err := filesystems.ParseFileSystemID(id) return err }, func(ctx context.Context, d *pluginsdk.ResourceData, meta interface{}) ([]*pluginsdk.ResourceData, error) { storageClients := meta.(*clients.Client).Storage - id, err := filesystems.ParseResourceID(d.Id()) + domainSuffix := storageClients.Environment.StorageEndpointSuffix + id, err := filesystems.ParseFileSystemID(d.Id(), domainSuffix) if err != nil { return []*pluginsdk.ResourceData{d}, fmt.Errorf("parsing ID %q for import of Data Lake Gen2 File System: %v", d.Id(), err) } // we then need to look up the Storage Account ID - account, err := storageClients.FindAccount(ctx, id.AccountName) + account, err := storageClients.FindAccount(ctx, id.AccountId.AccountName) if err != nil { - return []*pluginsdk.ResourceData{d}, fmt.Errorf("retrieving Account %q for Data Lake Gen2 File System %q: %s", id.AccountName, id.DirectoryName, err) + return []*pluginsdk.ResourceData{d}, fmt.Errorf("retrieving Account %q for Data Lake Gen2 File System %q: %s", id.AccountId.AccountName, id.FileSystemName, err) } if account == nil { - return []*pluginsdk.ResourceData{d}, fmt.Errorf("Unable to locate Storage Account %q!", id.AccountName) + return []*pluginsdk.ResourceData{d}, fmt.Errorf("Unable to locate Storage Account %q!", id.AccountId.AccountName) } d.Set("storage_account_id", account.ID) diff --git a/internal/services/storage/validate/storage_container.go b/internal/services/storage/validate/storage_container.go index 365e785a3495..bb378de43f13 100644 --- a/internal/services/storage/validate/storage_container.go +++ b/internal/services/storage/validate/storage_container.go @@ -6,8 +6,6 @@ package validate import ( "fmt" "regexp" - - "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/parse" ) func StorageContainerName(v interface{}, k string) (warnings []string, errors []error) { @@ -28,17 +26,3 @@ func StorageContainerName(v interface{}, k string) (warnings []string, errors [] } return warnings, errors } - -func StorageContainerDataPlaneID(input interface{}, key string) (warnings []string, errors []error) { - v, ok := input.(string) - if !ok { - errors = append(errors, fmt.Errorf("expected %q to be a string", key)) - return - } - - if _, err := parse.StorageContainerDataPlaneID(v); err != nil { - errors = append(errors, err) - } - - return -} diff --git a/internal/services/storage/validate/storage_share_name.go b/internal/services/storage/validate/storage_share_name.go index b79e4ee93606..d9a2a03dcf44 100644 --- a/internal/services/storage/validate/storage_share_name.go +++ b/internal/services/storage/validate/storage_share_name.go @@ -6,8 +6,6 @@ package validate import ( "fmt" "regexp" - - "github.com/hashicorp/terraform-provider-azurerm/internal/services/storage/parse" ) func StorageShareName(v interface{}, k string) (warnings []string, errors []error) { @@ -33,18 +31,3 @@ func StorageShareName(v interface{}, k string) (warnings []string, errors []erro } return warnings, errors } - -func StorageShareID(i interface{}, k string) (warnings []string, errors []error) { - v, ok := i.(string) - if !ok { - errors = append(errors, fmt.Errorf("expected type of %q to be string", k)) - return - } - - if _, err := parse.StorageShareDataPlaneID(v); err != nil { - errors = append(errors, fmt.Errorf("Can not parse %q as a resource id: %v", k, err)) - return - } - - return warnings, errors -} diff --git a/vendor/github.com/google/uuid/CHANGELOG.md b/vendor/github.com/google/uuid/CHANGELOG.md index 2bd78667afbb..7ed347d3ad73 100644 --- a/vendor/github.com/google/uuid/CHANGELOG.md +++ b/vendor/github.com/google/uuid/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## [1.4.0](https://github.com/google/uuid/compare/v1.3.1...v1.4.0) (2023-10-26) + + +### Features + +* UUIDs slice type with Strings() convenience method ([#133](https://github.com/google/uuid/issues/133)) ([cd5fbbd](https://github.com/google/uuid/commit/cd5fbbdd02f3e3467ac18940e07e062be1f864b4)) + +### Fixes + +* Clarify that Parse's job is to parse but not necessarily validate strings. (Documents current behavior) + ## [1.3.1](https://github.com/google/uuid/compare/v1.3.0...v1.3.1) (2023-08-18) diff --git a/vendor/github.com/google/uuid/CONTRIBUTING.md b/vendor/github.com/google/uuid/CONTRIBUTING.md index 5566888726d9..a502fdc515ac 100644 --- a/vendor/github.com/google/uuid/CONTRIBUTING.md +++ b/vendor/github.com/google/uuid/CONTRIBUTING.md @@ -11,7 +11,7 @@ please explain why in the pull request description. ### Releasing -Commits that would precipitate a SemVer change, as desrcibed in the Conventional +Commits that would precipitate a SemVer change, as described in the Conventional Commits Specification, will trigger [`release-please`](https://github.com/google-github-actions/release-please-action) to create a release candidate pull request. Once submitted, `release-please` will create a release. diff --git a/vendor/github.com/google/uuid/uuid.go b/vendor/github.com/google/uuid/uuid.go index a56138cc4bd0..dc75f7d99091 100644 --- a/vendor/github.com/google/uuid/uuid.go +++ b/vendor/github.com/google/uuid/uuid.go @@ -56,11 +56,15 @@ func IsInvalidLengthError(err error) bool { return ok } -// Parse decodes s into a UUID or returns an error. Both the standard UUID -// forms of xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and -// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx are decoded as well as the -// Microsoft encoding {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} and the raw hex -// encoding: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx. +// Parse decodes s into a UUID or returns an error if it cannot be parsed. Both +// the standard UUID forms defined in RFC 4122 +// (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and +// urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx) are decoded. In addition, +// Parse accepts non-standard strings such as the raw hex encoding +// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx and 38 byte "Microsoft style" encodings, +// e.g. {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}. Only the middle 36 bytes are +// examined in the latter case. Parse should not be used to validate strings as +// it parses non-standard encodings as indicated above. func Parse(s string) (UUID, error) { var uuid UUID switch len(s) { @@ -294,3 +298,15 @@ func DisableRandPool() { poolMu.Lock() poolPos = randPoolSize } + +// UUIDs is a slice of UUID types. +type UUIDs []UUID + +// Strings returns a string slice containing the string form of each UUID in uuids. +func (uuids UUIDs) Strings() []string { + var uuidStrs = make([]string, len(uuids)) + for i, uuid := range uuids { + uuidStrs[i] = uuid.String() + } + return uuidStrs +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/client.go b/vendor/github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/client.go new file mode 100644 index 000000000000..675cccfd3140 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/client.go @@ -0,0 +1,35 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + +package dataplane + +import ( + "context" + + "github.com/hashicorp/go-azure-sdk/sdk/client" +) + +type Client struct { + Client *client.Client + + // ApiVersion specifies the version of the API being used, which (by design) will be consistent across a client + // as we intentionally split out multiple API Versions into different clients, rather than using composite API + // Versions/packages which can cause confusion about which version is being used. + ApiVersion string +} + +func NewDataPlaneClient(baseUri string, serviceName, apiVersion string) *Client { + client := &Client{ + Client: client.NewClient(baseUri, serviceName, apiVersion), + ApiVersion: apiVersion, + } + return client +} + +func (c *Client) Execute(ctx context.Context, req *client.Request) (*client.Response, error) { + return c.Client.Execute(ctx, req) +} + +func (c *Client) ExecutePaged(ctx context.Context, req *client.Request) (*client.Response, error) { + return c.Client.ExecutePaged(ctx, req) +} diff --git a/vendor/github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/storage/client.go b/vendor/github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/storage/client.go new file mode 100644 index 000000000000..47f74a981650 --- /dev/null +++ b/vendor/github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/storage/client.go @@ -0,0 +1,84 @@ +// Copyright (c) HashiCorp, Inc. +// SPDX-License-Identifier: MPL-2.0 + +package storage + +import ( + "context" + "fmt" + "net/url" + + "github.com/hashicorp/go-azure-sdk/sdk/auth" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/client/dataplane" +) + +var storageDefaultRetryFunctions = []client.RequestRetryFunc{ + // TODO: stuff n tings +} + +type BaseClient struct { + Client *dataplane.Client +} + +func NewBaseClient(baseUri string, componentName, apiVersion string) (*BaseClient, error) { + // NOTE: both the domain name _and_ the domain format can change entirely depending on the type of storage account being used + // when provisioned in an edge zone, and when AzureDNSZone is used, as such we require the baseUri is provided here + return &BaseClient{ + Client: dataplane.NewDataPlaneClient(baseUri, fmt.Sprintf("storage/%s", componentName), apiVersion), + }, nil +} + +func (c *BaseClient) NewRequest(ctx context.Context, input client.RequestOptions) (*client.Request, error) { + // TODO move these validations to base client method + if _, ok := ctx.Deadline(); !ok { + return nil, fmt.Errorf("the context used must have a deadline attached for polling purposes, but got no deadline") + } + if err := input.Validate(); err != nil { + return nil, fmt.Errorf("pre-validating request payload: %+v", err) + } + + req, err := c.Client.Client.NewRequest(ctx, input) + if err != nil { + return nil, fmt.Errorf("building %s request: %+v", input.HttpMethod, err) + } + + req.Client = c + req.Header.Add("x-ms-version", c.Client.ApiVersion) + + query := url.Values{} + if input.OptionsObject != nil { + if h := input.OptionsObject.ToHeaders(); h != nil { + for k, v := range h.Headers() { + req.Header[k] = v + } + } + + if q := input.OptionsObject.ToQuery(); q != nil { + query = q.Values() + } + + if o := input.OptionsObject.ToOData(); o != nil { + req.Header = o.AppendHeaders(req.Header) + query = o.AppendValues(query) + } + } + + req.URL.RawQuery = query.Encode() + req.RetryFunc = client.RequestRetryAny(storageDefaultRetryFunctions...) + req.ValidStatusCodes = input.ExpectedStatusCodes + + return req, nil +} + +func (c *BaseClient) Execute(ctx context.Context, req *client.Request) (*client.Response, error) { + return c.Client.Execute(ctx, req) +} + +func (c *BaseClient) ExecutePaged(ctx context.Context, req *client.Request) (*client.Response, error) { + return c.Client.ExecutePaged(ctx, req) +} + +func (c *BaseClient) WithAuthorizer(auth auth.Authorizer) { + c.Client.Client.Authorizer = auth +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/README.md b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/README.md index 5fa24a74e9bb..fd69cf79e810 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/README.md +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/README.md @@ -16,7 +16,6 @@ import ( "fmt" "time" - "github.com/Azure/go-autorest/autorest" "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts" ) diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/client.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/client.go index 0162ebbb0c33..1a3c314feecb 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/client.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/client.go @@ -1,25 +1,22 @@ package accounts import ( - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" + "fmt" + + "github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/storage" ) // Client is the base client for Blob Storage Blobs. type Client struct { - autorest.Client - BaseURI string -} - -// New creates an instance of the Client client. -func New() Client { - return NewWithEnvironment(azure.PublicCloud) + Client *storage.BaseClient } -// NewWithBaseURI creates an instance of the Client client. -func NewWithEnvironment(environment azure.Environment) Client { - return Client{ - Client: autorest.NewClientWithUserAgent(UserAgent()), - BaseURI: environment.StorageEndpointSuffix, +func NewWithBaseUri(baseUri string) (*Client, error) { + baseClient, err := storage.NewBaseClient(baseUri, componentName, apiVersion) + if err != nil { + return nil, fmt.Errorf("building base client: %+v", err) } + return &Client{ + Client: baseClient, + }, nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/get_service_properties.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/get_service_properties.go index e622fff3ba46..01ea987863cc 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/get_service_properties.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/get_service_properties.go @@ -2,82 +2,47 @@ package accounts import ( "context" + "fmt" "net/http" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" ) type GetServicePropertiesResult struct { - autorest.Response - - ContentType string - StorageServiceProperties *StorageServiceProperties -} - -// GetServicePropertiesPreparer prepares the GetServiceProperties request. -func (client Client) GetServicePropertiesPreparer(ctx context.Context, accountName string) (*http.Request, error) { - queryParameters := map[string]interface{}{ - "restype": "service", - "comp": "properties", - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithHeaders(headers), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -func (client Client) GetServicePropertiesSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + HttpResponse *client.Response + Model *StorageServiceProperties } -func (client Client) GetServicePropertiesResponder(resp *http.Response) (result GetServicePropertiesResult, err error) { - if resp != nil && resp.Header != nil { - result.ContentType = resp.Header.Get("Content-Type") - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingXML(&result.StorageServiceProperties), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -func (client Client) GetServiceProperties(ctx context.Context, accountName string) (result GetServicePropertiesResult, err error) { +func (c Client) GetServiceProperties(ctx context.Context, accountName string) (resp GetServicePropertiesResult, err error) { if accountName == "" { - return result, validation.NewError("accounts.Client", "GetServiceProperties", "`accountName` cannot be an empty string.") + return resp, fmt.Errorf("`accountName` cannot be an empty string") } - req, err := client.GetServicePropertiesPreparer(ctx, accountName) + opts := client.RequestOptions{ + ContentType: "text/xml", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: servicePropertiesOptions{}, + Path: "/", + } + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - err = autorest.NewErrorWithError(err, "accounts.Client", "GetServiceProperties", nil, "Failure preparing request") + err = fmt.Errorf("building request: %+v", err) return } - - resp, err := client.GetServicePropertiesSender(req) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "accounts.Client", "GetServiceProperties", resp, "Failure sending request") + err = fmt.Errorf("executing request: %+v", err) return } - result, err = client.GetServicePropertiesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "accounts.Client", "GetServiceProperties", resp, "Failure responding to request") - return + if resp.HttpResponse != nil { + if err = resp.HttpResponse.Unmarshal(&resp.Model); err != nil { + err = fmt.Errorf("unmarshaling response: %+v", err) + return + } } return diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/models.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/models.go index 3a2891439bee..c36d45ecb8c5 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/models.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/models.go @@ -1,11 +1,5 @@ package accounts -import "github.com/Azure/go-autorest/autorest" - -type SetServicePropertiesResult struct { - autorest.Response -} - type StorageServiceProperties struct { // Cors - Specifies CORS rules for the Blob service. You can include up to five CorsRule elements in the request. If no CorsRule elements are included in the request body, all CORS rules will be deleted, and CORS will be disabled for the Blob service. Cors *CorsRules `xml:"Cors,omitempty"` diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/resource_id.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/resource_id.go new file mode 100644 index 000000000000..e6c6303f9f79 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/resource_id.go @@ -0,0 +1,155 @@ +package accounts + +import ( + "fmt" + "net/url" + "strings" + + "github.com/hashicorp/go-azure-helpers/lang/pointer" + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" +) + +type SubDomainType string + +const ( + BlobSubDomainType SubDomainType = "blob" + DataLakeStoreSubDomainType SubDomainType = "dfs" + FileSubDomainType SubDomainType = "file" + QueueSubDomainType SubDomainType = "queue" + TableSubDomainType SubDomainType = "table" +) + +func PossibleValuesForSubDomainType() []SubDomainType { + return []SubDomainType{ + BlobSubDomainType, + DataLakeStoreSubDomainType, + FileSubDomainType, + QueueSubDomainType, + TableSubDomainType, + } +} + +// TODO: update this to implement `resourceids.ResourceId` once +// https://github.com/hashicorp/go-azure-helpers/issues/187 is fixed +var _ resourceids.Id = AccountId{} + +type AccountId struct { + AccountName string + ZoneName *string + SubDomainType SubDomainType + DomainSuffix string + IsEdgeZone bool +} + +func (a AccountId) ID() string { + components := []string{ + a.AccountName, + } + if a.IsEdgeZone { + // Storage Accounts hosted in an Edge Zone + // `{accountname}.{component}.{edgezone}.edgestorage.azure.net` + components = append(components, string(a.SubDomainType)) + if a.ZoneName != nil { + components = append(components, *a.ZoneName) + } + } else { + // Storage Accounts using a DNS Zone + // `{accountname}.{dnszone}.{component}.storage.azure.net` + // or a Regular Storage Account + // `{accountname}.{component}.core.windows.net` + if a.ZoneName != nil { + components = append(components, *a.ZoneName) + } + components = append(components, string(a.SubDomainType)) + } + components = append(components, a.DomainSuffix) + return fmt.Sprintf("https://%s", strings.Join(components, ".")) +} + +func (a AccountId) String() string { + components := []string{ + fmt.Sprintf("IsEdgeZone %t", a.IsEdgeZone), + fmt.Sprintf("ZoneName %q", pointer.From(a.ZoneName)), + fmt.Sprintf("Subdomain Type %q", string(a.SubDomainType)), + fmt.Sprintf("DomainSuffix %q", a.DomainSuffix), + } + return fmt.Sprintf("Account %q (%s)", a.AccountName, strings.Join(components, " / ")) +} + +func ParseAccountID(input, domainSuffix string) (*AccountId, error) { + uri, err := url.Parse(input) + if err != nil { + return nil, fmt.Errorf("parsing %q as a URL: %s", input, err) + } + + if !strings.HasSuffix(uri.Host, domainSuffix) { + return nil, fmt.Errorf("expected the account %q to use a domain suffix of %q", uri.Host, domainSuffix) + } + + // There's 3 different types of Storage Account ID: + // 1. Regular ol' Storage Accounts + // `{name}.{component}.core.windows.net` (e.g. `example1.blob.core.windows.net`) + // 2. Storage Accounts using a DNS Zone + // `{accountname}.{dnszone}.{component}.storage.azure.net` + // 3. Storage Accounts hosted in an Edge Zone + // `{accountname}.{component}.{edgezone}.edgestorage.azure.net` + // since both `dnszone` and `edgezone` are the only two identifiers, we need to check if `domainSuffix` includes `edge` + // to know how to treat these + + hostName := strings.TrimSuffix(uri.Host, fmt.Sprintf(".%s", domainSuffix)) + components := strings.Split(hostName, ".") + accountId := AccountId{ + DomainSuffix: domainSuffix, + IsEdgeZone: strings.Contains(strings.ToLower(domainSuffix), "edge"), + } + + if len(components) == 2 { + // this will be a regular Storage Account (e.g. `example1.blob.core.windows.net`) + accountId.AccountName = components[0] + subDomainType, err := parseSubDomainType(components[1]) + if err != nil { + return nil, err + } + accountId.SubDomainType = *subDomainType + return &accountId, nil + } + + if len(components) == 3 { + // This can either be a Zone'd Storage Account or a Storage Account within an Edge Zone + accountName := "" + subDomainTypeRaw := "" + zone := "" + if accountId.IsEdgeZone { + // `{accountname}.{component}.{edgezone}.edgestorage.azure.net` + accountName = components[0] + subDomainTypeRaw = components[1] + zone = components[2] + } else { + // `{accountname}.{dnszone}.{component}.storage.azure.net` + accountName = components[0] + zone = components[1] + subDomainTypeRaw = components[2] + } + + accountId.AccountName = accountName + subDomainType, err := parseSubDomainType(subDomainTypeRaw) + if err != nil { + return nil, err + } + accountId.SubDomainType = *subDomainType + accountId.ZoneName = pointer.To(zone) + return &accountId, nil + } + + return nil, fmt.Errorf("unknown storage account domain type %q", input) +} + +func parseSubDomainType(input string) (*SubDomainType, error) { + for _, k := range PossibleValuesForSubDomainType() { + if strings.EqualFold(input, string(k)) { + return pointer.To(k), nil + } + } + + return nil, fmt.Errorf("expected the subdomain type to be one of [%+v] but got %q", PossibleValuesForSubDomainType(), input) +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/service_properties_shared.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/service_properties_shared.go new file mode 100644 index 000000000000..3019155f9183 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/service_properties_shared.go @@ -0,0 +1,26 @@ +package accounts + +import ( + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +var _ client.Options = servicePropertiesOptions{} + +type servicePropertiesOptions struct { +} + +func (servicePropertiesOptions) ToHeaders() *client.Headers { + return nil +} + +func (servicePropertiesOptions) ToOData() *odata.Query { + return nil +} + +func (servicePropertiesOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "properties") + out.Append("restype", "service") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/set_service_properties.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/set_service_properties.go index 17b7bcc7e763..173a80f0f7d9 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/set_service_properties.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/set_service_properties.go @@ -2,74 +2,42 @@ package accounts import ( "context" + "fmt" "net/http" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" ) -// SetServicePropertiesSender sends the SetServiceProperties request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SetServicePropertiesSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +type SetServicePropertiesResult struct { + HttpResponse *client.Response } -// SetServicePropertiesPreparer prepares the SetServiceProperties request. -func (client Client) SetServicePropertiesPreparer(ctx context.Context, accountName string, input StorageServiceProperties) (*http.Request, error) { - queryParameters := map[string]interface{}{ - "restype": "service", - "comp": "properties", - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithHeaders(headers), - autorest.WithXML(input), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// SetServicePropertiesResponder handles the response to the SetServiceProperties request. The method always -// closes the http.Response Body. -func (client Client) SetServicePropertiesResponder(resp *http.Response) (result SetServicePropertiesResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusAccepted), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -func (client Client) SetServiceProperties(ctx context.Context, accountName string, input StorageServiceProperties) (result SetServicePropertiesResult, err error) { +func (c Client) SetServiceProperties(ctx context.Context, accountName string, input StorageServiceProperties) (resp SetServicePropertiesResult, err error) { if accountName == "" { - return result, validation.NewError("accounts.Client", "SetServiceProperties", "`accountName` cannot be an empty string.") + return resp, fmt.Errorf("`accountName` cannot be an empty string") } - req, err := client.SetServicePropertiesPreparer(ctx, accountName, input) + opts := client.RequestOptions{ + ContentType: "text/xml", + ExpectedStatusCodes: []int{ + http.StatusAccepted, + }, + HttpMethod: http.MethodPut, + OptionsObject: servicePropertiesOptions{}, + Path: "/", + } + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - err = autorest.NewErrorWithError(err, "accounts.Client", "SetServiceProperties", nil, "Failure preparing request") + err = fmt.Errorf("building request: %+v", err) return } - - resp, err := client.SetServicePropertiesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "accounts.Client", "SetServiceProperties", resp, "Failure sending request") + if err = req.Marshal(&input); err != nil { + err = fmt.Errorf("marshaling request: %+v", err) return } - - result, err = client.SetServicePropertiesResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "accounts.Client", "SetServiceProperties", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/version.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/version.go index 3d6d01147003..d575c4f40957 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/version.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts/version.go @@ -1,14 +1,4 @@ package accounts -import ( - "fmt" - - "github.com/tombuildsstuff/giovanni/version" -) - -// APIVersion is the version of the API used for all Storage API Operations -const APIVersion = "2020-08-04" - -func UserAgent() string { - return fmt.Sprintf("tombuildsstuff/giovanni/%s storage/%s", version.Number, APIVersion) -} +const apiVersion = "2020-08-04" +const componentName = "blob/accounts" diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/README.md b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/README.md index 19218cf9fd85..4afa786462c9 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/README.md +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/README.md @@ -17,7 +17,7 @@ import ( "fmt" "time" - "github.com/Azure/go-autorest/autorest" + "github.com/hashicorp/go-azure-sdk/sdk/auth" "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs" ) @@ -25,18 +25,26 @@ func Example() error { accountName := "storageaccount1" storageAccountKey := "ABC123...." containerName := "mycontainer" + domainSuffix := "core.windows.net" fileName := "example-large-file.iso" - - storageAuth := autorest.NewSharedKeyLiteAuthorizer(accountName, storageAccountKey) - blobClient := blobs.New() - blobClient.Client.Authorizer = storageAuth + + blobClient, err := blobs.NewWithBaseUri(fmt.Sprintf("https://%s.blob.%s", accountName, domainSuffix)) + if err != nil { + return fmt.Errorf("building client for environment: %+v", err) + } + + auth, err := auth.NewSharedKeyAuthorizer(accountName, storageAccountKey, auth.SharedKey) + if err != nil { + return fmt.Errorf("building SharedKey authorizer: %+v", err) + } + blobClient.Client.WithAuthorizer(auth) ctx := context.TODO() copyInput := blobs.CopyInput{ CopySource: "http://releases.ubuntu.com/14.04/ubuntu-14.04.6-desktop-amd64.iso", } refreshInterval := 5 * time.Second - if err := blobClient.CopyAndWait(ctx, accountName, containerName, fileName, copyInput, refreshInterval); err != nil { + if err := blobClient.CopyAndWait(ctx, containerName, fileName, copyInput, refreshInterval); err != nil { return fmt.Errorf("Error copying: %s", err) } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/api.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/api.go index 7e4f6494c2d1..167240825039 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/api.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/api.go @@ -3,43 +3,39 @@ package blobs import ( "context" "os" - "time" - - "github.com/Azure/go-autorest/autorest" ) type StorageBlob interface { - AppendBlock(ctx context.Context, accountName, containerName, blobName string, input AppendBlockInput) (result AppendBlockResult, err error) - Copy(ctx context.Context, accountName, containerName, blobName string, input CopyInput) (result CopyResult, err error) - AbortCopy(ctx context.Context, accountName, containerName, blobName string, input AbortCopyInput) (result autorest.Response, err error) - CopyAndWait(ctx context.Context, accountName, containerName, blobName string, input CopyInput, pollingInterval time.Duration) error - Delete(ctx context.Context, accountName, containerName, blobName string, input DeleteInput) (result autorest.Response, err error) - DeleteSnapshot(ctx context.Context, accountName, containerName, blobName string, input DeleteSnapshotInput) (result autorest.Response, err error) - DeleteSnapshots(ctx context.Context, accountName, containerName, blobName string, input DeleteSnapshotsInput) (result autorest.Response, err error) - Get(ctx context.Context, accountName, containerName, blobName string, input GetInput) (result GetResult, err error) - GetBlockList(ctx context.Context, accountName, containerName, blobName string, input GetBlockListInput) (result GetBlockListResult, err error) - GetPageRanges(ctx context.Context, accountName, containerName, blobName string, input GetPageRangesInput) (result GetPageRangesResult, err error) - IncrementalCopyBlob(ctx context.Context, accountName, containerName, blobName string, input IncrementalCopyBlobInput) (result autorest.Response, err error) - AcquireLease(ctx context.Context, accountName, containerName, blobName string, input AcquireLeaseInput) (result AcquireLeaseResult, err error) - BreakLease(ctx context.Context, accountName, containerName, blobName string, input BreakLeaseInput) (result autorest.Response, err error) - ChangeLease(ctx context.Context, accountName, containerName, blobName string, input ChangeLeaseInput) (result ChangeLeaseResponse, err error) - ReleaseLease(ctx context.Context, accountName, containerName, blobName, leaseID string) (result autorest.Response, err error) - RenewLease(ctx context.Context, accountName, containerName, blobName, leaseID string) (result autorest.Response, err error) - SetMetaData(ctx context.Context, accountName, containerName, blobName string, input SetMetaDataInput) (result autorest.Response, err error) - GetProperties(ctx context.Context, accountName, containerName, blobName string, input GetPropertiesInput) (result GetPropertiesResult, err error) - SetProperties(ctx context.Context, accountName, containerName, blobName string, input SetPropertiesInput) (result SetPropertiesResult, err error) - PutAppendBlob(ctx context.Context, accountName, containerName, blobName string, input PutAppendBlobInput) (result autorest.Response, err error) - PutBlock(ctx context.Context, accountName, containerName, blobName string, input PutBlockInput) (result PutBlockResult, err error) - PutBlockBlob(ctx context.Context, accountName, containerName, blobName string, input PutBlockBlobInput) (result autorest.Response, err error) - PutBlockBlobFromFile(ctx context.Context, accountName, containerName, blobName string, file *os.File, input PutBlockBlobInput) error - PutBlockList(ctx context.Context, accountName, containerName, blobName string, input PutBlockListInput) (result PutBlockListResult, err error) - PutBlockFromURL(ctx context.Context, accountName, containerName, blobName string, input PutBlockFromURLInput) (result PutBlockFromURLResult, err error) - PutPageBlob(ctx context.Context, accountName, containerName, blobName string, input PutPageBlobInput) (result autorest.Response, err error) - PutPageClear(ctx context.Context, accountName, containerName, blobName string, input PutPageClearInput) (result autorest.Response, err error) - PutPageUpdate(ctx context.Context, accountName, containerName, blobName string, input PutPageUpdateInput) (result PutPageUpdateResult, err error) - GetResourceID(accountName, containerName, blobName string) string - SetTier(ctx context.Context, accountName, containerName, blobName string, tier AccessTier) (result autorest.Response, err error) - Snapshot(ctx context.Context, accountName, containerName, blobName string, input SnapshotInput) (result SnapshotResult, err error) - GetSnapshotProperties(ctx context.Context, accountName, containerName, blobName string, input GetSnapshotPropertiesInput) (result GetPropertiesResult, err error) - Undelete(ctx context.Context, accountName, containerName, blobName string) (result autorest.Response, err error) + AppendBlock(ctx context.Context, containerName string, blobName string, input AppendBlockInput) (AppendBlockResponse, error) + Copy(ctx context.Context, containerName string, blobName string, input CopyInput) (CopyResponse, error) + AbortCopy(ctx context.Context, containerName string, blobName string, input AbortCopyInput) (CopyAbortResponse, error) + CopyAndWait(ctx context.Context, containerName string, blobName string, input CopyInput) error + Delete(ctx context.Context, containerName string, blobName string, input DeleteInput) (DeleteResponse, error) + DeleteSnapshot(ctx context.Context, containerName string, blobName string, input DeleteSnapshotInput) (DeleteSnapshotResponse, error) + DeleteSnapshots(ctx context.Context, containerName string, blobName string, input DeleteSnapshotsInput) (DeleteSnapshotsResponse, error) + Get(ctx context.Context, containerName string, blobName string, input GetInput) (GetResponse, error) + GetBlockList(ctx context.Context, containerName string, blobName string, input GetBlockListInput) (GetBlockListResponse, error) + GetPageRanges(ctx context.Context, containerName, blobName string, input GetPageRangesInput) (GetPageRangesResponse, error) + IncrementalCopyBlob(ctx context.Context, containerName string, blobName string, input IncrementalCopyBlobInput) (IncrementalCopyBlob, error) + AcquireLease(ctx context.Context, containerName string, blobName string, input AcquireLeaseInput) (AcquireLeaseResponse, error) + BreakLease(ctx context.Context, containerName string, blobName string, input BreakLeaseInput) (BreakLeaseResponse, error) + ChangeLease(ctx context.Context, containerName string, blobName string, input ChangeLeaseInput) (ChangeLeaseResponse, error) + ReleaseLease(ctx context.Context, containerName string, blobName string, input ReleaseLeaseInput) (ReleaseLeaseResponse, error) + RenewLease(ctx context.Context, containerName string, blobName string, input RenewLeaseInput) (RenewLeaseResponse, error) + SetMetaData(ctx context.Context, containerName string, blobName string, input SetMetaDataInput) (SetMetaDataResponse, error) + GetProperties(ctx context.Context, containerName string, blobName string, input GetPropertiesInput) (GetPropertiesResponse, error) + SetProperties(ctx context.Context, containerName string, blobName string, input SetPropertiesInput) (SetPropertiesResponse, error) + PutAppendBlob(ctx context.Context, containerName string, blobName string, input PutAppendBlobInput) (PutAppendBlobResponse, error) + PutBlock(ctx context.Context, containerName string, blobName string, input PutBlockInput) (PutBlockResponse, error) + PutBlockBlob(ctx context.Context, containerName string, blobName string, input PutBlockBlobInput) (PutBlockBlobResponse, error) + PutBlockBlobFromFile(ctx context.Context, containerName string, blobName string, file *os.File, input PutBlockBlobInput) error + PutBlockList(ctx context.Context, containerName string, blobName string, input PutBlockListInput) (PutBlockListResponse, error) + PutBlockFromURL(ctx context.Context, containerName string, blobName string, input PutBlockFromURLInput) (PutBlockFromURLResponse, error) + PutPageBlob(ctx context.Context, containerName string, blobName string, input PutPageBlobInput) (PutPageBlobResponse, error) + PutPageClear(ctx context.Context, containerName string, blobName string, input PutPageClearInput) (PutPageClearResponse, error) + PutPageUpdate(ctx context.Context, containerName string, blobName string, input PutPageUpdateInput) (PutPageUpdateResponse, error) + SetTier(ctx context.Context, containerName string, blobName string, input SetTierInput) (SetTierResponse, error) + Snapshot(ctx context.Context, containerName string, blobName string, input SnapshotInput) (SnapshotResponse, error) + GetSnapshotProperties(ctx context.Context, containerName string, blobName string, input GetSnapshotPropertiesInput) (GetPropertiesResponse, error) + Undelete(ctx context.Context, containerName string, blobName string) (UndeleteResponse, error) } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/append_block.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/append_block.go index b7705c202518..a1068d459c5c 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/append_block.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/append_block.go @@ -1,16 +1,16 @@ package blobs import ( + "bytes" "context" "fmt" + "io" "net/http" "strconv" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type AppendBlockInput struct { @@ -45,8 +45,8 @@ type AppendBlockInput struct { LeaseID *string } -type AppendBlockResult struct { - autorest.Response +type AppendBlockResponse struct { + HttpResponse *client.Response BlobAppendOffset string BlobCommittedBlockCount int64 @@ -56,125 +56,105 @@ type AppendBlockResult struct { } // AppendBlock commits a new block of data to the end of an existing append blob. -func (client Client) AppendBlock(ctx context.Context, accountName, containerName, blobName string, input AppendBlockInput) (result AppendBlockResult, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "AppendBlock", "`accountName` cannot be an empty string.") - } +func (c Client) AppendBlock(ctx context.Context, containerName, blobName string, input AppendBlockInput) (resp AppendBlockResponse, err error) { + if containerName == "" { - return result, validation.NewError("blobs.Client", "AppendBlock", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } + if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "AppendBlock", "`containerName` must be a lower-cased string.") + return resp, fmt.Errorf("`containerName` must be a lower-cased string") } + if blobName == "" { - return result, validation.NewError("blobs.Client", "AppendBlock", "`blobName` cannot be an empty string.") + return resp, fmt.Errorf("`blobName` cannot be an empty string") } + if input.Content != nil && len(*input.Content) > (4*1024*1024) { - return result, validation.NewError("files.Client", "PutByteRange", "`input.Content` must be at most 4MB.") + return resp, fmt.Errorf("`input.Content` must be at most 4MB") } - req, err := client.AppendBlockPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "AppendBlock", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: appendBlockOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), } - resp, err := client.AppendBlockSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "AppendBlock", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.AppendBlockResponder(resp) + if input.Content != nil { + req.Body = io.NopCloser(bytes.NewReader(*input.Content)) + } + + req.ContentLength = int64(len(*input.Content)) + + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "AppendBlock", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } - return -} + if resp.HttpResponse != nil { + if resp.HttpResponse.Header != nil { + resp.BlobAppendOffset = resp.HttpResponse.Header.Get("x-ms-blob-append-offset") + resp.ContentMD5 = resp.HttpResponse.Header.Get("Content-MD5") + resp.ETag = resp.HttpResponse.Header.Get("ETag") + resp.LastModified = resp.HttpResponse.Header.Get("Last-Modified") + + if v := resp.HttpResponse.Header.Get("x-ms-blob-committed-block-count"); v != "" { + i, innerErr := strconv.Atoi(v) + if innerErr != nil { + err = fmt.Errorf("error parsing %q as an integer: %s", v, innerErr) + return + } + resp.BlobCommittedBlockCount = int64(i) + } -// AppendBlockPreparer prepares the AppendBlock request. -func (client Client) AppendBlockPreparer(ctx context.Context, accountName, containerName, blobName string, input AppendBlockInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), + } } - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "appendblock"), - } + return +} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } +type appendBlockOptions struct { + input AppendBlockInput +} - if input.BlobConditionAppendPosition != nil { - headers["x-ms-blob-condition-appendpos"] = *input.BlobConditionAppendPosition +func (a appendBlockOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + if a.input.BlobConditionAppendPosition != nil { + headers.Append("x-ms-blob-condition-appendpos", strconv.Itoa(int(*a.input.BlobConditionAppendPosition))) } - if input.BlobConditionMaxSize != nil { - headers["x-ms-blob-condition-maxsize"] = *input.BlobConditionMaxSize + if a.input.BlobConditionMaxSize != nil { + headers.Append("x-ms-blob-condition-maxsize", strconv.Itoa(int(*a.input.BlobConditionMaxSize))) } - if input.ContentMD5 != nil { - headers["x-ms-blob-content-md5"] = *input.ContentMD5 + if a.input.ContentMD5 != nil { + headers.Append("x-ms-blob-content-md5", *a.input.ContentMD5) } - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID - } - if input.Content != nil { - headers["Content-Length"] = int(len(*input.Content)) + if a.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *a.input.LeaseID) } - - decorators := []autorest.PrepareDecorator{ - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers), - } - - if input.Content != nil { - decorators = append(decorators, autorest.WithBytes(input.Content)) + if a.input.Content != nil { + headers.Append("Content-Length", strconv.Itoa(len(*a.input.Content))) } - - preparer := autorest.CreatePreparer(decorators...) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// AppendBlockSender sends the AppendBlock request. The method will close the -// http.Response Body if it receives an error. -func (client Client) AppendBlockSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (a appendBlockOptions) ToOData() *odata.Query { + return nil } -// AppendBlockResponder handles the response to the AppendBlock request. The method always -// closes the http.Response Body. -func (client Client) AppendBlockResponder(resp *http.Response) (result AppendBlockResult, err error) { - if resp != nil && resp.Header != nil { - result.BlobAppendOffset = resp.Header.Get("x-ms-blob-append-offset") - result.ContentMD5 = resp.Header.Get("ETag") - result.ETag = resp.Header.Get("ETag") - result.LastModified = resp.Header.Get("Last-Modified") - - if v := resp.Header.Get("x-ms-blob-committed-block-count"); v != "" { - i, innerErr := strconv.Atoi(v) - if innerErr != nil { - err = fmt.Errorf("Error parsing %q as an integer: %s", v, innerErr) - return - } - - result.BlobCommittedBlockCount = int64(i) - } - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return +func (a appendBlockOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "appendblock") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/client.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/client.go index db20391922bb..8cb42d8f98eb 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/client.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/client.go @@ -1,25 +1,22 @@ package blobs import ( - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" + "fmt" + + "github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/storage" ) // Client is the base client for Blob Storage Blobs. type Client struct { - autorest.Client - BaseURI string -} - -// New creates an instance of the Client client. -func New() Client { - return NewWithEnvironment(azure.PublicCloud) + Client *storage.BaseClient } -// NewWithBaseURI creates an instance of the Client client. -func NewWithEnvironment(environment azure.Environment) Client { - return Client{ - Client: autorest.NewClientWithUserAgent(UserAgent()), - BaseURI: environment.StorageEndpointSuffix, +func NewWithBaseUri(baseUri string) (*Client, error) { + baseClient, err := storage.NewBaseClient(baseUri, componentName, apiVersion) + if err != nil { + return nil, fmt.Errorf("building base client: %+v", err) } + return &Client{ + Client: baseClient, + }, nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/copy.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/copy.go index febaab5f9a91..2ff309cc75da 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/copy.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/copy.go @@ -2,13 +2,12 @@ package blobs import ( "context" + "fmt" "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" "github.com/tombuildsstuff/giovanni/storage/internal/metadata" ) @@ -106,130 +105,126 @@ type CopyInput struct { SourceIfUnmodifiedSince *string } -type CopyResult struct { - autorest.Response +type CopyResponse struct { + HttpResponse *client.Response CopyID string CopyStatus string } // Copy copies a blob to a destination within the storage account asynchronously. -func (client Client) Copy(ctx context.Context, accountName, containerName, blobName string, input CopyInput) (result CopyResult, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "Copy", "`accountName` cannot be an empty string.") - } +func (c Client) Copy(ctx context.Context, containerName, blobName string, input CopyInput) (resp CopyResponse, err error) { + if containerName == "" { - return result, validation.NewError("blobs.Client", "Copy", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } + if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "Copy", "`containerName` must be a lower-cased string.") + return resp, fmt.Errorf("`containerName` must be a lower-cased string") } + if blobName == "" { - return result, validation.NewError("blobs.Client", "Copy", "`blobName` cannot be an empty string.") + return resp, fmt.Errorf("`blobName` cannot be an empty string") } + if input.CopySource == "" { - return result, validation.NewError("blobs.Client", "Copy", "`input.CopySource` cannot be an empty string.") + return resp, fmt.Errorf("`input.CopySource` cannot be an empty string") } - req, err := client.CopyPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "Copy", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusAccepted, + }, + HttpMethod: http.MethodPut, + OptionsObject: copyOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), } - resp, err := client.CopySender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "Copy", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.CopyResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "Copy", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } + if resp.HttpResponse != nil { + if resp.HttpResponse.Header != nil { + resp.CopyID = resp.HttpResponse.Header.Get("x-ms-copy-id") + resp.CopyStatus = resp.HttpResponse.Header.Get("x-ms-copy-status") + } + } + return } -// CopyPreparer prepares the Copy request. -func (client Client) CopyPreparer(ctx context.Context, accountName, containerName, blobName string, input CopyInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } +type copyOptions struct { + input CopyInput +} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-copy-source": autorest.Encode("header", input.CopySource), - } +func (c copyOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("x-ms-copy-source", c.input.CopySource) - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID + if c.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *c.input.LeaseID) } - if input.SourceLeaseID != nil { - headers["x-ms-source-lease-id"] = *input.SourceLeaseID + + if c.input.SourceLeaseID != nil { + headers.Append("x-ms-source-lease-id", *c.input.SourceLeaseID) } - if input.AccessTier != nil { - headers["x-ms-access-tier"] = string(*input.AccessTier) + + if c.input.AccessTier != nil { + headers.Append("x-ms-access-tier", string(*c.input.AccessTier)) } - if input.IfMatch != nil { - headers["If-Match"] = *input.IfMatch + if c.input.IfMatch != nil { + headers.Append("If-Match", *c.input.IfMatch) } - if input.IfNoneMatch != nil { - headers["If-None-Match"] = *input.IfNoneMatch + + if c.input.IfNoneMatch != nil { + headers.Append("If-None-Match", *c.input.IfNoneMatch) } - if input.IfUnmodifiedSince != nil { - headers["If-Unmodified-Since"] = *input.IfUnmodifiedSince + + if c.input.IfUnmodifiedSince != nil { + headers.Append("If-Unmodified-Since", *c.input.IfUnmodifiedSince) } - if input.IfModifiedSince != nil { - headers["If-Modified-Since"] = *input.IfModifiedSince + + if c.input.IfModifiedSince != nil { + headers.Append("If-Modified-Since", *c.input.IfModifiedSince) } - if input.SourceIfMatch != nil { - headers["x-ms-source-if-match"] = *input.SourceIfMatch + if c.input.SourceIfMatch != nil { + headers.Append("x-ms-source-if-match", *c.input.SourceIfMatch) } - if input.SourceIfNoneMatch != nil { - headers["x-ms-source-if-none-match"] = *input.SourceIfNoneMatch + + if c.input.SourceIfNoneMatch != nil { + headers.Append("x-ms-source-if-none-match", *c.input.SourceIfNoneMatch) } - if input.SourceIfModifiedSince != nil { - headers["x-ms-source-if-modified-since"] = *input.SourceIfModifiedSince + + if c.input.SourceIfModifiedSince != nil { + headers.Append("x-ms-source-if-modified-since", *c.input.SourceIfModifiedSince) } - if input.SourceIfUnmodifiedSince != nil { - headers["x-ms-source-if-unmodified-since"] = *input.SourceIfUnmodifiedSince + + if c.input.SourceIfUnmodifiedSince != nil { + headers.Append("x-ms-source-if-unmodified-since", *c.input.SourceIfUnmodifiedSince) } - headers = metadata.SetIntoHeaders(headers, input.MetaData) + headers.Merge(metadata.SetMetaDataHeaders(c.input.MetaData)) - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// CopySender sends the Copy request. The method will close the -// http.Response Body if it receives an error. -func (client Client) CopySender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (c copyOptions) ToOData() *odata.Query { + return nil } -// CopyResponder handles the response to the Copy request. The method always -// closes the http.Response Body. -func (client Client) CopyResponder(resp *http.Response) (result CopyResult, err error) { - if resp != nil && resp.Header != nil { - result.CopyID = resp.Header.Get("x-ms-copy-id") - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusAccepted), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return +func (c copyOptions) ToQuery() *client.QueryParams { + return nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/copy_abort.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/copy_abort.go index a992ff199bb1..064c56f09ab8 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/copy_abort.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/copy_abort.go @@ -2,13 +2,12 @@ package blobs import ( "context" + "fmt" "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type AbortCopyInput struct { @@ -20,91 +19,76 @@ type AbortCopyInput struct { LeaseID *string } +type CopyAbortResponse struct { + HttpResponse *client.Response +} + // AbortCopy aborts a pending Copy Blob operation, and leaves a destination blob with zero length and full metadata. -func (client Client) AbortCopy(ctx context.Context, accountName, containerName, blobName string, input AbortCopyInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "AbortCopy", "`accountName` cannot be an empty string.") - } +func (c Client) AbortCopy(ctx context.Context, containerName, blobName string, input AbortCopyInput) (resp CopyAbortResponse, err error) { + if containerName == "" { - return result, validation.NewError("blobs.Client", "AbortCopy", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } + if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "AbortCopy", "`containerName` must be a lower-cased string.") + return resp, fmt.Errorf("`containerName` must be a lower-cased string") } + if blobName == "" { - return result, validation.NewError("blobs.Client", "AbortCopy", "`blobName` cannot be an empty string.") + return resp, fmt.Errorf("`blobName` cannot be an empty string") } + if input.CopyID == "" { - return result, validation.NewError("blobs.Client", "AbortCopy", "`input.CopyID` cannot be an empty string.") + return resp, fmt.Errorf("`input.CopyID` cannot be an empty string") } - req, err := client.AbortCopyPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "AbortCopy", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusNoContent, + }, + HttpMethod: http.MethodPut, + OptionsObject: copyAbortOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), } - resp, err := client.AbortCopySender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "AbortCopy", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.AbortCopyResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "AbortCopy", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// AbortCopyPreparer prepares the AbortCopy request. -func (client Client) AbortCopyPreparer(ctx context.Context, accountName, containerName, blobName string, input AbortCopyInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "copy"), - "copyid": autorest.Encode("query", input.CopyID), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-copy-action": "abort", - } +type copyAbortOptions struct { + input AbortCopyInput +} - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID +func (c copyAbortOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("x-ms-copy-action", "abort") + if c.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *c.input.LeaseID) } - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// AbortCopySender sends the AbortCopy request. The method will close the -// http.Response Body if it receives an error. -func (client Client) AbortCopySender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (c copyAbortOptions) ToOData() *odata.Query { + return nil } -// AbortCopyResponder handles the response to the AbortCopy request. The method always -// closes the http.Response Body. -func (client Client) AbortCopyResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusNoContent), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - return +func (c copyAbortOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "copy") + out.Append("copyid", c.input.CopyID) + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/copy_and_wait.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/copy_and_wait.go index a1e7fa453dc0..5ec7c239fe32 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/copy_and_wait.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/copy_and_wait.go @@ -4,38 +4,25 @@ import ( "context" "fmt" "time" + + "github.com/hashicorp/go-azure-sdk/sdk/client/pollers" ) // CopyAndWait copies a blob to a destination within the storage account and waits for it to finish copying. -func (client Client) CopyAndWait(ctx context.Context, accountName, containerName, blobName string, input CopyInput, pollingInterval time.Duration) error { - if _, err := client.Copy(ctx, accountName, containerName, blobName, input); err != nil { - return fmt.Errorf("Error copying: %s", err) +func (c Client) CopyAndWait(ctx context.Context, containerName, blobName string, input CopyInput) error { + if _, err := c.Copy(ctx, containerName, blobName, input); err != nil { + return fmt.Errorf("error copying: %s", err) } - for true { - getInput := GetPropertiesInput{ - LeaseID: input.LeaseID, - } - getResult, err := client.GetProperties(ctx, accountName, containerName, blobName, getInput) - if err != nil { - return fmt.Errorf("") - } - - switch getResult.CopyStatus { - case Aborted: - return fmt.Errorf("Copy was aborted: %s", getResult.CopyStatusDescription) - - case Failed: - return fmt.Errorf("Copy failed: %s", getResult.CopyStatusDescription) - - case Success: - return nil + getInput := GetPropertiesInput{ + LeaseID: input.LeaseID, + } - case Pending: - time.Sleep(pollingInterval) - continue - } + pollerType := NewCopyAndWaitPoller(&c, containerName, blobName, getInput) + poller := pollers.NewPoller(pollerType, 10*time.Second, pollers.DefaultNumberOfDroppedConnectionsToAllow) + if err := poller.PollUntilDone(ctx); err != nil { + return fmt.Errorf("waiting for file to copy: %+v", err) } - return fmt.Errorf("Unexpected error waiting for the copy to complete") + return nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/copy_and_wait_poller.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/copy_and_wait_poller.go new file mode 100644 index 000000000000..313f4863206e --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/copy_and_wait_poller.go @@ -0,0 +1,48 @@ +package blobs + +import ( + "context" + "fmt" + "strings" + "time" + + "github.com/hashicorp/go-azure-sdk/sdk/client/pollers" +) + +var _ pollers.PollerType = ©AndWaitPoller{} + +func NewCopyAndWaitPoller(client *Client, containerName, blobName string, getPropertiesInput GetPropertiesInput) *copyAndWaitPoller { + return ©AndWaitPoller{ + client: client, + containerName: containerName, + blobName: blobName, + getPropertiesInput: getPropertiesInput, + } +} + +type copyAndWaitPoller struct { + client *Client + containerName string + blobName string + getPropertiesInput GetPropertiesInput +} + +func (p *copyAndWaitPoller) Poll(ctx context.Context) (*pollers.PollResult, error) { + props, err := p.client.GetProperties(ctx, p.containerName, p.blobName, p.getPropertiesInput) + if err != nil { + return nil, fmt.Errorf("retrieving properties (container: %s blob: %s) : %+v", p.containerName, p.blobName, err) + } + + if strings.EqualFold(string(props.CopyStatus), string(Success)) { + return &pollers.PollResult{ + Status: pollers.PollingStatusSucceeded, + PollInterval: 10 * time.Second, + }, nil + } + + // Processing + return &pollers.PollResult{ + Status: pollers.PollingStatusInProgress, + PollInterval: 10 * time.Second, + }, nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/delete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/delete.go index c1c642d7d781..e13aaa599fe6 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/delete.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/delete.go @@ -2,13 +2,12 @@ package blobs import ( "context" + "fmt" "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type DeleteInput struct { @@ -21,85 +20,73 @@ type DeleteInput struct { LeaseID *string } +type DeleteResponse struct { + HttpResponse *client.Response +} + // Delete marks the specified blob or snapshot for deletion. The blob is later deleted during garbage collection. -func (client Client) Delete(ctx context.Context, accountName, containerName, blobName string, input DeleteInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "Delete", "`accountName` cannot be an empty string.") - } +func (c Client) Delete(ctx context.Context, containerName, blobName string, input DeleteInput) (resp DeleteResponse, err error) { + if containerName == "" { - return result, validation.NewError("blobs.Client", "Delete", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } + if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "Delete", "`containerName` must be a lower-cased string.") + return resp, fmt.Errorf("`containerName` must be a lower-cased string") } + if blobName == "" { - return result, validation.NewError("blobs.Client", "Delete", "`blobName` cannot be an empty string.") + return resp, fmt.Errorf("`blobName` cannot be an empty string") } - req, err := client.DeletePreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "Delete", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusAccepted, + }, + HttpMethod: http.MethodDelete, + OptionsObject: deleteOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), } - resp, err := client.DeleteSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "Delete", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.DeleteResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "Delete", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// DeletePreparer prepares the Delete request. -func (client Client) DeletePreparer(ctx context.Context, accountName, containerName, blobName string, input DeleteInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } +type deleteOptions struct { + input DeleteInput +} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } +func (d deleteOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID + if d.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *d.input.LeaseID) } - if input.DeleteSnapshots { - headers["x-ms-delete-snapshots"] = "include" + if d.input.DeleteSnapshots { + headers.Append("x-ms-delete-snapshots", "include") } - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client Client) DeleteSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (d deleteOptions) ToOData() *odata.Query { + return nil } -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client Client) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusAccepted), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - return +func (d deleteOptions) ToQuery() *client.QueryParams { + return nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/delete_snapshot.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/delete_snapshot.go index 18c3d4cffe3f..0407eb1f7829 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/delete_snapshot.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/delete_snapshot.go @@ -2,13 +2,12 @@ package blobs import ( "context" + "fmt" "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type DeleteSnapshotInput struct { @@ -20,89 +19,74 @@ type DeleteSnapshotInput struct { SnapshotDateTime string } +type DeleteSnapshotResponse struct { + HttpResponse *client.Response +} + // DeleteSnapshot marks a single Snapshot of a Blob for Deletion based on it's DateTime, which will be deleted during the next Garbage Collection cycle. -func (client Client) DeleteSnapshot(ctx context.Context, accountName, containerName, blobName string, input DeleteSnapshotInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "DeleteSnapshot", "`accountName` cannot be an empty string.") - } +func (c Client) DeleteSnapshot(ctx context.Context, containerName, blobName string, input DeleteSnapshotInput) (resp DeleteSnapshotResponse, err error) { + if containerName == "" { - return result, validation.NewError("blobs.Client", "DeleteSnapshot", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } + if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "DeleteSnapshot", "`containerName` must be a lower-cased string.") + return resp, fmt.Errorf("`containerName` must be a lower-cased string") } + if blobName == "" { - return result, validation.NewError("blobs.Client", "DeleteSnapshot", "`blobName` cannot be an empty string.") + return resp, fmt.Errorf("`blobName` cannot be an empty string") } + if input.SnapshotDateTime == "" { - return result, validation.NewError("blobs.Client", "DeleteSnapshot", "`input.SnapshotDateTime` cannot be an empty string.") + return resp, fmt.Errorf("`input.SnapshotDateTime` cannot be an empty string") } - req, err := client.DeleteSnapshotPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "DeleteSnapshot", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusAccepted, + }, + HttpMethod: http.MethodDelete, + OptionsObject: deleteSnapshotOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), } - resp, err := client.DeleteSnapshotSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "DeleteSnapshot", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.DeleteSnapshotResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "DeleteSnapshot", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// DeleteSnapshotPreparer prepares the DeleteSnapshot request. -func (client Client) DeleteSnapshotPreparer(ctx context.Context, accountName, containerName, blobName string, input DeleteSnapshotInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - queryParameters := map[string]interface{}{ - "snapshot": autorest.Encode("query", input.SnapshotDateTime), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } +type deleteSnapshotOptions struct { + input DeleteSnapshotInput +} - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID +func (d deleteSnapshotOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + if d.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *d.input.LeaseID) } - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// DeleteSnapshotSender sends the DeleteSnapshot request. The method will close the -// http.Response Body if it receives an error. -func (client Client) DeleteSnapshotSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (d deleteSnapshotOptions) ToOData() *odata.Query { + return nil } -// DeleteSnapshotResponder handles the response to the DeleteSnapshot request. The method always -// closes the http.Response Body. -func (client Client) DeleteSnapshotResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusAccepted), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - return +func (d deleteSnapshotOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("snapshot", d.input.SnapshotDateTime) + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/delete_snapshots.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/delete_snapshots.go index e7e2b664d74d..34b3beb623a8 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/delete_snapshots.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/delete_snapshots.go @@ -2,13 +2,12 @@ package blobs import ( "context" + "fmt" "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type DeleteSnapshotsInput struct { @@ -17,83 +16,69 @@ type DeleteSnapshotsInput struct { LeaseID *string } +type DeleteSnapshotsResponse struct { + HttpResponse *client.Response +} + // DeleteSnapshots marks all Snapshots of a Blob for Deletion, which will be deleted during the next Garbage Collection Cycle. -func (client Client) DeleteSnapshots(ctx context.Context, accountName, containerName, blobName string, input DeleteSnapshotsInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "DeleteSnapshots", "`accountName` cannot be an empty string.") - } +func (c Client) DeleteSnapshots(ctx context.Context, containerName, blobName string, input DeleteSnapshotsInput) (resp DeleteSnapshotsResponse, err error) { + if containerName == "" { - return result, validation.NewError("blobs.Client", "DeleteSnapshots", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } + if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "DeleteSnapshots", "`containerName` must be a lower-cased string.") + return resp, fmt.Errorf("`containerName` must be a lower-cased string") } + if blobName == "" { - return result, validation.NewError("blobs.Client", "DeleteSnapshots", "`blobName` cannot be an empty string.") + return resp, fmt.Errorf("`blobName` cannot be an empty string") } - req, err := client.DeleteSnapshotsPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "DeleteSnapshots", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusAccepted, + }, + HttpMethod: http.MethodDelete, + OptionsObject: deleteSnapshotsOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), } - resp, err := client.DeleteSnapshotsSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "DeleteSnapshots", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.DeleteSnapshotsResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "DeleteSnapshots", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// DeleteSnapshotsPreparer prepares the DeleteSnapshots request. -func (client Client) DeleteSnapshotsPreparer(ctx context.Context, accountName, containerName, blobName string, input DeleteSnapshotsInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } +type deleteSnapshotsOptions struct { + input DeleteSnapshotsInput +} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - // only delete the snapshots but leave the blob as-is - "x-ms-delete-snapshots": "only", - } +func (d deleteSnapshotsOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("x-ms-delete-snapshots", "only") - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID + if d.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *d.input.LeaseID) } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// DeleteSnapshotsSender sends the DeleteSnapshots request. The method will close the -// http.Response Body if it receives an error. -func (client Client) DeleteSnapshotsSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (d deleteSnapshotsOptions) ToOData() *odata.Query { + return nil } -// DeleteSnapshotsResponder handles the response to the DeleteSnapshots request. The method always -// closes the http.Response Body. -func (client Client) DeleteSnapshotsResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusAccepted), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - return +func (d deleteSnapshotsOptions) ToQuery() *client.QueryParams { + return nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/get.go index 7e0d6ee9fbd5..0f5572a8b9c2 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/get.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/get.go @@ -6,10 +6,8 @@ import ( "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type GetInput struct { @@ -18,99 +16,86 @@ type GetInput struct { EndByte *int64 } -type GetResult struct { - autorest.Response +type GetResponse struct { + HttpResponse *client.Response Contents []byte } // Get reads or downloads a blob from the system, including its metadata and properties. -func (client Client) Get(ctx context.Context, accountName, containerName, blobName string, input GetInput) (result GetResult, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "Get", "`accountName` cannot be an empty string.") - } +func (c Client) Get(ctx context.Context, containerName, blobName string, input GetInput) (resp GetResponse, err error) { + if containerName == "" { - return result, validation.NewError("blobs.Client", "Get", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } + if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "Get", "`containerName` must be a lower-cased string.") + return resp, fmt.Errorf("`containerName` must be a lower-cased string") } + if blobName == "" { - return result, validation.NewError("blobs.Client", "Get", "`blobName` cannot be an empty string.") + return resp, fmt.Errorf("`blobName` cannot be an empty string") } + if input.LeaseID != nil && *input.LeaseID == "" { - return result, validation.NewError("blobs.Client", "Get", "`input.LeaseID` should either be specified or nil, not an empty string.") + return resp, fmt.Errorf("`input.LeaseID` should either be specified or nil, not an empty string") } + if (input.StartByte != nil && input.EndByte == nil) || input.StartByte == nil && input.EndByte != nil { - return result, validation.NewError("blobs.Client", "Get", "`input.StartByte` and `input.EndByte` must both be specified, or both be nil.") + return resp, fmt.Errorf("`input.StartByte` and `input.EndByte` must both be specified, or both be nil") } - req, err := client.GetPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "Get", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusOK, + http.StatusPartialContent, + }, + HttpMethod: http.MethodGet, + OptionsObject: getOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), } - resp, err := client.GetSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "Get", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.GetResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "Get", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } + if resp.HttpResponse != nil { + err = resp.HttpResponse.Unmarshal(&resp.Contents) + if err != nil { + return resp, fmt.Errorf("unmarshalling response: %v", err) + } + } + return } -// GetPreparer prepares the Get request. -func (client Client) GetPreparer(ctx context.Context, accountName, containerName, blobName string, input GetInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } +type getOptions struct { + input GetInput +} - if input.StartByte != nil && input.EndByte != nil { - headers["x-ms-range"] = fmt.Sprintf("bytes=%d-%d", *input.StartByte, *input.EndByte) +func (g getOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + if g.input.StartByte != nil && g.input.EndByte != nil { + headers.Append("x-ms-range", fmt.Sprintf("bytes=%d-%d", *g.input.StartByte, *g.input.EndByte)) } + return headers - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) } -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (g getOptions) ToOData() *odata.Query { + return nil } -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client Client) GetResponder(resp *http.Response) (result GetResult, err error) { - if resp != nil && int(resp.ContentLength) > 0 { - result.Contents = make([]byte, resp.ContentLength) - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusPartialContent), - autorest.ByUnmarshallingBytes(&result.Contents), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return +func (g getOptions) ToQuery() *client.QueryParams { + return nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/get_block_list.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/get_block_list.go index 9f8120c6c8c3..9a783cb6ebac 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/get_block_list.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/get_block_list.go @@ -7,10 +7,8 @@ import ( "strconv" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type GetBlockListInput struct { @@ -18,11 +16,11 @@ type GetBlockListInput struct { LeaseID *string } -type GetBlockListResult struct { - autorest.Response +type GetBlockListResponse struct { + HttpResponse *client.Response // The size of the blob in bytes - ContentLength *int64 + BlobContentLength *int64 // The Content Type of the blob ContentType string @@ -38,103 +36,87 @@ type GetBlockListResult struct { } // GetBlockList retrieves the list of blocks that have been uploaded as part of a block blob. -func (client Client) GetBlockList(ctx context.Context, accountName, containerName, blobName string, input GetBlockListInput) (result GetBlockListResult, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "GetBlockList", "`accountName` cannot be an empty string.") - } +func (c Client) GetBlockList(ctx context.Context, containerName, blobName string, input GetBlockListInput) (resp GetBlockListResponse, err error) { + if containerName == "" { - return result, validation.NewError("blobs.Client", "GetBlockList", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } + if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "GetBlockList", "`containerName` must be a lower-cased string.") + return resp, fmt.Errorf("`containerName` must be a lower-cased string") } + if blobName == "" { - return result, validation.NewError("blobs.Client", "GetBlockList", "`blobName` cannot be an empty string.") + return resp, fmt.Errorf("`blobName` cannot be an empty string") } - req, err := client.GetBlockListPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "GetBlockList", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: getBlockListOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), } - resp, err := client.GetBlockListSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "GetBlockList", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.GetBlockListResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "GetBlockList", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } - return -} - -// GetBlockListPreparer prepares the GetBlockList request. -func (client Client) GetBlockListPreparer(ctx context.Context, accountName, containerName, blobName string, input GetBlockListInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - queryParameters := map[string]interface{}{ - "blocklisttype": autorest.Encode("query", string(input.BlockListType)), - "comp": autorest.Encode("query", "blocklist"), - } + if resp.HttpResponse != nil { + if resp.HttpResponse.Header != nil { + resp.ContentType = resp.HttpResponse.Header.Get("Content-Type") + resp.ETag = resp.HttpResponse.Header.Get("ETag") - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } + if v := resp.HttpResponse.Header.Get("x-ms-blob-content-length"); v != "" { + i, innerErr := strconv.Atoi(v) + if innerErr != nil { + err = fmt.Errorf("error parsing %q as an integer: %s", v, innerErr) + return + } - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID + i64 := int64(i) + resp.BlobContentLength = &i64 + } + } + err = resp.HttpResponse.Unmarshal(&resp) + if err != nil { + return resp, fmt.Errorf("unmarshalling response: %v", err) + } } - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return } -// GetBlockListSender sends the GetBlockList request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetBlockListSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +type getBlockListOptions struct { + input GetBlockListInput } -// GetBlockListResponder handles the response to the GetBlockList request. The method always -// closes the http.Response Body. -func (client Client) GetBlockListResponder(resp *http.Response) (result GetBlockListResult, err error) { - if resp != nil && resp.Header != nil { - result.ContentType = resp.Header.Get("Content-Type") - result.ETag = resp.Header.Get("ETag") - - if v := resp.Header.Get("x-ms-blob-content-length"); v != "" { - i, innerErr := strconv.Atoi(v) - if innerErr != nil { - err = fmt.Errorf("Error parsing %q as an integer: %s", v, innerErr) - return - } - - i64 := int64(i) - result.ContentLength = &i64 - } +func (g getBlockListOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + if g.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *g.input.LeaseID) } + return headers +} - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingXML(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return +func (g getBlockListOptions) ToOData() *odata.Query { + return nil +} + +func (g getBlockListOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("blocklisttype", string(g.input.BlockListType)) + out.Append("comp", "blocklist") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/get_page_ranges.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/get_page_ranges.go index 37abf631a28a..6d0f54163eaa 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/get_page_ranges.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/get_page_ranges.go @@ -7,10 +7,8 @@ import ( "strconv" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type GetPageRangesInput struct { @@ -20,8 +18,8 @@ type GetPageRangesInput struct { EndByte *int64 } -type GetPageRangesResult struct { - autorest.Response +type GetPageRangesResponse struct { + HttpResponse *client.Response // The size of the blob in bytes ContentLength *int64 @@ -44,109 +42,97 @@ type PageRange struct { } // GetPageRanges returns the list of valid page ranges for a page blob or snapshot of a page blob. -func (client Client) GetPageRanges(ctx context.Context, accountName, containerName, blobName string, input GetPageRangesInput) (result GetPageRangesResult, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "GetPageRanges", "`accountName` cannot be an empty string.") - } +func (c Client) GetPageRanges(ctx context.Context, containerName, blobName string, input GetPageRangesInput) (resp GetPageRangesResponse, err error) { + if containerName == "" { - return result, validation.NewError("blobs.Client", "GetPageRanges", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } + if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "GetPageRanges", "`containerName` must be a lower-cased string.") + return resp, fmt.Errorf("`containerName` must be a lower-cased string") } + if blobName == "" { - return result, validation.NewError("blobs.Client", "GetPageRanges", "`blobName` cannot be an empty string.") + return resp, fmt.Errorf("`blobName` cannot be an empty string") } + if (input.StartByte != nil && input.EndByte == nil) || input.StartByte == nil && input.EndByte != nil { - return result, validation.NewError("blobs.Client", "GetPageRanges", "`input.StartByte` and `input.EndByte` must both be specified, or both be nil.") + return resp, fmt.Errorf("`input.StartByte` and `input.EndByte` must both be specified, or both be nil") } - req, err := client.GetPageRangesPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "GetPageRanges", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: getPageRangesOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), } - resp, err := client.GetPageRangesSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "GetPageRanges", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.GetPageRangesResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "GetPageRanges", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } - return -} + if resp.HttpResponse != nil { + if resp.HttpResponse.Header != nil { + resp.ContentType = resp.HttpResponse.Header.Get("Content-Type") + resp.ETag = resp.HttpResponse.Header.Get("ETag") -// GetPageRangesPreparer prepares the GetPageRanges request. -func (client Client) GetPageRangesPreparer(ctx context.Context, accountName, containerName, blobName string, input GetPageRangesInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } + if v := resp.HttpResponse.Header.Get("x-ms-blob-content-length"); v != "" { + i, innerErr := strconv.Atoi(v) + if innerErr != nil { + err = fmt.Errorf("Error parsing %q as an integer: %s", v, innerErr) + return + } - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "pagelist"), - } + i64 := int64(i) + resp.ContentLength = &i64 + } + } - headers := map[string]interface{}{ - "x-ms-version": APIVersion, + err = resp.HttpResponse.Unmarshal(&resp) + if err != nil { + return resp, fmt.Errorf("unmarshalling response: %s", err) + } } - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID + return +} + +type getPageRangesOptions struct { + input GetPageRangesInput +} + +func (g getPageRangesOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + + if g.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *g.input.LeaseID) } - if input.StartByte != nil && input.EndByte != nil { - headers["x-ms-range"] = fmt.Sprintf("bytes=%d-%d", *input.StartByte, *input.EndByte) + if g.input.StartByte != nil && g.input.EndByte != nil { + headers.Append("x-ms-range", fmt.Sprintf("bytes=%d-%d", *g.input.StartByte, *g.input.EndByte)) } - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// GetPageRangesSender sends the GetPageRanges request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetPageRangesSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (g getPageRangesOptions) ToOData() *odata.Query { + return nil } -// GetPageRangesResponder handles the response to the GetPageRanges request. The method always -// closes the http.Response Body. -func (client Client) GetPageRangesResponder(resp *http.Response) (result GetPageRangesResult, err error) { - if resp != nil && resp.Header != nil { - result.ContentType = resp.Header.Get("Content-Type") - result.ETag = resp.Header.Get("ETag") - - if v := resp.Header.Get("x-ms-blob-content-length"); v != "" { - i, innerErr := strconv.Atoi(v) - if innerErr != nil { - err = fmt.Errorf("Error parsing %q as an integer: %s", v, innerErr) - return - } - - i64 := int64(i) - result.ContentLength = &i64 - } - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingXML(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return +func (g getPageRangesOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "pagelist") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/incremental_copy_blob.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/incremental_copy_blob.go index 7fb7e6b55489..d059f11e2bc7 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/incremental_copy_blob.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/incremental_copy_blob.go @@ -2,13 +2,12 @@ package blobs import ( "context" + "fmt" "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type IncrementalCopyBlobInput struct { @@ -19,102 +18,88 @@ type IncrementalCopyBlobInput struct { IfNoneMatch *string } +type IncrementalCopyBlob struct { + HttpResponse *client.Response +} + // IncrementalCopyBlob copies a snapshot of the source page blob to a destination page blob. // The snapshot is copied such that only the differential changes between the previously copied // snapshot are transferred to the destination. // The copied snapshots are complete copies of the original snapshot and can be read or copied from as usual. -func (client Client) IncrementalCopyBlob(ctx context.Context, accountName, containerName, blobName string, input IncrementalCopyBlobInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "IncrementalCopyBlob", "`accountName` cannot be an empty string.") - } +func (c Client) IncrementalCopyBlob(ctx context.Context, containerName, blobName string, input IncrementalCopyBlobInput) (resp IncrementalCopyBlob, err error) { + if containerName == "" { - return result, validation.NewError("blobs.Client", "IncrementalCopyBlob", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } + if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "IncrementalCopyBlob", "`containerName` must be a lower-cased string.") + return resp, fmt.Errorf("`containerName` must be a lower-cased string") } + if blobName == "" { - return result, validation.NewError("blobs.Client", "IncrementalCopyBlob", "`blobName` cannot be an empty string.") + return resp, fmt.Errorf("`blobName` cannot be an empty string") } + if input.CopySource == "" { - return result, validation.NewError("blobs.Client", "IncrementalCopyBlob", "`input.CopySource` cannot be an empty string.") + return resp, fmt.Errorf("`input.CopySource` cannot be an empty string") } - req, err := client.IncrementalCopyBlobPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "IncrementalCopyBlob", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusAccepted, + }, + HttpMethod: http.MethodPut, + OptionsObject: incrementalCopyBlobOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), } - resp, err := client.IncrementalCopyBlobSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "IncrementalCopyBlob", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.IncrementalCopyBlobResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "IncrementalCopyBlob", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// IncrementalCopyBlobPreparer prepares the IncrementalCopyBlob request. -func (client Client) IncrementalCopyBlobPreparer(ctx context.Context, accountName, containerName, blobName string, input IncrementalCopyBlobInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } +type incrementalCopyBlobOptions struct { + input IncrementalCopyBlobInput +} - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "incrementalcopy"), - } +func (i incrementalCopyBlobOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-copy-source": input.CopySource, - } + headers.Append("x-ms-copy-source", i.input.CopySource) - if input.IfModifiedSince != nil { - headers["If-Modified-Since"] = *input.IfModifiedSince + if i.input.IfModifiedSince != nil { + headers.Append("If-Modified-Since", *i.input.IfModifiedSince) } - if input.IfUnmodifiedSince != nil { - headers["If-Unmodified-Since"] = *input.IfUnmodifiedSince + if i.input.IfUnmodifiedSince != nil { + headers.Append("If-Unmodified-Since", *i.input.IfUnmodifiedSince) } - if input.IfMatch != nil { - headers["If-Match"] = *input.IfMatch + if i.input.IfMatch != nil { + headers.Append("If-Match", *i.input.IfMatch) } - if input.IfNoneMatch != nil { - headers["If-None-Match"] = *input.IfNoneMatch + if i.input.IfNoneMatch != nil { + headers.Append("If-None-Match", *i.input.IfNoneMatch) } - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// IncrementalCopyBlobSender sends the IncrementalCopyBlob request. The method will close the -// http.Response Body if it receives an error. -func (client Client) IncrementalCopyBlobSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (i incrementalCopyBlobOptions) ToOData() *odata.Query { + return nil } -// IncrementalCopyBlobResponder handles the response to the IncrementalCopyBlob request. The method always -// closes the http.Response Body. -func (client Client) IncrementalCopyBlobResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusAccepted), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - return +func (i incrementalCopyBlobOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "incrementalcopy") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_acquire.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_acquire.go index c4b49d73ae71..214808ca0713 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_acquire.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_acquire.go @@ -2,13 +2,13 @@ package blobs import ( "context" + "fmt" "net/http" + "strconv" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type AcquireLeaseInput struct { @@ -23,113 +23,98 @@ type AcquireLeaseInput struct { ProposedLeaseID *string } -type AcquireLeaseResult struct { - autorest.Response +type AcquireLeaseResponse struct { + HttpResponse *client.Response LeaseID string } // AcquireLease establishes and manages a lock on a blob for write and delete operations. -func (client Client) AcquireLease(ctx context.Context, accountName, containerName, blobName string, input AcquireLeaseInput) (result AcquireLeaseResult, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "AcquireLease", "`accountName` cannot be an empty string.") - } +func (c Client) AcquireLease(ctx context.Context, containerName, blobName string, input AcquireLeaseInput) (resp AcquireLeaseResponse, err error) { + if containerName == "" { - return result, validation.NewError("blobs.Client", "AcquireLease", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } + if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "AcquireLease", "`containerName` must be a lower-cased string.") + return resp, fmt.Errorf("`containerName` must be a lower-cased string") } + if blobName == "" { - return result, validation.NewError("blobs.Client", "AcquireLease", "`blobName` cannot be an empty string.") + return resp, fmt.Errorf("`blobName` cannot be an empty string") } + if input.LeaseID != nil && *input.LeaseID == "" { - return result, validation.NewError("blobs.Client", "AcquireLease", "`input.LeaseID` cannot be an empty string, if specified.") + return resp, fmt.Errorf("`input.LeaseID` cannot be an empty string, if specified") } + if input.ProposedLeaseID != nil && *input.ProposedLeaseID == "" { - return result, validation.NewError("blobs.Client", "AcquireLease", "`input.ProposedLeaseID` cannot be an empty string, if specified.") + return resp, fmt.Errorf("`input.ProposedLeaseID` cannot be an empty string, if specified") } // An infinite lease duration is -1 seconds. A non-infinite lease can be between 15 and 60 seconds if input.LeaseDuration != -1 && (input.LeaseDuration <= 15 || input.LeaseDuration >= 60) { - return result, validation.NewError("blobs.Client", "AcquireLease", "`input.LeaseDuration` must be -1 (infinite), or between 15 and 60 seconds.") + return resp, fmt.Errorf("`input.LeaseDuration` must be -1 (infinite), or between 15 and 60 seconds") } - req, err := client.AcquireLeasePreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "AcquireLease", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: acquireLeaseOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), } - resp, err := client.AcquireLeaseSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "AcquireLease", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.AcquireLeaseResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "AcquireLease", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } + if resp.HttpResponse != nil { + if resp.HttpResponse.Header != nil { + resp.LeaseID = resp.HttpResponse.Header.Get("x-ms-lease-id") + } + } + return } -// AcquireLeasePreparer prepares the AcquireLease request. -func (client Client) AcquireLeasePreparer(ctx context.Context, accountName, containerName, blobName string, input AcquireLeaseInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } +type acquireLeaseOptions struct { + input AcquireLeaseInput +} - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "lease"), - } +func (a acquireLeaseOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-lease-action": "acquire", - "x-ms-lease-duration": input.LeaseDuration, - } + headers.Append("x-ms-lease-action", "acquire") + headers.Append("x-ms-lease-duration", strconv.Itoa(a.input.LeaseDuration)) - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID + if a.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *a.input.LeaseID) } - if input.ProposedLeaseID != nil { - headers["x-ms-proposed-lease-id"] = *input.ProposedLeaseID + if a.input.ProposedLeaseID != nil { + headers.Append("x-ms-proposed-lease-id", *a.input.ProposedLeaseID) } - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// AcquireLeaseSender sends the AcquireLease request. The method will close the -// http.Response Body if it receives an error. -func (client Client) AcquireLeaseSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (a acquireLeaseOptions) ToOData() *odata.Query { + return nil } -// AcquireLeaseResponder handles the response to the AcquireLease request. The method always -// closes the http.Response Body. -func (client Client) AcquireLeaseResponder(resp *http.Response) (result AcquireLeaseResult, err error) { - if resp != nil && resp.Header != nil { - result.LeaseID = resp.Header.Get("x-ms-lease-id") - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return +func (a acquireLeaseOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "lease") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_break.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_break.go index d5642045d20d..858c3061793f 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_break.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_break.go @@ -2,13 +2,13 @@ package blobs import ( "context" + "fmt" "net/http" + "strconv" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type BreakLeaseInput struct { @@ -26,7 +26,7 @@ type BreakLeaseInput struct { } type BreakLeaseResponse struct { - autorest.Response + HttpResponse *client.Response // Approximate time remaining in the lease period, in seconds. // If the break is immediate, 0 is returned. @@ -34,91 +34,73 @@ type BreakLeaseResponse struct { } // BreakLease breaks an existing lock on a blob using the LeaseID. -func (client Client) BreakLease(ctx context.Context, accountName, containerName, blobName string, input BreakLeaseInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "BreakLease", "`accountName` cannot be an empty string.") - } +func (c Client) BreakLease(ctx context.Context, containerName, blobName string, input BreakLeaseInput) (resp BreakLeaseResponse, err error) { + if containerName == "" { - return result, validation.NewError("blobs.Client", "BreakLease", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } + if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "BreakLease", "`containerName` must be a lower-cased string.") + return resp, fmt.Errorf("`containerName` must be a lower-cased string") } + if blobName == "" { - return result, validation.NewError("blobs.Client", "BreakLease", "`blobName` cannot be an empty string.") + return resp, fmt.Errorf("`blobName` cannot be an empty string") } + if input.LeaseID == "" { - return result, validation.NewError("blobs.Client", "BreakLease", "`input.LeaseID` cannot be an empty string.") + return resp, fmt.Errorf("`input.LeaseID` cannot be an empty string") } - req, err := client.BreakLeasePreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "BreakLease", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusAccepted, + }, + HttpMethod: http.MethodPut, + OptionsObject: breakLeaseOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), } - resp, err := client.BreakLeaseSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "BreakLease", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.BreakLeaseResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "BreakLease", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// BreakLeasePreparer prepares the BreakLease request. -func (client Client) BreakLeasePreparer(ctx context.Context, accountName, containerName, blobName string, input BreakLeaseInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } +type breakLeaseOptions struct { + input BreakLeaseInput +} - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "lease"), - } +func (b breakLeaseOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-lease-action": "break", - "x-ms-lease-id": input.LeaseID, - } + headers.Append("x-ms-lease-action", "break") + headers.Append("x-ms-lease-id", b.input.LeaseID) - if input.BreakPeriod != nil { - headers["x-ms-lease-break-period"] = *input.BreakPeriod + if b.input.BreakPeriod != nil { + headers.Append("x-ms-lease-break-period", strconv.Itoa(*b.input.BreakPeriod)) } - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// BreakLeaseSender sends the BreakLease request. The method will close the -// http.Response Body if it receives an error. -func (client Client) BreakLeaseSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (b breakLeaseOptions) ToOData() *odata.Query { + return nil } -// BreakLeaseResponder handles the response to the BreakLease request. The method always -// closes the http.Response Body. -func (client Client) BreakLeaseResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusAccepted), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return +func (b breakLeaseOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "lease") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_change.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_change.go index c57f9db875b0..c69d05483b89 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_change.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_change.go @@ -2,13 +2,12 @@ package blobs import ( "context" + "fmt" "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type ChangeLeaseInput struct { @@ -17,101 +16,84 @@ type ChangeLeaseInput struct { } type ChangeLeaseResponse struct { - autorest.Response + HttpResponse *client.Response LeaseID string } // ChangeLease changes an existing lock on a blob for another lock. -func (client Client) ChangeLease(ctx context.Context, accountName, containerName, blobName string, input ChangeLeaseInput) (result ChangeLeaseResponse, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "ChangeLease", "`accountName` cannot be an empty string.") - } +func (c Client) ChangeLease(ctx context.Context, containerName, blobName string, input ChangeLeaseInput) (resp ChangeLeaseResponse, err error) { + if containerName == "" { - return result, validation.NewError("blobs.Client", "ChangeLease", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } + if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "ChangeLease", "`containerName` must be a lower-cased string.") + return resp, fmt.Errorf("`containerName` must be a lower-cased string") } + if blobName == "" { - return result, validation.NewError("blobs.Client", "ChangeLease", "`blobName` cannot be an empty string.") + return resp, fmt.Errorf("`blobName` cannot be an empty string") } + if input.ExistingLeaseID == "" { - return result, validation.NewError("blobs.Client", "ChangeLease", "`input.ExistingLeaseID` cannot be an empty string.") + return resp, fmt.Errorf("`input.ExistingLeaseID` cannot be an empty string") } + if input.ProposedLeaseID == "" { - return result, validation.NewError("blobs.Client", "ChangeLease", "`input.ProposedLeaseID` cannot be an empty string.") + return resp, fmt.Errorf("`input.ProposedLeaseID` cannot be an empty string") } - req, err := client.ChangeLeasePreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "ChangeLease", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPut, + OptionsObject: changeLeaseOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), } - resp, err := client.ChangeLeaseSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "ChangeLease", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.ChangeLeaseResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "ChangeLease", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } - return -} - -// ChangeLeasePreparer prepares the ChangeLease request. -func (client Client) ChangeLeasePreparer(ctx context.Context, accountName, containerName, blobName string, input ChangeLeaseInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "lease"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-lease-action": "change", - "x-ms-lease-id": input.ExistingLeaseID, - "x-ms-proposed-lease-id": input.ProposedLeaseID, + if resp.HttpResponse != nil { + if resp.HttpResponse.Header != nil { + resp.LeaseID = resp.HttpResponse.Header.Get("x-ms-lease-id") + } } - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return } -// ChangeLeaseSender sends the ChangeLease request. The method will close the -// http.Response Body if it receives an error. -func (client Client) ChangeLeaseSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +type changeLeaseOptions struct { + input ChangeLeaseInput } -// ChangeLeaseResponder handles the response to the ChangeLease request. The method always -// closes the http.Response Body. -func (client Client) ChangeLeaseResponder(resp *http.Response) (result ChangeLeaseResponse, err error) { - if resp != nil && resp.Header != nil { - result.LeaseID = resp.Header.Get("x-ms-lease-id") - } +func (c changeLeaseOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("x-ms-lease-action", "change") + headers.Append("x-ms-lease-id", c.input.ExistingLeaseID) + headers.Append("x-ms-proposed-lease-id", c.input.ProposedLeaseID) + return headers +} - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} +func (c changeLeaseOptions) ToOData() *odata.Query { + return nil +} - return +func (c changeLeaseOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "lease") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_release.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_release.go index 0226cdf37552..350493da229b 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_release.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_release.go @@ -2,97 +2,84 @@ package blobs import ( "context" + "fmt" "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) +type ReleaseLeaseResponse struct { + HttpResponse *client.Response +} + +type ReleaseLeaseInput struct { + LeaseID string +} + // ReleaseLease releases a lock based on the Lease ID. -func (client Client) ReleaseLease(ctx context.Context, accountName, containerName, blobName, leaseID string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "ReleaseLease", "`accountName` cannot be an empty string.") - } +func (c Client) ReleaseLease(ctx context.Context, containerName, blobName string, input ReleaseLeaseInput) (resp ReleaseLeaseResponse, err error) { + if containerName == "" { - return result, validation.NewError("blobs.Client", "ReleaseLease", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } + if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "ReleaseLease", "`containerName` must be a lower-cased string.") + return resp, fmt.Errorf("`containerName` must be a lower-cased string") } + if blobName == "" { - return result, validation.NewError("blobs.Client", "ReleaseLease", "`blobName` cannot be an empty string.") + return resp, fmt.Errorf("`blobName` cannot be an empty string") } - if leaseID == "" { - return result, validation.NewError("blobs.Client", "ReleaseLease", "`leaseID` cannot be an empty string.") + + if input.LeaseID == "" { + return resp, fmt.Errorf("`input.LeaseID` cannot be an empty string") } - req, err := client.ReleaseLeasePreparer(ctx, accountName, containerName, blobName, leaseID) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "ReleaseLease", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPut, + OptionsObject: releaseLeaseOptions{ + leaseID: input.LeaseID, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), } - resp, err := client.ReleaseLeaseSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "ReleaseLease", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.ReleaseLeaseResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "ReleaseLease", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// ReleaseLeasePreparer prepares the ReleaseLease request. -func (client Client) ReleaseLeasePreparer(ctx context.Context, accountName, containerName, blobName, leaseID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "lease"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-lease-action": "release", - "x-ms-lease-id": leaseID, - } - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) +type releaseLeaseOptions struct { + leaseID string } -// ReleaseLeaseSender sends the ReleaseLease request. The method will close the -// http.Response Body if it receives an error. -func (client Client) ReleaseLeaseSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (r releaseLeaseOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("x-ms-lease-action", "release") + headers.Append("x-ms-lease-id", r.leaseID) + return headers } -// ReleaseLeaseResponder handles the response to the ReleaseLease request. The method always -// closes the http.Response Body. -func (client Client) ReleaseLeaseResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result = autorest.Response{Response: resp} +func (r releaseLeaseOptions) ToOData() *odata.Query { + return nil +} - return +func (r releaseLeaseOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "lease") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_renew.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_renew.go index 69c495bd9898..2a82a0af2a9e 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_renew.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/lease_renew.go @@ -2,96 +2,83 @@ package blobs import ( "context" + "fmt" "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) -func (client Client) RenewLease(ctx context.Context, accountName, containerName, blobName, leaseID string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "RenewLease", "`accountName` cannot be an empty string.") - } +type RenewLeaseResponse struct { + HttpResponse *client.Response +} + +type RenewLeaseInput struct { + LeaseID string +} + +func (c Client) RenewLease(ctx context.Context, containerName, blobName string, input RenewLeaseInput) (resp RenewLeaseResponse, err error) { + if containerName == "" { - return result, validation.NewError("blobs.Client", "RenewLease", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } + if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "RenewLease", "`containerName` must be a lower-cased string.") + return resp, fmt.Errorf("`containerName` must be a lower-cased string") } + if blobName == "" { - return result, validation.NewError("blobs.Client", "RenewLease", "`blobName` cannot be an empty string.") + return resp, fmt.Errorf("`blobName` cannot be an empty string") } - if leaseID == "" { - return result, validation.NewError("blobs.Client", "RenewLease", "`leaseID` cannot be an empty string.") + + if input.LeaseID == "" { + return resp, fmt.Errorf("`input.LeaseID` cannot be an empty string") } - req, err := client.RenewLeasePreparer(ctx, accountName, containerName, blobName, leaseID) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "RenewLease", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPut, + OptionsObject: renewLeaseOptions{ + leaseID: input.LeaseID, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), } - resp, err := client.RenewLeaseSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "RenewLease", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.RenewLeaseResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "RenewLease", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// RenewLeasePreparer prepares the RenewLease request. -func (client Client) RenewLeasePreparer(ctx context.Context, accountName, containerName, blobName, leaseID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "lease"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-lease-action": "renew", - "x-ms-lease-id": leaseID, - } - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) +type renewLeaseOptions struct { + leaseID string } -// RenewLeaseSender sends the RenewLease request. The method will close the -// http.Response Body if it receives an error. -func (client Client) RenewLeaseSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (r renewLeaseOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("x-ms-lease-action", "renew") + headers.Append("x-ms-lease-id", r.leaseID) + return headers } -// RenewLeaseResponder handles the response to the RenewLease request. The method always -// closes the http.Response Body. -func (client Client) RenewLeaseResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result = autorest.Response{Response: resp} +func (r renewLeaseOptions) ToOData() *odata.Query { + return nil +} - return +func (r renewLeaseOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "lease") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/metadata_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/metadata_set.go index ec69152a5f98..604e7a7bd31d 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/metadata_set.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/metadata_set.go @@ -6,10 +6,8 @@ import ( "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" "github.com/tombuildsstuff/giovanni/storage/internal/metadata" ) @@ -22,92 +20,74 @@ type SetMetaDataInput struct { MetaData map[string]string } +type SetMetaDataResponse struct { + HttpResponse *client.Response +} + // SetMetaData marks the specified blob or snapshot for deletion. The blob is later deleted during garbage collection. -func (client Client) SetMetaData(ctx context.Context, accountName, containerName, blobName string, input SetMetaDataInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "GetProperties", "`accountName` cannot be an empty string.") - } +func (c Client) SetMetaData(ctx context.Context, containerName, blobName string, input SetMetaDataInput) (resp SetMetaDataResponse, err error) { + if containerName == "" { - return result, validation.NewError("blobs.Client", "GetProperties", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } + if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "GetProperties", "`containerName` must be a lower-cased string.") + return resp, fmt.Errorf("`containerName` must be a lower-cased string") } + if blobName == "" { - return result, validation.NewError("blobs.Client", "GetProperties", "`blobName` cannot be an empty string.") + return resp, fmt.Errorf("`blobName` cannot be an empty string") } + if err := metadata.Validate(input.MetaData); err != nil { - return result, validation.NewError("blobs.Client", "GetProperties", fmt.Sprintf("`input.MetaData` is not valid: %s.", err)) + return resp, fmt.Errorf(fmt.Sprintf("`input.MetaData` is not valid: %s.", err)) } - req, err := client.SetMetaDataPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "SetMetaData", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPut, + OptionsObject: setMetadataOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), } - resp, err := client.SetMetaDataSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "SetMetaData", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.SetMetaDataResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "SetMetaData", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// SetMetaDataPreparer prepares the SetMetaData request. -func (client Client) SetMetaDataPreparer(ctx context.Context, accountName, containerName, blobName string, input SetMetaDataInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "metadata"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } +type setMetadataOptions struct { + input SetMetaDataInput +} - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID +func (s setMetadataOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + if s.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *s.input.LeaseID) } - - headers = metadata.SetIntoHeaders(headers, input.MetaData) - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + headers.Merge(metadata.SetMetaDataHeaders(s.input.MetaData)) + return headers } -// SetMetaDataSender sends the SetMetaData request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SetMetaDataSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (s setMetadataOptions) ToOData() *odata.Query { + return nil } -// SetMetaDataResponder handles the response to the SetMetaData request. The method always -// closes the http.Response Body. -func (client Client) SetMetaDataResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return +func (s setMetadataOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "metadata") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/properties_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/properties_get.go index 5640687d6d92..86b7c1100bd5 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/properties_get.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/properties_get.go @@ -7,10 +7,8 @@ import ( "strconv" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" "github.com/tombuildsstuff/giovanni/storage/internal/metadata" ) @@ -20,8 +18,8 @@ type GetPropertiesInput struct { LeaseID *string } -type GetPropertiesResult struct { - autorest.Response +type GetPropertiesResponse struct { + HttpResponse *client.Response // The tier of page blob on a premium storage account or tier of block blob on blob storage or general purpose v2 account. AccessTier AccessTier @@ -163,148 +161,127 @@ type GetPropertiesResult struct { } // GetProperties returns all user-defined metadata, standard HTTP properties, and system properties for the blob -func (client Client) GetProperties(ctx context.Context, accountName, containerName, blobName string, input GetPropertiesInput) (result GetPropertiesResult, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "GetProperties", "`accountName` cannot be an empty string.") - } +func (c Client) GetProperties(ctx context.Context, containerName, blobName string, input GetPropertiesInput) (resp GetPropertiesResponse, err error) { + if containerName == "" { - return result, validation.NewError("blobs.Client", "GetProperties", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "GetProperties", "`containerName` must be a lower-cased string.") + return resp, fmt.Errorf("`containerName` must be a lower-cased string") } if blobName == "" { - return result, validation.NewError("blobs.Client", "GetProperties", "`blobName` cannot be an empty string.") + return resp, fmt.Errorf("`blobName` cannot be an empty string") } - req, err := client.GetPropertiesPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "GetProperties", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodHead, + OptionsObject: getPropertiesOptions{ + leaseID: input.LeaseID, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), } - resp, err := client.GetPropertiesSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "GetProperties", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.GetPropertiesResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "GetProperties", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } - return -} - -// GetPropertiesPreparer prepares the GetProperties request. -func (client Client) GetPropertiesPreparer(ctx context.Context, accountName, containerName, blobName string, input GetPropertiesInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID - } - - preparer := autorest.CreatePreparer( - autorest.AsHead(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetPropertiesSender sends the GetProperties request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetPropertiesSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// GetPropertiesResponder handles the response to the GetProperties request. The method always -// closes the http.Response Body. -func (client Client) GetPropertiesResponder(resp *http.Response) (result GetPropertiesResult, err error) { - if resp != nil && resp.Header != nil { - result.AccessTier = AccessTier(resp.Header.Get("x-ms-access-tier")) - result.AccessTierChangeTime = resp.Header.Get(" x-ms-access-tier-change-time") - result.ArchiveStatus = ArchiveStatus(resp.Header.Get(" x-ms-archive-status")) - result.BlobCommittedBlockCount = resp.Header.Get("x-ms-blob-committed-block-count") - result.BlobSequenceNumber = resp.Header.Get("x-ms-blob-sequence-number") - result.BlobType = BlobType(resp.Header.Get("x-ms-blob-type")) - result.CacheControl = resp.Header.Get("Cache-Control") - result.ContentDisposition = resp.Header.Get("Content-Disposition") - result.ContentEncoding = resp.Header.Get("Content-Encoding") - result.ContentLanguage = resp.Header.Get("Content-Language") - result.ContentMD5 = resp.Header.Get("Content-MD5") - result.ContentType = resp.Header.Get("Content-Type") - result.CopyCompletionTime = resp.Header.Get("x-ms-copy-completion-time") - result.CopyDestinationSnapshot = resp.Header.Get("x-ms-copy-destination-snapshot") - result.CopyID = resp.Header.Get("x-ms-copy-id") - result.CopyProgress = resp.Header.Get("x-ms-copy-progress") - result.CopySource = resp.Header.Get("x-ms-copy-source") - result.CopyStatus = CopyStatus(resp.Header.Get("x-ms-copy-status")) - result.CopyStatusDescription = resp.Header.Get("x-ms-copy-status-description") - result.CreationTime = resp.Header.Get("x-ms-creation-time") - result.ETag = resp.Header.Get("Etag") - result.LastModified = resp.Header.Get("Last-Modified") - result.LeaseDuration = LeaseDuration(resp.Header.Get("x-ms-lease-duration")) - result.LeaseState = LeaseState(resp.Header.Get("x-ms-lease-state")) - result.LeaseStatus = LeaseStatus(resp.Header.Get("x-ms-lease-status")) - result.MetaData = metadata.ParseFromHeaders(resp.Header) - - if v := resp.Header.Get("x-ms-access-tier-inferred"); v != "" { - b, innerErr := strconv.ParseBool(v) - if innerErr != nil { - err = fmt.Errorf("Error parsing %q as a bool: %s", v, innerErr) - return + if resp.HttpResponse != nil { + if resp.HttpResponse.Header != nil { + resp.AccessTier = AccessTier(resp.HttpResponse.Header.Get("x-ms-access-tier")) + resp.AccessTierChangeTime = resp.HttpResponse.Header.Get("x-ms-access-tier-change-time") + resp.ArchiveStatus = ArchiveStatus(resp.HttpResponse.Header.Get("x-ms-archive-status")) + resp.BlobCommittedBlockCount = resp.HttpResponse.Header.Get("x-ms-blob-committed-block-count") + resp.BlobSequenceNumber = resp.HttpResponse.Header.Get("x-ms-blob-sequence-number") + resp.BlobType = BlobType(resp.HttpResponse.Header.Get("x-ms-blob-type")) + resp.CacheControl = resp.HttpResponse.Header.Get("Cache-Control") + resp.ContentDisposition = resp.HttpResponse.Header.Get("Content-Disposition") + resp.ContentEncoding = resp.HttpResponse.Header.Get("Content-Encoding") + resp.ContentLanguage = resp.HttpResponse.Header.Get("Content-Language") + resp.ContentMD5 = resp.HttpResponse.Header.Get("Content-MD5") + resp.ContentType = resp.HttpResponse.Header.Get("Content-Type") + resp.CopyCompletionTime = resp.HttpResponse.Header.Get("x-ms-copy-completion-time") + resp.CopyDestinationSnapshot = resp.HttpResponse.Header.Get("x-ms-copy-destination-snapshot") + resp.CopyID = resp.HttpResponse.Header.Get("x-ms-copy-id") + resp.CopyProgress = resp.HttpResponse.Header.Get("x-ms-copy-progress") + resp.CopySource = resp.HttpResponse.Header.Get("x-ms-copy-source") + resp.CopyStatus = CopyStatus(resp.HttpResponse.Header.Get("x-ms-copy-status")) + resp.CopyStatusDescription = resp.HttpResponse.Header.Get("x-ms-copy-status-description") + resp.CreationTime = resp.HttpResponse.Header.Get("x-ms-creation-time") + resp.ETag = resp.HttpResponse.Header.Get("Etag") + resp.LastModified = resp.HttpResponse.Header.Get("Last-Modified") + resp.LeaseDuration = LeaseDuration(resp.HttpResponse.Header.Get("x-ms-lease-duration")) + resp.LeaseState = LeaseState(resp.HttpResponse.Header.Get("x-ms-lease-state")) + resp.LeaseStatus = LeaseStatus(resp.HttpResponse.Header.Get("x-ms-lease-status")) + resp.MetaData = metadata.ParseFromHeaders(resp.HttpResponse.Header) + + if v := resp.HttpResponse.Header.Get("x-ms-access-tier-inferred"); v != "" { + b, innerErr := strconv.ParseBool(v) + if innerErr != nil { + err = fmt.Errorf("error parsing %q as a bool: %s", v, innerErr) + return + } + resp.AccessTierInferred = b } - result.AccessTierInferred = b - } + if v := resp.HttpResponse.Header.Get("Content-Length"); v != "" { + i, innerErr := strconv.Atoi(v) + if innerErr != nil { + err = fmt.Errorf("error parsing %q as an integer: %s", v, innerErr) + } + resp.ContentLength = int64(i) + } - if v := resp.Header.Get("Content-Length"); v != "" { - i, innerErr := strconv.Atoi(v) - if innerErr != nil { - err = fmt.Errorf("Error parsing %q as an integer: %s", v, innerErr) + if v := resp.HttpResponse.Header.Get("x-ms-incremental-copy"); v != "" { + b, innerErr := strconv.ParseBool(v) + if innerErr != nil { + err = fmt.Errorf("error parsing %q as a bool: %s", v, innerErr) + return + } + resp.IncrementalCopy = b } - result.ContentLength = int64(i) + if v := resp.HttpResponse.Header.Get("x-ms-server-encrypted"); v != "" { + b, innerErr := strconv.ParseBool(v) + if innerErr != nil { + err = fmt.Errorf("error parsing %q as a bool: %s", v, innerErr) + return + } + resp.ServerEncrypted = b + } } + } - if v := resp.Header.Get("x-ms-incremental-copy"); v != "" { - b, innerErr := strconv.ParseBool(v) - if innerErr != nil { - err = fmt.Errorf("Error parsing %q as a bool: %s", v, innerErr) - return - } + return +} - result.IncrementalCopy = b - } +type getPropertiesOptions struct { + leaseID *string +} - if v := resp.Header.Get("x-ms-server-encrypted"); v != "" { - b, innerErr := strconv.ParseBool(v) - if innerErr != nil { - err = fmt.Errorf("Error parsing %q as a bool: %s", v, innerErr) - return - } +func (g getPropertiesOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} - result.IncrementalCopy = b - } + if g.leaseID != nil { + headers.Append("x-ms-lease-id", *g.leaseID) } + return headers +} - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return +func (g getPropertiesOptions) ToOData() *odata.Query { + return nil +} + +func (g getPropertiesOptions) ToQuery() *client.QueryParams { + return nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/properties_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/properties_set.go index a8c0ed8cba95..ebe098556ded 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/properties_set.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/properties_set.go @@ -2,13 +2,13 @@ package blobs import ( "context" + "fmt" "net/http" + "strconv" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type SetPropertiesInput struct { @@ -24,44 +24,48 @@ type SetPropertiesInput struct { BlobSequenceNumber *string } -type SetPropertiesResult struct { - autorest.Response +type SetPropertiesResponse struct { + HttpResponse *client.Response BlobSequenceNumber string Etag string } // SetProperties sets system properties on the blob. -func (client Client) SetProperties(ctx context.Context, accountName, containerName, blobName string, input SetPropertiesInput) (result SetPropertiesResult, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "SetProperties", "`accountName` cannot be an empty string.") - } +func (c Client) SetProperties(ctx context.Context, containerName, blobName string, input SetPropertiesInput) (resp SetPropertiesResponse, err error) { + if containerName == "" { - return result, validation.NewError("blobs.Client", "SetProperties", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } + if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "SetProperties", "`containerName` must be a lower-cased string.") + return resp, fmt.Errorf("`containerName` must be a lower-cased string") } + if blobName == "" { - return result, validation.NewError("blobs.Client", "SetProperties", "`blobName` cannot be an empty string.") + return resp, fmt.Errorf("`blobName` cannot be an empty string") } - req, err := client.SetPropertiesPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "SetProperties", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPut, + OptionsObject: setPropertiesOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), } - resp, err := client.SetPropertiesSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "SetProperties", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.SetPropertiesResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "SetProperties", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } @@ -76,81 +80,53 @@ var ( Update SequenceNumberAction = "update" ) -// SetPropertiesPreparer prepares the SetProperties request. -func (client Client) SetPropertiesPreparer(ctx context.Context, accountName, containerName, blobName string, input SetPropertiesInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "properties"), - } +type setPropertiesOptions struct { + input SetPropertiesInput +} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } +func (s setPropertiesOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} - if input.CacheControl != nil { - headers["x-ms-blob-cache-control"] = *input.CacheControl + if s.input.CacheControl != nil { + headers.Append("x-ms-blob-cache-control", *s.input.CacheControl) } - if input.ContentDisposition != nil { - headers["x-ms-blob-content-disposition"] = *input.ContentDisposition + if s.input.ContentDisposition != nil { + headers.Append("x-ms-blob-content-disposition", *s.input.ContentDisposition) } - if input.ContentEncoding != nil { - headers["x-ms-blob-content-encoding"] = *input.ContentEncoding + if s.input.ContentEncoding != nil { + headers.Append("x-ms-blob-content-encoding", *s.input.ContentEncoding) } - if input.ContentLanguage != nil { - headers["x-ms-blob-content-language"] = *input.ContentLanguage + if s.input.ContentLanguage != nil { + headers.Append("x-ms-blob-content-language", *s.input.ContentLanguage) } - if input.ContentMD5 != nil { - headers["x-ms-blob-content-md5"] = *input.ContentMD5 + if s.input.ContentMD5 != nil { + headers.Append("x-ms-blob-content-md5", *s.input.ContentMD5) } - if input.ContentType != nil { - headers["x-ms-blob-content-type"] = *input.ContentType + if s.input.ContentType != nil { + headers.Append("x-ms-blob-content-type", *s.input.ContentType) } - if input.ContentLength != nil { - headers["x-ms-blob-content-length"] = *input.ContentLength + if s.input.ContentLength != nil { + headers.Append("x-ms-blob-content-length", strconv.Itoa(int(*s.input.ContentLength))) } - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID + if s.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *s.input.LeaseID) } - if input.SequenceNumberAction != nil { - headers["x-ms-sequence-number-action"] = string(*input.SequenceNumberAction) + if s.input.SequenceNumberAction != nil { + headers.Append("x-ms-sequence-number-action", string(*s.input.SequenceNumberAction)) } - if input.BlobSequenceNumber != nil { - headers["x-ms-blob-sequence-number"] = *input.BlobSequenceNumber + if s.input.BlobSequenceNumber != nil { + headers.Append("x-ms-blob-sequence-number", *s.input.BlobSequenceNumber) } - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// SetPropertiesSender sends the SetProperties request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SetPropertiesSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (s setPropertiesOptions) ToOData() *odata.Query { + return nil } -// SetPropertiesResponder handles the response to the SetProperties request. The method always -// closes the http.Response Body. -func (client Client) SetPropertiesResponder(resp *http.Response) (result SetPropertiesResult, err error) { - if resp != nil && resp.Header != nil { - result.BlobSequenceNumber = resp.Header.Get("x-ms-blob-sequence-number") - result.Etag = resp.Header.Get("Etag") - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return +func (s setPropertiesOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "properties") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_append_blob.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_append_blob.go index ef2c5025d606..0f3aa30733a5 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_append_blob.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_append_blob.go @@ -6,10 +6,8 @@ import ( "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" "github.com/tombuildsstuff/giovanni/storage/internal/metadata" ) @@ -24,111 +22,96 @@ type PutAppendBlobInput struct { MetaData map[string]string } +type PutAppendBlobResponse struct { + HttpResponse *client.Response +} + // PutAppendBlob is a wrapper around the Put API call (with a stricter input object) // which creates a new append blob, or updates the content of an existing blob. -func (client Client) PutAppendBlob(ctx context.Context, accountName, containerName, blobName string, input PutAppendBlobInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "PutAppendBlob", "`accountName` cannot be an empty string.") - } +func (c Client) PutAppendBlob(ctx context.Context, containerName, blobName string, input PutAppendBlobInput) (resp PutAppendBlobResponse, err error) { + if containerName == "" { - return result, validation.NewError("blobs.Client", "PutAppendBlob", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } + if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "PutAppendBlob", "`containerName` must be a lower-cased string.") + return resp, fmt.Errorf("`containerName` must be a lower-cased string") } + if blobName == "" { - return result, validation.NewError("blobs.Client", "PutAppendBlob", "`blobName` cannot be an empty string.") + return resp, fmt.Errorf("`blobName` cannot be an empty string") } + if err := metadata.Validate(input.MetaData); err != nil { - return result, validation.NewError("blobs.Client", "PutAppendBlob", fmt.Sprintf("`input.MetaData` is not valid: %s.", err)) + return resp, fmt.Errorf(fmt.Sprintf("`input.MetaData` is not valid: %s.", err)) } - req, err := client.PutAppendBlobPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "PutAppendBlob", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: putAppendBlobOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), } - resp, err := client.PutAppendBlobSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "PutAppendBlob", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.PutAppendBlobResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "PutAppendBlob", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// PutAppendBlobPreparer prepares the PutAppendBlob request. -func (client Client) PutAppendBlobPreparer(ctx context.Context, accountName, containerName, blobName string, input PutAppendBlobInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } +type putAppendBlobOptions struct { + input PutAppendBlobInput +} - headers := map[string]interface{}{ - "x-ms-blob-type": string(AppendBlob), - "x-ms-version": APIVersion, +func (p putAppendBlobOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} - // For a page blob or an append blob, the value of this header must be set to zero, - // as Put Blob is used only to initialize the blob - "Content-Length": 0, - } + headers.Append("x-ms-blob-type", string(AppendBlob)) + headers.Append("Content-Length", "0") - if input.CacheControl != nil { - headers["x-ms-blob-cache-control"] = *input.CacheControl + if p.input.CacheControl != nil { + headers.Append("x-ms-blob-cache-control", *p.input.CacheControl) } - if input.ContentDisposition != nil { - headers["x-ms-blob-content-disposition"] = *input.ContentDisposition + if p.input.ContentDisposition != nil { + headers.Append("x-ms-blob-content-disposition", *p.input.ContentDisposition) } - if input.ContentEncoding != nil { - headers["x-ms-blob-content-encoding"] = *input.ContentEncoding + if p.input.ContentEncoding != nil { + headers.Append("x-ms-blob-content-encoding", *p.input.ContentEncoding) } - if input.ContentLanguage != nil { - headers["x-ms-blob-content-language"] = *input.ContentLanguage + if p.input.ContentLanguage != nil { + headers.Append("x-ms-blob-content-language", *p.input.ContentLanguage) } - if input.ContentMD5 != nil { - headers["x-ms-blob-content-md5"] = *input.ContentMD5 + if p.input.ContentMD5 != nil { + headers.Append("x-ms-blob-content-md5", *p.input.ContentMD5) } - if input.ContentType != nil { - headers["x-ms-blob-content-type"] = *input.ContentType + if p.input.ContentType != nil { + headers.Append("x-ms-blob-content-type", *p.input.ContentType) } - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID + if p.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *p.input.LeaseID) } - headers = metadata.SetIntoHeaders(headers, input.MetaData) - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + headers.Merge(metadata.SetMetaDataHeaders(p.input.MetaData)) + return headers } -// PutAppendBlobSender sends the PutAppendBlob request. The method will close the -// http.Response Body if it receives an error. -func (client Client) PutAppendBlobSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (p putAppendBlobOptions) ToOData() *odata.Query { + return nil } -// PutAppendBlobResponder handles the response to the PutAppendBlob request. The method always -// closes the http.Response Body. -func (client Client) PutAppendBlobResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return +func (p putAppendBlobOptions) ToQuery() *client.QueryParams { + return nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block.go index 6d41bda13b55..a6059c4aed27 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block.go @@ -2,13 +2,13 @@ package blobs import ( "context" + "fmt" "net/http" + "strconv" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type PutBlockInput struct { @@ -18,109 +18,91 @@ type PutBlockInput struct { LeaseID *string } -type PutBlockResult struct { - autorest.Response +type PutBlockResponse struct { + HttpResponse *client.Response ContentMD5 string } // PutBlock creates a new block to be committed as part of a blob. -func (client Client) PutBlock(ctx context.Context, accountName, containerName, blobName string, input PutBlockInput) (result PutBlockResult, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "PutBlock", "`accountName` cannot be an empty string.") - } +func (c Client) PutBlock(ctx context.Context, containerName, blobName string, input PutBlockInput) (resp PutBlockResponse, err error) { + if containerName == "" { - return result, validation.NewError("blobs.Client", "PutBlock", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } + if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "PutBlock", "`containerName` must be a lower-cased string.") + return resp, fmt.Errorf("`containerName` must be a lower-cased string") } + if blobName == "" { - return result, validation.NewError("blobs.Client", "PutBlock", "`blobName` cannot be an empty string.") + return resp, fmt.Errorf("`blobName` cannot be an empty string") } + if input.BlockID == "" { - return result, validation.NewError("blobs.Client", "PutBlock", "`input.BlockID` cannot be an empty string.") + return resp, fmt.Errorf("`input.BlockID` cannot be an empty string") } + if len(input.Content) == 0 { - return result, validation.NewError("blobs.Client", "PutBlock", "`input.Content` cannot be empty.") + return resp, fmt.Errorf("`input.Content` cannot be empty") + } + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: putBlockOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), } - req, err := client.PutBlockPreparer(ctx, accountName, containerName, blobName, input) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "PutBlock", nil, "Failure preparing request") + err = fmt.Errorf("building request: %+v", err) return } - resp, err := client.PutBlockSender(req) + err = req.Marshal(&input.Content) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "PutBlock", resp, "Failure sending request") - return + return resp, fmt.Errorf("marshalling request: %v", err) } - result, err = client.PutBlockResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "PutBlock", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// PutBlockPreparer prepares the PutBlock request. -func (client Client) PutBlockPreparer(ctx context.Context, accountName, containerName, blobName string, input PutBlockInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "block"), - "blockid": autorest.Encode("query", input.BlockID), - } +type putBlockOptions struct { + input PutBlockInput +} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "Content-Length": int(len(input.Content)), - } +func (p putBlockOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("Content-Length", strconv.Itoa(len(p.input.Content))) - if input.ContentMD5 != nil { - headers["x-ms-blob-content-md5"] = *input.ContentMD5 + if p.input.ContentMD5 != nil { + headers.Append("x-ms-blob-content-md5", *p.input.ContentMD5) } - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID + if p.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *p.input.LeaseID) } - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers), - autorest.WithBytes(&input.Content)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// PutBlockSender sends the PutBlock request. The method will close the -// http.Response Body if it receives an error. -func (client Client) PutBlockSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (p putBlockOptions) ToOData() *odata.Query { + return nil } -// PutBlockResponder handles the response to the PutBlock request. The method always -// closes the http.Response Body. -func (client Client) PutBlockResponder(resp *http.Response) (result PutBlockResult, err error) { - if resp != nil && resp.Header != nil { - result.ContentMD5 = resp.Header.Get("Content-MD5") - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return +func (p putBlockOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "block") + out.Append("blockid", p.input.BlockID) + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block_blob.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block_blob.go index f5c1a971b306..462ea17272a0 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block_blob.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block_blob.go @@ -4,12 +4,11 @@ import ( "context" "fmt" "net/http" + "strconv" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" "github.com/tombuildsstuff/giovanni/storage/internal/metadata" ) @@ -25,120 +24,107 @@ type PutBlockBlobInput struct { MetaData map[string]string } +type PutBlockBlobResponse struct { + HttpResponse *client.Response +} + // PutBlockBlob is a wrapper around the Put API call (with a stricter input object) // which creates a new block append blob, or updates the content of an existing block blob. -func (client Client) PutBlockBlob(ctx context.Context, accountName, containerName, blobName string, input PutBlockBlobInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "PutBlockBlob", "`accountName` cannot be an empty string.") - } +func (c Client) PutBlockBlob(ctx context.Context, containerName, blobName string, input PutBlockBlobInput) (resp PutBlockBlobResponse, err error) { + if containerName == "" { - return result, validation.NewError("blobs.Client", "PutBlockBlob", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } + if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "PutBlockBlob", "`containerName` must be a lower-cased string.") + return resp, fmt.Errorf("`containerName` must be a lower-cased string") } + if blobName == "" { - return result, validation.NewError("blobs.Client", "PutBlockBlob", "`blobName` cannot be an empty string.") + return resp, fmt.Errorf("`blobName` cannot be an empty string") } + if input.Content != nil && len(*input.Content) == 0 { - return result, validation.NewError("blobs.Client", "PutBlockBlob", "`input.Content` must either be nil or not empty.") + return resp, fmt.Errorf("`input.Content` must either be nil or not empty") } + if err := metadata.Validate(input.MetaData); err != nil { - return result, validation.NewError("blobs.Client", "PutBlockBlob", fmt.Sprintf("`input.MetaData` is not valid: %s.", err)) + return resp, fmt.Errorf(fmt.Sprintf("`input.MetaData` is not valid: %s.", err)) + } + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: putBlockBlobOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), } - req, err := client.PutBlockBlobPreparer(ctx, accountName, containerName, blobName, input) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "PutBlockBlob", nil, "Failure preparing request") + err = fmt.Errorf("building request: %+v", err) return } - resp, err := client.PutBlockBlobSender(req) + err = req.Marshal(&input.Content) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "PutBlockBlob", resp, "Failure sending request") - return + return resp, fmt.Errorf("marshalling request: %v", err) } - result, err = client.PutBlockBlobResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "PutBlockBlob", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// PutBlockBlobPreparer prepares the PutBlockBlob request. -func (client Client) PutBlockBlobPreparer(ctx context.Context, accountName, containerName, blobName string, input PutBlockBlobInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } +type putBlockBlobOptions struct { + input PutBlockBlobInput +} - headers := map[string]interface{}{ - "x-ms-blob-type": string(BlockBlob), - "x-ms-version": APIVersion, - } +func (p putBlockBlobOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("x-ms-blob-type", string(BlockBlob)) - if input.CacheControl != nil { - headers["x-ms-blob-cache-control"] = *input.CacheControl - } - if input.ContentDisposition != nil { - headers["x-ms-blob-content-disposition"] = *input.ContentDisposition + if p.input.CacheControl != nil { + headers.Append("x-ms-blob-cache-control", *p.input.CacheControl) } - if input.ContentEncoding != nil { - headers["x-ms-blob-content-encoding"] = *input.ContentEncoding + if p.input.ContentDisposition != nil { + headers.Append("x-ms-blob-content-disposition", *p.input.ContentDisposition) } - if input.ContentLanguage != nil { - headers["x-ms-blob-content-language"] = *input.ContentLanguage + if p.input.ContentEncoding != nil { + headers.Append("x-ms-blob-content-encoding", *p.input.ContentEncoding) } - if input.ContentMD5 != nil { - headers["x-ms-blob-content-md5"] = *input.ContentMD5 + if p.input.ContentLanguage != nil { + headers.Append("x-ms-blob-content-language", *p.input.ContentLanguage) } - if input.ContentType != nil { - headers["x-ms-blob-content-type"] = *input.ContentType + if p.input.ContentMD5 != nil { + headers.Append("x-ms-blob-content-md5", *p.input.ContentMD5) } - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID + if p.input.ContentType != nil { + headers.Append("x-ms-blob-content-type", *p.input.ContentType) } - if input.Content != nil { - headers["Content-Length"] = int(len(*input.Content)) + if p.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *p.input.LeaseID) } - - headers = metadata.SetIntoHeaders(headers, input.MetaData) - - decorators := []autorest.PrepareDecorator{ - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers), + if p.input.Content != nil { + headers.Append("Content-Length", strconv.Itoa(len(*p.input.Content))) } - if input.Content != nil { - decorators = append(decorators, autorest.WithBytes(input.Content)) - } + headers.Merge(metadata.SetMetaDataHeaders(p.input.MetaData)) - preparer := autorest.CreatePreparer(decorators...) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// PutBlockBlobSender sends the PutBlockBlob request. The method will close the -// http.Response Body if it receives an error. -func (client Client) PutBlockBlobSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (p putBlockBlobOptions) ToOData() *odata.Query { + return nil } -// PutBlockBlobResponder handles the response to the PutBlockBlob request. The method always -// closes the http.Response Body. -func (client Client) PutBlockBlobResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return +func (p putBlockBlobOptions) ToQuery() *client.QueryParams { + return nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block_blob_file.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block_blob_file.go index b7499498aeca..932fb320607d 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block_blob_file.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block_blob_file.go @@ -8,10 +8,10 @@ import ( ) // PutBlockBlobFromFile is a helper method which takes a file, and automatically chunks it up, rather than having to do this yourself -func (client Client) PutBlockBlobFromFile(ctx context.Context, accountName, containerName, blobName string, file *os.File, input PutBlockBlobInput) error { +func (c Client) PutBlockBlobFromFile(ctx context.Context, containerName, blobName string, file *os.File, input PutBlockBlobInput) error { fileInfo, err := file.Stat() if err != nil { - return fmt.Errorf("Error loading file info: %s", err) + return fmt.Errorf("error loading file info: %s", err) } fileSize := fileInfo.Size() @@ -26,8 +26,8 @@ func (client Client) PutBlockBlobFromFile(ctx context.Context, accountName, cont input.Content = &bytes - if _, err = client.PutBlockBlob(ctx, accountName, containerName, blobName, input); err != nil { - return fmt.Errorf("Error putting bytes: %s", err) + if _, err = c.PutBlockBlob(ctx, containerName, blobName, input); err != nil { + return fmt.Errorf("error putting bytes: %s", err) } return nil diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block_list.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block_list.go index f80524790be5..bfe451b941c9 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block_list.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block_list.go @@ -2,13 +2,12 @@ package blobs import ( "context" + "fmt" "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" "github.com/tombuildsstuff/giovanni/storage/internal/metadata" ) @@ -34,8 +33,8 @@ type PutBlockListInput struct { LeaseID *string } -type PutBlockListResult struct { - autorest.Response +type PutBlockListResponse struct { + HttpResponse *client.Response ContentMD5 string ETag string @@ -45,113 +44,99 @@ type PutBlockListResult struct { // PutBlockList writes a blob by specifying the list of block IDs that make up the blob. // In order to be written as part of a blob, a block must have been successfully written // to the server in a prior Put Block operation. -func (client Client) PutBlockList(ctx context.Context, accountName, containerName, blobName string, input PutBlockListInput) (result PutBlockListResult, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "PutBlockList", "`accountName` cannot be an empty string.") - } +func (c Client) PutBlockList(ctx context.Context, containerName, blobName string, input PutBlockListInput) (resp PutBlockListResponse, err error) { + if containerName == "" { - return result, validation.NewError("blobs.Client", "PutBlockList", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } + if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "PutBlockList", "`containerName` must be a lower-cased string.") + return resp, fmt.Errorf("`containerName` must be a lower-cased string") } + if blobName == "" { - return result, validation.NewError("blobs.Client", "PutBlockList", "`blobName` cannot be an empty string.") + return resp, fmt.Errorf("`blobName` cannot be an empty string") } - req, err := client.PutBlockListPreparer(ctx, accountName, containerName, blobName, input) + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: putBlockListOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), + } + + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "PutBlockList", nil, "Failure preparing request") + err = fmt.Errorf("building request: %+v", err) return } - resp, err := client.PutBlockListSender(req) + err = req.Marshal(&input.BlockList) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "PutBlockList", resp, "Failure sending request") - return + return resp, fmt.Errorf("marshalling request: %v", err) } - result, err = client.PutBlockListResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "PutBlockList", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } + if resp.HttpResponse != nil { + if resp.HttpResponse.Header != nil { + resp.ContentMD5 = resp.HttpResponse.Header.Get("Content-MD5") + resp.ETag = resp.HttpResponse.Header.Get("ETag") + resp.LastModified = resp.HttpResponse.Header.Get("Last-Modified") + } + } + return } -// PutBlockListPreparer prepares the PutBlockList request. -func (client Client) PutBlockListPreparer(ctx context.Context, accountName, containerName, blobName string, input PutBlockListInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "blocklist"), - } +type putBlockListOptions struct { + input PutBlockListInput +} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } +func (p putBlockListOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} - if input.CacheControl != nil { - headers["x-ms-blob-cache-control"] = *input.CacheControl + if p.input.CacheControl != nil { + headers.Append("x-ms-blob-cache-control", *p.input.CacheControl) } - if input.ContentDisposition != nil { - headers["x-ms-blob-content-disposition"] = *input.ContentDisposition + if p.input.ContentDisposition != nil { + headers.Append("x-ms-blob-content-disposition", *p.input.ContentDisposition) } - if input.ContentEncoding != nil { - headers["x-ms-blob-content-encoding"] = *input.ContentEncoding + if p.input.ContentEncoding != nil { + headers.Append("x-ms-blob-content-encoding", *p.input.ContentEncoding) } - if input.ContentLanguage != nil { - headers["x-ms-blob-content-language"] = *input.ContentLanguage + if p.input.ContentLanguage != nil { + headers.Append("x-ms-blob-content-language", *p.input.ContentLanguage) } - if input.ContentMD5 != nil { - headers["x-ms-blob-content-md5"] = *input.ContentMD5 + if p.input.ContentMD5 != nil { + headers.Append("x-ms-blob-content-md5", *p.input.ContentMD5) } - if input.ContentType != nil { - headers["x-ms-blob-content-type"] = *input.ContentType + if p.input.ContentType != nil { + headers.Append("x-ms-blob-content-type", *p.input.ContentType) } - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID + if p.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *p.input.LeaseID) } - headers = metadata.SetIntoHeaders(headers, input.MetaData) + headers.Merge(metadata.SetMetaDataHeaders(p.input.MetaData)) - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers), - autorest.WithXML(input.BlockList)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// PutBlockListSender sends the PutBlockList request. The method will close the -// http.Response Body if it receives an error. -func (client Client) PutBlockListSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (p putBlockListOptions) ToOData() *odata.Query { + return nil } -// PutBlockListResponder handles the response to the PutBlockList request. The method always -// closes the http.Response Body. -func (client Client) PutBlockListResponder(resp *http.Response) (result PutBlockListResult, err error) { - if resp != nil && resp.Header != nil { - result.ContentMD5 = resp.Header.Get("Content-MD5") - result.ETag = resp.Header.Get("ETag") - result.LastModified = resp.Header.Get("Last-Modified") - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return +func (p putBlockListOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "blocklist") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block_url.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block_url.go index 95ad974698bd..cd8487c5c265 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block_url.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_block_url.go @@ -2,13 +2,12 @@ package blobs import ( "context" + "fmt" "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type PutBlockFromURLInput struct { @@ -20,110 +19,94 @@ type PutBlockFromURLInput struct { Range *string } -type PutBlockFromURLResult struct { - autorest.Response - ContentMD5 string +type PutBlockFromURLResponse struct { + HttpResponse *client.Response + ContentMD5 string } // PutBlockFromURL creates a new block to be committed as part of a blob where the contents are read from a URL -func (client Client) PutBlockFromURL(ctx context.Context, accountName, containerName, blobName string, input PutBlockFromURLInput) (result PutBlockFromURLResult, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "PutBlockFromURL", "`accountName` cannot be an empty string.") - } +func (c Client) PutBlockFromURL(ctx context.Context, containerName, blobName string, input PutBlockFromURLInput) (resp PutBlockFromURLResponse, err error) { + if containerName == "" { - return result, validation.NewError("blobs.Client", "PutBlockFromURL", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } + if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "PutBlockFromURL", "`containerName` must be a lower-cased string.") + return resp, fmt.Errorf("`containerName` must be a lower-cased string") } + if blobName == "" { - return result, validation.NewError("blobs.Client", "PutBlockFromURL", "`blobName` cannot be an empty string.") + return resp, fmt.Errorf("`blobName` cannot be an empty string") } + if input.BlockID == "" { - return result, validation.NewError("blobs.Client", "PutBlockFromURL", "`input.BlockID` cannot be an empty string.") + return resp, fmt.Errorf("`input.BlockID` cannot be an empty string") } + if input.CopySource == "" { - return result, validation.NewError("blobs.Client", "PutBlockFromURL", "`input.CopySource` cannot be an empty string.") + return resp, fmt.Errorf("`input.CopySource` cannot be an empty string") } - req, err := client.PutBlockFromURLPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "PutBlockFromURL", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: putBlockUrlOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), } - resp, err := client.PutBlockFromURLSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "PutBlockFromURL", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.PutBlockFromURLResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "PutBlockFromURL", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } + if resp.HttpResponse != nil { + if resp.HttpResponse.Header != nil { + resp.ContentMD5 = resp.HttpResponse.Header.Get("Content-MD5") + } + } + return } -// PutBlockFromURLPreparer prepares the PutBlockFromURL request. -func (client Client) PutBlockFromURLPreparer(ctx context.Context, accountName, containerName, blobName string, input PutBlockFromURLInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } +type putBlockUrlOptions struct { + input PutBlockFromURLInput +} - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "block"), - "blockid": autorest.Encode("query", input.BlockID), - } +func (p putBlockUrlOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-copy-source": input.CopySource, - } + headers.Append("x-ms-copy-source", p.input.CopySource) - if input.ContentMD5 != nil { - headers["x-ms-source-content-md5"] = *input.ContentMD5 + if p.input.ContentMD5 != nil { + headers.Append("x-ms-source-content-md5", *p.input.ContentMD5) } - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID + if p.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *p.input.LeaseID) } - if input.Range != nil { - headers["x-ms-source-range"] = *input.Range + if p.input.Range != nil { + headers.Append("x-ms-source-range", *p.input.Range) } - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// PutBlockFromURLSender sends the PutBlockFromURL request. The method will close the -// http.Response Body if it receives an error. -func (client Client) PutBlockFromURLSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (p putBlockUrlOptions) ToOData() *odata.Query { + return nil } -// PutBlockFromURLResponder handles the response to the PutBlockFromURL request. The method always -// closes the http.Response Body. -func (client Client) PutBlockFromURLResponder(resp *http.Response) (result PutBlockFromURLResult, err error) { - if resp != nil && resp.Header != nil { - result.ContentMD5 = resp.Header.Get("Content-MD5") - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return +func (p putBlockUrlOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "block") + out.Append("blockid", p.input.BlockID) + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_page_blob.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_page_blob.go index 4cfba95ae37b..2b733c4c1311 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_page_blob.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_page_blob.go @@ -2,13 +2,13 @@ package blobs import ( "context" + "fmt" "net/http" + "strconv" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" "github.com/tombuildsstuff/giovanni/storage/internal/metadata" ) @@ -27,122 +27,117 @@ type PutPageBlobInput struct { AccessTier *AccessTier } +type PutPageBlobResponse struct { + HttpResponse *client.Response +} + // PutPageBlob is a wrapper around the Put API call (with a stricter input object) // which creates a new block blob, or updates the content of an existing page blob. -func (client Client) PutPageBlob(ctx context.Context, accountName, containerName, blobName string, input PutPageBlobInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "PutPageBlob", "`accountName` cannot be an empty string.") - } +func (c Client) PutPageBlob(ctx context.Context, containerName, blobName string, input PutPageBlobInput) (resp PutPageBlobResponse, err error) { + if containerName == "" { - return result, validation.NewError("blobs.Client", "PutPageBlob", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } + if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "PutPageBlob", "`containerName` must be a lower-cased string.") + return resp, fmt.Errorf("`containerName` must be a lower-cased string") } + if blobName == "" { - return result, validation.NewError("blobs.Client", "PutPageBlob", "`blobName` cannot be an empty string.") + return resp, fmt.Errorf("`blobName` cannot be an empty string") } + if input.BlobContentLengthBytes == 0 || input.BlobContentLengthBytes%512 != 0 { - return result, validation.NewError("blobs.Client", "PutPageBlob", "`input.BlobContentLengthBytes` must be aligned to a 512-byte boundary.") + return resp, fmt.Errorf("`input.BlobContentLengthBytes` must be aligned to a 512-byte boundary") } - req, err := client.PutPageBlobPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "PutPageBlob", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: putPageBlobOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), } - resp, err := client.PutPageBlobSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "PutPageBlob", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.PutPageBlobResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "PutPageBlob", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// PutPageBlobPreparer prepares the PutPageBlob request. -func (client Client) PutPageBlobPreparer(ctx context.Context, accountName, containerName, blobName string, input PutPageBlobInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } +type putPageBlobOptions struct { + input PutPageBlobInput +} - headers := map[string]interface{}{ - "x-ms-blob-type": string(PageBlob), - "x-ms-version": APIVersion, +func (p putPageBlobOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} - // For a page blob or an page blob, the value of this header must be set to zero, - // as Put Blob is used only to initialize the blob - "Content-Length": 0, + headers.Append("x-ms-blob-type", string(PageBlob)) - // This header specifies the maximum size for the page blob, up to 8 TB. - // The page blob size must be aligned to a 512-byte boundary. - "x-ms-blob-content-length": input.BlobContentLengthBytes, - } + // For a page blob or an page blob, the value of this header must be set to zero, + // as Put Blob is used only to initialize the blob + headers.Append("Content-Length", "0") - if input.AccessTier != nil { - headers["x-ms-access-tier"] = string(*input.AccessTier) - } - if input.BlobSequenceNumber != nil { - headers["x-ms-blob-sequence-number"] = *input.BlobSequenceNumber + // This header specifies the maximum size for the page blob, up to 8 TB. + // The page blob size must be aligned to a 512-byte boundary. + headers.Append("x-ms-blob-content-length", strconv.Itoa(int(p.input.BlobContentLengthBytes))) + + if p.input.AccessTier != nil { + headers.Append("x-ms-access-tier", string(*p.input.AccessTier)) } - if input.CacheControl != nil { - headers["x-ms-blob-cache-control"] = *input.CacheControl + if p.input.BlobSequenceNumber != nil { + headers.Append("x-ms-blob-sequence-number", strconv.Itoa(int(*p.input.BlobSequenceNumber))) } - if input.ContentDisposition != nil { - headers["x-ms-blob-content-disposition"] = *input.ContentDisposition + + if p.input.CacheControl != nil { + headers.Append("x-ms-blob-cache-control", *p.input.CacheControl) } - if input.ContentEncoding != nil { - headers["x-ms-blob-content-encoding"] = *input.ContentEncoding + + if p.input.ContentDisposition != nil { + headers.Append("x-ms-blob-content-disposition", *p.input.ContentDisposition) } - if input.ContentLanguage != nil { - headers["x-ms-blob-content-language"] = *input.ContentLanguage + + if p.input.ContentEncoding != nil { + headers.Append("x-ms-blob-content-encoding", *p.input.ContentEncoding) } - if input.ContentMD5 != nil { - headers["x-ms-blob-content-md5"] = *input.ContentMD5 + + if p.input.ContentLanguage != nil { + headers.Append("x-ms-blob-content-language", *p.input.ContentLanguage) } - if input.ContentType != nil { - headers["x-ms-blob-content-type"] = *input.ContentType + + if p.input.ContentMD5 != nil { + headers.Append("x-ms-blob-content-md5", *p.input.ContentMD5) } - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID + + if p.input.ContentType != nil { + headers.Append("x-ms-blob-content-type", *p.input.ContentType) } - headers = metadata.SetIntoHeaders(headers, input.MetaData) + if p.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *p.input.LeaseID) + } - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + headers.Merge(metadata.SetMetaDataHeaders(p.input.MetaData)) + return headers } -// PutPageBlobSender sends the PutPageBlob request. The method will close the -// http.Response Body if it receives an error. -func (client Client) PutPageBlobSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (p putPageBlobOptions) ToOData() *odata.Query { + return nil } -// PutPageBlobResponder handles the response to the PutPageBlob request. The method always -// closes the http.Response Body. -func (client Client) PutPageBlobResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return +func (p putPageBlobOptions) ToQuery() *client.QueryParams { + return nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_page_clear.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_page_clear.go index 59feaa5d93d0..1a995138d166 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_page_clear.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_page_clear.go @@ -6,10 +6,8 @@ import ( "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type PutPageClearInput struct { @@ -19,95 +17,81 @@ type PutPageClearInput struct { LeaseID *string } +type PutPageClearResponse struct { + HttpResponse *client.Response +} + // PutPageClear clears a range of pages within a page blob. -func (client Client) PutPageClear(ctx context.Context, accountName, containerName, blobName string, input PutPageClearInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "PutPageClear", "`accountName` cannot be an empty string.") - } +func (c Client) PutPageClear(ctx context.Context, containerName, blobName string, input PutPageClearInput) (resp PutPageClearResponse, err error) { + if containerName == "" { - return result, validation.NewError("blobs.Client", "PutPageClear", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } + if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "PutPageClear", "`containerName` must be a lower-cased string.") + return resp, fmt.Errorf("`containerName` must be a lower-cased string") } + if blobName == "" { - return result, validation.NewError("blobs.Client", "PutPageClear", "`blobName` cannot be an empty string.") + return resp, fmt.Errorf("`blobName` cannot be an empty string") } + if input.StartByte < 0 { - return result, validation.NewError("blobs.Client", "PutPageClear", "`input.StartByte` must be greater than or equal to 0.") + return resp, fmt.Errorf("`input.StartByte` must be greater than or equal to 0") } + if input.EndByte <= 0 { - return result, validation.NewError("blobs.Client", "PutPageClear", "`input.EndByte` must be greater than 0.") + return resp, fmt.Errorf("`input.EndByte` must be greater than 0") } - req, err := client.PutPageClearPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "PutPageClear", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: putPageClearOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), } - resp, err := client.PutPageClearSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "PutPageClear", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.PutPageClearResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "PutPageClear", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// PutPageClearPreparer prepares the PutPageClear request. -func (client Client) PutPageClearPreparer(ctx context.Context, accountName, containerName, blobName string, input PutPageClearInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } +type putPageClearOptions struct { + input PutPageClearInput +} - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "page"), - } +func (p putPageClearOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-page-write": "clear", - "x-ms-range": fmt.Sprintf("bytes=%d-%d", input.StartByte, input.EndByte), - } + headers.Append("x-ms-page-write", "clear") + headers.Append("x-ms-range", fmt.Sprintf("bytes=%d-%d", p.input.StartByte, p.input.EndByte)) - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID + if p.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *p.input.LeaseID) } - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// PutPageClearSender sends the PutPageClear request. The method will close the -// http.Response Body if it receives an error. -func (client Client) PutPageClearSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (p putPageClearOptions) ToOData() *odata.Query { + return nil } -// PutPageClearResponder handles the response to the PutPageClear request. The method always -// closes the http.Response Body. -func (client Client) PutPageClearResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return +func (p putPageClearOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "page") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_page_update.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_page_update.go index 3799381e5525..448fe343d903 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_page_update.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/put_page_update.go @@ -1,15 +1,16 @@ package blobs import ( + "bytes" "context" "fmt" + "io" "net/http" + "strconv" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type PutPageUpdateInput struct { @@ -27,8 +28,8 @@ type PutPageUpdateInput struct { LeaseID *string } -type PutPageUpdateResult struct { - autorest.Response +type PutPageUpdateResponse struct { + HttpResponse *client.Response BlobSequenceNumber string ContentMD5 string @@ -36,129 +37,120 @@ type PutPageUpdateResult struct { } // PutPageUpdate writes a range of pages to a page blob. -func (client Client) PutPageUpdate(ctx context.Context, accountName, containerName, blobName string, input PutPageUpdateInput) (result PutPageUpdateResult, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "PutPageUpdate", "`accountName` cannot be an empty string.") - } +func (c Client) PutPageUpdate(ctx context.Context, containerName, blobName string, input PutPageUpdateInput) (resp PutPageUpdateResponse, err error) { + if containerName == "" { - return result, validation.NewError("blobs.Client", "PutPageUpdate", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } + if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "PutPageUpdate", "`containerName` must be a lower-cased string.") + return resp, fmt.Errorf("`containerName` must be a lower-cased string") } + if blobName == "" { - return result, validation.NewError("blobs.Client", "PutPageUpdate", "`blobName` cannot be an empty string.") + return resp, fmt.Errorf("`blobName` cannot be an empty string") } + if input.StartByte < 0 { - return result, validation.NewError("blobs.Client", "PutPageUpdate", "`input.StartByte` must be greater than or equal to 0.") + return resp, fmt.Errorf("`input.StartByte` must be greater than or equal to 0") } + if input.EndByte <= 0 { - return result, validation.NewError("blobs.Client", "PutPageUpdate", "`input.EndByte` must be greater than 0.") + return resp, fmt.Errorf("`input.EndByte` must be greater than 0") } expectedSize := (input.EndByte - input.StartByte) + 1 actualSize := int64(len(input.Content)) if expectedSize != actualSize { - return result, validation.NewError("blobs.Client", "PutPageUpdate", fmt.Sprintf("Content Size was defined as %d but got %d.", expectedSize, actualSize)) + return resp, fmt.Errorf(fmt.Sprintf("Content Size was defined as %d but got %d.", expectedSize, actualSize)) } - req, err := client.PutPageUpdatePreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "PutPageUpdate", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: putPageUpdateOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), } - resp, err := client.PutPageUpdateSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "PutPageUpdate", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.PutPageUpdateResponder(resp) + req.Body = io.NopCloser(bytes.NewReader(input.Content)) + req.ContentLength = int64(len(input.Content)) + + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "PutPageUpdate", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } + if resp.HttpResponse != nil && resp.HttpResponse.Header != nil { + resp.BlobSequenceNumber = resp.HttpResponse.Header.Get("x-ms-blob-sequence-number") + resp.ContentMD5 = resp.HttpResponse.Header.Get("Content-MD5") + resp.LastModified = resp.HttpResponse.Header.Get("Last-Modified") + } + return } -// PutPageUpdatePreparer prepares the PutPageUpdate request. -func (client Client) PutPageUpdatePreparer(ctx context.Context, accountName, containerName, blobName string, input PutPageUpdateInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } +type putPageUpdateOptions struct { + input PutPageUpdateInput +} - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "page"), - } +func (p putPageUpdateOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("x-ms-page-write", "update") + headers.Append("x-ms-range", fmt.Sprintf("bytes=%d-%d", p.input.StartByte, p.input.EndByte)) + headers.Append("Content-Length", strconv.Itoa(len(p.input.Content))) - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-page-write": "update", - "x-ms-range": fmt.Sprintf("bytes=%d-%d", input.StartByte, input.EndByte), - "Content-Length": int(len(input.Content)), + if p.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *p.input.LeaseID) } - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID - } - if input.IfSequenceNumberEQ != nil { - headers["x-ms-if-sequence-number-eq"] = *input.IfSequenceNumberEQ + if p.input.IfSequenceNumberEQ != nil { + headers.Append("x-ms-if-sequence-number-eq", *p.input.IfSequenceNumberEQ) } - if input.IfSequenceNumberLE != nil { - headers["x-ms-if-sequence-number-le"] = *input.IfSequenceNumberLE + + if p.input.IfSequenceNumberLE != nil { + headers.Append("x-ms-if-sequence-number-le", *p.input.IfSequenceNumberLE) } - if input.IfSequenceNumberLT != nil { - headers["x-ms-if-sequence-number-lt"] = *input.IfSequenceNumberLT + + if p.input.IfSequenceNumberLT != nil { + headers.Append("x-ms-if-sequence-number-lt", *p.input.IfSequenceNumberLT) } - if input.IfModifiedSince != nil { - headers["If-Modified-Since"] = *input.IfModifiedSince + + if p.input.IfModifiedSince != nil { + headers.Append("If-Modified-Since", *p.input.IfModifiedSince) } - if input.IfUnmodifiedSince != nil { - headers["If-Unmodified-Since"] = *input.IfUnmodifiedSince + + if p.input.IfUnmodifiedSince != nil { + headers.Append("If-Unmodified-Since", *p.input.IfUnmodifiedSince) } - if input.IfMatch != nil { - headers["If-Match"] = *input.IfMatch + + if p.input.IfMatch != nil { + headers.Append("If-Match", *p.input.IfMatch) } - if input.IfNoneMatch != nil { - headers["If-None-Match"] = *input.IfNoneMatch + + if p.input.IfNoneMatch != nil { + headers.Append("If-None-Match", *p.input.IfNoneMatch) } - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers), - autorest.WithBytes(&input.Content)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// PutPageUpdateSender sends the PutPageUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client Client) PutPageUpdateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (p putPageUpdateOptions) ToOData() *odata.Query { + return nil } -// PutPageUpdateResponder handles the response to the PutPageUpdate request. The method always -// closes the http.Response Body. -func (client Client) PutPageUpdateResponder(resp *http.Response) (result PutPageUpdateResult, err error) { - if resp != nil && resp.Header != nil { - result.BlobSequenceNumber = resp.Header.Get("x-ms-blob-sequence-number") - result.ContentMD5 = resp.Header.Get("Content-MD5") - result.LastModified = resp.Header.Get("Last-Modified") - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return +func (p putPageUpdateOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "page") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/resource_id.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/resource_id.go index 4057cf275676..a31673f4e25a 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/resource_id.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/resource_id.go @@ -5,51 +5,78 @@ import ( "net/url" "strings" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" + "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts" ) -// GetResourceID returns the Resource ID for the given Blob -// This can be useful when, for example, you're using this as a unique identifier -func (client Client) GetResourceID(accountName, containerName, blobName string) string { - domain := endpoints.GetBlobEndpoint(client.BaseURI, accountName) - return fmt.Sprintf("%s/%s/%s", domain, containerName, blobName) -} +// TODO: update this to implement `resourceids.ResourceId` once +// https://github.com/hashicorp/go-azure-helpers/issues/187 is fixed +var _ resourceids.Id = BlobId{} + +type BlobId struct { + // AccountId specifies the ID of the Storage Account where this Blob exists. + AccountId accounts.AccountId -type ResourceID struct { - AccountName string + // ContainerName specifies the name of the Container within this Storage Account where this + // Blob exists. ContainerName string - BlobName string + + // BlobName specifies the name of this Blob. + BlobName string +} + +func NewBlobID(accountId accounts.AccountId, containerName, blobName string) BlobId { + return BlobId{ + AccountId: accountId, + ContainerName: containerName, + BlobName: blobName, + } } -// ParseResourceID parses the Resource ID and returns an object which can be used -// to interact with the Blob Resource -func ParseResourceID(id string) (*ResourceID, error) { +func (b BlobId) ID() string { + return fmt.Sprintf("%s/%s/%s", b.AccountId.ID(), b.ContainerName, b.BlobName) +} + +func (b BlobId) String() string { + components := []string{ + fmt.Sprintf("Account %q", b.AccountId.String()), + fmt.Sprintf("Container Name %q", b.ContainerName), + } + return fmt.Sprintf("Blob %q (%s)", b.BlobName, strings.Join(components, " / ")) +} + +// ParseBlobID parses `input` into a Blob ID using a known `domainSuffix` +func ParseBlobID(input, domainSuffix string) (*BlobId, error) { // example: https://foo.blob.core.windows.net/Bar/example.vhd - if id == "" { - return nil, fmt.Errorf("`id` was empty") + if input == "" { + return nil, fmt.Errorf("`input` was empty") } - uri, err := url.Parse(id) + account, err := accounts.ParseAccountID(input, domainSuffix) if err != nil { - return nil, fmt.Errorf("Error parsing ID as a URL: %s", err) + return nil, fmt.Errorf("parsing account %q: %+v", input, err) + } + + if account.SubDomainType != accounts.BlobSubDomainType { + return nil, fmt.Errorf("expected the subdomain type to be %q but got %q", string(accounts.BlobSubDomainType), string(account.SubDomainType)) } - accountName, err := endpoints.GetAccountNameFromEndpoint(uri.Host) + uri, err := url.Parse(input) if err != nil { - return nil, fmt.Errorf("Error parsing Account Name: %s", err) + return nil, fmt.Errorf("parsing %q as a uri: %+v", input, err) } path := strings.TrimPrefix(uri.Path, "/") segments := strings.Split(path, "/") - if len(segments) == 0 { - return nil, fmt.Errorf("Expected the path to contain segments but got none") + if len(segments) != 2 { + return nil, fmt.Errorf("expected the path to contain 2 segments but got %d", len(segments)) } containerName := segments[0] blobName := strings.TrimPrefix(path, containerName) blobName = strings.TrimPrefix(blobName, "/") - return &ResourceID{ - AccountName: *accountName, + return &BlobId{ + AccountId: *account, ContainerName: containerName, BlobName: blobName, }, nil diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/set_tier.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/set_tier.go index dd0f0b8782b1..35cca5b8d7f9 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/set_tier.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/set_tier.go @@ -2,92 +2,80 @@ package blobs import ( "context" + "fmt" "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) +type SetTierInput struct { + Tier AccessTier +} + +type SetTierResponse struct { + HttpResponse *client.Response +} + // SetTier sets the tier on a blob. -func (client Client) SetTier(ctx context.Context, accountName, containerName, blobName string, tier AccessTier) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "SetTier", "`accountName` cannot be an empty string.") - } +func (c Client) SetTier(ctx context.Context, containerName, blobName string, input SetTierInput) (resp SetTierResponse, err error) { + if containerName == "" { - return result, validation.NewError("blobs.Client", "SetTier", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } + if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "SetTier", "`containerName` must be a lower-cased string.") + return resp, fmt.Errorf("`containerName` must be a lower-cased string") } + if blobName == "" { - return result, validation.NewError("blobs.Client", "SetTier", "`blobName` cannot be an empty string.") + return resp, fmt.Errorf("`blobName` cannot be an empty string") } - req, err := client.SetTierPreparer(ctx, accountName, containerName, blobName, tier) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "SetTier", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusOK, + http.StatusAccepted, + }, + HttpMethod: http.MethodPut, + OptionsObject: setTierOptions{ + tier: input.Tier, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), } - resp, err := client.SetTierSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "SetTier", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.SetTierResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "SetTier", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// SetTierPreparer prepares the SetTier request. -func (client Client) SetTierPreparer(ctx context.Context, accountName, containerName, blobName string, tier AccessTier) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("path", "tier"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-access-tier": string(tier), - } +type setTierOptions struct { + tier AccessTier +} - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) +func (s setTierOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("x-ms-access-tier", string(s.tier)) + return headers } -// SetTierSender sends the SetTier request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SetTierSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (s setTierOptions) ToOData() *odata.Query { + return nil } -// SetTierResponder handles the response to the SetTier request. The method always -// closes the http.Response Body. -func (client Client) SetTierResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - return +func (s setTierOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "tier") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/snapshot.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/snapshot.go index 180070b29469..8a90dcdaf204 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/snapshot.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/snapshot.go @@ -6,10 +6,8 @@ import ( "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" "github.com/tombuildsstuff/giovanni/storage/internal/metadata" ) @@ -42,8 +40,8 @@ type SnapshotInput struct { IfNoneMatch *string } -type SnapshotResult struct { - autorest.Response +type SnapshotResponse struct { + HttpResponse *client.Response // The ETag of the snapshot ETag string @@ -55,109 +53,92 @@ type SnapshotResult struct { } // Snapshot captures a Snapshot of a given Blob -func (client Client) Snapshot(ctx context.Context, accountName, containerName, blobName string, input SnapshotInput) (result SnapshotResult, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "Snapshot", "`accountName` cannot be an empty string.") - } +func (c Client) Snapshot(ctx context.Context, containerName, blobName string, input SnapshotInput) (resp SnapshotResponse, err error) { + if containerName == "" { - return result, validation.NewError("blobs.Client", "Snapshot", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } + if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "Snapshot", "`containerName` must be a lower-cased string.") + return resp, fmt.Errorf("`containerName` must be a lower-cased string") } + if blobName == "" { - return result, validation.NewError("blobs.Client", "Snapshot", "`blobName` cannot be an empty string.") + return resp, fmt.Errorf("`blobName` cannot be an empty string") } + if err := metadata.Validate(input.MetaData); err != nil { - return result, validation.NewError("blobs.Client", "Snapshot", fmt.Sprintf("`input.MetaData` is not valid: %s.", err)) + return resp, fmt.Errorf(fmt.Sprintf("`input.MetaData` is not valid: %s.", err)) } - req, err := client.SnapshotPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "Snapshot", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: snapshotOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), } - resp, err := client.SnapshotSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "Snapshot", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.SnapshotResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "Snapshot", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } + if resp.HttpResponse != nil && resp.HttpResponse.Header != nil { + resp.ETag = resp.HttpResponse.Header.Get("ETag") + resp.SnapshotDateTime = resp.HttpResponse.Header.Get("x-ms-snapshot") + } + return } -// SnapshotPreparer prepares the Snapshot request. -func (client Client) SnapshotPreparer(ctx context.Context, accountName, containerName, blobName string, input SnapshotInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } +type snapshotOptions struct { + input SnapshotInput +} - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "snapshot"), - } +func (s snapshotOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, + if s.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *s.input.LeaseID) } - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID + if s.input.IfModifiedSince != nil { + headers.Append("If-Modified-Since", *s.input.IfModifiedSince) } - if input.IfModifiedSince != nil { - headers["If-Modified-Since"] = *input.IfModifiedSince - } - if input.IfUnmodifiedSince != nil { - headers["If-Unmodified-Since"] = *input.IfUnmodifiedSince + if s.input.IfUnmodifiedSince != nil { + headers.Append("If-Unmodified-Since", *s.input.IfUnmodifiedSince) } - if input.IfMatch != nil { - headers["If-Match"] = *input.IfMatch - } - if input.IfNoneMatch != nil { - headers["If-None-Match"] = *input.IfNoneMatch + + if s.input.IfMatch != nil { + headers.Append("If-Match", *s.input.IfMatch) } - headers = metadata.SetIntoHeaders(headers, input.MetaData) + if s.input.IfNoneMatch != nil { + headers.Append("If-None-Match", *s.input.IfNoneMatch) + } - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + headers.Merge(metadata.SetMetaDataHeaders(s.input.MetaData)) + return headers } -// SnapshotSender sends the Snapshot request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SnapshotSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (s snapshotOptions) ToOData() *odata.Query { + return nil } -// SnapshotResponder handles the response to the Snapshot request. The method always -// closes the http.Response Body. -func (client Client) SnapshotResponder(resp *http.Response) (result SnapshotResult, err error) { - if resp != nil && resp.Header != nil { - result.ETag = resp.Header.Get("ETag") - result.SnapshotDateTime = resp.Header.Get("x-ms-snapshot") - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return +func (s snapshotOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "snapshot") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/snapshot_get_properties.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/snapshot_get_properties.go index fe1be63ab216..57a02f34e819 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/snapshot_get_properties.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/snapshot_get_properties.go @@ -2,12 +2,14 @@ package blobs import ( "context" + "fmt" "net/http" + "strconv" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" + "github.com/tombuildsstuff/giovanni/storage/internal/metadata" ) type GetSnapshotPropertiesInput struct { @@ -21,70 +23,138 @@ type GetSnapshotPropertiesInput struct { // GetSnapshotProperties returns all user-defined metadata, standard HTTP properties, and system properties for // the specified snapshot of a blob -func (client Client) GetSnapshotProperties(ctx context.Context, accountName, containerName, blobName string, input GetSnapshotPropertiesInput) (result GetPropertiesResult, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "GetSnapshotProperties", "`accountName` cannot be an empty string.") - } +func (c Client) GetSnapshotProperties(ctx context.Context, containerName, blobName string, input GetSnapshotPropertiesInput) (resp GetPropertiesResponse, err error) { + if containerName == "" { - return result, validation.NewError("blobs.Client", "GetSnapshotProperties", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } + if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "GetSnapshotProperties", "`containerName` must be a lower-cased string.") + return resp, fmt.Errorf("`containerName` must be a lower-cased string") } + if blobName == "" { - return result, validation.NewError("blobs.Client", "GetSnapshotProperties", "`blobName` cannot be an empty string.") + return resp, fmt.Errorf("`blobName` cannot be an empty string") } + if input.SnapshotID == "" { - return result, validation.NewError("blobs.Client", "GetSnapshotProperties", "`input.SnapshotID` cannot be an empty string.") + return resp, fmt.Errorf("`input.SnapshotID` cannot be an empty string") } - req, err := client.GetSnapshotPropertiesPreparer(ctx, accountName, containerName, blobName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "GetSnapshotProperties", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodHead, + OptionsObject: snapshotGetPropertiesOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), } - // we re-use the GetProperties methods since this is otherwise the same - resp, err := client.GetPropertiesSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "GetSnapshotProperties", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.GetPropertiesResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "GetSnapshotProperties", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } - return -} + if resp.HttpResponse != nil { + if resp.HttpResponse.Header != nil { + resp.AccessTier = AccessTier(resp.HttpResponse.Header.Get("x-ms-access-tier")) + resp.AccessTierChangeTime = resp.HttpResponse.Header.Get("x-ms-access-tier-change-time") + resp.ArchiveStatus = ArchiveStatus(resp.HttpResponse.Header.Get("x-ms-archive-status")) + resp.BlobCommittedBlockCount = resp.HttpResponse.Header.Get("x-ms-blob-committed-block-count") + resp.BlobSequenceNumber = resp.HttpResponse.Header.Get("x-ms-blob-sequence-number") + resp.BlobType = BlobType(resp.HttpResponse.Header.Get("x-ms-blob-type")) + resp.CacheControl = resp.HttpResponse.Header.Get("Cache-Control") + resp.ContentDisposition = resp.HttpResponse.Header.Get("Content-Disposition") + resp.ContentEncoding = resp.HttpResponse.Header.Get("Content-Encoding") + resp.ContentLanguage = resp.HttpResponse.Header.Get("Content-Language") + resp.ContentMD5 = resp.HttpResponse.Header.Get("Content-MD5") + resp.ContentType = resp.HttpResponse.Header.Get("Content-Type") + resp.CopyCompletionTime = resp.HttpResponse.Header.Get("x-ms-copy-completion-time") + resp.CopyDestinationSnapshot = resp.HttpResponse.Header.Get("x-ms-copy-destination-snapshot") + resp.CopyID = resp.HttpResponse.Header.Get("x-ms-copy-id") + resp.CopyProgress = resp.HttpResponse.Header.Get("x-ms-copy-progress") + resp.CopySource = resp.HttpResponse.Header.Get("x-ms-copy-source") + resp.CopyStatus = CopyStatus(resp.HttpResponse.Header.Get("x-ms-copy-status")) + resp.CopyStatusDescription = resp.HttpResponse.Header.Get("x-ms-copy-status-description") + resp.CreationTime = resp.HttpResponse.Header.Get("x-ms-creation-time") + resp.ETag = resp.HttpResponse.Header.Get("Etag") + resp.LastModified = resp.HttpResponse.Header.Get("Last-Modified") + resp.LeaseDuration = LeaseDuration(resp.HttpResponse.Header.Get("x-ms-lease-duration")) + resp.LeaseState = LeaseState(resp.HttpResponse.Header.Get("x-ms-lease-state")) + resp.LeaseStatus = LeaseStatus(resp.HttpResponse.Header.Get("x-ms-lease-status")) + resp.MetaData = metadata.ParseFromHeaders(resp.HttpResponse.Header) -// GetSnapshotPreparer prepares the GetSnapshot request. -func (client Client) GetSnapshotPropertiesPreparer(ctx context.Context, accountName, containerName, blobName string, input GetSnapshotPropertiesInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } + if v := resp.HttpResponse.Header.Get("x-ms-access-tier-inferred"); v != "" { + b, innerErr := strconv.ParseBool(v) + if innerErr != nil { + err = fmt.Errorf("error parsing %q as a bool: %s", v, innerErr) + return + } - queryParameters := map[string]interface{}{ - "snapshot": autorest.Encode("query", input.SnapshotID), - } + resp.AccessTierInferred = b + } + + if v := resp.HttpResponse.Header.Get("Content-Length"); v != "" { + i, innerErr := strconv.Atoi(v) + if innerErr != nil { + err = fmt.Errorf("error parsing %q as an integer: %s", v, innerErr) + } - headers := map[string]interface{}{ - "x-ms-version": APIVersion, + resp.ContentLength = int64(i) + } + + if v := resp.HttpResponse.Header.Get("x-ms-incremental-copy"); v != "" { + b, innerErr := strconv.ParseBool(v) + if innerErr != nil { + err = fmt.Errorf("error parsing %q as a bool: %s", v, innerErr) + return + } + + resp.IncrementalCopy = b + } + + if v := resp.HttpResponse.Header.Get("x-ms-server-encrypted"); v != "" { + b, innerErr := strconv.ParseBool(v) + if innerErr != nil { + err = fmt.Errorf("error parsing %q as a bool: %s", v, innerErr) + return + } + + resp.ServerEncrypted = b + } + } } - if input.LeaseID != nil { - headers["x-ms-lease-id"] = *input.LeaseID + return +} + +type snapshotGetPropertiesOptions struct { + input GetSnapshotPropertiesInput +} + +func (s snapshotGetPropertiesOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + if s.input.LeaseID != nil { + headers.Append("x-ms-lease-id", *s.input.LeaseID) } + return headers +} + +func (s snapshotGetPropertiesOptions) ToOData() *odata.Query { + return nil +} - preparer := autorest.CreatePreparer( - autorest.AsHead(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithHeaders(headers), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) +func (s snapshotGetPropertiesOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("snapshot", s.input.SnapshotID) + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/undelete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/undelete.go index 9be2f81a66f2..e46277c77af1 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/undelete.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/undelete.go @@ -2,91 +2,69 @@ package blobs import ( "context" + "fmt" "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) +type UndeleteResponse struct { + HttpResponse *client.Response +} + // Undelete restores the contents and metadata of soft deleted blob and any associated soft deleted snapshots. -func (client Client) Undelete(ctx context.Context, accountName, containerName, blobName string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("blobs.Client", "Undelete", "`accountName` cannot be an empty string.") - } +func (c Client) Undelete(ctx context.Context, containerName, blobName string) (resp UndeleteResponse, err error) { + if containerName == "" { - return result, validation.NewError("blobs.Client", "Undelete", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } + if strings.ToLower(containerName) != containerName { - return result, validation.NewError("blobs.Client", "Undelete", "`containerName` must be a lower-cased string.") + return resp, fmt.Errorf("`containerName` must be a lower-cased string") } + if blobName == "" { - return result, validation.NewError("blobs.Client", "Undelete", "`blobName` cannot be an empty string.") + return resp, fmt.Errorf("`blobName` cannot be an empty string") } - req, err := client.UndeletePreparer(ctx, accountName, containerName, blobName) - if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "Undelete", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPut, + OptionsObject: undeleteOptions{}, + Path: fmt.Sprintf("/%s/%s", containerName, blobName), } - resp, err := client.UndeleteSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "blobs.Client", "Undelete", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.UndeleteResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "blobs.Client", "Undelete", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// UndeletePreparer prepares the Undelete request. -func (client Client) UndeletePreparer(ctx context.Context, accountName, containerName, blobName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - "blobName": autorest.Encode("path", blobName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("path", "undelete"), - } +type undeleteOptions struct{} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}/{blobName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) +func (u undeleteOptions) ToHeaders() *client.Headers { + return nil } -// UndeleteSender sends the Undelete request. The method will close the -// http.Response Body if it receives an error. -func (client Client) UndeleteSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (u undeleteOptions) ToOData() *odata.Query { + return nil } -// UndeleteResponder handles the response to the Undelete request. The method always -// closes the http.Response Body. -func (client Client) UndeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - return +func (u undeleteOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "undelete") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/version.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/version.go index b6d69e2233b5..414d3405774a 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/version.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs/version.go @@ -1,14 +1,5 @@ package blobs -import ( - "fmt" - - "github.com/tombuildsstuff/giovanni/version" -) - // APIVersion is the version of the API used for all Storage API Operations -const APIVersion = "2020-08-04" - -func UserAgent() string { - return fmt.Sprintf("tombuildsstuff/giovanni/%s storage/%s", version.Number, APIVersion) -} +const apiVersion = "2020-08-04" +const componentName = "blob/blobs" diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/README.md b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/README.md index 9d375483ee8e..fcebd0367384 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/README.md +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/README.md @@ -17,9 +17,8 @@ package main import ( "context" "fmt" - "time" - - "github.com/Azure/go-autorest/autorest" + + "github.com/hashicorp/go-azure-sdk/sdk/auth" "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers" ) @@ -27,16 +26,24 @@ func Example() error { accountName := "storageaccount1" storageAccountKey := "ABC123...." containerName := "mycontainer" - - storageAuth := autorest.NewSharedKeyLiteAuthorizer(accountName, storageAccountKey) - containersClient := containers.New() - containersClient.Client.Authorizer = storageAuth + domainSuffix := "core.windows.net" + + containersClient, err := containers.NewWithBaseUri(fmt.Sprintf("https://%s.blob.%s", accountName, domainSuffix)) + if err != nil { + return fmt.Errorf("building client for environment: %+v", err) + } + + auth, err := auth.NewSharedKeyAuthorizer(accountName, storageAccountKey, auth.SharedKey) + if err != nil { + return fmt.Errorf("building SharedKey authorizer: %+v", err) + } + containersClient.Client.WithAuthorizer(auth) ctx := context.TODO() createInput := containers.CreateInput{ AccessLevel: containers.Private, } - if _, err := containersClient.Create(ctx, accountName, containerName, createInput); err != nil { + if _, err := containersClient.Create(ctx, containerName, createInput); err != nil { return fmt.Errorf("Error creating Container: %s", err) } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/api.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/api.go index 622f2b00eed7..0c6b65a274b5 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/api.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/api.go @@ -2,24 +2,19 @@ package containers import ( "context" - - "github.com/Azure/go-autorest/autorest" ) type StorageContainer interface { - Create(ctx context.Context, accountName, containerName string, input CreateInput) (result CreateResponse, err error) - Delete(ctx context.Context, accountName, containerName string) (result autorest.Response, err error) - GetProperties(ctx context.Context, accountName, containerName string) (ContainerProperties, error) - GetPropertiesWithLeaseID(ctx context.Context, accountName, containerName, leaseID string) (result ContainerProperties, err error) - AcquireLease(ctx context.Context, accountName, containerName string, input AcquireLeaseInput) (result AcquireLeaseResponse, err error) - BreakLease(ctx context.Context, accountName, containerName string, input BreakLeaseInput) (result BreakLeaseResponse, err error) - ChangeLease(ctx context.Context, accountName, containerName string, input ChangeLeaseInput) (result ChangeLeaseResponse, err error) - ReleaseLease(ctx context.Context, accountName, containerName, leaseID string) (result autorest.Response, err error) - RenewLease(ctx context.Context, accountName, containerName, leaseID string) (result autorest.Response, err error) - ListBlobs(ctx context.Context, accountName, containerName string, input ListBlobsInput) (result ListBlobsResult, err error) + Create(ctx context.Context, containerName string, input CreateInput) (CreateResponse, error) + Delete(ctx context.Context, containerName string) (DeleteResponse, error) + GetProperties(ctx context.Context, containerName string, input GetPropertiesInput) (GetPropertiesResponse, error) + AcquireLease(ctx context.Context, containerName string, input AcquireLeaseInput) (AcquireLeaseResponse, error) + BreakLease(ctx context.Context, containerName string, input BreakLeaseInput) (BreakLeaseResponse, error) + ChangeLease(ctx context.Context, containerName string, input ChangeLeaseInput) (ChangeLeaseResponse, error) + ReleaseLease(ctx context.Context, containerName string, input ReleaseLeaseInput) (ReleaseLeaseResponse, error) + RenewLease(ctx context.Context, containerName string, input RenewLeaseInput) (RenewLeaseResponse, error) + ListBlobs(ctx context.Context, containerName string, input ListBlobsInput) (ListBlobsResponse, error) GetResourceManagerResourceID(subscriptionID, resourceGroup, accountName, containerName string) string - SetAccessControl(ctx context.Context, accountName, containerName string, level AccessLevel) (autorest.Response, error) - SetAccessControlWithLeaseID(ctx context.Context, accountName, containerName, leaseID string, level AccessLevel) (result autorest.Response, err error) - SetMetaData(ctx context.Context, accountName, containerName string, metaData map[string]string) (autorest.Response, error) - SetMetaDataWithLeaseID(ctx context.Context, accountName, containerName, leaseID string, metaData map[string]string) (result autorest.Response, err error) + SetAccessControl(ctx context.Context, containerName string, input SetAccessControlInput) (SetAccessControlResponse, error) + SetMetaData(ctx context.Context, containerName string, metaData SetMetaDataInput) (SetMetaDataResponse, error) } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/client.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/client.go index 7bf494734484..72174cb6e57a 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/client.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/client.go @@ -1,34 +1,22 @@ package containers import ( - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" + "fmt" + + "github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/storage" ) // Client is the base client for Blob Storage Containers. type Client struct { - autorest.Client - BaseURI string -} - -// New creates an instance of the Client client. -func New() Client { - return NewWithEnvironment(azure.PublicCloud) + Client *storage.BaseClient } -// NewWithBaseURI creates an instance of the Client client. -func NewWithEnvironment(environment azure.Environment) Client { - return Client{ - Client: autorest.NewClientWithUserAgent(UserAgent()), - BaseURI: environment.StorageEndpointSuffix, +func NewWithBaseUri(baseUri string) (*Client, error) { + baseClient, err := storage.NewBaseClient(baseUri, componentName, apiVersion) + if err != nil { + return nil, fmt.Errorf("building base client: %+v", err) } -} - -func (client Client) setAccessLevelIntoHeaders(headers map[string]interface{}, level AccessLevel) map[string]interface{} { - // If this header is not included in the request, container data is private to the account owner. - if level != Private { - headers["x-ms-blob-public-access"] = string(level) - } - - return headers + return &Client{ + Client: baseClient, + }, nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/create.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/create.go index 84c2887d7d1a..1acbae869d91 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/create.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/create.go @@ -5,10 +5,8 @@ import ( "fmt" "net/http" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" "github.com/tombuildsstuff/giovanni/storage/internal/metadata" ) @@ -21,103 +19,70 @@ type CreateInput struct { } type CreateResponse struct { - autorest.Response - Error *ErrorResponse `xml:"Error"` + HttpResponse *client.Response + Error *ErrorResponse `xml:"Error"` } // Create creates a new container under the specified account. // If the container with the same name already exists, the operation fails. -func (client Client) Create(ctx context.Context, accountName, containerName string, input CreateInput) (result CreateResponse, err error) { - if accountName == "" { - return result, validation.NewError("containers.Client", "Create", "`accountName` cannot be an empty string.") - } +func (c Client) Create(ctx context.Context, containerName string, input CreateInput) (resp CreateResponse, err error) { if containerName == "" { - return result, validation.NewError("containers.Client", "Create", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } if err := metadata.Validate(input.MetaData); err != nil { - return result, validation.NewError("containers.Client", "Create", fmt.Sprintf("`input.MetaData` is not valid: %s.", err)) + return resp, fmt.Errorf("`input.MetaData` is not valid: %+v", err) } - req, err := client.CreatePreparer(ctx, accountName, containerName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "Create", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: createOptions{ + accessLevel: input.AccessLevel, + metaData: input.MetaData, + }, + Path: fmt.Sprintf("/%s", containerName), } - - resp, err := client.CreateSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "containers.Client", "Create", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - - result, err = client.CreateResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "Create", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// CreatePreparer prepares the Create request. -func (client Client) CreatePreparer(ctx context.Context, accountName string, containerName string, input CreateInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - } +var _ client.Options = createOptions{} - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("path", "container"), - } +type createOptions struct { + accessLevel AccessLevel + metaData map[string]string +} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } +func (o createOptions) ToHeaders() *client.Headers { + headers := containerOptions{ + metaData: o.metaData, + }.ToHeaders() - headers = client.setAccessLevelIntoHeaders(headers, input.AccessLevel) - headers = metadata.SetIntoHeaders(headers, input.MetaData) + // If this header is not included in the request, container data is private to the account owner. + if o.accessLevel != Private { + headers.Append("x-ms-blob-public-access", string(o.accessLevel)) + } - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// CreateSender sends the Create request. The method will close the -// http.Response Body if it receives an error. -func (client Client) CreateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (createOptions) ToOData() *odata.Query { + return nil } -// CreateResponder handles the response to the Create request. The method always -// closes the http.Response Body. -func (client Client) CreateResponder(resp *http.Response) (result CreateResponse, err error) { - successfulStatusCodes := []int{ - http.StatusCreated, - } - if autorest.ResponseHasStatusCode(resp, successfulStatusCodes...) { - // when successful there's no response - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(successfulStatusCodes...), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - } else { - // however when there's an error the error's in the response - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(successfulStatusCodes...), - autorest.ByUnmarshallingXML(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - } - - return +func (createOptions) ToQuery() *client.QueryParams { + return containerOptions{}.ToQuery() } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/delete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/delete.go index 30958295388e..0aea0ed7f1df 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/delete.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/delete.go @@ -2,84 +2,42 @@ package containers import ( "context" + "fmt" "net/http" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" ) +type DeleteResponse struct { + HttpResponse *client.Response +} + // Delete marks the specified container for deletion. // The container and any blobs contained within it are later deleted during garbage collection. -func (client Client) Delete(ctx context.Context, accountName, containerName string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("containers.Client", "Delete", "`accountName` cannot be an empty string.") - } +func (c Client) Delete(ctx context.Context, containerName string) (resp DeleteResponse, err error) { if containerName == "" { - return result, validation.NewError("containers.Client", "Delete", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } - req, err := client.DeletePreparer(ctx, accountName, containerName) - if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "Delete", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusAccepted, + }, + HttpMethod: http.MethodDelete, + OptionsObject: containerOptions{}, + Path: fmt.Sprintf("/%s", containerName), } - - resp, err := client.DeleteSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "Delete", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - - result, err = client.DeleteResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "Delete", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } - -// DeletePreparer prepares the Delete request. -func (client Client) DeletePreparer(ctx context.Context, accountName string, containerName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("path", "container"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsDelete(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client Client) DeleteSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client Client) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusAccepted), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/get_properties.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/get_properties.go index 1e308da67c55..2655b0ba89e1 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/get_properties.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/get_properties.go @@ -2,123 +2,100 @@ package containers import ( "context" + "fmt" "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" "github.com/tombuildsstuff/giovanni/storage/internal/metadata" ) -// GetProperties returns the properties for this Container without a Lease -func (client Client) GetProperties(ctx context.Context, accountName, containerName string) (ContainerProperties, error) { - // If specified, Get Container Properties only succeeds if the container’s lease is active and matches this ID. - // If there is no active lease or the ID does not match, 412 (Precondition Failed) is returned. - return client.GetPropertiesWithLeaseID(ctx, accountName, containerName, "") +type GetPropertiesInput struct { + LeaseId string } -// GetPropertiesWithLeaseID returns the properties for this Container using the specified LeaseID -func (client Client) GetPropertiesWithLeaseID(ctx context.Context, accountName, containerName, leaseID string) (result ContainerProperties, err error) { - if accountName == "" { - return result, validation.NewError("containers.Client", "GetPropertiesWithLeaseID", "`accountName` cannot be an empty string.") - } +type GetPropertiesResponse struct { + HttpResponse *client.Response + Model *ContainerProperties +} + +// GetProperties returns the properties for this Container without a Lease +func (c Client) GetProperties(ctx context.Context, containerName string, input GetPropertiesInput) (resp GetPropertiesResponse, err error) { if containerName == "" { - return result, validation.NewError("containers.Client", "GetPropertiesWithLeaseID", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } - req, err := client.GetPropertiesWithLeaseIDPreparer(ctx, accountName, containerName, leaseID) + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: getPropertiesOptions{ + leaseId: input.LeaseId, + }, + Path: fmt.Sprintf("/%s", containerName), + } + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "GetProperties", nil, "Failure preparing request") + err = fmt.Errorf("building request: %+v", err) return } - - resp, err := client.GetPropertiesWithLeaseIDSender(req) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "containers.Client", "GetProperties", resp, "Failure sending request") + err = fmt.Errorf("executing request: %+v", err) return } - result, err = client.GetPropertiesWithLeaseIDResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "GetProperties", resp, "Failure responding to request") - return + if resp.HttpResponse != nil { + resp.Model = &ContainerProperties{} + resp.Model.LeaseStatus = LeaseStatus(resp.HttpResponse.Header.Get("x-ms-lease-status")) + resp.Model.LeaseState = LeaseState(resp.HttpResponse.Header.Get("x-ms-lease-state")) + if resp.Model.LeaseStatus == Locked { + duration := LeaseDuration(resp.HttpResponse.Header.Get("x-ms-lease-duration")) + resp.Model.LeaseDuration = &duration + } + + // If this header is not returned in the response, the container is private to the account owner. + accessLevel := resp.HttpResponse.Header.Get("x-ms-blob-public-access") + if accessLevel != "" { + resp.Model.AccessLevel = AccessLevel(accessLevel) + } else { + resp.Model.AccessLevel = Private + } + + // we can't necessarily use strconv.ParseBool here since this could be nil (only in some API versions) + resp.Model.HasImmutabilityPolicy = strings.EqualFold(resp.HttpResponse.Header.Get("x-ms-has-immutability-policy"), "true") + resp.Model.HasLegalHold = strings.EqualFold(resp.HttpResponse.Header.Get("x-ms-has-legal-hold"), "true") + resp.Model.MetaData = metadata.ParseFromHeaders(resp.HttpResponse.Header) } return } -// GetPropertiesWithLeaseIDPreparer prepares the GetPropertiesWithLeaseID request. -func (client Client) GetPropertiesWithLeaseIDPreparer(ctx context.Context, accountName, containerName, leaseID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - } +var _ client.Options = getPropertiesOptions{} - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("path", "container"), - } +type getPropertiesOptions struct { + leaseId string +} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } +func (o getPropertiesOptions) ToHeaders() *client.Headers { + headers := containerOptions{}.ToHeaders() // If specified, Get Container Properties only succeeds if the container’s lease is active and matches this ID. // If there is no active lease or the ID does not match, 412 (Precondition Failed) is returned. - if leaseID != "" { - headers["x-ms-lease-id"] = leaseID + if o.leaseId != "" { + headers.Append("x-ms-lease-id", o.leaseId) } - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// GetPropertiesWithLeaseIDSender sends the GetPropertiesWithLeaseID request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetPropertiesWithLeaseIDSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (getPropertiesOptions) ToOData() *odata.Query { + return nil } -// GetPropertiesWithLeaseIDResponder handles the response to the GetPropertiesWithLeaseID request. The method always -// closes the http.Response Body. -func (client Client) GetPropertiesWithLeaseIDResponder(resp *http.Response) (result ContainerProperties, err error) { - if resp != nil { - result.LeaseStatus = LeaseStatus(resp.Header.Get("x-ms-lease-status")) - result.LeaseState = LeaseState(resp.Header.Get("x-ms-lease-state")) - if result.LeaseStatus == Locked { - duration := LeaseDuration(resp.Header.Get("x-ms-lease-duration")) - result.LeaseDuration = &duration - } - - // If this header is not returned in the response, the container is private to the account owner. - accessLevel := resp.Header.Get("x-ms-blob-public-access") - if accessLevel != "" { - result.AccessLevel = AccessLevel(accessLevel) - } else { - result.AccessLevel = Private - } - - // we can't necessarily use strconv.ParseBool here since this could be nil (only in some API versions) - result.HasImmutabilityPolicy = strings.EqualFold(resp.Header.Get("x-ms-has-immutability-policy"), "true") - result.HasLegalHold = strings.EqualFold(resp.Header.Get("x-ms-has-legal-hold"), "true") - - result.MetaData = metadata.ParseFromHeaders(resp.Header) - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return +func (getPropertiesOptions) ToQuery() *client.QueryParams { + return containerOptions{}.ToQuery() } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_acquire.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_acquire.go index 061c863c43f9..409f15a47172 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_acquire.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_acquire.go @@ -2,12 +2,11 @@ package containers import ( "context" + "fmt" "net/http" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type AcquireLeaseInput struct { @@ -19,97 +18,82 @@ type AcquireLeaseInput struct { } type AcquireLeaseResponse struct { - autorest.Response + HttpResponse *client.Response + Model *AcquireLeaseModel +} +type AcquireLeaseModel struct { LeaseID string } // AcquireLease establishes and manages a lock on a container for delete operations. -func (client Client) AcquireLease(ctx context.Context, accountName, containerName string, input AcquireLeaseInput) (result AcquireLeaseResponse, err error) { - if accountName == "" { - return result, validation.NewError("containers.Client", "AcquireLease", "`accountName` cannot be an empty string.") - } +func (c Client) AcquireLease(ctx context.Context, containerName string, input AcquireLeaseInput) (resp AcquireLeaseResponse, err error) { if containerName == "" { - return result, validation.NewError("containers.Client", "AcquireLease", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } // An infinite lease duration is -1 seconds. A non-infinite lease can be between 15 and 60 seconds if input.LeaseDuration != -1 && (input.LeaseDuration <= 15 || input.LeaseDuration >= 60) { - return result, validation.NewError("containers.Client", "AcquireLease", "`input.LeaseDuration` must be -1 (infinite), or between 15 and 60 seconds.") + return resp, fmt.Errorf("`input.LeaseDuration` must be -1 (infinite), or between 15 and 60 seconds") } - req, err := client.AcquireLeasePreparer(ctx, accountName, containerName, input) + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: acquireLeaseOptions{ + leaseDuration: input.LeaseDuration, + proposedLeaseId: input.ProposedLeaseID, + }, + Path: fmt.Sprintf("/%s", containerName), + } + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "AcquireLease", nil, "Failure preparing request") + err = fmt.Errorf("building request: %+v", err) return } - - resp, err := client.AcquireLeaseSender(req) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "containers.Client", "AcquireLease", resp, "Failure sending request") + err = fmt.Errorf("executing request: %+v", err) return } - result, err = client.AcquireLeaseResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "AcquireLease", resp, "Failure responding to request") - return + if resp.HttpResponse != nil { + resp.Model = &AcquireLeaseModel{ + LeaseID: resp.HttpResponse.Header.Get("x-ms-lease-id"), + } } return } -// AcquireLeasePreparer prepares the AcquireLease request. -func (client Client) AcquireLeasePreparer(ctx context.Context, accountName string, containerName string, input AcquireLeaseInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - } +var _ client.Options = acquireLeaseOptions{} - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("path", "container"), - "comp": autorest.Encode("path", "lease"), - } +type acquireLeaseOptions struct { + leaseDuration int + proposedLeaseId string +} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-lease-action": "acquire", - "x-ms-lease-duration": input.LeaseDuration, - } +func (o acquireLeaseOptions) ToHeaders() *client.Headers { + headers := containerOptions{}.ToHeaders() - if input.ProposedLeaseID != "" { - headers["x-ms-proposed-lease-id"] = input.ProposedLeaseID + headers.Append("x-ms-lease-action", "acquire") + headers.Append("x-ms-lease-duration", fmt.Sprintf("%d", o.leaseDuration)) + + if o.proposedLeaseId != "" { + headers.Append("x-ms-proposed-lease-id", o.proposedLeaseId) } - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// AcquireLeaseSender sends the AcquireLease request. The method will close the -// http.Response Body if it receives an error. -func (client Client) AcquireLeaseSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (o acquireLeaseOptions) ToOData() *odata.Query { + return nil } -// AcquireLeaseResponder handles the response to the AcquireLease request. The method always -// closes the http.Response Body. -func (client Client) AcquireLeaseResponder(resp *http.Response) (result AcquireLeaseResponse, err error) { - if resp != nil { - result.LeaseID = resp.Header.Get("x-ms-lease-id") - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return +func (o acquireLeaseOptions) ToQuery() *client.QueryParams { + query := containerOptions{}.ToQuery() + query.Append("comp", "lease") + return query } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_break.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_break.go index 08acfb7a3116..0ede9a818a0f 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_break.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_break.go @@ -2,13 +2,12 @@ package containers import ( "context" + "fmt" "net/http" "strconv" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type BreakLeaseInput struct { @@ -26,104 +25,88 @@ type BreakLeaseInput struct { } type BreakLeaseResponse struct { - autorest.Response + HttpResponse *client.Response + Model *BreakLeaseModel +} +type BreakLeaseModel struct { // Approximate time remaining in the lease period, in seconds. // If the break is immediate, 0 is returned. LeaseTime int } // BreakLease breaks a lock based on it's Lease ID -func (client Client) BreakLease(ctx context.Context, accountName, containerName string, input BreakLeaseInput) (result BreakLeaseResponse, err error) { - if accountName == "" { - return result, validation.NewError("containers.Client", "BreakLease", "`accountName` cannot be an empty string.") - } +func (c Client) BreakLease(ctx context.Context, containerName string, input BreakLeaseInput) (resp BreakLeaseResponse, err error) { if containerName == "" { - return result, validation.NewError("containers.Client", "BreakLease", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } if input.LeaseID == "" { - return result, validation.NewError("containers.Client", "BreakLease", "`input.LeaseID` cannot be an empty string.") + return resp, fmt.Errorf("`input.LeaseID` cannot be an empty string") } - req, err := client.BreakLeasePreparer(ctx, accountName, containerName, input) + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusAccepted, + }, + HttpMethod: http.MethodPut, + OptionsObject: breakLeaseOptions{ + breakPeriod: input.BreakPeriod, + leaseId: input.LeaseID, + }, + Path: fmt.Sprintf("/%s", containerName), + } + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "BreakLease", nil, "Failure preparing request") + err = fmt.Errorf("building request: %+v", err) return } - - resp, err := client.BreakLeaseSender(req) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "containers.Client", "BreakLease", resp, "Failure sending request") + err = fmt.Errorf("executing request: %+v", err) return } - result, err = client.BreakLeaseResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "BreakLease", resp, "Failure responding to request") - return + if resp.HttpResponse != nil { + leaseRaw := resp.HttpResponse.Header.Get("x-ms-lease-time") + if leaseRaw != "" { + if i, err := strconv.Atoi(leaseRaw); err == nil { + resp.Model = &BreakLeaseModel{ + LeaseTime: i, + } + } + } } return } -// BreakLeasePreparer prepares the BreakLease request. -func (client Client) BreakLeasePreparer(ctx context.Context, accountName string, containerName string, input BreakLeaseInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - } +var _ client.Options = breakLeaseOptions{} - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("path", "container"), - "comp": autorest.Encode("path", "lease"), - } +type breakLeaseOptions struct { + breakPeriod *int + leaseId string +} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-lease-action": "break", - "x-ms-lease-id": input.LeaseID, - } +func (o breakLeaseOptions) ToHeaders() *client.Headers { + headers := containerOptions{}.ToHeaders() + + headers.Append("x-ms-lease-action", "break") + headers.Append("x-ms-lease-id", o.leaseId) - if input.BreakPeriod != nil { - headers["x-ms-lease-break-period"] = *input.BreakPeriod + if o.breakPeriod != nil { + headers.Append("x-ms-lease-break-period", fmt.Sprintf("%d", *o.breakPeriod)) } - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// BreakLeaseSender sends the BreakLease request. The method will close the -// http.Response Body if it receives an error. -func (client Client) BreakLeaseSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (o breakLeaseOptions) ToOData() *odata.Query { + return nil } -// BreakLeaseResponder handles the response to the BreakLease request. The method always -// closes the http.Response Body. -func (client Client) BreakLeaseResponder(resp *http.Response) (result BreakLeaseResponse, err error) { - if resp != nil { - leaseRaw := resp.Header.Get("x-ms-lease-time") - if leaseRaw != "" { - i, err := strconv.Atoi(leaseRaw) - if err == nil { - result.LeaseTime = i - } - } - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusAccepted), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return +func (o breakLeaseOptions) ToQuery() *client.QueryParams { + query := containerOptions{}.ToQuery() + query.Append("comp", "lease") + return query } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_change.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_change.go index dfbcb132dae3..6326507707ee 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_change.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_change.go @@ -2,12 +2,11 @@ package containers import ( "context" + "fmt" "net/http" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type ChangeLeaseInput struct { @@ -16,96 +15,81 @@ type ChangeLeaseInput struct { } type ChangeLeaseResponse struct { - autorest.Response + HttpResponse *client.Response + Model *ChangeLeaseModel +} +type ChangeLeaseModel struct { LeaseID string } // ChangeLease changes the lock from one Lease ID to another Lease ID -func (client Client) ChangeLease(ctx context.Context, accountName, containerName string, input ChangeLeaseInput) (result ChangeLeaseResponse, err error) { - if accountName == "" { - return result, validation.NewError("containers.Client", "ChangeLease", "`accountName` cannot be an empty string.") - } +func (c Client) ChangeLease(ctx context.Context, containerName string, input ChangeLeaseInput) (resp ChangeLeaseResponse, err error) { if containerName == "" { - return result, validation.NewError("containers.Client", "ChangeLease", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } if input.ExistingLeaseID == "" { - return result, validation.NewError("containers.Client", "ChangeLease", "`input.ExistingLeaseID` cannot be an empty string.") + return resp, fmt.Errorf("`input.ExistingLeaseID` cannot be an empty string") } if input.ProposedLeaseID == "" { - return result, validation.NewError("containers.Client", "ChangeLease", "`input.ProposedLeaseID` cannot be an empty string.") + return resp, fmt.Errorf("`input.ProposedLeaseID` cannot be an empty string") } - req, err := client.ChangeLeasePreparer(ctx, accountName, containerName, input) + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPut, + OptionsObject: changeLeaseOptions{ + existingLeaseId: input.ExistingLeaseID, + proposedLeaseId: input.ProposedLeaseID, + }, + Path: fmt.Sprintf("/%s", containerName), + } + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "ChangeLease", nil, "Failure preparing request") + err = fmt.Errorf("building request: %+v", err) return } - - resp, err := client.ChangeLeaseSender(req) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "containers.Client", "ChangeLease", resp, "Failure sending request") + err = fmt.Errorf("executing request: %+v", err) return } - result, err = client.ChangeLeaseResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "ChangeLease", resp, "Failure responding to request") - return + if resp.HttpResponse != nil { + resp.Model = &ChangeLeaseModel{ + LeaseID: resp.HttpResponse.Header.Get("x-ms-lease-id"), + } } return } -// ChangeLeasePreparer prepares the ChangeLease request. -func (client Client) ChangeLeasePreparer(ctx context.Context, accountName string, containerName string, input ChangeLeaseInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - } +var _ client.Options = changeLeaseOptions{} - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("path", "container"), - "comp": autorest.Encode("path", "lease"), - } +type changeLeaseOptions struct { + existingLeaseId string + proposedLeaseId string +} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-lease-action": "change", - "x-ms-lease-id": input.ExistingLeaseID, - "x-ms-proposed-lease-id": input.ProposedLeaseID, - } +func (o changeLeaseOptions) ToHeaders() *client.Headers { + headers := containerOptions{}.ToHeaders() - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} + headers.Append("x-ms-lease-action", "change") + headers.Append("x-ms-lease-id", o.existingLeaseId) + headers.Append("x-ms-proposed-lease-id", o.proposedLeaseId) -// ChangeLeaseSender sends the ChangeLease request. The method will close the -// http.Response Body if it receives an error. -func (client Client) ChangeLeaseSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + return headers } -// ChangeLeaseResponder handles the response to the ChangeLease request. The method always -// closes the http.Response Body. -func (client Client) ChangeLeaseResponder(resp *http.Response) (result ChangeLeaseResponse, err error) { - if resp != nil { - result.LeaseID = resp.Header.Get("x-ms-lease-id") - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} +func (o changeLeaseOptions) ToOData() *odata.Query { + return nil +} - return +func (o changeLeaseOptions) ToQuery() *client.QueryParams { + query := containerOptions{}.ToQuery() + query.Append("comp", "lease") + return query } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_release.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_release.go index fafcf98f1e67..8a2cf4114e00 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_release.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_release.go @@ -2,91 +2,76 @@ package containers import ( "context" + "fmt" "net/http" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) +type ReleaseLeaseInput struct { + LeaseId string +} + +type ReleaseLeaseResponse struct { + HttpResponse *client.Response +} + // ReleaseLease releases the lock based on the Lease ID -func (client Client) ReleaseLease(ctx context.Context, accountName, containerName, leaseID string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("containers.Client", "ReleaseLease", "`accountName` cannot be an empty string.") - } +func (c Client) ReleaseLease(ctx context.Context, containerName string, input ReleaseLeaseInput) (resp ReleaseLeaseResponse, err error) { if containerName == "" { - return result, validation.NewError("containers.Client", "ReleaseLease", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } - if leaseID == "" { - return result, validation.NewError("containers.Client", "ReleaseLease", "`leaseID` cannot be an empty string.") + if input.LeaseId == "" { + return resp, fmt.Errorf("`input.LeaseId` cannot be an empty string") } - req, err := client.ReleaseLeasePreparer(ctx, accountName, containerName, leaseID) - if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "ReleaseLease", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPut, + OptionsObject: releaseLeaseOptions{ + leaseId: input.LeaseId, + }, + Path: fmt.Sprintf("/%s", containerName), } - - resp, err := client.ReleaseLeaseSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "containers.Client", "ReleaseLease", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - - result, err = client.ReleaseLeaseResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "ReleaseLease", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// ReleaseLeasePreparer prepares the ReleaseLease request. -func (client Client) ReleaseLeasePreparer(ctx context.Context, accountName string, containerName string, leaseID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - } +var _ client.Options = releaseLeaseOptions{} - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("path", "container"), - "comp": autorest.Encode("path", "lease"), - } +type releaseLeaseOptions struct { + leaseId string +} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-lease-action": "release", - "x-ms-lease-id": leaseID, - } +func (o releaseLeaseOptions) ToHeaders() *client.Headers { + headers := containerOptions{}.ToHeaders() - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} + headers.Append("x-ms-lease-action", "release") + headers.Append("x-ms-lease-id", o.leaseId) -// ReleaseLeaseSender sends the ReleaseLease request. The method will close the -// http.Response Body if it receives an error. -func (client Client) ReleaseLeaseSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + return headers } -// ReleaseLeaseResponder handles the response to the ReleaseLease request. The method always -// closes the http.Response Body. -func (client Client) ReleaseLeaseResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result = autorest.Response{Response: resp} +func (o releaseLeaseOptions) ToOData() *odata.Query { + return nil +} - return +func (o releaseLeaseOptions) ToQuery() *client.QueryParams { + query := containerOptions{}.ToQuery() + query.Append("comp", "lease") + return query } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_renew.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_renew.go index cab50bff9d21..eda202989f23 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_renew.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/lease_renew.go @@ -2,91 +2,76 @@ package containers import ( "context" + "fmt" "net/http" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) +type RenewLeaseInput struct { + LeaseId string +} + +type RenewLeaseResponse struct { + HttpResponse *client.Response +} + // RenewLease renews the lock based on the Lease ID -func (client Client) RenewLease(ctx context.Context, accountName, containerName, leaseID string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("containers.Client", "RenewLease", "`accountName` cannot be an empty string.") - } +func (c Client) RenewLease(ctx context.Context, containerName string, input RenewLeaseInput) (resp RenewLeaseResponse, err error) { if containerName == "" { - return result, validation.NewError("containers.Client", "RenewLease", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } - if leaseID == "" { - return result, validation.NewError("containers.Client", "RenewLease", "`leaseID` cannot be an empty string.") + if input.LeaseId == "" { + return resp, fmt.Errorf("`input.LeaseId` cannot be an empty string") } - req, err := client.RenewLeasePreparer(ctx, accountName, containerName, leaseID) - if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "RenewLease", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPut, + OptionsObject: renewLeaseOptions{ + leaseId: input.LeaseId, + }, + Path: fmt.Sprintf("/%s", containerName), } - - resp, err := client.RenewLeaseSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "containers.Client", "RenewLease", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - - result, err = client.RenewLeaseResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "RenewLease", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// RenewLeasePreparer prepares the RenewLease request. -func (client Client) RenewLeasePreparer(ctx context.Context, accountName string, containerName string, leaseID string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - } +var _ client.Options = renewLeaseOptions{} - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("path", "container"), - "comp": autorest.Encode("path", "lease"), - } +type renewLeaseOptions struct { + leaseId string +} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-lease-action": "renew", - "x-ms-lease-id": leaseID, - } +func (o renewLeaseOptions) ToHeaders() *client.Headers { + headers := containerOptions{}.ToHeaders() - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} + headers.Append("x-ms-lease-action", "renew") + headers.Append("x-ms-lease-id", o.leaseId) -// RenewLeaseSender sends the RenewLease request. The method will close the -// http.Response Body if it receives an error. -func (client Client) RenewLeaseSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) + return headers } -// RenewLeaseResponder handles the response to the RenewLease request. The method always -// closes the http.Response Body. -func (client Client) RenewLeaseResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result = autorest.Response{Response: resp} +func (o renewLeaseOptions) ToOData() *odata.Query { + return nil +} - return +func (o renewLeaseOptions) ToQuery() *client.QueryParams { + query := containerOptions{}.ToQuery() + query.Append("comp", "lease") + return query } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/list_blobs.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/list_blobs.go index 82797d091d36..f3bd4674d30d 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/list_blobs.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/list_blobs.go @@ -2,13 +2,12 @@ package containers import ( "context" + "fmt" "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type ListBlobsInput struct { @@ -19,9 +18,12 @@ type ListBlobsInput struct { Prefix *string } -type ListBlobsResult struct { - autorest.Response +type ListBlobsResponse struct { + HttpResponse *client.Response + Model *ListBlobsResult +} +type ListBlobsResult struct { Delimiter string `xml:"Delimiter"` Marker string `xml:"Marker"` MaxResults int `xml:"MaxResults"` @@ -78,102 +80,90 @@ type BlobPrefix struct { } // ListBlobs lists the blobs matching the specified query within the specified Container -func (client Client) ListBlobs(ctx context.Context, accountName, containerName string, input ListBlobsInput) (result ListBlobsResult, err error) { - if accountName == "" { - return result, validation.NewError("containers.Client", "ListBlobs", "`accountName` cannot be an empty string.") - } +func (c Client) ListBlobs(ctx context.Context, containerName string, input ListBlobsInput) (resp ListBlobsResponse, err error) { if containerName == "" { - return result, validation.NewError("containers.Client", "ListBlobs", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } if input.MaxResults != nil && (*input.MaxResults <= 0 || *input.MaxResults > 5000) { - return result, validation.NewError("containers.Client", "ListBlobs", "`input.MaxResults` can either be nil or between 0 and 5000.") + return resp, fmt.Errorf("`input.MaxResults` can either be nil or between 0 and 5000") } - - req, err := client.ListBlobsPreparer(ctx, accountName, containerName, input) + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: listBlobsOptions{ + delimiter: input.Delimiter, + include: input.Include, + marker: input.Marker, + maxResults: input.MaxResults, + prefix: input.Prefix, + }, + Path: fmt.Sprintf("/%s", containerName), + } + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "ListBlobs", nil, "Failure preparing request") + err = fmt.Errorf("building request: %+v", err) return } - - resp, err := client.ListBlobsSender(req) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "containers.Client", "ListBlobs", resp, "Failure sending request") + err = fmt.Errorf("executing request: %+v", err) return } - result, err = client.ListBlobsResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "ListBlobs", resp, "Failure responding to request") - return + if resp.HttpResponse != nil { + if err = resp.HttpResponse.Unmarshal(&resp.Model); err != nil { + err = fmt.Errorf("unmarshaling response: %+v", err) + return + } } return } -// ListBlobsPreparer prepares the ListBlobs request. -func (client Client) ListBlobsPreparer(ctx context.Context, accountName, containerName string, input ListBlobsInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - } +var _ client.Options = listBlobsOptions{} - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "list"), - "restype": autorest.Encode("query", "container"), - } +type listBlobsOptions struct { + delimiter *string + include *[]Dataset + marker *string + maxResults *int + prefix *string +} - if input.Delimiter != nil { - queryParameters["delimiter"] = autorest.Encode("query", *input.Delimiter) +func (o listBlobsOptions) ToHeaders() *client.Headers { + return nil +} + +func (o listBlobsOptions) ToOData() *odata.Query { + return nil +} + +func (o listBlobsOptions) ToQuery() *client.QueryParams { + query := containerOptions{}.ToQuery() + query.Append("comp", "list") + + if o.delimiter != nil { + query.Append("delimiter", *o.delimiter) } - if input.Include != nil { + if o.include != nil { vals := make([]string, 0) - for _, v := range *input.Include { + for _, v := range *o.include { vals = append(vals, string(v)) } include := strings.Join(vals, ",") - queryParameters["include"] = autorest.Encode("query", include) + query.Append("include", include) } - if input.Marker != nil { - queryParameters["marker"] = autorest.Encode("query", *input.Marker) + if o.marker != nil { + query.Append("marker", *o.marker) } - if input.MaxResults != nil { - queryParameters["maxresults"] = autorest.Encode("query", *input.MaxResults) + if o.maxResults != nil { + query.Append("maxresults", fmt.Sprintf("%d", *o.maxResults)) } - if input.Prefix != nil { - queryParameters["prefix"] = autorest.Encode("query", *input.Prefix) + if o.prefix != nil { + query.Append("prefix", *o.prefix) } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListBlobsSender sends the ListBlobs request. The method will close the -// http.Response Body if it receives an error. -func (client Client) ListBlobsSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ListBlobsResponder handles the response to the ListBlobs request. The method always -// closes the http.Response Body. -func (client Client) ListBlobsResponder(resp *http.Response) (result ListBlobsResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingXML(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return + return query } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/models.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/models.go index adba36818aa1..ddfe1953aae6 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/models.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/models.go @@ -1,7 +1,5 @@ package containers -import "github.com/Azure/go-autorest/autorest" - type AccessLevel string var ( @@ -21,8 +19,6 @@ var ( ) type ContainerProperties struct { - autorest.Response - AccessLevel AccessLevel LeaseStatus LeaseStatus LeaseState LeaseState diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/options.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/options.go new file mode 100644 index 000000000000..73fadf16ae8f --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/options.go @@ -0,0 +1,35 @@ +package containers + +import ( + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" + "github.com/tombuildsstuff/giovanni/storage/internal/metadata" +) + +var _ client.Options = containerOptions{} + +type containerOptions struct { + metaData map[string]string +} + +func (o containerOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + + metaDataHeaders := make(map[string]interface{}) + metadata.SetIntoHeaders(metaDataHeaders, o.metaData) + for k, v := range metaDataHeaders { + headers.Append(k, v.(string)) + } + + return headers +} + +func (containerOptions) ToOData() *odata.Query { + return nil +} + +func (containerOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "container") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/resource_id.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/resource_id.go index d35674a7868d..321ea60e4a29 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/resource_id.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/resource_id.go @@ -5,49 +5,77 @@ import ( "net/url" "strings" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" + "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts" ) -// GetResourceID returns the Resource ID for the given Container -// This can be useful when, for example, you're using this as a unique identifier -func (client Client) GetResourceID(accountName, containerName string) string { - domain := endpoints.GetBlobEndpoint(client.BaseURI, accountName) - return fmt.Sprintf("%s/%s", domain, containerName) -} - // GetResourceManagerResourceID returns the Resource Manager specific // ResourceID for a specific Storage Container -func (client Client) GetResourceManagerResourceID(subscriptionID, resourceGroup, accountName, containerName string) string { +func (c Client) GetResourceManagerResourceID(subscriptionID, resourceGroup, accountName, containerName string) string { fmtStr := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Storage/storageAccounts/%s/blobServices/default/containers/%s" return fmt.Sprintf(fmtStr, subscriptionID, resourceGroup, accountName, containerName) } -type ResourceID struct { - AccountName string +// TODO: update this to implement `resourceids.ResourceId` once +// https://github.com/hashicorp/go-azure-helpers/issues/187 is fixed +var _ resourceids.Id = ContainerId{} + +type ContainerId struct { + // AccountId specifies the ID of the Storage Account where this Container exists. + AccountId accounts.AccountId + + // ContainerName specifies the name of this Container. ContainerName string } -// ParseResourceID parses the Resource ID and returns an object which can be used -// to interact with the Container Resource -func ParseResourceID(id string) (*ResourceID, error) { +func NewContainerID(accountId accounts.AccountId, containerName string) ContainerId { + return ContainerId{ + AccountId: accountId, + ContainerName: containerName, + } +} + +func (b ContainerId) ID() string { + return fmt.Sprintf("%s/%s", b.AccountId.ID(), b.ContainerName) +} + +func (b ContainerId) String() string { + components := []string{ + fmt.Sprintf("Account %q", b.AccountId.String()), + } + return fmt.Sprintf("Container %q (%s)", b.ContainerName, strings.Join(components, " / ")) +} + +// ParseContainerID parses `input` into a Container ID using a known `domainSuffix` +func ParseContainerID(input, domainSuffix string) (*ContainerId, error) { // example: https://foo.blob.core.windows.net/Bar - if id == "" { - return nil, fmt.Errorf("`id` was empty") + if input == "" { + return nil, fmt.Errorf("`input` was empty") } - uri, err := url.Parse(id) + account, err := accounts.ParseAccountID(input, domainSuffix) if err != nil { - return nil, fmt.Errorf("Error parsing ID as a URL: %s", err) + return nil, fmt.Errorf("parsing account %q: %+v", input, err) } - accountName, err := endpoints.GetAccountNameFromEndpoint(uri.Host) + if account.SubDomainType != accounts.BlobSubDomainType { + return nil, fmt.Errorf("expected the subdomain type to be %q but got %q", string(accounts.BlobSubDomainType), string(account.SubDomainType)) + } + + uri, err := url.Parse(input) if err != nil { - return nil, fmt.Errorf("Error parsing Account Name: %s", err) + return nil, fmt.Errorf("parsing %q as a uri: %+v", input, err) + } + + path := strings.TrimPrefix(uri.Path, "/") + segments := strings.Split(path, "/") + if len(segments) != 1 { + return nil, fmt.Errorf("expected the path to contain 1 segment but got %d", len(segments)) } containerName := strings.TrimPrefix(uri.Path, "/") - return &ResourceID{ - AccountName: *accountName, + return &ContainerId{ + AccountId: *account, ContainerName: containerName, }, nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/set_acl.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/set_acl.go index fcf4e1056fa4..642053735ff4 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/set_acl.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/set_acl.go @@ -2,99 +2,85 @@ package containers import ( "context" + "fmt" "net/http" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) -// SetAccessControl sets the Access Control for a Container without a Lease ID -func (client Client) SetAccessControl(ctx context.Context, accountName, containerName string, level AccessLevel) (autorest.Response, error) { - return client.SetAccessControlWithLeaseID(ctx, accountName, containerName, "", level) +type SetAccessControlInput struct { + AccessLevel AccessLevel + LeaseId string } -// SetAccessControlWithLeaseID sets the Access Control for a Container using the specified Lease ID -func (client Client) SetAccessControlWithLeaseID(ctx context.Context, accountName, containerName, leaseID string, level AccessLevel) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("containers.Client", "SetAccessControl", "`accountName` cannot be an empty string.") - } +type SetAccessControlResponse struct { + HttpResponse *client.Response +} + +// SetAccessControl sets the Access Control for a Container without a Lease ID +// NOTE: The SetAccessControl operation only supports Shared Key authorization. +func (c Client) SetAccessControl(ctx context.Context, containerName string, input SetAccessControlInput) (resp SetAccessControlResponse, err error) { if containerName == "" { - return result, validation.NewError("containers.Client", "SetAccessControl", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } - req, err := client.SetAccessControlWithLeaseIDPreparer(ctx, accountName, containerName, leaseID, level) - if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "SetAccessControl", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPut, + OptionsObject: setAccessControlListOptions{ + accessLevel: input.AccessLevel, + leaseId: input.LeaseId, + }, + Path: fmt.Sprintf("/%s", containerName), } - - resp, err := client.SetAccessControlWithLeaseIDSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "containers.Client", "SetAccessControl", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - - result, err = client.SetAccessControlWithLeaseIDResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "SetAccessControl", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// SetAccessControlWithLeaseIDPreparer prepares the SetAccessControlWithLeaseID request. -func (client Client) SetAccessControlWithLeaseIDPreparer(ctx context.Context, accountName, containerName, leaseID string, level AccessLevel) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - } +var _ client.Options = setAccessControlListOptions{} - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("path", "acl"), - "restype": autorest.Encode("path", "container"), - } +type setAccessControlListOptions struct { + accessLevel AccessLevel + leaseId string +} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } +func (o setAccessControlListOptions) ToHeaders() *client.Headers { + headers := containerOptions{}.ToHeaders() - headers = client.setAccessLevelIntoHeaders(headers, level) + // If this header is not included in the request, container data is private to the account owner. + if o.accessLevel != Private { + headers.Append("x-ms-blob-public-access", string(o.accessLevel)) + } // If specified, Get Container Properties only succeeds if the container’s lease is active and matches this ID. // If there is no active lease or the ID does not match, 412 (Precondition Failed) is returned. - if leaseID != "" { - headers["x-ms-lease-id"] = leaseID + if o.leaseId != "" { + headers.Append("x-ms-lease-id", o.leaseId) } - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// SetAccessControlWithLeaseIDSender sends the SetAccessControlWithLeaseID request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SetAccessControlWithLeaseIDSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (o setAccessControlListOptions) ToOData() *odata.Query { + return nil } -// SetAccessControlWithLeaseIDResponder handles the response to the SetAccessControlWithLeaseID request. The method always -// closes the http.Response Body. -func (client Client) SetAccessControlWithLeaseIDResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return +func (o setAccessControlListOptions) ToQuery() *client.QueryParams { + query := containerOptions{}.ToQuery() + query.Append("comp", "acl") + return query } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/set_metadata.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/set_metadata.go index fb9e07fdefa9..578c9a169558 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/set_metadata.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/set_metadata.go @@ -5,101 +5,82 @@ import ( "fmt" "net/http" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" "github.com/tombuildsstuff/giovanni/storage/internal/metadata" ) -// SetMetaData sets the specified MetaData on the Container without a Lease ID -func (client Client) SetMetaData(ctx context.Context, accountName, containerName string, metaData map[string]string) (autorest.Response, error) { - return client.SetMetaDataWithLeaseID(ctx, accountName, containerName, "", metaData) +type SetMetaDataInput struct { + MetaData map[string]string + LeaseId string } -// SetMetaDataWithLeaseID sets the specified MetaData on the Container using the specified Lease ID -func (client Client) SetMetaDataWithLeaseID(ctx context.Context, accountName, containerName, leaseID string, metaData map[string]string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("containers.Client", "SetMetaData", "`accountName` cannot be an empty string.") - } +type SetMetaDataResponse struct { + HttpResponse *client.Response +} + +// SetMetaData sets the specified MetaData on the Container without a Lease ID +func (c Client) SetMetaData(ctx context.Context, containerName string, input SetMetaDataInput) (resp SetMetaDataResponse, err error) { if containerName == "" { - return result, validation.NewError("containers.Client", "SetMetaData", "`containerName` cannot be an empty string.") + return resp, fmt.Errorf("`containerName` cannot be an empty string") } - if err := metadata.Validate(metaData); err != nil { - return result, validation.NewError("containers.Client", "SetMetaData", fmt.Sprintf("`metaData` is not valid: %s.", err)) + if err := metadata.Validate(input.MetaData); err != nil { + return resp, fmt.Errorf("`input.MetaData` is not valid: %s", err) } - req, err := client.SetMetaDataWithLeaseIDPreparer(ctx, accountName, containerName, leaseID, metaData) - if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "SetMetaData", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPut, + OptionsObject: setMetaDataOptions{ + metaData: input.MetaData, + leaseId: input.LeaseId, + }, + Path: fmt.Sprintf("/%s", containerName), } - - resp, err := client.SetMetaDataWithLeaseIDSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "containers.Client", "SetMetaData", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - - result, err = client.SetMetaDataWithLeaseIDResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "containers.Client", "SetMetaData", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// SetMetaDataWithLeaseIDPreparer prepares the SetMetaDataWithLeaseID request. -func (client Client) SetMetaDataWithLeaseIDPreparer(ctx context.Context, accountName, containerName, leaseID string, metaData map[string]string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "containerName": autorest.Encode("path", containerName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("path", "metadata"), - "restype": autorest.Encode("path", "container"), - } +var _ client.Options = setMetaDataOptions{} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } +type setMetaDataOptions struct { + metaData map[string]string + leaseId string +} - headers = metadata.SetIntoHeaders(headers, metaData) +func (o setMetaDataOptions) ToHeaders() *client.Headers { + headers := containerOptions{ + metaData: o.metaData, + }.ToHeaders() // If specified, Get Container Properties only succeeds if the container’s lease is active and matches this ID. // If there is no active lease or the ID does not match, 412 (Precondition Failed) is returned. - if leaseID != "" { - headers["x-ms-lease-id"] = leaseID + if o.leaseId != "" { + headers.Append("x-ms-lease-id", o.leaseId) } - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetBlobEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{containerName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// SetMetaDataWithLeaseIDSender sends the SetMetaDataWithLeaseID request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SetMetaDataWithLeaseIDSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (o setMetaDataOptions) ToOData() *odata.Query { + return nil } -// SetMetaDataWithLeaseIDResponder handles the response to the SetMetaDataWithLeaseID request. The method always -// closes the http.Response Body. -func (client Client) SetMetaDataWithLeaseIDResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return +func (o setMetaDataOptions) ToQuery() *client.QueryParams { + query := containerOptions{}.ToQuery() + query.Append("comp", "metadata") + return query } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/version.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/version.go index d3138cb35875..d55e9ee67f88 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/version.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers/version.go @@ -1,14 +1,4 @@ package containers -import ( - "fmt" - - "github.com/tombuildsstuff/giovanni/version" -) - -// APIVersion is the version of the API used for all Storage API Operations -const APIVersion = "2020-08-04" - -func UserAgent() string { - return fmt.Sprintf("tombuildsstuff/giovanni/%s storage/%s", version.Number, APIVersion) -} +const apiVersion = "2020-08-04" +const componentName = "blob/containers" diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/README.md b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/README.md index be6fb76139d5..2ba37865f25b 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/README.md +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/README.md @@ -15,67 +15,37 @@ import ( "context" "fmt" "os" - "time" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/adal" - "github.com/Azure/go-autorest/autorest/azure" "github.com/hashicorp/go-azure-helpers/authentication" "github.com/hashicorp/go-azure-helpers/sender" + "github.com/hashicorp/go-azure-sdk/sdk/auth" "github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems" ) func Example() error { accountName := "storageaccount1" fileSystemName := "filesystem1" + storageAccountKey := "ABC123...." + domainSuffix := "core.windows.net" + - builder := &authentication.Builder{ - SubscriptionID: os.Getenv("ARM_SUBSCRIPTION_ID"), - ClientID: os.Getenv("ARM_CLIENT_ID"), - ClientSecret: os.Getenv("ARM_CLIENT_SECRET"), - TenantID: os.Getenv("ARM_TENANT_ID"), - Environment: os.Getenv("ARM_ENVIRONMENT"), - - // Feature Toggles - SupportsClientSecretAuth: true, - } - - c, err := builder.Build() - if err != nil { - return fmt.Errorf("Error building AzureRM Client: %s", err) - } - - env, err := authentication.DetermineEnvironment(c.Environment) - if err != nil { - return err - } - - oauthConfig, err := adal.NewOAuthConfig(env.ActiveDirectoryEndpoint, c.TenantID) + auth, err := auth.NewSharedKeyAuthorizer(accountName, storageAccountKey, auth.SharedKey) if err != nil { - return err - } - - // OAuthConfigForTenant returns a pointer, which can be nil. - if oauthConfig == nil { - return fmt.Errorf("Unable to configure OAuthConfig for tenant %s", c.TenantID) + return fmt.Errorf("building SharedKey authorizer: %+v", err) } - - sender := sender.BuildSender("AzureRM") - ctx := context.Background() - - storageAuth, err := config.GetAuthorizationToken(sender, oauthConfig, "https://storage.azure.com/") + + fileSystemsClient, err := filesystems.NewWithBaseUri(fmt.Sprintf("https://%s.dfs.%s", accountName, domainSuffix)) if err != nil { - return fmt.Errorf("Error retrieving Authorization Token") + return fmt.Errorf("building client for environment: %+v", err) } - - - fileSystemsClient := filesystems.NewWithEnvironment(env) - fileSystemsClient.Client.Authorizer = storageAuth + fileSystemsClient.Client.WithAuthorizer(auth) input := filesystems.CreateInput{ Properties: map[string]string{}, } - if _, err = fileSystemsClient.Create(ctx, accountName, fileSystemName, input); err != nil { + + ctx := context.Background() + if _, err = fileSystemsClient.Create(ctx, fileSystemName, input); err != nil { return fmt.Errorf("Error creating: %s", err) } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/client.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/client.go index 91d3fe1cf45e..27e96d1bcc86 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/client.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/client.go @@ -1,25 +1,23 @@ package filesystems import ( - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" + "fmt" + + "github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/storage" ) -// Client is the base client for Data Lake Storage FileSystem +// Client is the base client for Data Lake Store Filesystems. type Client struct { - autorest.Client - BaseURI string -} - -// New creates an instance of the Data Lake Storage FileSystem client. -func New() Client { - return NewWithEnvironment(azure.PublicCloud) + Client *storage.BaseClient } -// NewWithEnvironment creates an instance of the Data Lake Storage FileSystem client. -func NewWithEnvironment(environment azure.Environment) Client { - return Client{ - Client: autorest.NewClientWithUserAgent(UserAgent()), - BaseURI: environment.StorageEndpointSuffix, +func NewWithBaseUri(baseUri string) (*Client, error) { + baseClient, err := storage.NewBaseClient(baseUri, componentName, apiVersion) + if err != nil { + return nil, fmt.Errorf("building base client: %+v", err) } + + return &Client{ + Client: baseClient, + }, nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/create.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/create.go index 4217cb80af0e..d0d4bab6321e 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/create.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/create.go @@ -2,12 +2,11 @@ package filesystems import ( "context" + "fmt" "net/http" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type CreateInput struct { @@ -18,77 +17,63 @@ type CreateInput struct { Properties map[string]string } +type CreateResponse struct { + HttpResponse *client.Response +} + // Create creates a Data Lake Store Gen2 FileSystem within a Storage Account -func (client Client) Create(ctx context.Context, accountName string, fileSystemName string, input CreateInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("datalakestore.Client", "Create", "`accountName` cannot be an empty string.") - } +func (c Client) Create(ctx context.Context, fileSystemName string, input CreateInput) (resp CreateResponse, err error) { + if fileSystemName == "" { - return result, validation.NewError("datalakestore.Client", "Create", "`fileSystemName` cannot be an empty string.") + return resp, fmt.Errorf("`fileSystemName` cannot be an empty string") } - req, err := client.CreatePreparer(ctx, accountName, fileSystemName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "datalakestore.Client", "Create", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: createOptions{ + properties: input.Properties, + }, + + Path: fmt.Sprintf("/%s", fileSystemName), } - resp, err := client.CreateSender(req) + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "datalakestore.Client", "Create", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - - result, err = client.CreateResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "datalakestore.Client", "Create", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) + return } return } -// CreatePreparer prepares the Create request. -func (client Client) CreatePreparer(ctx context.Context, accountName string, fileSystemName string, input CreateInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "fileSystemName": autorest.Encode("path", fileSystemName), - } - - queryParameters := map[string]interface{}{ - "resource": autorest.Encode("query", "filesystem"), - } +type createOptions struct { + properties map[string]string +} - headers := map[string]interface{}{ - "x-ms-properties": buildProperties(input.Properties), - "x-ms-version": APIVersion, +func (o createOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + props := buildProperties(o.properties) + if props != "" { + headers.Append("x-ms-properties", props) } - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetDataLakeStoreEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{fileSystemName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// CreateSender sends the Create request. The method will close the -// http.Response Body if it receives an error. -func (client Client) CreateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (createOptions) ToOData() *odata.Query { + return nil } -// CreateResponder handles the response to the Create request. The method always -// closes the http.Response Body. -func (client Client) CreateResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return +func (createOptions) ToQuery() *client.QueryParams { + return fileSystemOptions{}.ToQuery() } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/delete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/delete.go index fabc589da940..a6d33b332801 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/delete.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/delete.go @@ -2,84 +2,42 @@ package filesystems import ( "context" + "fmt" "net/http" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" ) +type DeleteResponse struct { + HttpResponse *client.Response +} + // Delete deletes a Data Lake Store Gen2 FileSystem within a Storage Account -func (client Client) Delete(ctx context.Context, accountName string, fileSystemName string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("datalakestore.Client", "Delete", "`accountName` cannot be an empty string.") - } +func (c Client) Delete(ctx context.Context, fileSystemName string) (resp DeleteResponse, err error) { + if fileSystemName == "" { - return result, validation.NewError("datalakestore.Client", "Delete", "`fileSystemName` cannot be an empty string.") + return resp, fmt.Errorf("`fileSystemName` cannot be an empty string") } - req, err := client.DeletePreparer(ctx, accountName, fileSystemName) - if err != nil { - err = autorest.NewErrorWithError(err, "datalakestore.Client", "Delete", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusAccepted, + }, + HttpMethod: http.MethodDelete, + OptionsObject: fileSystemOptions{}, + Path: fmt.Sprintf("/%s", fileSystemName), } - - resp, err := client.DeleteSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "datalakestore.Client", "Delete", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - - result, err = client.DeleteResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "datalakestore.Client", "Delete", resp, "Failure responding to request") - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client Client) DeletePreparer(ctx context.Context, accountName string, fileSystemName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "fileSystemName": autorest.Encode("path", fileSystemName), - } - - queryParameters := map[string]interface{}{ - "resource": autorest.Encode("query", "filesystem"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, + err = fmt.Errorf("executing request: %+v", err) + return } - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(endpoints.GetDataLakeStoreEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{fileSystemName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client Client) DeleteSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client Client) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusAccepted), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - return } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/options.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/options.go new file mode 100644 index 000000000000..aee33a0c4595 --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/options.go @@ -0,0 +1,32 @@ +package filesystems + +import ( + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +var _ client.Options = fileSystemOptions{} + +type fileSystemOptions struct { + properties map[string]string +} + +func (o fileSystemOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + props := buildProperties(o.properties) + if props != "" { + headers.Append("x-ms-properties", props) + } + + return headers +} + +func (fileSystemOptions) ToOData() *odata.Query { + return nil +} + +func (fileSystemOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("resource", "filesystem") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/properties_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/properties_get.go index 0b96c95edd52..e8e4a67d0a05 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/properties_get.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/properties_get.go @@ -2,17 +2,15 @@ package filesystems import ( "context" + "fmt" "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" ) type GetPropertiesResponse struct { - autorest.Response + HttpResponse *client.Response // A map of base64-encoded strings to store as user-defined properties with the File System // Note that items may only contain ASCII characters in the ISO-8859-1 character set. @@ -25,88 +23,46 @@ type GetPropertiesResponse struct { } // GetProperties gets the properties for a Data Lake Store Gen2 FileSystem within a Storage Account -func (client Client) GetProperties(ctx context.Context, accountName string, fileSystemName string) (result GetPropertiesResponse, err error) { - if accountName == "" { - return result, validation.NewError("datalakestore.Client", "GetProperties", "`accountName` cannot be an empty string.") - } +func (c Client) GetProperties(ctx context.Context, fileSystemName string) (resp GetPropertiesResponse, err error) { + if fileSystemName == "" { - return result, validation.NewError("datalakestore.Client", "GetProperties", "`fileSystemName` cannot be an empty string.") + return resp, fmt.Errorf("`fileSystemName` cannot be an empty string") } - req, err := client.GetPropertiesPreparer(ctx, accountName, fileSystemName) - if err != nil { - err = autorest.NewErrorWithError(err, "datalakestore.Client", "GetProperties", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodHead, + OptionsObject: fileSystemOptions{}, + Path: fmt.Sprintf("/%s", fileSystemName), } - resp, err := client.GetPropertiesSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "datalakestore.Client", "GetProperties", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.GetPropertiesResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "datalakestore.Client", "GetProperties", resp, "Failure responding to request") - } - - return -} - -// GetPropertiesPreparer prepares the GetProperties request. -func (client Client) GetPropertiesPreparer(ctx context.Context, accountName string, fileSystemName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "fileSystemName": autorest.Encode("path", fileSystemName), - } - - queryParameters := map[string]interface{}{ - "resource": autorest.Encode("query", "filesystem"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, + err = fmt.Errorf("executing request: %+v", err) + return } - preparer := autorest.CreatePreparer( - autorest.AsHead(), - autorest.WithBaseURL(endpoints.GetDataLakeStoreEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{fileSystemName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) + if resp.HttpResponse != nil { - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetPropertiesSender sends the GetProperties request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetPropertiesSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// GetPropertiesResponder handles the response to the GetProperties request. The method always -// closes the http.Response Body. -func (client Client) GetPropertiesResponder(resp *http.Response) (result GetPropertiesResponse, err error) { - if resp != nil && resp.Header != nil { - - propertiesRaw := resp.Header.Get("x-ms-properties") + propertiesRaw := resp.HttpResponse.Header.Get("x-ms-properties") var properties *map[string]string properties, err = parseProperties(propertiesRaw) if err != nil { return } - result.Properties = *properties - result.NamespaceEnabled = strings.EqualFold(resp.Header.Get("x-ms-namespace-enabled"), "tru") - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} + resp.Properties = *properties + resp.NamespaceEnabled = strings.EqualFold(resp.HttpResponse.Header.Get("x-ms-namespace-enabled"), "true") + } return } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/properties_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/properties_set.go index dde02a4455b9..82c259a236e8 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/properties_set.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/properties_set.go @@ -2,12 +2,11 @@ package filesystems import ( "context" + "fmt" "net/http" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type SetPropertiesInput struct { @@ -26,84 +25,75 @@ type SetPropertiesInput struct { IfUnmodifiedSince *string } +type SetPropertiesResponse struct { + HttpResponse *client.Response +} + // SetProperties sets the Properties for a Data Lake Store Gen2 FileSystem within a Storage Account -func (client Client) SetProperties(ctx context.Context, accountName string, fileSystemName string, input SetPropertiesInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("datalakestore.Client", "SetProperties", "`accountName` cannot be an empty string.") - } +func (c Client) SetProperties(ctx context.Context, fileSystemName string, input SetPropertiesInput) (resp SetPropertiesResponse, err error) { + if fileSystemName == "" { - return result, validation.NewError("datalakestore.Client", "SetProperties", "`fileSystemName` cannot be an empty string.") + return resp, fmt.Errorf("`fileSystemName` cannot be an empty string") } - req, err := client.SetPropertiesPreparer(ctx, accountName, fileSystemName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "datalakestore.Client", "SetProperties", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPatch, + OptionsObject: setPropertiesOptions{ + properties: input.Properties, + ifUnmodifiedSince: input.IfUnmodifiedSince, + ifModifiedSince: input.IfModifiedSince, + }, + + Path: fmt.Sprintf("/%s", fileSystemName), } - resp, err := client.SetPropertiesSender(req) + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "datalakestore.Client", "SetProperties", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - - result, err = client.SetPropertiesResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "datalakestore.Client", "SetProperties", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) + return } return } -// SetPropertiesPreparer prepares the SetProperties request. -func (client Client) SetPropertiesPreparer(ctx context.Context, accountName string, fileSystemName string, input SetPropertiesInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "fileSystemName": autorest.Encode("path", fileSystemName), - } +type setPropertiesOptions struct { + properties map[string]string + ifModifiedSince *string + ifUnmodifiedSince *string +} - queryParameters := map[string]interface{}{ - "resource": autorest.Encode("query", "filesystem"), - } +func (o setPropertiesOptions) ToHeaders() *client.Headers { - headers := map[string]interface{}{ - "x-ms-properties": buildProperties(input.Properties), - "x-ms-version": APIVersion, + headers := &client.Headers{} + props := buildProperties(o.properties) + if props != "" { + headers.Append("x-ms-properties", props) } - if input.IfModifiedSince != nil { - headers["If-Modified-Since"] = *input.IfModifiedSince + if o.ifModifiedSince != nil { + headers.Append("If-Modified-Since", *o.ifModifiedSince) } - if input.IfUnmodifiedSince != nil { - headers["If-Unmodified-Since"] = *input.IfUnmodifiedSince + if o.ifUnmodifiedSince != nil { + headers.Append("If-Unmodified-Since", *o.ifUnmodifiedSince) } - preparer := autorest.CreatePreparer( - autorest.AsPatch(), - autorest.WithBaseURL(endpoints.GetDataLakeStoreEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{fileSystemName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// SetPropertiesSender sends the SetProperties request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SetPropertiesSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (setPropertiesOptions) ToOData() *odata.Query { + return nil } -// SetPropertiesResponder handles the response to the SetProperties request. The method always -// closes the http.Response Body. -func (client Client) SetPropertiesResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return +func (setPropertiesOptions) ToQuery() *client.QueryParams { + return fileSystemOptions{}.ToQuery() } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/resource_id.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/resource_id.go index 34797b20b7a9..a2664ac47590 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/resource_id.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/resource_id.go @@ -5,42 +5,77 @@ import ( "net/url" "strings" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" + "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts" ) -// GetResourceID returns the Resource ID for the given Data Lake Storage FileSystem -// This can be useful when, for example, you're using this as a unique identifier -func (client Client) GetResourceID(accountName, shareName string) string { - domain := endpoints.GetDataLakeStoreEndpoint(client.BaseURI, accountName) - return fmt.Sprintf("%s/%s", domain, shareName) +// GetResourceManagerResourceID returns the Resource Manager specific +// ResourceID for a specific Data Lake FileSystem +func (c Client) GetResourceManagerResourceID(subscriptionID, resourceGroup, accountName, fileSystemName string) string { + fmtStr := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Storage/storageAccounts/%s/blobServices/default/containers/%s" + return fmt.Sprintf(fmtStr, subscriptionID, resourceGroup, accountName, fileSystemName) } -type ResourceID struct { - AccountName string - DirectoryName string +// TODO: update this to implement `resourceids.ResourceId` once +// https://github.com/hashicorp/go-azure-helpers/issues/187 is fixed +var _ resourceids.Id = FileSystemId{} + +type FileSystemId struct { + // AccountId specifies the ID of the Storage Account where this Data Lake FileSystem exists. + AccountId accounts.AccountId + + // FileSystemName specifies the name of this Data Lake FileSystem. + FileSystemName string +} + +func NewFileSystemID(accountId accounts.AccountId, fileSystemName string) FileSystemId { + return FileSystemId{ + AccountId: accountId, + FileSystemName: fileSystemName, + } +} + +func (b FileSystemId) ID() string { + return fmt.Sprintf("%s/%s", b.AccountId.ID(), b.FileSystemName) } -// ParseResourceID parses the specified Resource ID and returns an object -// which can be used to interact with the Data Lake Storage FileSystem API's -func ParseResourceID(id string) (*ResourceID, error) { +func (b FileSystemId) String() string { + components := []string{ + fmt.Sprintf("Account %q", b.AccountId.String()), + } + return fmt.Sprintf("File System %q (%s)", b.FileSystemName, strings.Join(components, " / ")) +} + +// ParseFileSystemID parses `input` into a File System ID using a known `domainSuffix` +func ParseFileSystemID(input, domainSuffix string) (*FileSystemId, error) { // example: https://foo.dfs.core.windows.net/Bar - if id == "" { - return nil, fmt.Errorf("`id` was empty") + if input == "" { + return nil, fmt.Errorf("`input` was empty") } - uri, err := url.Parse(id) + account, err := accounts.ParseAccountID(input, domainSuffix) if err != nil { - return nil, fmt.Errorf("Error parsing ID as a URL: %s", err) + return nil, fmt.Errorf("parsing account %q: %+v", input, err) } - accountName, err := endpoints.GetAccountNameFromEndpoint(uri.Host) + if account.SubDomainType != accounts.DataLakeStoreSubDomainType { + return nil, fmt.Errorf("expected the subdomain type to be %q but got %q", string(accounts.DataLakeStoreSubDomainType), string(account.SubDomainType)) + } + + uri, err := url.Parse(input) if err != nil { - return nil, fmt.Errorf("Error parsing Account Name: %s", err) + return nil, fmt.Errorf("parsing %q as a uri: %+v", input, err) + } + + path := strings.TrimPrefix(uri.Path, "/") + segments := strings.Split(path, "/") + if len(segments) != 1 { + return nil, fmt.Errorf("expected the path to contain 1 segment but got %d", len(segments)) } - directoryName := strings.TrimPrefix(uri.Path, "/") - return &ResourceID{ - AccountName: *accountName, - DirectoryName: directoryName, + fileSystemName := segments[0] + return &FileSystemId{ + AccountId: *account, + FileSystemName: fileSystemName, }, nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/version.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/version.go index 7447ea9ade09..ff22a87f4eca 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/version.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/filesystems/version.go @@ -1,14 +1,4 @@ package filesystems -import ( - "fmt" - - "github.com/tombuildsstuff/giovanni/version" -) - -// APIVersion is the version of the API used for all Storage API Operations -const APIVersion = "2020-08-04" - -func UserAgent() string { - return fmt.Sprintf("tombuildsstuff/giovanni/%s storage/%s", version.Number, APIVersion) -} +const apiVersion = "2020-08-04" +const componentName = "datalakestore/filesystems" diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/client.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/client.go index 3fb087bf8c8d..27e70be8f022 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/client.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/client.go @@ -1,25 +1,22 @@ package paths import ( - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" + "fmt" + "github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/storage" ) // Client is the base client for Data Lake Storage Path type Client struct { - autorest.Client - BaseURI string + Client *storage.BaseClient } -// New creates an instance of the Data Lake Storage Path client. -func New() Client { - return NewWithEnvironment(azure.PublicCloud) -} - -// NewWithEnvironment creates an instance of the Data Lake Storage Path client. -func NewWithEnvironment(environment azure.Environment) Client { - return Client{ - Client: autorest.NewClientWithUserAgent(UserAgent()), - BaseURI: environment.StorageEndpointSuffix, +func NewWithBaseUri(baseUri string) (*Client, error) { + baseClient, err := storage.NewBaseClient(baseUri, componentName, apiVersion) + if err != nil { + return nil, fmt.Errorf("building base client: %+v", err) } + + return &Client{ + Client: baseClient, + }, nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/create.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/create.go index 600bd75a9a87..c95ea17ba1a5 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/create.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/create.go @@ -2,12 +2,11 @@ package paths import ( "context" + "fmt" "net/http" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type PathResource string @@ -19,77 +18,55 @@ type CreateInput struct { Resource PathResource } +type CreateResponse struct { + HttpResponse *client.Response +} + // Create creates a Data Lake Store Gen2 Path within a Storage Account -func (client Client) Create(ctx context.Context, accountName string, fileSystemName string, path string, input CreateInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("datalakestore.Client", "Create", "`accountName` cannot be an empty string.") - } +func (c Client) Create(ctx context.Context, fileSystemName string, path string, input CreateInput) (resp CreateResponse, err error) { + if fileSystemName == "" { - return result, validation.NewError("datalakestore.Client", "Create", "`fileSystemName` cannot be an empty string.") + return resp, fmt.Errorf("`fileSystemName` cannot be an empty string") } - req, err := client.CreatePreparer(ctx, accountName, fileSystemName, path, input) - if err != nil { - err = autorest.NewErrorWithError(err, "datalakestore.Client", "Create", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: CreateInput{ + Resource: input.Resource, + }, + + Path: fmt.Sprintf("/%s/%s", fileSystemName, path), } - resp, err := client.CreateSender(req) + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "datalakestore.Client", "Create", resp, "Failure sending request") - return + err = fmt.Errorf("building request: %+v", err) + return resp, err } - - result, err = client.CreateResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "datalakestore.Client", "Create", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) + return resp, err } return } -// CreatePreparer prepares the Create request. -func (client Client) CreatePreparer(ctx context.Context, accountName string, fileSystemName string, path string, input CreateInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "fileSystemName": autorest.Encode("path", fileSystemName), - "path": autorest.Encode("path", path), - } - - queryParameters := map[string]interface{}{ - "resource": autorest.Encode("query", input.Resource), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetDataLakeStoreEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{fileSystemName}/{path}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - - return preparer.Prepare((&http.Request{}).WithContext(ctx)) +func (c CreateInput) ToHeaders() *client.Headers { + return nil } -// CreateSender sends the Create request. The method will close the -// http.Response Body if it receives an error. -func (client Client) CreateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (c CreateInput) ToOData() *odata.Query { + return nil } -// CreateResponder handles the response to the Create request. The method always -// closes the http.Response Body. -func (client Client) CreateResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return +func (c CreateInput) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("resource", string(c.Resource)) + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/delete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/delete.go index 078be57915af..4ea6e9312cdb 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/delete.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/delete.go @@ -2,80 +2,42 @@ package paths import ( "context" + "fmt" "net/http" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" ) +type DeleteResponse struct { + HttpResponse *client.Response +} + // Delete deletes a Data Lake Store Gen2 FileSystem within a Storage Account -func (client Client) Delete(ctx context.Context, accountName string, fileSystemName string, path string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("datalakestore.Client", "Delete", "`accountName` cannot be an empty string.") - } +func (c Client) Delete(ctx context.Context, fileSystemName string, path string) (resp DeleteResponse, err error) { + if fileSystemName == "" { - return result, validation.NewError("datalakestore.Client", "Delete", "`fileSystemName` cannot be an empty string.") + return resp, fmt.Errorf("`fileSystemName` cannot be an empty string") } - req, err := client.DeletePreparer(ctx, accountName, fileSystemName, path) - if err != nil { - err = autorest.NewErrorWithError(err, "datalakestore.Client", "Delete", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodDelete, + OptionsObject: nil, + Path: fmt.Sprintf("/%s/%s", fileSystemName, path), } - - resp, err := client.DeleteSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "datalakestore.Client", "Delete", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - - result, err = client.DeleteResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "datalakestore.Client", "Delete", resp, "Failure responding to request") - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client Client) DeletePreparer(ctx context.Context, accountName string, fileSystemName string, path string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "fileSystemName": autorest.Encode("path", fileSystemName), - "path": autorest.Encode("path", path), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, + err = fmt.Errorf("executing request: %+v", err) + return } - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(endpoints.GetDataLakeStoreEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{fileSystemName}/{path}", pathParameters), - autorest.WithHeaders(headers)) - - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client Client) DeleteSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client Client) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - return } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/properties_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/properties_get.go index 263dc53ed95b..2bb81afc574f 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/properties_get.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/properties_get.go @@ -2,17 +2,16 @@ package paths import ( "context" + "fmt" "net/http" "time" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type GetPropertiesResponse struct { - autorest.Response + HttpResponse *client.Response ETag string LastModified time.Time @@ -24,6 +23,10 @@ type GetPropertiesResponse struct { ACL string } +type GetPropertiesInput struct { + action GetPropertiesAction +} + type GetPropertiesAction string const ( @@ -32,103 +35,69 @@ const ( ) // GetProperties gets the properties for a Data Lake Store Gen2 Path in a FileSystem within a Storage Account -func (client Client) GetProperties(ctx context.Context, accountName string, fileSystemName string, path string, action GetPropertiesAction) (result GetPropertiesResponse, err error) { - if accountName == "" { - return result, validation.NewError("datalakestore.Client", "GetProperties", "`accountName` cannot be an empty string.") - } +func (c Client) GetProperties(ctx context.Context, fileSystemName string, path string, input GetPropertiesInput) (resp GetPropertiesResponse, err error) { if fileSystemName == "" { - return result, validation.NewError("datalakestore.Client", "GetProperties", "`fileSystemName` cannot be an empty string.") + return resp, fmt.Errorf("`fileSystemName` cannot be an empty string") } - req, err := client.GetPropertiesPreparer(ctx, accountName, fileSystemName, path, action) - if err != nil { - err = autorest.NewErrorWithError(err, "datalakestore.Client", "GetProperties", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodHead, + OptionsObject: getPropertyOptions{ + action: input.action, + }, + Path: fmt.Sprintf("/%s/%s", fileSystemName, path), } - resp, err := client.GetPropertiesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "datalakestore.Client", "GetProperties", resp, "Failure sending request") - return - } + req, err := c.Client.NewRequest(ctx, opts) - result, err = client.GetPropertiesResponder(resp) if err != nil { - err = autorest.NewErrorWithError(err, "datalakestore.Client", "GetProperties", resp, "Failure responding to request") - } - - return -} - -// GetPropertiesPreparer prepares the GetProperties request. -func (client Client) GetPropertiesPreparer(ctx context.Context, accountName string, fileSystemName string, path string, action GetPropertiesAction) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "fileSystemName": autorest.Encode("path", fileSystemName), - "path": autorest.Encode("path", path), - } - - queryParameters := map[string]interface{}{ - "action": autorest.Encode("query", string(action)), + err = fmt.Errorf("building request: %+v", err) + return resp, err } - headers := map[string]interface{}{ - "x-ms-version": APIVersion, + resp.HttpResponse, err = req.Execute(ctx) + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return resp, err } - preparer := autorest.CreatePreparer( - autorest.AsHead(), - autorest.WithBaseURL(endpoints.GetDataLakeStoreEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{fileSystemName}/{path}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} + if resp.HttpResponse != nil { + resp.ResourceType = PathResource(resp.HttpResponse.Header.Get("x-ms-resource-type")) + resp.ETag = resp.HttpResponse.Header.Get("ETag") -// GetPropertiesSender sends the GetProperties request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetPropertiesSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// GetPropertiesResponder handles the response to the GetProperties request. The method always -// closes the http.Response Body. -func (client Client) GetPropertiesResponder(resp *http.Response) (result GetPropertiesResponse, err error) { - result = GetPropertiesResponse{} - if resp != nil && resp.Header != nil { - - resourceTypeRaw := resp.Header.Get("x-ms-resource-type") - var resourceType PathResource - if resourceTypeRaw != "" { - resourceType, err = parsePathResource(resourceTypeRaw) - if err != nil { - return GetPropertiesResponse{}, err - } - result.ResourceType = resourceType - } - result.ETag = resp.Header.Get("ETag") - - if lastModifiedRaw := resp.Header.Get("Last-Modified"); lastModifiedRaw != "" { + if lastModifiedRaw := resp.HttpResponse.Header.Get("Last-Modified"); lastModifiedRaw != "" { lastModified, err := time.Parse(time.RFC1123, lastModifiedRaw) if err != nil { return GetPropertiesResponse{}, err } - result.LastModified = lastModified + resp.LastModified = lastModified } - result.Owner = resp.Header.Get("x-ms-owner") - result.Group = resp.Header.Get("x-ms-group") - result.ACL = resp.Header.Get("x-ms-acl") + resp.Owner = resp.HttpResponse.Header.Get("x-ms-owner") + resp.Group = resp.HttpResponse.Header.Get("x-ms-group") + resp.ACL = resp.HttpResponse.Header.Get("x-ms-acl") } - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), + return +} + +type getPropertyOptions struct { + action GetPropertiesAction +} - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} +func (g getPropertyOptions) ToHeaders() *client.Headers { + return nil +} + +func (g getPropertyOptions) ToOData() *odata.Query { + return nil +} - return result, err +func (g getPropertyOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("action", string(g.action)) + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/properties_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/properties_set.go index 7c0d677647d0..055f199cbc87 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/properties_set.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/properties_set.go @@ -2,12 +2,11 @@ package paths import ( "context" + "fmt" "net/http" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type SetAccessControlInput struct { @@ -24,93 +23,81 @@ type SetAccessControlInput struct { IfUnmodifiedSince *string } +type SetPropertiesResponse struct { + HttpResponse *client.Response +} + // SetProperties sets the access control properties for a Data Lake Store Gen2 Path within a Storage Account File System -func (client Client) SetAccessControl(ctx context.Context, accountName string, fileSystemName string, path string, input SetAccessControlInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("datalakestore.Client", "SetAccessControl", "`accountName` cannot be an empty string.") - } +func (c Client) SetAccessControl(ctx context.Context, fileSystemName string, path string, input SetAccessControlInput) (resp SetPropertiesResponse, err error) { + if fileSystemName == "" { - return result, validation.NewError("datalakestore.Client", "SetAccessControl", "`fileSystemName` cannot be an empty string.") + return resp, fmt.Errorf("`fileSystemName` cannot be an empty string") } - req, err := client.SetAccessControlPreparer(ctx, accountName, fileSystemName, path, input) - if err != nil { - err = autorest.NewErrorWithError(err, "datalakestore.Client", "SetAccessControl", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPatch, + OptionsObject: setPropertyOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", fileSystemName, path), } - resp, err := client.SetAccessControlSender(req) + req, err := c.Client.NewRequest(ctx, opts) + if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "datalakestore.Client", "SetAccessControl", resp, "Failure sending request") - return + err = fmt.Errorf("building request: %+v", err) + return resp, err } - result, err = client.SetAccessControlResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "datalakestore.Client", "SetAccessControl", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) + return resp, err } return } -// SetAccessControlPreparer prepares the SetAccessControl request. -func (client Client) SetAccessControlPreparer(ctx context.Context, accountName string, fileSystemName string, path string, input SetAccessControlInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "fileSystemName": autorest.Encode("path", fileSystemName), - "path": autorest.Encode("path", path), - } +type setPropertyOptions struct { + input SetAccessControlInput +} - queryParameters := map[string]interface{}{ - "action": autorest.Encode("query", "setAccessControl"), - } +func (s setPropertyOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, + if s.input.ACL != nil { + headers.Append("x-ms-acl", *s.input.ACL) } - if input.Owner != nil { - headers["x-ms-owner"] = *input.Owner - } - if input.Group != nil { - headers["x-ms-group"] = *input.Group - } - if input.ACL != nil { - headers["x-ms-acl"] = *input.ACL + if s.input.Owner != nil { + headers.Append("x-ms-owner", *s.input.Owner) } - if input.IfModifiedSince != nil { - headers["If-Modified-Since"] = *input.IfModifiedSince + if s.input.Group != nil { + headers.Append("x-ms-group", *s.input.Group) } - if input.IfUnmodifiedSince != nil { - headers["If-Unmodified-Since"] = *input.IfUnmodifiedSince + + if s.input.IfModifiedSince != nil { + headers.Append("If-Modified-Since", *s.input.IfModifiedSince) } - preparer := autorest.CreatePreparer( - autorest.AsPatch(), - autorest.WithBaseURL(endpoints.GetDataLakeStoreEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{fileSystemName}/{path}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) + if s.input.IfUnmodifiedSince != nil { + headers.Append("If-Unmodified-Since", *s.input.IfUnmodifiedSince) + } - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// SetAccessControlSender sends the SetAccessControl request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SetAccessControlSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (s setPropertyOptions) ToOData() *odata.Query { + return nil } -// SetAccessControlResponder handles the response to the SetAccessControl request. The method always -// closes the http.Response Body. -func (client Client) SetAccessControlResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - return +func (s setPropertyOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("action", "setAccessControl") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/resource_id.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/resource_id.go index c32841877067..61022090e774 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/resource_id.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/resource_id.go @@ -5,53 +5,76 @@ import ( "net/url" "strings" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" + "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts" ) -// GetResourceID returns the Resource ID for the given Data Lake Storage FileSystem -// This can be useful when, for example, you're using this as a unique identifier -func (client Client) GetResourceID(accountName, fileSystemName, path string) string { - domain := endpoints.GetDataLakeStoreEndpoint(client.BaseURI, accountName) - return fmt.Sprintf("%s/%s/%s", domain, fileSystemName, path) -} +// TODO: update this to implement `resourceids.ResourceId` once +// https://github.com/hashicorp/go-azure-helpers/issues/187 is fixed +var _ resourceids.Id = PathId{} + +type PathId struct { + // AccountId specifies the ID of the Storage Account where this path exists. + AccountId accounts.AccountId -type ResourceID struct { - AccountName string + // FileSystemName specifies the name of the Data Lake FileSystem where this Path exists. FileSystemName string - Path string + + // Path specifies the path in question. + Path string +} + +func NewPathID(accountId accounts.AccountId, fileSystemName, path string) PathId { + return PathId{ + AccountId: accountId, + FileSystemName: fileSystemName, + Path: path, + } } -// ParseResourceID parses the specified Resource ID and returns an object -// which can be used to interact with the Data Lake Storage FileSystem API's -func ParseResourceID(id string) (*ResourceID, error) { - // example: https://foo.dfs.core.windows.net/Bar - if id == "" { - return nil, fmt.Errorf("`id` was empty") +func (b PathId) ID() string { + return fmt.Sprintf("%s/%s/%s", b.AccountId.ID(), b.FileSystemName, b.Path) +} + +func (b PathId) String() string { + components := []string{ + fmt.Sprintf("File System %q", b.FileSystemName), + fmt.Sprintf("Account %q", b.AccountId.String()), } + return fmt.Sprintf("Path %q (%s)", b.Path, strings.Join(components, " / ")) +} - uri, err := url.Parse(id) +// ParsePathID parses `input` into a Path ID using a known `domainSuffix` +func ParsePathID(input, domainSuffix string) (*PathId, error) { + // example: https://foo.dfs.core.windows.net/Bar/some/path + if input == "" { + return nil, fmt.Errorf("`input` was empty") + } + + account, err := accounts.ParseAccountID(input, domainSuffix) if err != nil { - return nil, fmt.Errorf("Error parsing ID as a URL: %s", err) + return nil, fmt.Errorf("parsing account %q: %+v", input, err) + } + + if account.SubDomainType != accounts.DataLakeStoreSubDomainType { + return nil, fmt.Errorf("expected the subdomain type to be %q but got %q", string(accounts.DataLakeStoreSubDomainType), string(account.SubDomainType)) } - accountName, err := endpoints.GetAccountNameFromEndpoint(uri.Host) + uri, err := url.Parse(input) if err != nil { - return nil, fmt.Errorf("Error parsing Account Name: %s", err) + return nil, fmt.Errorf("parsing %q as a uri: %+v", input, err) } - fileSystemAndPath := strings.TrimPrefix(uri.Path, "/") - separatorIndex := strings.Index(fileSystemAndPath, "/") - var fileSystem, path string - if separatorIndex < 0 { - fileSystem = fileSystemAndPath - path = "" - } else { - fileSystem = fileSystemAndPath[0:separatorIndex] - path = fileSystemAndPath[separatorIndex+1:] + uriPath := strings.TrimPrefix(uri.Path, "/") + segments := strings.Split(uriPath, "/") + if len(segments) < 2 { + return nil, fmt.Errorf("expected the path to contain at least 2 segments but got %d", len(segments)) } - return &ResourceID{ - AccountName: *accountName, - FileSystemName: fileSystem, + fileSystemName := segments[0] + path := strings.Join(segments[1:], "/") + return &PathId{ + AccountId: *account, + FileSystemName: fileSystemName, Path: path, }, nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/version.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/version.go index 3ca5674ec31e..bd06c2d4d15c 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/version.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/datalakestore/paths/version.go @@ -1,14 +1,4 @@ package paths -import ( - "fmt" - - "github.com/tombuildsstuff/giovanni/version" -) - -// APIVersion is the version of the API used for all Storage API Operations -const APIVersion = "2020-08-04" - -func UserAgent() string { - return fmt.Sprintf("tombuildsstuff/giovanni/%s storage/%s", version.Number, APIVersion) -} +const apiVersion = "2020-08-04" +const componentName = "datalakestore/paths" diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/README.md b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/README.md index 25474c8bc44d..0ec880f9442d 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/README.md +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/README.md @@ -19,9 +19,8 @@ package main import ( "context" "fmt" - "time" - - "github.com/Azure/go-autorest/autorest" + + "github.com/hashicorp/go-azure-sdk/sdk/auth" "github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories" ) @@ -30,16 +29,28 @@ func Example() error { storageAccountKey := "ABC123...." shareName := "myshare" directoryName := "myfiles" - - storageAuth := autorest.NewSharedKeyLiteAuthorizer(accountName, storageAccountKey) - directoriesClient := directories.New() - directoriesClient.Client.Authorizer = storageAuth + domainSuffix := "core.windows.net" + + auth, err := auth.NewSharedKeyAuthorizer(accountName, storageAccountKey, auth.SharedKey) + if err != nil { + return fmt.Errorf("building SharedKey authorizer: %+v", err) + } + + directoriesClient, err := directories.NewWithBaseUri(fmt.Sprintf("https://%s.dfs.%s", accountName, domainSuffix)) + if err != nil { + return fmt.Errorf("building client for environment: %+v", err) + } + directoriesClient.Client.WithAuthorizer(auth) ctx := context.TODO() metadata := map[string]string{ "hello": "world", } - if _, err := directoriesClient.Create(ctx, accountName, shareName, directoryName, metadata); err != nil { + + input := directories.CreateDirectoryInput{ + MetaData: metadata, + } + if _, err := directoriesClient.Create(ctx, shareName, directoryName, input); err != nil { return fmt.Errorf("Error creating Directory: %s", err) } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/api.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/api.go index 2699e668022d..e46265705c07 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/api.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/api.go @@ -2,15 +2,12 @@ package directories import ( "context" - - "github.com/Azure/go-autorest/autorest" ) type StorageDirectory interface { - Delete(ctx context.Context, accountName, shareName, path string) (result autorest.Response, err error) - GetMetaData(ctx context.Context, accountName, shareName, path string) (result GetMetaDataResult, err error) - SetMetaData(ctx context.Context, accountName, shareName, path string, metaData map[string]string) (result autorest.Response, err error) - Create(ctx context.Context, accountName, shareName, path string, input CreateDirectoryInput) (result autorest.Response, err error) - GetResourceID(accountName, shareName, directoryName string) string - Get(ctx context.Context, accountName, shareName, path string) (result GetResult, err error) + Delete(ctx context.Context, shareName, path string) (resp DeleteResponse, err error) + GetMetaData(ctx context.Context, shareName, path string) (resp GetMetaDataResponse, err error) + SetMetaData(ctx context.Context, shareName, path string, input SetMetaDataInput) (resp SetMetaDataResponse, err error) + Create(ctx context.Context, shareName, path string, input CreateDirectoryInput) (resp CreateDirectoryResponse, err error) + Get(ctx context.Context, shareName, path string) (resp GetResponse, err error) } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/client.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/client.go index bf2d315a524d..86f9fd10074f 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/client.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/client.go @@ -1,25 +1,22 @@ package directories import ( - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" + "fmt" + + "github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/storage" ) // Client is the base client for File Storage Shares. type Client struct { - autorest.Client - BaseURI string -} - -// New creates an instance of the Client client. -func New() Client { - return NewWithEnvironment(azure.PublicCloud) + Client *storage.BaseClient } -// NewWithEnvironment creates an instance of the Client client. -func NewWithEnvironment(environment azure.Environment) Client { - return Client{ - Client: autorest.NewClientWithUserAgent(UserAgent()), - BaseURI: environment.StorageEndpointSuffix, +func NewWithBaseUri(baseUri string) (*Client, error) { + baseClient, err := storage.NewBaseClient(baseUri, componentName, apiVersion) + if err != nil { + return nil, fmt.Errorf("building base client: %+v", err) } + return &Client{ + Client: baseClient, + }, nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/create.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/create.go index 37298319be85..7f63f9f87737 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/create.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/create.go @@ -7,10 +7,8 @@ import ( "strings" "time" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" "github.com/tombuildsstuff/giovanni/storage/internal/metadata" ) @@ -29,103 +27,89 @@ type CreateDirectoryInput struct { MetaData map[string]string } +type CreateDirectoryResponse struct { + HttpResponse *client.Response +} + // Create creates a new directory under the specified share or parent directory. -func (client Client) Create(ctx context.Context, accountName, shareName, path string, input CreateDirectoryInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("directories.Client", "Create", "`accountName` cannot be an empty string.") - } +func (c Client) Create(ctx context.Context, shareName, path string, input CreateDirectoryInput) (resp CreateDirectoryResponse, err error) { + if shareName == "" { - return result, validation.NewError("directories.Client", "Create", "`shareName` cannot be an empty string.") + return resp, fmt.Errorf("`shareName` cannot be an empty string") } + if strings.ToLower(shareName) != shareName { - return result, validation.NewError("directories.Client", "Create", "`shareName` must be a lower-cased string.") + return resp, fmt.Errorf("`shareName` must be a lower-cased string") } - if path == "" { - return result, validation.NewError("directories.Client", "Create", "`path` cannot be an empty string.") + + if err = metadata.Validate(input.MetaData); err != nil { + return resp, fmt.Errorf("`input.MetaData` is not valid: %s", err) } - if err := metadata.Validate(input.MetaData); err != nil { - return result, validation.NewError("directories.Client", "Create", fmt.Sprintf("`metadata` is not valid: %s.", err)) + + if path == "" { + return resp, fmt.Errorf("`path` cannot be an empty string") } - req, err := client.CreatePreparer(ctx, accountName, shareName, path, input) - if err != nil { - err = autorest.NewErrorWithError(err, "directories.Client", "Create", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: CreateOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s", shareName, path), } - resp, err := client.CreateSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "directories.Client", "Create", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.CreateResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "directories.Client", "Create", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// CreatePreparer prepares the Create request. -func (client Client) CreatePreparer(ctx context.Context, accountName, shareName, path string, input CreateDirectoryInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - "directory": autorest.Encode("path", path), - } +type CreateOptions struct { + input CreateDirectoryInput +} - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("query", "directory"), +func (c CreateOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + + if len(c.input.MetaData) > 0 { + headers.Merge(metadata.SetMetaDataHeaders(c.input.MetaData)) } var coalesceDate = func(input *time.Time, defaultVal string) string { if input == nil { return defaultVal } - return input.Format(time.RFC1123) } - headers := map[string]interface{}{ - "x-ms-version": APIVersion, + // ... Yes I know these say File not Directory, I didn't design the API. + headers.Append("x-ms-file-permission", "inherit") // TODO: expose this in future + headers.Append("x-ms-file-attributes", "None") // TODO: expose this in future + headers.Append("x-ms-file-creation-time", coalesceDate(c.input.CreatedAt, "now")) + headers.Append("x-ms-file-last-write-time", coalesceDate(c.input.LastModified, "now")) - // ... Yes I know these say File not Directory, I didn't design the API. - "x-ms-file-permission": "inherit", // TODO: expose this in future - "x-ms-file-attributes": "None", // TODO: expose this in future - "x-ms-file-creation-time": coalesceDate(input.CreatedAt, "now"), - "x-ms-file-last-write-time": coalesceDate(input.LastModified, "now"), - } - - headers = metadata.SetIntoHeaders(headers, input.MetaData) - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}/{directory}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// CreateSender sends the Create request. The method will close the -// http.Response Body if it receives an error. -func (client Client) CreateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (c CreateOptions) ToOData() *odata.Query { + return nil } -// CreateResponder handles the response to the Create request. The method always -// closes the http.Response Body. -func (client Client) CreateResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return +func (c CreateOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "directory") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/delete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/delete.go index 9443c2592983..fb96108862e4 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/delete.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/delete.go @@ -2,94 +2,54 @@ package directories import ( "context" + "fmt" "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" ) +type DeleteResponse struct { + HttpResponse *client.Response +} + // Delete removes the specified empty directory // Note that the directory must be empty before it can be deleted. -func (client Client) Delete(ctx context.Context, accountName, shareName, path string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("directories.Client", "Delete", "`accountName` cannot be an empty string.") - } +func (c Client) Delete(ctx context.Context, shareName, path string) (resp DeleteResponse, err error) { + if shareName == "" { - return result, validation.NewError("directories.Client", "Delete", "`shareName` cannot be an empty string.") + return resp, fmt.Errorf("`shareName` cannot be an empty string") } + if strings.ToLower(shareName) != shareName { - return result, validation.NewError("directories.Client", "Delete", "`shareName` must be a lower-cased string.") + return resp, fmt.Errorf("`shareName` must be a lower-cased string") } + if path == "" { - return result, validation.NewError("directories.Client", "Delete", "`path` cannot be an empty string.") + return resp, fmt.Errorf("`path` cannot be an empty string") } - req, err := client.DeletePreparer(ctx, accountName, shareName, path) - if err != nil { - err = autorest.NewErrorWithError(err, "directories.Client", "Delete", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusAccepted, + }, + HttpMethod: http.MethodDelete, + OptionsObject: directoriesOptions{}, + Path: fmt.Sprintf("/%s/%s", shareName, path), } - resp, err := client.DeleteSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "directories.Client", "Delete", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.DeleteResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "directories.Client", "Delete", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } - -// DeletePreparer prepares the Delete request. -func (client Client) DeletePreparer(ctx context.Context, accountName, shareName, path string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - "directory": autorest.Encode("path", path), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("query", "directory"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsDelete(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}/{directory}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client Client) DeleteSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client Client) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusAccepted), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/get.go index 817d680b3fca..5c900c4d10ff 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/get.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/get.go @@ -2,18 +2,16 @@ package directories import ( "context" + "fmt" "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" "github.com/tombuildsstuff/giovanni/storage/internal/metadata" ) -type GetResult struct { - autorest.Response +type GetResponse struct { + HttpResponse *client.Response // A set of name-value pairs that contain metadata for the directory. MetaData map[string]string @@ -25,88 +23,47 @@ type GetResult struct { // Get returns all system properties for the specified directory, // and can also be used to check the existence of a directory. -func (client Client) Get(ctx context.Context, accountName, shareName, path string) (result GetResult, err error) { - if accountName == "" { - return result, validation.NewError("directories.Client", "Get", "`accountName` cannot be an empty string.") - } +func (c Client) Get(ctx context.Context, shareName, path string) (resp GetResponse, err error) { if shareName == "" { - return result, validation.NewError("directories.Client", "Get", "`shareName` cannot be an empty string.") + return resp, fmt.Errorf("`shareName` cannot be an empty string") } + if strings.ToLower(shareName) != shareName { - return result, validation.NewError("directories.Client", "Get", "`shareName` must be a lower-cased string.") + return resp, fmt.Errorf("`shareName` must be a lower-cased string") } + if path == "" { - return result, validation.NewError("directories.Client", "Get", "`path` cannot be an empty string.") + return resp, fmt.Errorf("`path` cannot be an empty string") } - req, err := client.GetPreparer(ctx, accountName, shareName, path) - if err != nil { - err = autorest.NewErrorWithError(err, "directories.Client", "Get", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: directoriesOptions{}, + Path: fmt.Sprintf("/%s/%s", shareName, path), } - resp, err := client.GetSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "directories.Client", "Get", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.GetResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "directories.Client", "Get", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } - return -} - -// GetPreparer prepares the Get request. -func (client Client) GetPreparer(ctx context.Context, accountName, shareName, path string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - "directory": autorest.Encode("path", path), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("query", "directory"), + if resp.HttpResponse != nil { + if resp.HttpResponse.Header != nil { + resp.MetaData = metadata.ParseFromHeaders(resp.HttpResponse.Header) + } + resp.DirectoryMetaDataEncrypted = strings.EqualFold(resp.HttpResponse.Header.Get("x-ms-server-encrypted"), "true") } - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}/{directory}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client Client) GetResponder(resp *http.Response) (result GetResult, err error) { - if resp != nil && resp.Header != nil { - result.MetaData = metadata.ParseFromHeaders(resp.Header) - result.DirectoryMetaDataEncrypted = strings.EqualFold(resp.Header.Get("x-ms-server-encrypted"), "true") - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/metadata_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/metadata_get.go index 173716de7400..1911d39616f4 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/metadata_get.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/metadata_get.go @@ -2,105 +2,79 @@ package directories import ( "context" + "fmt" "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" "github.com/tombuildsstuff/giovanni/storage/internal/metadata" ) -type GetMetaDataResult struct { - autorest.Response +type GetMetaDataResponse struct { + HttpResponse *client.Response MetaData map[string]string } // GetMetaData returns all user-defined metadata for the specified directory -func (client Client) GetMetaData(ctx context.Context, accountName, shareName, path string) (result GetMetaDataResult, err error) { - if accountName == "" { - return result, validation.NewError("directories.Client", "GetMetaData", "`accountName` cannot be an empty string.") - } +func (c Client) GetMetaData(ctx context.Context, shareName, path string) (resp GetMetaDataResponse, err error) { if shareName == "" { - return result, validation.NewError("directories.Client", "GetMetaData", "`shareName` cannot be an empty string.") + return resp, fmt.Errorf("`shareName` cannot be an empty string") } + if strings.ToLower(shareName) != shareName { - return result, validation.NewError("directories.Client", "GetMetaData", "`shareName` must be a lower-cased string.") + return resp, fmt.Errorf("`shareName` must be a lower-cased string") } + if path == "" { - return result, validation.NewError("directories.Client", "GetMetaData", "`path` cannot be an empty string.") + return resp, fmt.Errorf("`path` cannot be an empty string") } - req, err := client.GetMetaDataPreparer(ctx, accountName, shareName, path) - if err != nil { - err = autorest.NewErrorWithError(err, "directories.Client", "GetMetaData", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: GetMetaDataOptions{}, + Path: fmt.Sprintf("/%s/%s", shareName, path), } - resp, err := client.GetMetaDataSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "directories.Client", "GetMetaData", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.GetMetaDataResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "directories.Client", "GetMetaData", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } - return -} - -// GetMetaDataPreparer prepares the GetMetaData request. -func (client Client) GetMetaDataPreparer(ctx context.Context, accountName, shareName, path string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - "directory": autorest.Encode("path", path), + if resp.HttpResponse != nil { + if resp.HttpResponse.Header != nil { + resp.MetaData = metadata.ParseFromHeaders(resp.HttpResponse.Header) + } } - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("query", "directory"), - "comp": autorest.Encode("query", "metadata"), - } + return +} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } +type GetMetaDataOptions struct{} - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}/{directory}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) +func (g GetMetaDataOptions) ToHeaders() *client.Headers { + return nil } -// GetMetaDataSender sends the GetMetaData request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetMetaDataSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (g GetMetaDataOptions) ToOData() *odata.Query { + return nil } -// GetMetaDataResponder handles the response to the GetMetaData request. The method always -// closes the http.Response Body. -func (client Client) GetMetaDataResponder(resp *http.Response) (result GetMetaDataResult, err error) { - if resp != nil && resp.Header != nil { - result.MetaData = metadata.ParseFromHeaders(resp.Header) - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return +func (g GetMetaDataOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "directory") + out.Append("comp", "metadata") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/metadata_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/metadata_set.go index cb133127da00..965f5ffef12a 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/metadata_set.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/metadata_set.go @@ -6,97 +6,85 @@ import ( "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" "github.com/tombuildsstuff/giovanni/storage/internal/metadata" ) +type SetMetaDataResponse struct { + HttpResponse *client.Response +} + +type SetMetaDataInput struct { + MetaData map[string]string +} + // SetMetaData updates user defined metadata for the specified directory -func (client Client) SetMetaData(ctx context.Context, accountName, shareName, path string, metaData map[string]string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("directories.Client", "SetMetaData", "`accountName` cannot be an empty string.") - } +func (c Client) SetMetaData(ctx context.Context, shareName, path string, input SetMetaDataInput) (resp SetMetaDataResponse, err error) { + if shareName == "" { - return result, validation.NewError("directories.Client", "SetMetaData", "`shareName` cannot be an empty string.") + return resp, fmt.Errorf("`shareName` cannot be an empty string") } + if strings.ToLower(shareName) != shareName { - return result, validation.NewError("directories.Client", "SetMetaData", "`shareName` must be a lower-cased string.") + return resp, fmt.Errorf("`shareName` must be a lower-cased string") } - if path == "" { - return result, validation.NewError("directories.Client", "SetMetaData", "`path` cannot be an empty string.") + + if err := metadata.Validate(input.MetaData); err != nil { + return resp, fmt.Errorf("`metadata` is not valid: %s", err) } - if err := metadata.Validate(metaData); err != nil { - return result, validation.NewError("directories.Client", "SetMetaData", fmt.Sprintf("`metaData` is not valid: %s.", err)) + + if path == "" { + return resp, fmt.Errorf("`path` cannot be an empty string") } - req, err := client.SetMetaDataPreparer(ctx, accountName, shareName, path, metaData) - if err != nil { - err = autorest.NewErrorWithError(err, "directories.Client", "SetMetaData", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPut, + OptionsObject: SetMetaDataOptions{ + metaData: input.MetaData, + }, + Path: fmt.Sprintf("/%s/%s", shareName, path), } - resp, err := client.SetMetaDataSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "directories.Client", "SetMetaData", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.SetMetaDataResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "directories.Client", "SetMetaData", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// SetMetaDataPreparer prepares the SetMetaData request. -func (client Client) SetMetaDataPreparer(ctx context.Context, accountName, shareName, path string, metaData map[string]string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - "directory": autorest.Encode("path", path), - } +type SetMetaDataOptions struct { + metaData map[string]string +} - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("query", "directory"), - "comp": autorest.Encode("query", "metadata"), - } +func (s SetMetaDataOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, + if len(s.metaData) > 0 { + headers.Merge(metadata.SetMetaDataHeaders(s.metaData)) } - - headers = metadata.SetIntoHeaders(headers, metaData) - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}/{directory}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// SetMetaDataSender sends the SetMetaData request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SetMetaDataSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (s SetMetaDataOptions) ToOData() *odata.Query { + return nil } -// SetMetaDataResponder handles the response to the SetMetaData request. The method always -// closes the http.Response Body. -func (client Client) SetMetaDataResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return +func (s SetMetaDataOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "directory") + out.Append("comp", "metadata") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/options.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/options.go new file mode 100644 index 000000000000..9b324d54fbed --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/options.go @@ -0,0 +1,24 @@ +package directories + +import ( + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +var _ client.Options = directoriesOptions{} + +type directoriesOptions struct{} + +func (o directoriesOptions) ToHeaders() *client.Headers { + return &client.Headers{} +} + +func (directoriesOptions) ToOData() *odata.Query { + return nil +} + +func (directoriesOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "directory") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/resource_id.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/resource_id.go index 712ed3a00c39..26b0d4ca3f43 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/resource_id.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/resource_id.go @@ -5,52 +5,76 @@ import ( "net/url" "strings" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" + "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts" ) -// GetResourceID returns the Resource ID for the given Directory -// This can be useful when, for example, you're using this as a unique identifier -func (client Client) GetResourceID(accountName, shareName, directoryName string) string { - domain := endpoints.GetFileEndpoint(client.BaseURI, accountName) - return fmt.Sprintf("%s/%s/%s", domain, shareName, directoryName) +// TODO: update this to implement `resourceids.ResourceId` once +// https://github.com/hashicorp/go-azure-helpers/issues/187 is fixed +var _ resourceids.Id = DirectoryId{} + +type DirectoryId struct { + // AccountId specifies the ID of the Storage Account where this Directory exists. + AccountId accounts.AccountId + + // ShareName specifies the name of the File Share containing this Directory. + ShareName string + + // DirectoryPath specifies the path representing this Directory. + DirectoryPath string +} + +func NewDirectoryID(accountId accounts.AccountId, shareName, directoryPath string) DirectoryId { + return DirectoryId{ + AccountId: accountId, + ShareName: shareName, + DirectoryPath: directoryPath, + } } -type ResourceID struct { - AccountName string - DirectoryName string - ShareName string +func (b DirectoryId) ID() string { + return fmt.Sprintf("%s/%s/%s", b.AccountId.ID(), b.ShareName, b.DirectoryPath) } -// ParseResourceID parses the Resource ID into an Object -// which can be used to interact with the Directory within the File Share -func ParseResourceID(id string) (*ResourceID, error) { - // example: https://foo.file.core.windows.net/Bar/Folder - if id == "" { - return nil, fmt.Errorf("`id` was empty") +func (b DirectoryId) String() string { + components := []string{ + fmt.Sprintf("Share Name %q", b.ShareName), + fmt.Sprintf("Account %q", b.AccountId.String()), + } + return fmt.Sprintf("Directory Path %q (%s)", b.DirectoryPath, strings.Join(components, " / ")) +} + +// ParseDirectoryID parses `input` into a Directory ID using a known `domainSuffix` +func ParseDirectoryID(input, domainSuffix string) (*DirectoryId, error) { + // example: https://foo.file.core.windows.net/Bar/some/directory + if input == "" { + return nil, fmt.Errorf("`input` was empty") } - uri, err := url.Parse(id) + account, err := accounts.ParseAccountID(input, domainSuffix) if err != nil { - return nil, fmt.Errorf("Error parsing ID as a URL: %s", err) + return nil, fmt.Errorf("parsing account %q: %+v", input, err) } - accountName, err := endpoints.GetAccountNameFromEndpoint(uri.Host) + if account.SubDomainType != accounts.FileSubDomainType { + return nil, fmt.Errorf("expected the subdomain type to be %q but got %q", string(accounts.FileSubDomainType), string(account.SubDomainType)) + } + + uri, err := url.Parse(input) if err != nil { - return nil, fmt.Errorf("Error parsing Account Name: %s", err) + return nil, fmt.Errorf("parsing %q as a uri: %+v", input, err) } path := strings.TrimPrefix(uri.Path, "/") segments := strings.Split(path, "/") - if len(segments) == 0 { - return nil, fmt.Errorf("Expected the path to contain segments but got none") + if len(segments) < 2 { + return nil, fmt.Errorf("expected the path to contain at least 2 segments but got %d", len(segments)) } - shareName := segments[0] - directoryName := strings.TrimPrefix(path, shareName) - directoryName = strings.TrimPrefix(directoryName, "/") - return &ResourceID{ - AccountName: *accountName, + directoryPath := strings.Join(segments[1:], "/") + return &DirectoryId{ + AccountId: *account, ShareName: shareName, - DirectoryName: directoryName, + DirectoryPath: directoryPath, }, nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/version.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/version.go index 8446be29ebb2..508cbe75c3fe 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/version.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/directories/version.go @@ -1,14 +1,5 @@ package directories -import ( - "fmt" - - "github.com/tombuildsstuff/giovanni/version" -) - // APIVersion is the version of the API used for all Storage API Operations -const APIVersion = "2020-08-04" - -func UserAgent() string { - return fmt.Sprintf("tombuildsstuff/giovanni/%s storage/%s", version.Number, APIVersion) -} +const apiVersion = "2020-08-04" +const componentName = "file/directories" diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/README.md b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/README.md index 6ce6bbb13f96..9070e2385f6b 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/README.md +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/README.md @@ -19,9 +19,8 @@ package main import ( "context" "fmt" - "time" - - "github.com/Azure/go-autorest/autorest" + + "github.com/hashicorp/go-azure-sdk/sdk/auth" "github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files" ) @@ -31,14 +30,22 @@ func Example() error { shareName := "myshare" directoryName := "myfiles" fileName := "example.txt" - - storageAuth := autorest.NewSharedKeyLiteAuthorizer(accountName, storageAccountKey) - filesClient := files.New() - filesClient.Client.Authorizer = storageAuth + domainSuffix := "core.windows.net" + + auth, err := auth.NewSharedKeyAuthorizer(accountName, storageAccountKey, auth.SharedKey) + if err != nil { + return fmt.Errorf("building SharedKey authorizer: %+v", err) + } + + filesClient, err := files.NewWithBaseUri(fmt.Sprintf("https://%s.file.%s", accountName, domainSuffix)) + if err != nil { + return fmt.Errorf("building client for environment: %+v", err) + } + filesClient.Client.WithAuthorizer(auth) ctx := context.TODO() input := files.CreateInput{} - if _, err := filesClient.Create(ctx, accountName, shareName, directoryName, fileName, input); err != nil { + if _, err := filesClient.Create(ctx, shareName, directoryName, fileName, input); err != nil { return fmt.Errorf("Error creating File: %s", err) } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/api.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/api.go index 96a0491e70da..f28a708ded3a 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/api.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/api.go @@ -3,26 +3,22 @@ package files import ( "context" "os" - "time" - - "github.com/Azure/go-autorest/autorest" ) type StorageFile interface { - PutByteRange(ctx context.Context, accountName, shareName, path, fileName string, input PutByteRangeInput) (result autorest.Response, err error) - GetByteRange(ctx context.Context, accountName, shareName, path, fileName string, input GetByteRangeInput) (result GetByteRangeResult, err error) - ClearByteRange(ctx context.Context, accountName, shareName, path, fileName string, input ClearByteRangeInput) (result autorest.Response, err error) - SetProperties(ctx context.Context, accountName, shareName, path, fileName string, input SetPropertiesInput) (result autorest.Response, err error) - PutFile(ctx context.Context, accountName, shareName, path, fileName string, file *os.File, parallelism int) error - Copy(ctx context.Context, accountName, shareName, path, fileName string, input CopyInput) (result CopyResult, err error) - SetMetaData(ctx context.Context, accountName, shareName, path, fileName string, metaData map[string]string) (result autorest.Response, err error) - GetMetaData(ctx context.Context, accountName, shareName, path, fileName string) (result GetMetaDataResult, err error) - AbortCopy(ctx context.Context, accountName, shareName, path, fileName, copyID string) (result autorest.Response, err error) - GetFile(ctx context.Context, accountName, shareName, path, fileName string, parallelism int) (result autorest.Response, outputBytes []byte, err error) - GetResourceID(accountName, shareName, directoryName, filePath string) string - ListRanges(ctx context.Context, accountName, shareName, path, fileName string) (result ListRangesResult, err error) - GetProperties(ctx context.Context, accountName, shareName, path, fileName string) (result GetResult, err error) - Delete(ctx context.Context, accountName, shareName, path, fileName string) (result autorest.Response, err error) - Create(ctx context.Context, accountName, shareName, path, fileName string, input CreateInput) (result autorest.Response, err error) - CopyAndWait(ctx context.Context, accountName, shareName, path, fileName string, input CopyInput, pollDuration time.Duration) (result CopyResult, err error) + PutByteRange(ctx context.Context, shareName string, path string, fileName string, input PutByteRangeInput) (PutRangeResponse, error) + GetByteRange(ctx context.Context, shareName string, path string, fileName string, input GetByteRangeInput) (GetByteRangeResponse, error) + ClearByteRange(ctx context.Context, shareName string, path string, fileName string, input ClearByteRangeInput) (ClearByteRangeResponse, error) + SetProperties(ctx context.Context, shareName string, path string, fileName string, input SetPropertiesInput) (SetPropertiesResponse, error) + PutFile(ctx context.Context, shareName string, path string, fileName string, file *os.File, parallelism int) error + Copy(ctx context.Context, shareName, path, fileName string, input CopyInput) (CopyResponse, error) + SetMetaData(ctx context.Context, shareName string, path string, fileName string, input SetMetaDataInput) (SetMetaDataResponse, error) + GetMetaData(ctx context.Context, shareName string, path string, fileName string) (GetMetaDataResponse, error) + AbortCopy(ctx context.Context, shareName string, path string, fileName string, input CopyAbortInput) (CopyAbortResponse, error) + GetFile(ctx context.Context, shareName string, path string, fileName string, input GetFileInput) (GetFileResponse, error) + ListRanges(ctx context.Context, shareName, path, fileName string) (ListRangesResponse, error) + GetProperties(ctx context.Context, shareName string, path string, fileName string) (GetResponse, error) + Delete(ctx context.Context, shareName string, path string, fileName string) (DeleteResponse, error) + Create(ctx context.Context, shareName string, path string, fileName string, input CreateInput) (CreateResponse, error) + CopyAndWait(ctx context.Context, shareName, path, fileName string, input CopyInput) (CopyResponse, error) } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/client.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/client.go index ecca81586b5a..a875c772ae5e 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/client.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/client.go @@ -1,25 +1,22 @@ package files import ( - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" + "fmt" + + "github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/storage" ) // Client is the base client for File Storage Shares. type Client struct { - autorest.Client - BaseURI string -} - -// New creates an instance of the Client client. -func New() Client { - return NewWithEnvironment(azure.PublicCloud) + Client *storage.BaseClient } -// NewWithEnvironment creates an instance of the Client client. -func NewWithEnvironment(environment azure.Environment) Client { - return Client{ - Client: autorest.NewClientWithUserAgent(UserAgent()), - BaseURI: environment.StorageEndpointSuffix, +func NewWithBaseUri(baseUri string) (*Client, error) { + baseClient, err := storage.NewBaseClient(baseUri, componentName, apiVersion) + if err != nil { + return nil, fmt.Errorf("building base client: %+v", err) } + return &Client{ + Client: baseClient, + }, nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/copy.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/copy.go index 31768b3d52b7..577f95d60e30 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/copy.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/copy.go @@ -6,10 +6,8 @@ import ( "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" "github.com/tombuildsstuff/giovanni/storage/internal/metadata" ) @@ -26,8 +24,8 @@ type CopyInput struct { MetaData map[string]string } -type CopyResult struct { - autorest.Response +type CopyResponse struct { + HttpResponse *client.Response // The CopyID, which can be passed to AbortCopy to abort the copy. CopyID string @@ -37,96 +35,82 @@ type CopyResult struct { } // Copy copies a blob or file to a destination file within the storage account asynchronously. -func (client Client) Copy(ctx context.Context, accountName, shareName, path, fileName string, input CopyInput) (result CopyResult, err error) { - if accountName == "" { - return result, validation.NewError("files.Client", "Copy", "`accountName` cannot be an empty string.") - } +func (c Client) Copy(ctx context.Context, shareName, path, fileName string, input CopyInput) (resp CopyResponse, err error) { + if shareName == "" { - return result, validation.NewError("files.Client", "Copy", "`shareName` cannot be an empty string.") + return resp, fmt.Errorf("`shareName` cannot be an empty string") } + if strings.ToLower(shareName) != shareName { - return result, validation.NewError("files.Client", "Copy", "`shareName` must be a lower-cased string.") + return resp, fmt.Errorf("`shareName` must be a lower-cased string") } + if fileName == "" { - return result, validation.NewError("files.Client", "Copy", "`fileName` cannot be an empty string.") + return resp, fmt.Errorf("`fileName` cannot be an empty string") } + if input.CopySource == "" { - return result, validation.NewError("files.Client", "Copy", "`input.CopySource` cannot be an empty string.") + return resp, fmt.Errorf("`input.CopySource` cannot be an empty string") } - if err := metadata.Validate(input.MetaData); err != nil { - return result, validation.NewError("files.Client", "Copy", fmt.Sprintf("`input.MetaData` is not valid: %s.", err)) + + if err = metadata.Validate(input.MetaData); err != nil { + return resp, fmt.Errorf("`input.MetaData` is not valid: %s", err) } - req, err := client.CopyPreparer(ctx, accountName, shareName, path, fileName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "Copy", nil, "Failure preparing request") - return + if path != "" { + path = fmt.Sprintf("%s/", path) } - resp, err := client.CopySender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "files.Client", "Copy", resp, "Failure sending request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusAccepted, + }, + HttpMethod: http.MethodPut, + OptionsObject: CopyOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s%s", shareName, path, fileName), } - result, err = client.CopyResponder(resp) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "Copy", resp, "Failure responding to request") + err = fmt.Errorf("building request: %+v", err) return } - - return -} - -// CopyPreparer prepares the Copy request. -func (client Client) CopyPreparer(ctx context.Context, accountName, shareName, path, fileName string, input CopyInput) (*http.Request, error) { - if path != "" { - path = fmt.Sprintf("%s/", path) - } - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - "directory": autorest.Encode("path", path), - "fileName": autorest.Encode("path", fileName), + resp.HttpResponse, err = req.Execute(ctx) + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return } - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-copy-source": input.CopySource, + if resp.HttpResponse != nil { + if resp.HttpResponse.Header != nil { + resp.CopyID = resp.HttpResponse.Header.Get("x-ms-copy-id") + resp.CopySuccess = resp.HttpResponse.Header.Get("x-ms-copy-status") + } } - headers = metadata.SetIntoHeaders(headers, input.MetaData) - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}/{directory}{fileName}", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return } -// CopySender sends the Copy request. The method will close the -// http.Response Body if it receives an error. -func (client Client) CopySender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +type CopyOptions struct { + input CopyInput } -// CopyResponder handles the response to the Copy request. The method always -// closes the http.Response Body. -func (client Client) CopyResponder(resp *http.Response) (result CopyResult, err error) { - if resp != nil && resp.Header != nil { - result.CopyID = resp.Header.Get("x-ms-copy-id") - result.CopySuccess = resp.Header.Get("x-ms-copy-status") +func (c CopyOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + if len(c.input.MetaData) > 0 { + headers.Merge(metadata.SetMetaDataHeaders(c.input.MetaData)) } + headers.Append("x-ms-copy-source", c.input.CopySource) + return headers +} - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusAccepted), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} +func (c CopyOptions) ToOData() *odata.Query { + return nil +} - return +func (c CopyOptions) ToQuery() *client.QueryParams { + return nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/copy_abort.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/copy_abort.go index 2f0913185888..55611602d37e 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/copy_abort.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/copy_abort.go @@ -6,99 +6,85 @@ import ( "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) +type CopyAbortInput struct { + copyID string +} + +type CopyAbortResponse struct { + HttpResponse *client.Response +} + // AbortCopy aborts a pending Copy File operation, and leaves a destination file with zero length and full metadata -func (client Client) AbortCopy(ctx context.Context, accountName, shareName, path, fileName, copyID string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("files.Client", "AbortCopy", "`accountName` cannot be an empty string.") - } +func (c Client) AbortCopy(ctx context.Context, shareName, path, fileName string, input CopyAbortInput) (resp CopyAbortResponse, err error) { + if shareName == "" { - return result, validation.NewError("files.Client", "AbortCopy", "`shareName` cannot be an empty string.") + return resp, fmt.Errorf("`shareName` cannot be an empty string") } + if strings.ToLower(shareName) != shareName { - return result, validation.NewError("files.Client", "AbortCopy", "`shareName` must be a lower-cased string.") + return resp, fmt.Errorf("`shareName` must be a lower-cased string") } + if fileName == "" { - return result, validation.NewError("files.Client", "AbortCopy", "`fileName` cannot be an empty string.") + return resp, fmt.Errorf("`fileName` cannot be an empty string") } - if copyID == "" { - return result, validation.NewError("files.Client", "AbortCopy", "`copyID` cannot be an empty string.") + + if input.copyID == "" { + return resp, fmt.Errorf("`copyID` cannot be an empty string") } - req, err := client.AbortCopyPreparer(ctx, accountName, shareName, path, fileName, copyID) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "AbortCopy", nil, "Failure preparing request") - return + if path != "" { + path = fmt.Sprintf("%s/", path) } - resp, err := client.AbortCopySender(req) + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusNoContent, + }, + HttpMethod: http.MethodPut, + OptionsObject: CopyAbortOptions{ + copyId: input.copyID, + }, + Path: fmt.Sprintf("/%s/%s%s", shareName, path, fileName), + } + + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "files.Client", "AbortCopy", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.AbortCopyResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "AbortCopy", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// AbortCopyPreparer prepares the AbortCopy request. -func (client Client) AbortCopyPreparer(ctx context.Context, accountName, shareName, path, fileName, copyID string) (*http.Request, error) { - if path != "" { - path = fmt.Sprintf("%s/", path) - } - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - "directory": autorest.Encode("path", path), - "fileName": autorest.Encode("path", fileName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "copy"), - "copyid": autorest.Encode("query", copyID), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-copy-action": "abort", - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}/{directory}{fileName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) +type CopyAbortOptions struct { + copyId string } -// AbortCopySender sends the AbortCopy request. The method will close the -// http.Response Body if it receives an error. -func (client Client) AbortCopySender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (c CopyAbortOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("x-ms-copy-action", "abort") + return headers } -// AbortCopyResponder handles the response to the AbortCopy request. The method always -// closes the http.Response Body. -func (client Client) AbortCopyResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusNoContent), - autorest.ByClosing()) - result = autorest.Response{Response: resp} +func (c CopyAbortOptions) ToOData() *odata.Query { + return nil +} - return +func (c CopyAbortOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "copy") + out.Append("copyid", c.copyId) + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/copy_and_wait_poller.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/copy_and_wait_poller.go new file mode 100644 index 000000000000..9d6e8afcfcfb --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/copy_and_wait_poller.go @@ -0,0 +1,48 @@ +package files + +import ( + "context" + "fmt" + "strings" + "time" + + "github.com/hashicorp/go-azure-sdk/sdk/client/pollers" +) + +var _ pollers.PollerType = ©AndWaitPoller{} + +func NewCopyAndWaitPoller(client *Client, shareName, path, fileName string) *copyAndWaitPoller { + return ©AndWaitPoller{ + client: client, + shareName: shareName, + path: path, + fileName: fileName, + } +} + +type copyAndWaitPoller struct { + client *Client + shareName string + path string + fileName string +} + +func (p *copyAndWaitPoller) Poll(ctx context.Context) (*pollers.PollResult, error) { + props, err := p.client.GetProperties(ctx, p.shareName, p.path, p.fileName) + if err != nil { + return nil, fmt.Errorf("retrieving copy (shareName: %s path: %s fileName: %s) : %+v", p.shareName, p.path, p.fileName, err) + } + + if strings.EqualFold(props.CopyStatus, "success") { + return &pollers.PollResult{ + Status: pollers.PollingStatusSucceeded, + PollInterval: 10 * time.Second, + }, nil + } + + // Processing + return &pollers.PollResult{ + Status: pollers.PollingStatusInProgress, + PollInterval: 10 * time.Second, + }, nil +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/copy_wait.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/copy_wait.go index e6a646b1017b..1ccb5f31e635 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/copy_wait.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/copy_wait.go @@ -3,52 +3,26 @@ package files import ( "context" "fmt" - "strings" "time" - "github.com/Azure/go-autorest/autorest" + "github.com/hashicorp/go-azure-sdk/sdk/client/pollers" ) -type CopyAndWaitResult struct { - autorest.Response - - CopyID string -} - -const DefaultCopyPollDuration = 15 * time.Second - // CopyAndWait is a convenience method which doesn't exist in the API, which copies the file and then waits for the copy to complete -func (client Client) CopyAndWait(ctx context.Context, accountName, shareName, path, fileName string, input CopyInput, pollDuration time.Duration) (result CopyResult, err error) { - copy, e := client.Copy(ctx, accountName, shareName, path, fileName, input) +func (c Client) CopyAndWait(ctx context.Context, shareName, path, fileName string, input CopyInput) (resp CopyResponse, err error) { + copy, e := c.Copy(ctx, shareName, path, fileName, input) if err != nil { - result.Response = copy.Response - err = fmt.Errorf("Error copying: %s", e) + resp.HttpResponse = copy.HttpResponse + err = fmt.Errorf("error copying: %s", e) return } - result.CopyID = copy.CopyID - - // since the API doesn't return a LRO, this is a hack which also polls every 10s, but should be sufficient - for true { - props, e := client.GetProperties(ctx, accountName, shareName, path, fileName) - if e != nil { - result.Response = copy.Response - err = fmt.Errorf("Error waiting for copy: %s", e) - return - } - - switch strings.ToLower(props.CopyStatus) { - case "pending": - time.Sleep(pollDuration) - continue - - case "success": - return + resp.CopyID = copy.CopyID - default: - err = fmt.Errorf("Unexpected CopyState %q", e) - return - } + pollerType := NewCopyAndWaitPoller(&c, shareName, path, fileName) + poller := pollers.NewPoller(pollerType, 10*time.Second, pollers.DefaultNumberOfDroppedConnectionsToAllow) + if err := poller.PollUntilDone(ctx); err != nil { + return resp, fmt.Errorf("waiting for file to copy: %+v", err) } return diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/create.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/create.go index d2b4ff358120..7c08a85bc1f1 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/create.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/create.go @@ -4,13 +4,12 @@ import ( "context" "fmt" "net/http" + "strconv" "strings" "time" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" "github.com/tombuildsstuff/giovanni/storage/internal/metadata" ) @@ -51,56 +50,65 @@ type CreateInput struct { MetaData map[string]string } +type CreateResponse struct { + HttpResponse *client.Response +} + // Create creates a new file or replaces a file. -func (client Client) Create(ctx context.Context, accountName, shareName, path, fileName string, input CreateInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("files.Client", "Create", "`accountName` cannot be an empty string.") - } +func (c Client) Create(ctx context.Context, shareName, path, fileName string, input CreateInput) (resp CreateResponse, err error) { if shareName == "" { - return result, validation.NewError("files.Client", "Create", "`shareName` cannot be an empty string.") + return resp, fmt.Errorf("`shareName` cannot be an empty string") } + if strings.ToLower(shareName) != shareName { - return result, validation.NewError("files.Client", "Create", "`shareName` must be a lower-cased string.") + return resp, fmt.Errorf("`shareName` must be a lower-cased string") } + if fileName == "" { - return result, validation.NewError("files.Client", "Create", "`fileName` cannot be an empty string.") + return resp, fmt.Errorf("`fileName` cannot be an empty string") + } + + if err = metadata.Validate(input.MetaData); err != nil { + return resp, fmt.Errorf("`input.MetaData` is not valid: %s", err) } - if err := metadata.Validate(input.MetaData); err != nil { - return result, validation.NewError("files.Client", "Create", "`input.MetaData` cannot be an empty string.") + + if path != "" { + path = fmt.Sprintf("%s/", path) } - req, err := client.CreatePreparer(ctx, accountName, shareName, path, fileName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "Create", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: CreateOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s%s", shareName, path, fileName), } - resp, err := client.CreateSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "files.Client", "Create", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.CreateResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "Create", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// CreatePreparer prepares the Create request. -func (client Client) CreatePreparer(ctx context.Context, accountName, shareName, path, fileName string, input CreateInput) (*http.Request, error) { - if path != "" { - path = fmt.Sprintf("%s/", path) - } - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - "directory": autorest.Encode("path", path), - "fileName": autorest.Encode("path", fileName), - } +type CreateOptions struct { + input CreateInput +} + +func (c CreateOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} var coalesceDate = func(input *time.Time, defaultVal string) string { if input == nil { @@ -110,60 +118,41 @@ func (client Client) CreatePreparer(ctx context.Context, accountName, shareName, return input.Format(time.RFC1123) } - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-content-length": input.ContentLength, - "x-ms-type": "file", - - "x-ms-file-permission": "inherit", // TODO: expose this in future - "x-ms-file-attributes": "None", // TODO: expose this in future - "x-ms-file-creation-time": coalesceDate(input.CreatedAt, "now"), - "x-ms-file-last-write-time": coalesceDate(input.LastModified, "now"), + if len(c.input.MetaData) > 0 { + headers.Merge(metadata.SetMetaDataHeaders(c.input.MetaData)) } - if input.ContentDisposition != nil { - headers["x-ms-content-disposition"] = *input.ContentDisposition - } + headers.Append("x-ms-content-length", strconv.Itoa(int(c.input.ContentLength))) + headers.Append("x-ms-type", "file") + + headers.Append("x-ms-file-permission", "inherit") // TODO: expose this in future + headers.Append("x-ms-file-attributes", "None") // TODO: expose this in future + headers.Append("x-ms-file-creation-time", coalesceDate(c.input.CreatedAt, "now")) + headers.Append("x-ms-file-last-write-time", coalesceDate(c.input.LastModified, "now")) - if input.ContentEncoding != nil { - headers["x-ms-content-encoding"] = *input.ContentEncoding + if c.input.ContentDisposition != nil { + headers.Append("x-ms-content-disposition", *c.input.ContentDisposition) } - if input.ContentMD5 != nil { - headers["x-ms-content-md5"] = *input.ContentMD5 + if c.input.ContentEncoding != nil { + headers.Append("x-ms-content-encoding", *c.input.ContentEncoding) } - if input.ContentType != nil { - headers["x-ms-content-type"] = *input.ContentType + if c.input.ContentMD5 != nil { + headers.Append("x-ms-content-md5", *c.input.ContentMD5) } - headers = metadata.SetIntoHeaders(headers, input.MetaData) + if c.input.ContentType != nil { + headers.Append("x-ms-content-type", *c.input.ContentType) + } - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}/{directory}{fileName}", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// CreateSender sends the Create request. The method will close the -// http.Response Body if it receives an error. -func (client Client) CreateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (c CreateOptions) ToOData() *odata.Query { + return nil } -// CreateResponder handles the response to the Create request. The method always -// closes the http.Response Body. -func (client Client) CreateResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return +func (c CreateOptions) ToQuery() *client.QueryParams { + return nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/delete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/delete.go index 5debd767d1fd..d5e32405038f 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/delete.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/delete.go @@ -6,89 +6,53 @@ import ( "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" ) +type DeleteResponse struct { + HttpResponse *client.Response +} + // Delete immediately deletes the file from the File Share. -func (client Client) Delete(ctx context.Context, accountName, shareName, path, fileName string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("files.Client", "Delete", "`accountName` cannot be an empty string.") - } +func (c Client) Delete(ctx context.Context, shareName, path, fileName string) (resp DeleteResponse, err error) { + if shareName == "" { - return result, validation.NewError("files.Client", "Delete", "`shareName` cannot be an empty string.") + return resp, fmt.Errorf("`shareName` cannot be an empty string") } + if strings.ToLower(shareName) != shareName { - return result, validation.NewError("files.Client", "Delete", "`shareName` must be a lower-cased string.") + return resp, fmt.Errorf("`shareName` must be a lower-cased string") } + if fileName == "" { - return result, validation.NewError("files.Client", "Delete", "`fileName` cannot be an empty string.") + return resp, fmt.Errorf("`fileName` cannot be an empty string") } - req, err := client.DeletePreparer(ctx, accountName, shareName, path, fileName) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "Delete", nil, "Failure preparing request") - return + if path != "" { + path = fmt.Sprintf("/%s/", path) } - resp, err := client.DeleteSender(req) - if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "files.Client", "Delete", resp, "Failure sending request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusAccepted, + }, + HttpMethod: http.MethodDelete, + OptionsObject: nil, + Path: fmt.Sprintf("%s/%s%s", shareName, path, fileName), } - result, err = client.DeleteResponder(resp) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "Delete", resp, "Failure responding to request") + err = fmt.Errorf("building request: %+v", err) return } - return -} - -// DeletePreparer prepares the Delete request. -func (client Client) DeletePreparer(ctx context.Context, accountName, shareName, path, fileName string) (*http.Request, error) { - if path != "" { - path = fmt.Sprintf("%s/", path) - } - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - "directory": autorest.Encode("path", path), - "fileName": autorest.Encode("path", fileName), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, + resp.HttpResponse, err = req.Execute(ctx) + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return } - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsDelete(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}/{directory}{fileName}", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client Client) DeleteSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client Client) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusAccepted), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - return } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/metadata_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/metadata_get.go index fd62f90aec8f..3e0fbad008ad 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/metadata_get.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/metadata_get.go @@ -6,106 +6,78 @@ import ( "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" "github.com/tombuildsstuff/giovanni/storage/internal/metadata" ) -type GetMetaDataResult struct { - autorest.Response +type GetMetaDataResponse struct { + HttpResponse *client.Response MetaData map[string]string } // GetMetaData returns the MetaData for the specified File. -func (client Client) GetMetaData(ctx context.Context, accountName, shareName, path, fileName string) (result GetMetaDataResult, err error) { - if accountName == "" { - return result, validation.NewError("files.Client", "GetMetaData", "`accountName` cannot be an empty string.") - } +func (c Client) GetMetaData(ctx context.Context, shareName, path, fileName string) (resp GetMetaDataResponse, err error) { if shareName == "" { - return result, validation.NewError("files.Client", "GetMetaData", "`shareName` cannot be an empty string.") + return resp, fmt.Errorf("`shareName` cannot be an empty string") } + if strings.ToLower(shareName) != shareName { - return result, validation.NewError("files.Client", "GetMetaData", "`shareName` must be a lower-cased string.") + return resp, fmt.Errorf("`shareName` must be a lower-cased string") } + if fileName == "" { - return result, validation.NewError("files.Client", "GetMetaData", "`fileName` cannot be an empty string.") + return resp, fmt.Errorf("`fileName` cannot be an empty string") } - req, err := client.GetMetaDataPreparer(ctx, accountName, shareName, path, fileName) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "GetMetaData", nil, "Failure preparing request") - return + if path != "" { + path = fmt.Sprintf("%s/", path) + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: GetMetadataOptions{}, + Path: fmt.Sprintf("/%s/%s%s", shareName, path, fileName), } - resp, err := client.GetMetaDataSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "files.Client", "GetMetaData", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.GetMetaDataResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "GetMetaData", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } - return -} - -// GetMetaDataPreparer prepares the GetMetaData request. -func (client Client) GetMetaDataPreparer(ctx context.Context, accountName, shareName, path, fileName string) (*http.Request, error) { - if path != "" { - path = fmt.Sprintf("%s/", path) - } - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - "directory": autorest.Encode("path", path), - "fileName": autorest.Encode("path", fileName), + if resp.HttpResponse != nil { + if resp.HttpResponse.Header != nil { + resp.MetaData = metadata.ParseFromHeaders(resp.HttpResponse.Header) + } } - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "metadata"), - } + return +} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } +type GetMetadataOptions struct{} - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}/{directory}{fileName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) +func (m GetMetadataOptions) ToHeaders() *client.Headers { + return nil } -// GetMetaDataSender sends the GetMetaData request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetMetaDataSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (m GetMetadataOptions) ToOData() *odata.Query { + return nil } -// GetMetaDataResponder handles the response to the GetMetaData request. The method always -// closes the http.Response Body. -func (client Client) GetMetaDataResponder(resp *http.Response) (result GetMetaDataResult, err error) { - if resp != nil && resp.Header != nil { - result.MetaData = metadata.ParseFromHeaders(resp.Header) - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - //metadata.ByParsingFromHeaders(&result.MetaData), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return +func (m GetMetadataOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "metadata") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/metadata_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/metadata_set.go index 41e3ffcb8ff9..4087ef58fdc7 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/metadata_set.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/metadata_set.go @@ -6,100 +6,87 @@ import ( "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" "github.com/tombuildsstuff/giovanni/storage/internal/metadata" ) +type SetMetaDataResponse struct { + HttpResponse *client.Response +} + +type SetMetaDataInput struct { + MetaData map[string]string +} + // SetMetaData updates the specified File to have the specified MetaData. -func (client Client) SetMetaData(ctx context.Context, accountName, shareName, path, fileName string, metaData map[string]string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("files.Client", "SetMetaData", "`accountName` cannot be an empty string.") - } +func (c Client) SetMetaData(ctx context.Context, shareName, path, fileName string, input SetMetaDataInput) (resp SetMetaDataResponse, err error) { if shareName == "" { - return result, validation.NewError("files.Client", "SetMetaData", "`shareName` cannot be an empty string.") + return resp, fmt.Errorf("`shareName` cannot be an empty string") } + if strings.ToLower(shareName) != shareName { - return result, validation.NewError("files.Client", "SetMetaData", "`shareName` must be a lower-cased string.") + return resp, fmt.Errorf("`shareName` must be a lower-cased string") } + if fileName == "" { - return result, validation.NewError("files.Client", "SetMetaData", "`fileName` cannot be an empty string.") + return resp, fmt.Errorf("`fileName` cannot be an empty string") } - if err := metadata.Validate(metaData); err != nil { - return result, validation.NewError("files.Client", "SetMetaData", fmt.Sprintf("`metaData` is not valid: %s.", err)) + + if err = metadata.Validate(input.MetaData); err != nil { + return resp, fmt.Errorf("`input.MetaData` is not valid: %s", err) } - req, err := client.SetMetaDataPreparer(ctx, accountName, shareName, path, fileName, metaData) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "SetMetaData", nil, "Failure preparing request") - return + if path != "" { + path = fmt.Sprintf("/%s/", path) } - resp, err := client.SetMetaDataSender(req) + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPut, + OptionsObject: SetMetaDataOptions{ + metaData: input.MetaData, + }, + Path: fmt.Sprintf("%s/%s%s", shareName, path, fileName), + } + + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "files.Client", "SetMetaData", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.SetMetaDataResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "SetMetaData", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// SetMetaDataPreparer prepares the SetMetaData request. -func (client Client) SetMetaDataPreparer(ctx context.Context, accountName, shareName, path, fileName string, metaData map[string]string) (*http.Request, error) { - if path != "" { - path = fmt.Sprintf("%s/", path) - } - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - "directory": autorest.Encode("path", path), - "fileName": autorest.Encode("path", fileName), - } +type SetMetaDataOptions struct { + metaData map[string]string +} - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "metadata"), - } +func (s SetMetaDataOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, + if len(s.metaData) > 0 { + headers.Merge(metadata.SetMetaDataHeaders(s.metaData)) } - - headers = metadata.SetIntoHeaders(headers, metaData) - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}/{directory}{fileName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// SetMetaDataSender sends the SetMetaData request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SetMetaDataSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (s SetMetaDataOptions) ToOData() *odata.Query { + return nil } -// SetMetaDataResponder handles the response to the SetMetaData request. The method always -// closes the http.Response Body. -func (client Client) SetMetaDataResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return +func (s SetMetaDataOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "metadata") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/properties_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/properties_get.go index 0300b1ce5ec6..6a21f7784940 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/properties_get.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/properties_get.go @@ -7,15 +7,12 @@ import ( "strconv" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" "github.com/tombuildsstuff/giovanni/storage/internal/metadata" ) -type GetResult struct { - autorest.Response +type GetResponse struct { + HttpResponse *client.Response CacheControl string ContentDisposition string @@ -36,109 +33,73 @@ type GetResult struct { } // GetProperties returns the Properties for the specified file -func (client Client) GetProperties(ctx context.Context, accountName, shareName, path, fileName string) (result GetResult, err error) { - if accountName == "" { - return result, validation.NewError("files.Client", "GetProperties", "`accountName` cannot be an empty string.") - } +func (c Client) GetProperties(ctx context.Context, shareName, path, fileName string) (resp GetResponse, err error) { if shareName == "" { - return result, validation.NewError("files.Client", "GetProperties", "`shareName` cannot be an empty string.") + return resp, fmt.Errorf("`shareName` cannot be an empty string") } + if strings.ToLower(shareName) != shareName { - return result, validation.NewError("files.Client", "GetProperties", "`shareName` must be a lower-cased string.") + return resp, fmt.Errorf("`shareName` must be a lower-cased string") } + if fileName == "" { - return result, validation.NewError("files.Client", "GetProperties", "`fileName` cannot be an empty string.") + return resp, fmt.Errorf("`fileName` cannot be an empty string") } - req, err := client.GetPropertiesPreparer(ctx, accountName, shareName, path, fileName) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "GetProperties", nil, "Failure preparing request") - return + if path != "" { + path = fmt.Sprintf("/%s/", path) } - resp, err := client.GetPropertiesSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "files.Client", "GetProperties", resp, "Failure sending request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodHead, + OptionsObject: nil, + Path: fmt.Sprintf("%s/%s%s", shareName, path, fileName), } - result, err = client.GetPropertiesResponder(resp) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "GetProperties", resp, "Failure responding to request") + err = fmt.Errorf("building request: %+v", err) return } - return -} - -// GetPropertiesPreparer prepares the GetProperties request. -func (client Client) GetPropertiesPreparer(ctx context.Context, accountName, shareName, path, fileName string) (*http.Request, error) { - if path != "" { - path = fmt.Sprintf("%s/", path) - } - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - "directory": autorest.Encode("path", path), - "fileName": autorest.Encode("path", fileName), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, + resp.HttpResponse, err = req.Execute(ctx) + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return } - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsHead(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}/{directory}{fileName}", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetPropertiesSender sends the GetProperties request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetPropertiesSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// GetPropertiesResponder handles the response to the GetProperties request. The method always -// closes the http.Response Body. -func (client Client) GetPropertiesResponder(resp *http.Response) (result GetResult, err error) { - if resp != nil && resp.Header != nil { - result.CacheControl = resp.Header.Get("Cache-Control") - result.ContentDisposition = resp.Header.Get("Content-Disposition") - result.ContentEncoding = resp.Header.Get("Content-Encoding") - result.ContentLanguage = resp.Header.Get("Content-Language") - result.ContentMD5 = resp.Header.Get("Content-MD5") - result.ContentType = resp.Header.Get("Content-Type") - result.CopyID = resp.Header.Get("x-ms-copy-id") - result.CopyProgress = resp.Header.Get("x-ms-copy-progress") - result.CopySource = resp.Header.Get("x-ms-copy-source") - result.CopyStatus = resp.Header.Get("x-ms-copy-status") - result.CopyStatusDescription = resp.Header.Get("x-ms-copy-status-description") - result.CopyCompletionTime = resp.Header.Get("x-ms-copy-completion-time") - result.Encrypted = strings.EqualFold(resp.Header.Get("x-ms-server-encrypted"), "true") - result.MetaData = metadata.ParseFromHeaders(resp.Header) - - contentLengthRaw := resp.Header.Get("Content-Length") - if contentLengthRaw != "" { - contentLength, err := strconv.Atoi(contentLengthRaw) - if err != nil { - return result, fmt.Errorf("Error parsing %q for Content-Length as an integer: %s", contentLengthRaw, err) + if resp.HttpResponse != nil { + if resp.HttpResponse.Header != nil { + resp.CacheControl = resp.HttpResponse.Header.Get("Cache-Control") + resp.ContentDisposition = resp.HttpResponse.Header.Get("Content-Disposition") + resp.ContentEncoding = resp.HttpResponse.Header.Get("Content-Encoding") + resp.ContentLanguage = resp.HttpResponse.Header.Get("Content-Language") + resp.ContentMD5 = resp.HttpResponse.Header.Get("Content-MD5") + resp.ContentType = resp.HttpResponse.Header.Get("Content-Type") + resp.CopyID = resp.HttpResponse.Header.Get("x-ms-copy-id") + resp.CopyProgress = resp.HttpResponse.Header.Get("x-ms-copy-progress") + resp.CopySource = resp.HttpResponse.Header.Get("x-ms-copy-source") + resp.CopyStatus = resp.HttpResponse.Header.Get("x-ms-copy-status") + resp.CopyStatusDescription = resp.HttpResponse.Header.Get("x-ms-copy-status-description") + resp.CopyCompletionTime = resp.HttpResponse.Header.Get("x-ms-copy-completion-time") + resp.Encrypted = strings.EqualFold(resp.HttpResponse.Header.Get("x-ms-server-encrypted"), "true") + resp.MetaData = metadata.ParseFromHeaders(resp.HttpResponse.Header) + + contentLengthRaw := resp.HttpResponse.Header.Get("Content-Length") + if contentLengthRaw != "" { + contentLength, err := strconv.Atoi(contentLengthRaw) + if err != nil { + return resp, fmt.Errorf("error parsing %q for Content-Length as an integer: %s", contentLengthRaw, err) + } + contentLengthI64 := int64(contentLength) + resp.ContentLength = &contentLengthI64 } - contentLengthI64 := int64(contentLength) - result.ContentLength = &contentLengthI64 } } - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/properties_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/properties_set.go index 521b1bba7be7..0e2c547a8d96 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/properties_set.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/properties_set.go @@ -4,13 +4,12 @@ import ( "context" "fmt" "net/http" + "strconv" "strings" "time" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" "github.com/tombuildsstuff/giovanni/storage/internal/metadata" ) @@ -68,54 +67,61 @@ type SetPropertiesInput struct { MetaData map[string]string } +type SetPropertiesResponse struct { + HttpResponse *client.Response +} + // SetProperties sets the specified properties on the specified File -func (client Client) SetProperties(ctx context.Context, accountName, shareName, path, fileName string, input SetPropertiesInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("files.Client", "SetProperties", "`accountName` cannot be an empty string.") - } +func (c Client) SetProperties(ctx context.Context, shareName, path, fileName string, input SetPropertiesInput) (resp SetPropertiesResponse, err error) { if shareName == "" { - return result, validation.NewError("files.Client", "SetProperties", "`shareName` cannot be an empty string.") + return resp, fmt.Errorf("`shareName` cannot be an empty string") } + if strings.ToLower(shareName) != shareName { - return result, validation.NewError("files.Client", "SetProperties", "`shareName` must be a lower-cased string.") + return resp, fmt.Errorf("`shareName` must be a lower-cased string") } + if fileName == "" { - return result, validation.NewError("files.Client", "SetProperties", "`fileName` cannot be an empty string.") + return resp, fmt.Errorf("`fileName` cannot be an empty string") } - req, err := client.SetPropertiesPreparer(ctx, accountName, shareName, path, fileName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "SetProperties", nil, "Failure preparing request") - return + if path != "" { + path = fmt.Sprintf("/%s/", path) + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: SetPropertiesOptions{ + input: input, + }, + Path: fmt.Sprintf("%s/%s%s", shareName, path, fileName), } - resp, err := client.SetPropertiesSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "files.Client", "SetProperties", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.SetPropertiesResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "SetProperties", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// SetPropertiesPreparer prepares the SetProperties request. -func (client Client) SetPropertiesPreparer(ctx context.Context, accountName, shareName, path, fileName string, input SetPropertiesInput) (*http.Request, error) { - if path != "" { - path = fmt.Sprintf("%s/", path) - } - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - "directory": autorest.Encode("path", path), - "fileName": autorest.Encode("path", fileName), - } +type SetPropertiesOptions struct { + input SetPropertiesInput +} +func (s SetPropertiesOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} var coalesceDate = func(input *time.Time, defaultVal string) string { if input == nil { return defaultVal @@ -124,63 +130,44 @@ func (client Client) SetPropertiesPreparer(ctx context.Context, accountName, sha return input.Format(time.RFC1123) } - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-type": "file", + headers.Append("x-ms-type", "file") - "x-ms-content-length": input.ContentLength, - "x-ms-file-permission": "inherit", // TODO: expose this in future - "x-ms-file-attributes": "None", // TODO: expose this in future - "x-ms-file-creation-time": coalesceDate(input.CreatedAt, "now"), - "x-ms-file-last-write-time": coalesceDate(input.LastModified, "now"), - } + headers.Append("x-ms-content-length", strconv.Itoa(int(s.input.ContentLength))) + headers.Append("x-ms-file-permission", "inherit") // TODO: expose this in future + headers.Append("x-ms-file-attributes", "None") // TODO: expose this in future + headers.Append("x-ms-file-creation-time", coalesceDate(s.input.CreatedAt, "now")) + headers.Append("x-ms-file-last-write-time", coalesceDate(s.input.LastModified, "now")) - if input.ContentControl != nil { - headers["x-ms-cache-control"] = *input.ContentControl + if s.input.ContentControl != nil { + headers.Append("x-ms-cache-control", *s.input.ContentControl) } - if input.ContentDisposition != nil { - headers["x-ms-content-disposition"] = *input.ContentDisposition + if s.input.ContentDisposition != nil { + headers.Append("x-ms-content-disposition", *s.input.ContentDisposition) } - if input.ContentEncoding != nil { - headers["x-ms-content-encoding"] = *input.ContentEncoding + if s.input.ContentEncoding != nil { + headers.Append("x-ms-content-encoding", *s.input.ContentEncoding) } - if input.ContentLanguage != nil { - headers["x-ms-content-language"] = *input.ContentLanguage + if s.input.ContentLanguage != nil { + headers.Append("x-ms-content-language", *s.input.ContentLanguage) } - if input.ContentMD5 != nil { - headers["x-ms-content-md5"] = *input.ContentMD5 + if s.input.ContentMD5 != nil { + headers.Append("x-ms-content-md5", *s.input.ContentMD5) } - if input.ContentType != nil { - headers["x-ms-content-type"] = *input.ContentType + if s.input.ContentType != nil { + headers.Append("x-ms-content-type", *s.input.ContentType) } - headers = metadata.SetIntoHeaders(headers, input.MetaData) + if len(s.input.MetaData) > 0 { + headers.Merge(metadata.SetMetaDataHeaders(s.input.MetaData)) + } - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}/{directory}{fileName}", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// SetPropertiesSender sends the SetProperties request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SetPropertiesSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (s SetPropertiesOptions) ToOData() *odata.Query { + return nil } -// SetPropertiesResponder handles the response to the SetProperties request. The method always -// closes the http.Response Body. -func (client Client) SetPropertiesResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return +func (s SetPropertiesOptions) ToQuery() *client.QueryParams { + return nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_clear.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_clear.go index 5d8145fae422..c2391a1c9c04 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_clear.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_clear.go @@ -6,10 +6,8 @@ import ( "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type ClearByteRangeInput struct { @@ -17,96 +15,81 @@ type ClearByteRangeInput struct { EndBytes int64 } +type ClearByteRangeResponse struct { + HttpResponse *client.Response +} + // ClearByteRange clears the specified Byte Range from within the specified File -func (client Client) ClearByteRange(ctx context.Context, accountName, shareName, path, fileName string, input ClearByteRangeInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("files.Client", "ClearByteRange", "`accountName` cannot be an empty string.") - } +func (c Client) ClearByteRange(ctx context.Context, shareName, path, fileName string, input ClearByteRangeInput) (resp ClearByteRangeResponse, err error) { + if shareName == "" { - return result, validation.NewError("files.Client", "ClearByteRange", "`shareName` cannot be an empty string.") + return resp, fmt.Errorf("`shareName` cannot be an empty string") } + if strings.ToLower(shareName) != shareName { - return result, validation.NewError("files.Client", "ClearByteRange", "`shareName` must be a lower-cased string.") + return resp, fmt.Errorf("`shareName` must be a lower-cased string") } + if fileName == "" { - return result, validation.NewError("files.Client", "ClearByteRange", "`fileName` cannot be an empty string.") + return resp, fmt.Errorf("`fileName` cannot be an empty string") } + if input.StartBytes < 0 { - return result, validation.NewError("files.Client", "ClearByteRange", "`input.StartBytes` must be greater or equal to 0.") + return resp, fmt.Errorf("`input.StartBytes` must be greater or equal to 0") } + if input.EndBytes <= 0 { - return result, validation.NewError("files.Client", "ClearByteRange", "`input.EndBytes` must be greater than 0.") + return resp, fmt.Errorf("`input.EndBytes` must be greater than 0") } - req, err := client.ClearByteRangePreparer(ctx, accountName, shareName, path, fileName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "ClearByteRange", nil, "Failure preparing request") - return + if path != "" { + path = fmt.Sprintf("%s/", path) } - resp, err := client.ClearByteRangeSender(req) + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: ClearByteRangeOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s%s", shareName, path, fileName), + } + + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "files.Client", "ClearByteRange", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.ClearByteRangeResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "ClearByteRange", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// ClearByteRangePreparer prepares the ClearByteRange request. -func (client Client) ClearByteRangePreparer(ctx context.Context, accountName, shareName, path, fileName string, input ClearByteRangeInput) (*http.Request, error) { - if path != "" { - path = fmt.Sprintf("%s/", path) - } - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - "directory": autorest.Encode("path", path), - "fileName": autorest.Encode("path", fileName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "range"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-write": "clear", - "x-ms-range": fmt.Sprintf("bytes=%d-%d", input.StartBytes, input.EndBytes), - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}/{directory}{fileName}", pathParameters), - autorest.WithHeaders(headers), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) +type ClearByteRangeOptions struct { + input ClearByteRangeInput } -// ClearByteRangeSender sends the ClearByteRange request. The method will close the -// http.Response Body if it receives an error. -func (client Client) ClearByteRangeSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (c ClearByteRangeOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("x-ms-write", "clear") + headers.Append("x-ms-range", fmt.Sprintf("bytes=%d-%d", c.input.StartBytes, c.input.EndBytes)) + return headers } -// ClearByteRangeResponder handles the response to the ClearByteRange request. The method always -// closes the http.Response Body. -func (client Client) ClearByteRangeResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result = autorest.Response{Response: resp} +func (c ClearByteRangeOptions) ToOData() *odata.Query { + return nil +} - return +func (c ClearByteRangeOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "range") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_get.go index 733d3f525105..90a1089b3798 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_get.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_get.go @@ -3,13 +3,12 @@ package files import ( "context" "fmt" + "io" "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type GetByteRangeInput struct { @@ -17,105 +16,96 @@ type GetByteRangeInput struct { EndBytes int64 } -type GetByteRangeResult struct { - autorest.Response +type GetByteRangeResponse struct { + HttpResponse *client.Response Contents []byte } // GetByteRange returns the specified Byte Range from the specified File. -func (client Client) GetByteRange(ctx context.Context, accountName, shareName, path, fileName string, input GetByteRangeInput) (result GetByteRangeResult, err error) { - if accountName == "" { - return result, validation.NewError("files.Client", "GetByteRange", "`accountName` cannot be an empty string.") - } +func (c Client) GetByteRange(ctx context.Context, shareName, path, fileName string, input GetByteRangeInput) (resp GetByteRangeResponse, err error) { + if shareName == "" { - return result, validation.NewError("files.Client", "GetByteRange", "`shareName` cannot be an empty string.") + return resp, fmt.Errorf("`shareName` cannot be an empty string") } + if strings.ToLower(shareName) != shareName { - return result, validation.NewError("files.Client", "GetByteRange", "`shareName` must be a lower-cased string.") + return resp, fmt.Errorf("`shareName` must be a lower-cased string") } + if fileName == "" { - return result, validation.NewError("files.Client", "GetByteRange", "`fileName` cannot be an empty string.") + return resp, fmt.Errorf("`fileName` cannot be an empty string") } + if input.StartBytes < 0 { - return result, validation.NewError("files.Client", "GetByteRange", "`input.StartBytes` must be greater or equal to 0.") + return resp, fmt.Errorf("`input.StartBytes` must be greater or equal to 0") } + if input.EndBytes <= 0 { - return result, validation.NewError("files.Client", "GetByteRange", "`input.EndBytes` must be greater than 0.") + return resp, fmt.Errorf("`input.EndBytes` must be greater than 0") } + expectedBytes := input.EndBytes - input.StartBytes if expectedBytes < (4 * 1024) { - return result, validation.NewError("files.Client", "GetByteRange", "Requested Byte Range must be at least 4KB.") + return resp, fmt.Errorf("requested Byte Range must be at least 4KB") } if expectedBytes > (4 * 1024 * 1024) { - return result, validation.NewError("files.Client", "GetByteRange", "Requested Byte Range must be at most 4MB.") + return resp, fmt.Errorf("requested Byte Range must be at most 4MB") } - req, err := client.GetByteRangePreparer(ctx, accountName, shareName, path, fileName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "GetByteRange", nil, "Failure preparing request") - return + if path != "" { + path = fmt.Sprintf("%s/", path) } - resp, err := client.GetByteRangeSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "files.Client", "GetByteRange", resp, "Failure sending request") - return + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusOK, + http.StatusPartialContent, + }, + HttpMethod: http.MethodGet, + OptionsObject: GetByteRangeOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s/%s%s", shareName, path, fileName), } - result, err = client.GetByteRangeResponder(resp, expectedBytes) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "GetByteRange", resp, "Failure responding to request") + err = fmt.Errorf("building request: %+v", err) return } - return -} - -// GetByteRangePreparer prepares the GetByteRange request. -func (client Client) GetByteRangePreparer(ctx context.Context, accountName, shareName, path, fileName string, input GetByteRangeInput) (*http.Request, error) { - if path != "" { - path = fmt.Sprintf("%s/", path) - } - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - "directory": autorest.Encode("path", path), - "fileName": autorest.Encode("path", fileName), + resp.HttpResponse, err = req.Execute(ctx) + if err != nil { + err = fmt.Errorf("executing request: %+v", err) + return } - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-range": fmt.Sprintf("bytes=%d-%d", input.StartBytes, input.EndBytes-1), + if resp.HttpResponse != nil { + bytes, err := io.ReadAll(resp.HttpResponse.Body) + if err != nil { + return resp, fmt.Errorf("reading response body: %v", err) + } + resp.Contents = bytes } - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}/{directory}{fileName}", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return } -// GetByteRangeSender sends the GetByteRange request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetByteRangeSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +type GetByteRangeOptions struct { + input GetByteRangeInput } -// GetByteRangeResponder handles the response to the GetByteRange request. The method always -// closes the http.Response Body. -func (client Client) GetByteRangeResponder(resp *http.Response, length int64) (result GetByteRangeResult, err error) { - result.Contents = make([]byte, length) +func (g GetByteRangeOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("x-ms-range", fmt.Sprintf("bytes=%d-%d", g.input.StartBytes, g.input.EndBytes-1)) + return headers +} - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusPartialContent), - autorest.ByUnmarshallingBytes(&result.Contents), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} +func (g GetByteRangeOptions) ToOData() *odata.Query { + return nil +} - return +func (g GetByteRangeOptions) ToQuery() *client.QueryParams { + return nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_get_file.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_get_file.go index 9e5be17f85fc..f81852604283 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_get_file.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_get_file.go @@ -8,35 +8,46 @@ import ( "runtime" "sync" - "github.com/Azure/go-autorest/autorest" + "github.com/hashicorp/go-azure-sdk/sdk/client" ) +type GetFileInput struct { + Parallelism int +} + +type GetFileResponse struct { + HttpResponse *client.Response + + OutputBytes []byte +} + // GetFile is a helper method to download a file by chunking it automatically -func (client Client) GetFile(ctx context.Context, accountName, shareName, path, fileName string, parallelism int) (result autorest.Response, outputBytes []byte, err error) { +func (c Client) GetFile(ctx context.Context, shareName, path, fileName string, input GetFileInput) (resp GetFileResponse, err error) { // first look up the file and check out how many bytes it is - file, e := client.GetProperties(ctx, accountName, shareName, path, fileName) + file, e := c.GetProperties(ctx, shareName, path, fileName) if err != nil { - result = file.Response + resp.HttpResponse = file.HttpResponse err = e return } if file.ContentLength == nil { - err = fmt.Errorf("Content-Length was nil!") + err = fmt.Errorf("Content-Length was nil") return } - length := int64(*file.ContentLength) + resp.HttpResponse = file.HttpResponse + length := *file.ContentLength chunkSize := int64(4 * 1024 * 1024) // 4MB if chunkSize > length { chunkSize = length } - // then split that up into chunks and retrieve it retrieve it into the 'results' set + // then split that up into chunks and retrieve it into the 'results' set chunks := int(math.Ceil(float64(length) / float64(chunkSize))) - workerCount := parallelism * runtime.NumCPU() + workerCount := input.Parallelism * runtime.NumCPU() if workerCount > chunks { workerCount = chunks } @@ -57,7 +68,7 @@ func (client Client) GetFile(ctx context.Context, accountName, shareName, path, fileSize: length, } - result, err := client.downloadFileChunk(ctx, accountName, shareName, path, fileName, dfci) + result, err := c.downloadFileChunk(ctx, shareName, path, fileName, dfci) if err != nil { errors <- err waitGroup.Done() @@ -84,7 +95,7 @@ func (client Client) GetFile(ctx context.Context, accountName, shareName, path, copy(output[v.startBytes:v.endBytes], v.bytes) } - outputBytes = output + resp.OutputBytes = output return } @@ -100,7 +111,7 @@ type downloadFileChunkResult struct { bytes []byte } -func (client Client) downloadFileChunk(ctx context.Context, accountName, shareName, path, fileName string, input downloadFileChunkInput) (*downloadFileChunkResult, error) { +func (c Client) downloadFileChunk(ctx context.Context, shareName, path, fileName string, input downloadFileChunkInput) (*downloadFileChunkResult, error) { startBytes := input.chunkSize * int64(input.thisChunk) endBytes := startBytes + input.chunkSize @@ -114,9 +125,9 @@ func (client Client) downloadFileChunk(ctx context.Context, accountName, shareNa StartBytes: startBytes, EndBytes: endBytes, } - result, err := client.GetByteRange(ctx, accountName, shareName, path, fileName, getInput) + result, err := c.GetByteRange(ctx, shareName, path, fileName, getInput) if err != nil { - return nil, fmt.Errorf("Error putting bytes: %s", err) + return nil, fmt.Errorf("error putting bytes: %s", err) } output := downloadFileChunkResult{ diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_put.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_put.go index 20e4d398d590..7588f8b4131e 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_put.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_put.go @@ -1,15 +1,16 @@ package files import ( + "bytes" "context" "fmt" + "io" "net/http" + "strconv" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type PutByteRangeInput struct { @@ -21,107 +22,93 @@ type PutByteRangeInput struct { Content []byte } +type PutRangeResponse struct { + HttpResponse *client.Response +} + // PutByteRange puts the specified Byte Range in the specified File. -func (client Client) PutByteRange(ctx context.Context, accountName, shareName, path, fileName string, input PutByteRangeInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("files.Client", "PutByteRange", "`accountName` cannot be an empty string.") - } +func (c Client) PutByteRange(ctx context.Context, shareName, path, fileName string, input PutByteRangeInput) (resp PutRangeResponse, err error) { + if shareName == "" { - return result, validation.NewError("files.Client", "PutByteRange", "`shareName` cannot be an empty string.") + return resp, fmt.Errorf("`shareName` cannot be an empty string") } + if strings.ToLower(shareName) != shareName { - return result, validation.NewError("files.Client", "PutByteRange", "`shareName` must be a lower-cased string.") + return resp, fmt.Errorf("`shareName` must be a lower-cased string") } + if fileName == "" { - return result, validation.NewError("files.Client", "PutByteRange", "`fileName` cannot be an empty string.") + return resp, fmt.Errorf("`fileName` cannot be an empty string") } + if input.StartBytes < 0 { - return result, validation.NewError("files.Client", "PutByteRange", "`input.StartBytes` must be greater or equal to 0.") + return resp, fmt.Errorf("`input.StartBytes` must be greater or equal to 0") } if input.EndBytes <= 0 { - return result, validation.NewError("files.Client", "PutByteRange", "`input.EndBytes` must be greater than 0.") + return resp, fmt.Errorf("`input.EndBytes` must be greater than 0") } expectedBytes := input.EndBytes - input.StartBytes actualBytes := len(input.Content) if expectedBytes != int64(actualBytes) { - return result, validation.NewError("files.Client", "PutByteRange", fmt.Sprintf("The specified byte-range (%d) didn't match the content size (%d).", expectedBytes, actualBytes)) + return resp, fmt.Errorf(fmt.Sprintf("The specified byte-range (%d) didn't match the content size (%d).", expectedBytes, actualBytes)) } if expectedBytes > (4 * 1024 * 1024) { - return result, validation.NewError("files.Client", "PutByteRange", "Specified Byte Range must be at most 4MB.") + return resp, fmt.Errorf("specified Byte Range must be at most 4MB") } - req, err := client.PutByteRangePreparer(ctx, accountName, shareName, path, fileName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "PutByteRange", nil, "Failure preparing request") - return + if path != "" { + path = fmt.Sprintf("/%s/", path) + } + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: PutRangeOptions{ + input: input, + }, + Path: fmt.Sprintf("%s/%s%s", shareName, path, fileName), } - resp, err := client.PutByteRangeSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "files.Client", "PutByteRange", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.PutByteRangeResponder(resp) + req.Body = io.NopCloser(bytes.NewReader(input.Content)) + req.ContentLength = int64(len(input.Content)) + + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "PutByteRange", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// PutByteRangePreparer prepares the PutByteRange request. -func (client Client) PutByteRangePreparer(ctx context.Context, accountName, shareName, path, fileName string, input PutByteRangeInput) (*http.Request, error) { - if path != "" { - path = fmt.Sprintf("%s/", path) - } - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - "directory": autorest.Encode("path", path), - "fileName": autorest.Encode("path", fileName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "range"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-write": "update", - "x-ms-range": fmt.Sprintf("bytes=%d-%d", input.StartBytes, input.EndBytes-1), - "Content-Length": int(len(input.Content)), - } - - preparer := autorest.CreatePreparer( - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}/{directory}{fileName}", pathParameters), - autorest.WithHeaders(headers), - autorest.WithQueryParameters(queryParameters), - autorest.WithBytes(&input.Content)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) +type PutRangeOptions struct { + input PutByteRangeInput } -// PutByteRangeSender sends the PutByteRange request. The method will close the -// http.Response Body if it receives an error. -func (client Client) PutByteRangeSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (p PutRangeOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("x-ms-write", "update") + headers.Append("x-ms-range", fmt.Sprintf("bytes=%d-%d", p.input.StartBytes, p.input.EndBytes-1)) + headers.Append("Content-Length", strconv.Itoa(len(p.input.Content))) + return headers } -// PutByteRangeResponder handles the response to the PutByteRange request. The method always -// closes the http.Response Body. -func (client Client) PutByteRangeResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result = autorest.Response{Response: resp} +func (p PutRangeOptions) ToOData() *odata.Query { + return nil +} - return +func (p PutRangeOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "range") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_put_file.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_put_file.go index a74845dd61ca..16cb68719311 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_put_file.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/range_put_file.go @@ -8,15 +8,17 @@ import ( "math" "os" "sync" - - "github.com/Azure/go-autorest/autorest" ) // PutFile is a helper method which takes a file, and automatically chunks it up, rather than having to do this yourself -func (client Client) PutFile(ctx context.Context, accountName, shareName, path, fileName string, file *os.File, parallelism int) error { +func (c Client) PutFile(ctx context.Context, shareName, path, fileName string, file *os.File, parallelism int) error { fileInfo, err := file.Stat() if err != nil { - return fmt.Errorf("Error loading file info: %s", err) + return fmt.Errorf("error loading file info: %s", err) + } + + if fileInfo.Size() == 0 { + return fmt.Errorf("file is empty which is not supported") } fileSize := fileInfo.Size() @@ -48,7 +50,7 @@ func (client Client) PutFile(ctx context.Context, accountName, shareName, path, fileSize: fileSize, } - _, err := client.uploadChunk(ctx, accountName, shareName, path, fileName, uci, file) + _, err := c.uploadChunk(ctx, shareName, path, fileName, uci, file) if err != nil { errors <- err } @@ -77,7 +79,7 @@ type uploadChunkInput struct { fileSize int64 } -func (client Client) uploadChunk(ctx context.Context, accountName, shareName, path, fileName string, input uploadChunkInput, file *os.File) (result autorest.Response, err error) { +func (c Client) uploadChunk(ctx context.Context, shareName, path, fileName string, input uploadChunkInput, file *os.File) (result PutRangeResponse, err error) { startBytes := int64(input.chunkSize * input.thisChunk) endBytes := startBytes + int64(input.chunkSize) @@ -102,9 +104,9 @@ func (client Client) uploadChunk(ctx context.Context, accountName, shareName, pa EndBytes: endBytes, Content: bytes, } - result, err = client.PutByteRange(ctx, accountName, shareName, path, fileName, putBytesInput) + result, err = c.PutByteRange(ctx, shareName, path, fileName, putBytesInput) if err != nil { - return result, fmt.Errorf("Error putting bytes: %s", err) + return result, fmt.Errorf("error putting bytes: %s", err) } return diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/ranges_list.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/ranges_list.go index ea309f97ddb2..9a67cab82857 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/ranges_list.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/ranges_list.go @@ -6,14 +6,12 @@ import ( "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) -type ListRangesResult struct { - autorest.Response +type ListRangesResponse struct { + HttpResponse *client.Response Ranges []Range `xml:"Range"` } @@ -24,91 +22,69 @@ type Range struct { } // ListRanges returns the list of valid ranges for the specified File. -func (client Client) ListRanges(ctx context.Context, accountName, shareName, path, fileName string) (result ListRangesResult, err error) { - if accountName == "" { - return result, validation.NewError("files.Client", "ListRanges", "`accountName` cannot be an empty string.") - } +func (c Client) ListRanges(ctx context.Context, shareName, path, fileName string) (resp ListRangesResponse, err error) { + if shareName == "" { - return result, validation.NewError("files.Client", "ListRanges", "`shareName` cannot be an empty string.") + return resp, fmt.Errorf("`shareName` cannot be an empty string") } + if strings.ToLower(shareName) != shareName { - return result, validation.NewError("files.Client", "ListRanges", "`shareName` must be a lower-cased string.") + return resp, fmt.Errorf("`shareName` must be a lower-cased string") } + if path == "" { - return result, validation.NewError("files.Client", "ListRanges", "`path` cannot be an empty string.") + return resp, fmt.Errorf("`path` cannot be an empty string") } + if fileName == "" { - return result, validation.NewError("files.Client", "ListRanges", "`fileName` cannot be an empty string.") + return resp, fmt.Errorf("`fileName` cannot be an empty string") } - req, err := client.ListRangesPreparer(ctx, accountName, shareName, path, fileName) - if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "ListRanges", nil, "Failure preparing request") - return + if path != "" { + path = fmt.Sprintf("%s/", path) } - resp, err := client.ListRangesSender(req) + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: ListRangeOptions{}, + Path: fmt.Sprintf("/%s/%s%s", shareName, path, fileName), + } + + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "files.Client", "ListRanges", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.ListRangesResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "files.Client", "ListRanges", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } - return -} - -// ListRangesPreparer prepares the ListRanges request. -func (client Client) ListRangesPreparer(ctx context.Context, accountName, shareName, path, fileName string) (*http.Request, error) { - if path != "" { - path = fmt.Sprintf("%s/", path) - } - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - "directory": autorest.Encode("path", path), - "fileName": autorest.Encode("path", fileName), + if resp.HttpResponse != nil { + resp.HttpResponse.Unmarshal(&resp) } - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "rangelist"), - } + return +} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } +type ListRangeOptions struct{} - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}/{directory}{fileName}", pathParameters), - autorest.WithHeaders(headers), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) +func (l ListRangeOptions) ToHeaders() *client.Headers { + return nil } -// ListRangesSender sends the ListRanges request. The method will close the -// http.Response Body if it receives an error. -func (client Client) ListRangesSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (l ListRangeOptions) ToOData() *odata.Query { + return nil } -// ListRangesResponder handles the response to the ListRanges request. The method always -// closes the http.Response Body. -func (client Client) ListRangesResponder(resp *http.Response) (result ListRangesResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingXML(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return +func (l ListRangeOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "rangelist") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/resource_id.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/resource_id.go index f18e702e81d9..b29471c87e32 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/resource_id.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/resource_id.go @@ -5,60 +5,83 @@ import ( "net/url" "strings" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" + "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts" ) -// GetResourceID returns the Resource ID for the given File -// This can be useful when, for example, you're using this as a unique identifier -func (client Client) GetResourceID(accountName, shareName, directoryName, filePath string) string { - domain := endpoints.GetFileEndpoint(client.BaseURI, accountName) - return fmt.Sprintf("%s/%s/%s/%s", domain, shareName, directoryName, filePath) +// TODO: update this to implement `resourceids.ResourceId` once +// https://github.com/hashicorp/go-azure-helpers/issues/187 is fixed +var _ resourceids.Id = FileId{} + +type FileId struct { + // AccountId specifies the ID of the Storage Account where this File exists. + AccountId accounts.AccountId + + // ShareName specifies the name of the File Share containing this File. + ShareName string + + // DirectoryPath specifies the path representing the Directory where this File exists. + DirectoryPath string + + // FileName specifies the name of the File. + FileName string } -type ResourceID struct { - AccountName string - DirectoryName string - FileName string - ShareName string +func NewFileID(accountId accounts.AccountId, shareName, directoryPath, fileName string) FileId { + return FileId{ + AccountId: accountId, + ShareName: shareName, + DirectoryPath: directoryPath, + FileName: fileName, + } } -// ParseResourceID parses the specified Resource ID and returns an object -// which can be used to interact with Files within a Storage Share. -func ParseResourceID(id string) (*ResourceID, error) { - // example: https://account1.file.core.chinacloudapi.cn/share1/directory1/file1.txt - // example: https://account1.file.core.chinacloudapi.cn/share1/directory1/directory2/file1.txt +func (b FileId) ID() string { + return fmt.Sprintf("%s/%s/%s/%s", b.AccountId.ID(), b.ShareName, b.DirectoryPath, b.FileName) +} - if id == "" { - return nil, fmt.Errorf("`id` was empty") +func (b FileId) String() string { + components := []string{ + fmt.Sprintf("Directory Path %q", b.DirectoryPath), + fmt.Sprintf("Share Name %q", b.ShareName), + fmt.Sprintf("Account %q", b.AccountId.String()), + } + return fmt.Sprintf("File %q (%s)", b.FileName, strings.Join(components, " / ")) +} + +// ParseFileID parses `input` into a File ID using a known `domainSuffix` +func ParseFileID(input, domainSuffix string) (*FileId, error) { + // example: https://foo.file.core.windows.net/Bar/some/directory/some-file.txt + if input == "" { + return nil, fmt.Errorf("`input` was empty") } - uri, err := url.Parse(id) + account, err := accounts.ParseAccountID(input, domainSuffix) if err != nil { - return nil, fmt.Errorf("Error parsing ID as a URL: %s", err) + return nil, fmt.Errorf("parsing account %q: %+v", input, err) } - accountName, err := endpoints.GetAccountNameFromEndpoint(uri.Host) + if account.SubDomainType != accounts.FileSubDomainType { + return nil, fmt.Errorf("expected the subdomain type to be %q but got %q", string(accounts.FileSubDomainType), string(account.SubDomainType)) + } + + uri, err := url.Parse(input) if err != nil { - return nil, fmt.Errorf("Error parsing Account Name: %s", err) + return nil, fmt.Errorf("parsing %q as a uri: %+v", input, err) } path := strings.TrimPrefix(uri.Path, "/") segments := strings.Split(path, "/") - if len(segments) == 0 { - return nil, fmt.Errorf("Expected the path to contain segments but got none") + if len(segments) < 3 { + return nil, fmt.Errorf("expected the path to contain at least 3 segments but got %d", len(segments)) } - shareName := segments[0] + directoryPath := strings.Join(segments[1:len(segments)-1], "/") fileName := segments[len(segments)-1] - - directoryName := strings.TrimPrefix(path, shareName) - directoryName = strings.TrimPrefix(directoryName, "/") - directoryName = strings.TrimSuffix(directoryName, fileName) - directoryName = strings.TrimSuffix(directoryName, "/") - return &ResourceID{ - AccountName: *accountName, + return &FileId{ + AccountId: *account, ShareName: shareName, - DirectoryName: directoryName, + DirectoryPath: directoryPath, FileName: fileName, }, nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/version.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/version.go index 7c8231033703..5b70f293ad01 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/version.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/files/version.go @@ -1,14 +1,4 @@ package files -import ( - "fmt" - - "github.com/tombuildsstuff/giovanni/version" -) - -// APIVersion is the version of the API used for all Storage API Operations -const APIVersion = "2020-08-04" - -func UserAgent() string { - return fmt.Sprintf("tombuildsstuff/giovanni/%s storage/%s", version.Number, APIVersion) -} +const apiVersion = "2020-08-04" +const componentName = "file/files" diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/README.md b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/README.md index ecc0f13ae9bb..314895f36902 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/README.md +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/README.md @@ -15,9 +15,8 @@ package main import ( "context" "fmt" - "time" - - "github.com/Azure/go-autorest/autorest" + + "github.com/hashicorp/go-azure-sdk/sdk/auth" "github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares" ) @@ -25,16 +24,24 @@ func Example() error { accountName := "storageaccount1" storageAccountKey := "ABC123...." shareName := "myshare" - - storageAuth := autorest.NewSharedKeyLiteAuthorizer(accountName, storageAccountKey) - sharesClient := shares.New() - sharesClient.Client.Authorizer = storageAuth + domainSuffix := "core.windows.net" + + auth, err := auth.NewSharedKeyAuthorizer(accountName, storageAccountKey, auth.SharedKey) + if err != nil { + return fmt.Errorf("building SharedKey authorizer: %+v", err) + } + + sharesClient, err := shares.NewWithBaseUri(fmt.Sprintf("https://%s.file.%s", accountName, domainSuffix)) + if err != nil { + return fmt.Errorf("building SharedKey authorizer: %+v", err) + } + sharesClient.Client.WithAuthorizer(auth) ctx := context.TODO() input := shares.CreateInput{ QuotaInGB: 2, } - if _, err := sharesClient.Create(ctx, accountName, shareName, input); err != nil { + if _, err := sharesClient.Create(ctx, shareName, input); err != nil { return fmt.Errorf("Error creating Share: %s", err) } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/acl_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/acl_get.go index ea6ff4c2dd26..56aa6413d4b8 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/acl_get.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/acl_get.go @@ -2,97 +2,75 @@ package shares import ( "context" + "fmt" "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type GetACLResult struct { - autorest.Response + HttpResponse *client.Response SignedIdentifiers []SignedIdentifier `xml:"SignedIdentifier"` } // GetACL get the Access Control List for the specified Storage Share -func (client Client) GetACL(ctx context.Context, accountName, shareName string) (result GetACLResult, err error) { - if accountName == "" { - return result, validation.NewError("shares.Client", "GetACL", "`accountName` cannot be an empty string.") - } +func (c Client) GetACL(ctx context.Context, shareName string) (resp GetACLResult, err error) { + if shareName == "" { - return result, validation.NewError("shares.Client", "GetACL", "`shareName` cannot be an empty string.") + return resp, fmt.Errorf("`shareName` cannot be an empty string") } if strings.ToLower(shareName) != shareName { - return result, validation.NewError("shares.Client", "GetACL", "`shareName` must be a lower-cased string.") + return resp, fmt.Errorf("`shareName` must be a lower-cased string") } - req, err := client.GetACLPreparer(ctx, accountName, shareName) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "GetACL", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: getAclOptions{}, + Path: fmt.Sprintf("/%s", shareName), } - resp, err := client.GetACLSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "shares.Client", "GetACL", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.GetACLResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "GetACL", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } + if resp.HttpResponse != nil { + err = resp.HttpResponse.Unmarshal(&resp) + if err != nil { + return resp, fmt.Errorf("unmarshalling response: %v", err) + } + } return } -// GetACLPreparer prepares the GetACL request. -func (client Client) GetACLPreparer(ctx context.Context, accountName, shareName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("query", "share"), - "comp": autorest.Encode("query", "acl"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) +type getAclOptions struct { } -// GetACLSender sends the GetACL request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetACLSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (g getAclOptions) ToHeaders() *client.Headers { + return nil } -// GetACLResponder handles the response to the GetACL request. The method always -// closes the http.Response Body. -func (client Client) GetACLResponder(resp *http.Response) (result GetACLResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingXML(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} +func (g getAclOptions) ToOData() *odata.Query { + return nil +} - return +func (g getAclOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "share") + out.Append("comp", "acl") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/acl_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/acl_set.go index 18d1788a2ee4..33b7c84a47d0 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/acl_set.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/acl_set.go @@ -1,103 +1,89 @@ package shares import ( + "bytes" "context" "encoding/xml" + "fmt" + "io" "net/http" + "strconv" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) -type setAcl struct { +type SetAclResponse struct { + HttpResponse *client.Response +} + +type SetAclInput struct { SignedIdentifiers []SignedIdentifier `xml:"SignedIdentifier"` XMLName xml.Name `xml:"SignedIdentifiers"` } // SetACL sets the specified Access Control List on the specified Storage Share -func (client Client) SetACL(ctx context.Context, accountName, shareName string, acls []SignedIdentifier) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("shares.Client", "SetACL", "`accountName` cannot be an empty string.") - } +func (c Client) SetACL(ctx context.Context, shareName string, input SetAclInput) (resp SetAclResponse, err error) { + if shareName == "" { - return result, validation.NewError("shares.Client", "SetACL", "`shareName` cannot be an empty string.") + return resp, fmt.Errorf("`shareName` cannot be an empty string") } + if strings.ToLower(shareName) != shareName { - return result, validation.NewError("shares.Client", "SetACL", "`shareName` must be a lower-cased string.") + return resp, fmt.Errorf("`shareName` must be a lower-cased string") } - req, err := client.SetACLPreparer(ctx, accountName, shareName, acls) + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPut, + OptionsObject: setAclOptions{}, + Path: fmt.Sprintf("/%s", shareName), + } + + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "SetACL", nil, "Failure preparing request") + err = fmt.Errorf("building request: %+v", err) return } - resp, err := client.SetACLSender(req) + b, err := xml.Marshal(&input) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "shares.Client", "SetACL", resp, "Failure sending request") - return + return resp, fmt.Errorf("marshalling input: %v", err) } + withHeader := xml.Header + string(b) + bytesWithHeader := []byte(withHeader) + req.ContentLength = int64(len(bytesWithHeader)) + req.Header.Set("Content-Length", strconv.Itoa(len(bytesWithHeader))) + req.Body = io.NopCloser(bytes.NewReader(bytesWithHeader)) - result, err = client.SetACLResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "SetACL", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } - return } -// SetACLPreparer prepares the SetACL request. -func (client Client) SetACLPreparer(ctx context.Context, accountName, shareName string, acls []SignedIdentifier) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("query", "share"), - "comp": autorest.Encode("query", "acl"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - input := setAcl{ - SignedIdentifiers: acls, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers), - autorest.WithXML(&input)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) +type setAclOptions struct { + SignedIdentifiers []SignedIdentifier `xml:"SignedIdentifier"` } -// SetACLSender sends the SetACL request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SetACLSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (s setAclOptions) ToHeaders() *client.Headers { + return nil } -// SetACLResponder handles the response to the SetACL request. The method always -// closes the http.Response Body. -func (client Client) SetACLResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result = autorest.Response{Response: resp} +func (s setAclOptions) ToOData() *odata.Query { + return nil +} - return +func (s setAclOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "share") + out.Append("comp", "acl") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/api.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/api.go index 91645912dfb6..553fb4899e46 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/api.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/api.go @@ -2,23 +2,20 @@ package shares import ( "context" - - "github.com/Azure/go-autorest/autorest" ) type StorageShare interface { - SetACL(ctx context.Context, accountName, shareName string, acls []SignedIdentifier) (result autorest.Response, err error) - GetSnapshot(ctx context.Context, accountName, shareName, snapshotShare string) (result GetSnapshotPropertiesResult, err error) - GetStats(ctx context.Context, accountName, shareName string) (result GetStatsResult, err error) - GetACL(ctx context.Context, accountName, shareName string) (result GetACLResult, err error) - SetMetaData(ctx context.Context, accountName, shareName string, metaData map[string]string) (result autorest.Response, err error) - GetMetaData(ctx context.Context, accountName, shareName string) (result GetMetaDataResult, err error) - SetProperties(ctx context.Context, accountName, shareName string, properties ShareProperties) (result autorest.Response, err error) - DeleteSnapshot(ctx context.Context, accountName, shareName string, shareSnapshot string) (result autorest.Response, err error) - CreateSnapshot(ctx context.Context, accountName, shareName string, input CreateSnapshotInput) (result CreateSnapshotResult, err error) - GetResourceID(accountName, shareName string) string + SetACL(ctx context.Context, shareName string, input SetAclInput) (SetAclResponse, error) + GetSnapshot(ctx context.Context, shareName string, input GetSnapshotPropertiesInput) (GetSnapshotPropertiesResponse, error) + GetStats(ctx context.Context, shareName string) (GetStatsResponse, error) + GetACL(ctx context.Context, shareName string) (GetACLResult, error) + SetMetaData(ctx context.Context, shareName string, input SetMetaDataInput) (SetMetaDataResponse, error) + GetMetaData(ctx context.Context, shareName string) (GetMetaDataResponse, error) + SetProperties(ctx context.Context, shareName string, properties ShareProperties) (SetPropertiesResponse, error) + DeleteSnapshot(ctx context.Context, accountName string, shareName string, shareSnapshot string) (DeleteSnapshotResponse, error) + CreateSnapshot(ctx context.Context, shareName string, input CreateSnapshotInput) (CreateSnapshotResponse, error) GetResourceManagerResourceID(subscriptionID, resourceGroup, accountName, shareName string) string - GetProperties(ctx context.Context, accountName, shareName string) (result GetPropertiesResult, err error) - Delete(ctx context.Context, accountName, shareName string, deleteSnapshots bool) (result autorest.Response, err error) - Create(ctx context.Context, accountName, shareName string, input CreateInput) (result autorest.Response, err error) + GetProperties(ctx context.Context, shareName string) (GetPropertiesResult, error) + Delete(ctx context.Context, shareName string, input DeleteInput) (DeleteResponse, error) + Create(ctx context.Context, shareName string, input CreateInput) (CreateResponse, error) } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/client.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/client.go index 4f3a6f9f99d0..6e5fd15b5d0f 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/client.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/client.go @@ -1,25 +1,22 @@ package shares import ( - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" + "fmt" + + "github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/storage" ) // Client is the base client for File Storage Shares. type Client struct { - autorest.Client - BaseURI string -} - -// New creates an instance of the Client client. -func New() Client { - return NewWithEnvironment(azure.PublicCloud) + Client *storage.BaseClient } -// NewWithEnvironment creates an instance of the Client client. -func NewWithEnvironment(environment azure.Environment) Client { - return Client{ - Client: autorest.NewClientWithUserAgent(UserAgent()), - BaseURI: environment.StorageEndpointSuffix, +func NewWithBaseUri(baseUri string) (*Client, error) { + baseClient, err := storage.NewBaseClient(baseUri, componentName, apiVersion) + if err != nil { + return nil, fmt.Errorf("building base client: %+v", err) } + return &Client{ + Client: baseClient, + }, nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/create.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/create.go index 10a1148f0368..b0184600af0e 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/create.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/create.go @@ -4,12 +4,11 @@ import ( "context" "fmt" "net/http" + "strconv" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" "github.com/tombuildsstuff/giovanni/storage/internal/metadata" ) @@ -36,99 +35,85 @@ type CreateInput struct { AccessTier *AccessTier } +type CreateResponse struct { + HttpResponse *client.Response +} + // Create creates the specified Storage Share within the specified Storage Account -func (client Client) Create(ctx context.Context, accountName, shareName string, input CreateInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("shares.Client", "Create", "`accountName` cannot be an empty string.") - } +func (c Client) Create(ctx context.Context, shareName string, input CreateInput) (resp CreateResponse, err error) { + if shareName == "" { - return result, validation.NewError("shares.Client", "Create", "`shareName` cannot be an empty string.") + return resp, fmt.Errorf("`shareName` cannot be an empty string") } + if strings.ToLower(shareName) != shareName { - return result, validation.NewError("shares.Client", "Create", "`shareName` must be a lower-cased string.") + return resp, fmt.Errorf("`shareName` must be a lower-cased string") } + if input.QuotaInGB <= 0 || input.QuotaInGB > 102400 { - return result, validation.NewError("shares.Client", "Create", "`input.QuotaInGB` must be greater than 0, and less than/equal to 100TB (102400 GB)") - } - if err := metadata.Validate(input.MetaData); err != nil { - return result, validation.NewError("shares.Client", "Create", fmt.Sprintf("`input.MetaData` is not valid: %s.", err)) + return resp, fmt.Errorf("`input.QuotaInGB` must be greater than 0, and less than/equal to 100TB (102400 GB)") } - req, err := client.CreatePreparer(ctx, accountName, shareName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "Create", nil, "Failure preparing request") - return + if err = metadata.Validate(input.MetaData); err != nil { + return resp, fmt.Errorf("`input.MetaData` is not valid: %s", err) } - resp, err := client.CreateSender(req) + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: CreateOptions{ + input: input, + }, + Path: fmt.Sprintf("/%s", shareName), + } + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "shares.Client", "Create", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - - result, err = client.CreateResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "Create", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } - return } -// CreatePreparer prepares the Create request. -func (client Client) CreatePreparer(ctx context.Context, accountName, shareName string, input CreateInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - } +type CreateOptions struct { + input CreateInput +} - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("path", "share"), - } +func (c CreateOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "x-ms-share-quota": input.QuotaInGB, + if len(c.input.MetaData) > 0 { + headers.Merge(metadata.SetMetaDataHeaders(c.input.MetaData)) } protocol := SMB - if input.EnabledProtocol != "" { - protocol = input.EnabledProtocol + if c.input.EnabledProtocol != "" { + protocol = c.input.EnabledProtocol } - headers["x-ms-enabled-protocols"] = protocol + headers.Append("x-ms-enabled-protocols", string(protocol)) - if input.AccessTier != nil { - headers["x-ms-access-tier"] = string(*input.AccessTier) + if c.input.AccessTier != nil { + headers.Append("x-ms-access-tier", string(*c.input.AccessTier)) } - headers = metadata.SetIntoHeaders(headers, input.MetaData) + headers.Append("x-ms-share-quota", strconv.Itoa(c.input.QuotaInGB)) - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// CreateSender sends the Create request. The method will close the -// http.Response Body if it receives an error. -func (client Client) CreateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (c CreateOptions) ToOData() *odata.Query { + return nil } -// CreateResponder handles the response to the Create request. The method always -// closes the http.Response Body. -func (client Client) CreateResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return +func (c CreateOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "share") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/delete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/delete.go index 70ef985d23bb..7ae11b3dbef3 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/delete.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/delete.go @@ -2,93 +2,76 @@ package shares import ( "context" + "fmt" "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) +type DeleteResponse struct { + HttpResponse *client.Response +} + +type DeleteInput struct { + DeleteSnapshots bool +} + // Delete deletes the specified Storage Share from within a Storage Account -func (client Client) Delete(ctx context.Context, accountName, shareName string, deleteSnapshots bool) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("shares.Client", "Delete", "`accountName` cannot be an empty string.") - } +func (c Client) Delete(ctx context.Context, shareName string, input DeleteInput) (resp DeleteResponse, err error) { if shareName == "" { - return result, validation.NewError("shares.Client", "Delete", "`shareName` cannot be an empty string.") + return resp, fmt.Errorf("`shareName` cannot be an empty string") } + if strings.ToLower(shareName) != shareName { - return result, validation.NewError("shares.Client", "Delete", "`shareName` must be a lower-cased string.") + return resp, fmt.Errorf("`shareName` must be a lower-cased string") } - req, err := client.DeletePreparer(ctx, accountName, shareName, deleteSnapshots) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "Delete", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusAccepted, + }, + HttpMethod: http.MethodDelete, + OptionsObject: DeleteOptions{ + deleteSnapshots: input.DeleteSnapshots, + }, + Path: fmt.Sprintf("/%s", shareName), } - - resp, err := client.DeleteSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "shares.Client", "Delete", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.DeleteResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "Delete", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// DeletePreparer prepares the Delete request. -func (client Client) DeletePreparer(ctx context.Context, accountName, shareName string, deleteSnapshots bool) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("path", "share"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } +type DeleteOptions struct { + deleteSnapshots bool +} - if deleteSnapshots { - headers["x-ms-delete-snapshots"] = "include" +func (d DeleteOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + if d.deleteSnapshots { + headers.Append("x-ms-delete-snapshots", "include") } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsDelete(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client Client) DeleteSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (d DeleteOptions) ToOData() *odata.Query { + return nil } -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client Client) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusAccepted), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return +func (d DeleteOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "share") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/metadata_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/metadata_get.go index 9fa4d9f07ed8..e31762bd2d8a 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/metadata_get.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/metadata_get.go @@ -2,101 +2,74 @@ package shares import ( "context" + "fmt" "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" "github.com/tombuildsstuff/giovanni/storage/internal/metadata" ) -type GetMetaDataResult struct { - autorest.Response +type GetMetaDataResponse struct { + HttpResponse *client.Response MetaData map[string]string } // GetMetaData returns the MetaData associated with the specified Storage Share -func (client Client) GetMetaData(ctx context.Context, accountName, shareName string) (result GetMetaDataResult, err error) { - if accountName == "" { - return result, validation.NewError("shares.Client", "GetMetaData", "`accountName` cannot be an empty string.") - } +func (c Client) GetMetaData(ctx context.Context, shareName string) (resp GetMetaDataResponse, err error) { if shareName == "" { - return result, validation.NewError("shares.Client", "GetMetaData", "`shareName` cannot be an empty string.") + return resp, fmt.Errorf("`shareName` cannot be an empty string") } if strings.ToLower(shareName) != shareName { - return result, validation.NewError("shares.Client", "GetMetaData", "`shareName` must be a lower-cased string.") + return resp, fmt.Errorf("`shareName` must be a lower-cased string") } - req, err := client.GetMetaDataPreparer(ctx, accountName, shareName) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "GetMetaData", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: GetMetaDataOptions{}, + Path: fmt.Sprintf("/%s", shareName), } - resp, err := client.GetMetaDataSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "shares.Client", "GetMetaData", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.GetMetaDataResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "GetMetaData", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } - return -} - -// GetMetaDataPreparer prepares the GetMetaData request. -func (client Client) GetMetaDataPreparer(ctx context.Context, accountName, shareName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), + if resp.HttpResponse != nil { + if resp.HttpResponse.Header != nil { + resp.MetaData = metadata.ParseFromHeaders(resp.HttpResponse.Header) + } } - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("query", "share"), - "comp": autorest.Encode("query", "metadata"), - } + return +} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } +type GetMetaDataOptions struct{} - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) +func (g GetMetaDataOptions) ToHeaders() *client.Headers { + return nil } -// GetMetaDataSender sends the GetMetaData request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetMetaDataSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (g GetMetaDataOptions) ToOData() *odata.Query { + return nil } -// GetMetaDataResponder handles the response to the GetMetaData request. The method always -// closes the http.Response Body. -func (client Client) GetMetaDataResponder(resp *http.Response) (result GetMetaDataResult, err error) { - if resp.Header != nil { - result.MetaData = metadata.ParseFromHeaders(resp.Header) - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return +func (g GetMetaDataOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "share") + out.Append("comp", "metadata") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/metadata_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/metadata_set.go index 7e64e60aca15..3a23d90e780f 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/metadata_set.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/metadata_set.go @@ -6,92 +6,77 @@ import ( "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" "github.com/tombuildsstuff/giovanni/storage/internal/metadata" ) +type SetMetaDataResponse struct { + HttpResponse *client.Response +} + +type SetMetaDataInput struct { + MetaData map[string]string +} + // SetMetaData sets the MetaData on the specified Storage Share -func (client Client) SetMetaData(ctx context.Context, accountName, shareName string, metaData map[string]string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("shares.Client", "SetMetaData", "`accountName` cannot be an empty string.") - } +func (c Client) SetMetaData(ctx context.Context, shareName string, input SetMetaDataInput) (resp SetMetaDataResponse, err error) { + if shareName == "" { - return result, validation.NewError("shares.Client", "SetMetaData", "`shareName` cannot be an empty string.") + return resp, fmt.Errorf("`shareName` cannot be an empty string") } + if strings.ToLower(shareName) != shareName { - return result, validation.NewError("shares.Client", "SetMetaData", "`shareName` must be a lower-cased string.") + return resp, fmt.Errorf("`shareName` must be a lower-cased string") } - if err := metadata.Validate(metaData); err != nil { - return result, validation.NewError("shares.Client", "SetMetaData", fmt.Sprintf("`metadata` is not valid: %s.", err)) + + if err := metadata.Validate(input.MetaData); err != nil { + return resp, fmt.Errorf("`metadata` is not valid: %v", err) } - req, err := client.SetMetaDataPreparer(ctx, accountName, shareName, metaData) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "SetMetaData", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPut, + OptionsObject: SetMetaDataOptions{ + metaData: input.MetaData, + }, + Path: fmt.Sprintf("/%s", shareName), } - resp, err := client.SetMetaDataSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "shares.Client", "SetMetaData", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.SetMetaDataResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "SetMetaData", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// SetMetaDataPreparer prepares the SetMetaData request. -func (client Client) SetMetaDataPreparer(ctx context.Context, accountName, shareName string, metaData map[string]string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("query", "share"), - "comp": autorest.Encode("query", "metadata"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - headers = metadata.SetIntoHeaders(headers, metaData) - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) +type SetMetaDataOptions struct { + metaData map[string]string } -// SetPropertiesSetMetaDataSender sends the SetMetaData request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SetMetaDataSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (s SetMetaDataOptions) ToHeaders() *client.Headers { + headers := metadata.SetMetaDataHeaders(s.metaData) + return &headers } -// SetMetaDataResponder handles the response to the SetMetaData request. The method always -// closes the http.Response Body. -func (client Client) SetMetaDataResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result = autorest.Response{Response: resp} +func (s SetMetaDataOptions) ToOData() *odata.Query { + return nil +} - return +func (s SetMetaDataOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "share") + out.Append("comp", "metadata") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/options.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/options.go new file mode 100644 index 000000000000..e2c1d5c9b4cd --- /dev/null +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/options.go @@ -0,0 +1,24 @@ +package shares + +import ( + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" +) + +var _ client.Options = sharesOptions{} + +type sharesOptions struct{} + +func (o sharesOptions) ToHeaders() *client.Headers { + return &client.Headers{} +} + +func (sharesOptions) ToOData() *odata.Query { + return nil +} + +func (sharesOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "share") + return out +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/properties_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/properties_get.go index 28e36e6d3eaf..763584ef648b 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/properties_get.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/properties_get.go @@ -7,15 +7,12 @@ import ( "strconv" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" "github.com/tombuildsstuff/giovanni/storage/internal/metadata" ) type GetPropertiesResult struct { - autorest.Response + HttpResponse *client.Response MetaData map[string]string QuotaInGB int @@ -24,103 +21,62 @@ type GetPropertiesResult struct { } // GetProperties returns the properties about the specified Storage Share -func (client Client) GetProperties(ctx context.Context, accountName, shareName string) (result GetPropertiesResult, err error) { - if accountName == "" { - return result, validation.NewError("shares.Client", "GetProperties", "`accountName` cannot be an empty string.") - } +func (c Client) GetProperties(ctx context.Context, shareName string) (resp GetPropertiesResult, err error) { if shareName == "" { - return result, validation.NewError("shares.Client", "GetProperties", "`shareName` cannot be an empty string.") + return resp, fmt.Errorf("`shareName` cannot be an empty string") } + if strings.ToLower(shareName) != shareName { - return result, validation.NewError("shares.Client", "GetProperties", "`shareName` must be a lower-cased string.") + return resp, fmt.Errorf("`shareName` must be a lower-cased string") } - req, err := client.GetPropertiesPreparer(ctx, accountName, shareName) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "GetProperties", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: sharesOptions{}, + Path: fmt.Sprintf("/%s", shareName), } - resp, err := client.GetPropertiesSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "shares.Client", "GetProperties", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.GetPropertiesResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "GetProperties", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } - return -} - -// GetPropertiesPreparer prepares the GetProperties request. -func (client Client) GetPropertiesPreparer(ctx context.Context, accountName, shareName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("query", "share"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetPropertiesSender sends the GetProperties request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetPropertiesSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// GetPropertiesResponder handles the response to the GetProperties request. The method always -// closes the http.Response Body. -func (client Client) GetPropertiesResponder(resp *http.Response) (result GetPropertiesResult, err error) { - if resp.Header != nil { - result.MetaData = metadata.ParseFromHeaders(resp.Header) - - quotaRaw := resp.Header.Get("x-ms-share-quota") - if quotaRaw != "" { - quota, e := strconv.Atoi(quotaRaw) - if e != nil { - return result, fmt.Errorf("Error converting %q to an integer: %s", quotaRaw, err) + if resp.HttpResponse != nil { + if resp.HttpResponse.Header != nil { + resp.MetaData = metadata.ParseFromHeaders(resp.HttpResponse.Header) + + quotaRaw := resp.HttpResponse.Header.Get("x-ms-share-quota") + if quotaRaw != "" { + quota, e := strconv.Atoi(quotaRaw) + if e != nil { + return resp, fmt.Errorf("error converting %q to an integer: %s", quotaRaw, err) + } + resp.QuotaInGB = quota } - result.QuotaInGB = quota - } - protocol := SMB - if protocolRaw := resp.Header.Get("x-ms-enabled-protocols"); protocolRaw != "" { - protocol = ShareProtocol(protocolRaw) - } + protocol := SMB + if protocolRaw := resp.HttpResponse.Header.Get("x-ms-enabled-protocols"); protocolRaw != "" { + protocol = ShareProtocol(protocolRaw) + } - if accessTierRaw := resp.Header.Get("x-ms-access-tier"); accessTierRaw != "" { - tier := AccessTier(accessTierRaw) - result.AccessTier = &tier + if accessTierRaw := resp.HttpResponse.Header.Get("x-ms-access-tier"); accessTierRaw != "" { + tier := AccessTier(accessTierRaw) + resp.AccessTier = &tier + } + resp.EnabledProtocol = protocol } - result.EnabledProtocol = protocol } - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/properties_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/properties_set.go index 70953c73e102..ef3854af6de9 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/properties_set.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/properties_set.go @@ -2,13 +2,13 @@ package shares import ( "context" + "fmt" "net/http" + "strconv" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type ShareProperties struct { @@ -16,91 +16,75 @@ type ShareProperties struct { AccessTier *AccessTier } +type SetPropertiesResponse struct { + HttpResponse *client.Response +} + // SetProperties lets you update the Quota for the specified Storage Share -func (client Client) SetProperties(ctx context.Context, accountName, shareName string, properties ShareProperties) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("shares.Client", "SetProperties", "`accountName` cannot be an empty string.") - } +func (c Client) SetProperties(ctx context.Context, shareName string, properties ShareProperties) (resp SetPropertiesResponse, err error) { + if shareName == "" { - return result, validation.NewError("shares.Client", "SetProperties", "`shareName` cannot be an empty string.") + return resp, fmt.Errorf("`shareName` cannot be an empty string") } + if strings.ToLower(shareName) != shareName { - return result, validation.NewError("shares.Client", "SetProperties", "`shareName` must be a lower-cased string.") + return resp, fmt.Errorf("`shareName` must be a lower-cased string") } + if newQuotaGB := properties.QuotaInGb; newQuotaGB != nil && (*newQuotaGB <= 0 || *newQuotaGB > 102400) { - return result, validation.NewError("shares.Client", "SetProperties", "`newQuotaGB` must be greater than 0, and less than/equal to 100TB (102400 GB)") + return resp, fmt.Errorf("`newQuotaGB` must be greater than 0, and less than/equal to 100TB (102400 GB)") } - req, err := client.SetPropertiesPreparer(ctx, accountName, shareName, properties) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "SetProperties", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodPut, + OptionsObject: SetPropertiesOptions{ + input: properties, + }, + Path: fmt.Sprintf("/%s", shareName), } - resp, err := client.SetPropertiesSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "shares.Client", "SetProperties", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.SetPropertiesResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "SetProperties", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// SetPropertiesPreparer prepares the SetProperties request. -func (client Client) SetPropertiesPreparer(ctx context.Context, accountName, shareName string, properties ShareProperties) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("query", "share"), - "comp": autorest.Encode("query", "properties"), - } +type SetPropertiesOptions struct { + input ShareProperties +} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - if properties.QuotaInGb != nil { - headers["x-ms-share-quota"] = *properties.QuotaInGb +func (s SetPropertiesOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + if s.input.QuotaInGb != nil { + headers.Append("x-ms-share-quota", strconv.Itoa(*s.input.QuotaInGb)) } - if properties.AccessTier != nil { - headers["x-ms-access-tier"] = string(*properties.AccessTier) + if s.input.AccessTier != nil { + headers.Append("x-ms-access-tier", string(*s.input.AccessTier)) } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return headers } -// SetPropertiesSender sends the SetProperties request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SetPropertiesSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (s SetPropertiesOptions) ToOData() *odata.Query { + return nil } -// SetPropertiesResponder handles the response to the SetProperties request. The method always -// closes the http.Response Body. -func (client Client) SetPropertiesResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return +func (s SetPropertiesOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "share") + out.Append("comp", "properties") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/resource_id.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/resource_id.go index c51d399ca062..73b93bd70768 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/resource_id.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/resource_id.go @@ -5,49 +5,77 @@ import ( "net/url" "strings" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" + "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts" ) -// GetResourceID returns the Resource ID for the given File Share -// This can be useful when, for example, you're using this as a unique identifier -func (client Client) GetResourceID(accountName, shareName string) string { - domain := endpoints.GetFileEndpoint(client.BaseURI, accountName) - return fmt.Sprintf("%s/%s", domain, shareName) -} - // GetResourceManagerResourceID returns the Resource Manager specific // ResourceID for a specific Storage Share -func (client Client) GetResourceManagerResourceID(subscriptionID, resourceGroup, accountName, shareName string) string { +func (c Client) GetResourceManagerResourceID(subscriptionID, resourceGroup, accountName, shareName string) string { fmtStr := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Storage/storageAccounts/%s/fileServices/default/shares/%s" return fmt.Sprintf(fmtStr, subscriptionID, resourceGroup, accountName, shareName) } -type ResourceID struct { - AccountName string - ShareName string +// TODO: update this to implement `resourceids.ResourceId` once +// https://github.com/hashicorp/go-azure-helpers/issues/187 is fixed +var _ resourceids.Id = ShareId{} + +type ShareId struct { + // AccountId specifies the ID of the Storage Account where this File Share exists. + AccountId accounts.AccountId + + // ShareName specifies the name of this File Share. + ShareName string +} + +func NewShareID(accountId accounts.AccountId, shareName string) ShareId { + return ShareId{ + AccountId: accountId, + ShareName: shareName, + } +} + +func (b ShareId) ID() string { + return fmt.Sprintf("%s/%s", b.AccountId.ID(), b.ShareName) +} + +func (b ShareId) String() string { + components := []string{ + fmt.Sprintf("Account %q", b.AccountId.String()), + } + return fmt.Sprintf("File Share %q (%s)", b.ShareName, strings.Join(components, " / ")) } -// ParseResourceID parses the specified Resource ID and returns an object -// which can be used to interact with the Storage Shares SDK -func ParseResourceID(id string) (*ResourceID, error) { +// ParseShareID parses `input` into a Share ID using a known `domainSuffix` +func ParseShareID(input, domainSuffix string) (*ShareId, error) { // example: https://foo.file.core.windows.net/Bar - if id == "" { - return nil, fmt.Errorf("`id` was empty") + if input == "" { + return nil, fmt.Errorf("`input` was empty") } - uri, err := url.Parse(id) + account, err := accounts.ParseAccountID(input, domainSuffix) if err != nil { - return nil, fmt.Errorf("Error parsing ID as a URL: %s", err) + return nil, fmt.Errorf("parsing account %q: %+v", input, err) } - accountName, err := endpoints.GetAccountNameFromEndpoint(uri.Host) + if account.SubDomainType != accounts.FileSubDomainType { + return nil, fmt.Errorf("expected the subdomain type to be %q but got %q", string(accounts.FileSubDomainType), string(account.SubDomainType)) + } + + uri, err := url.Parse(input) if err != nil { - return nil, fmt.Errorf("Error parsing Account Name: %s", err) + return nil, fmt.Errorf("parsing %q as a uri: %+v", input, err) + } + + path := strings.TrimPrefix(uri.Path, "/") + segments := strings.Split(path, "/") + if len(segments) == 0 { + return nil, fmt.Errorf("Expected the path to contain segments but got none") } shareName := strings.TrimPrefix(uri.Path, "/") - return &ResourceID{ - AccountName: *accountName, - ShareName: shareName, + return &ShareId{ + AccountId: *account, + ShareName: shareName, }, nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/snapshot_create.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/snapshot_create.go index 0ded38b1975a..8ba7a07c7b4a 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/snapshot_create.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/snapshot_create.go @@ -6,10 +6,8 @@ import ( "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" "github.com/tombuildsstuff/giovanni/storage/internal/metadata" ) @@ -17,8 +15,8 @@ type CreateSnapshotInput struct { MetaData map[string]string } -type CreateSnapshotResult struct { - autorest.Response +type CreateSnapshotResponse struct { + HttpResponse *client.Response // This header is a DateTime value that uniquely identifies the share snapshot. // The value of this header may be used in subsequent requests to access the share snapshot. @@ -29,87 +27,68 @@ type CreateSnapshotResult struct { // CreateSnapshot creates a read-only snapshot of the share // A share can support creation of 200 share snapshots. Attempting to create more than 200 share snapshots fails with 409 (Conflict). // Attempting to create a share snapshot while a previous Snapshot Share operation is in progress fails with 409 (Conflict). -func (client Client) CreateSnapshot(ctx context.Context, accountName, shareName string, input CreateSnapshotInput) (result CreateSnapshotResult, err error) { - if accountName == "" { - return result, validation.NewError("shares.Client", "CreateSnapshot", "`accountName` cannot be an empty string.") - } +func (c Client) CreateSnapshot(ctx context.Context, shareName string, input CreateSnapshotInput) (resp CreateSnapshotResponse, err error) { + if shareName == "" { - return result, validation.NewError("shares.Client", "CreateSnapshot", "`shareName` cannot be an empty string.") + return resp, fmt.Errorf("`shareName` cannot be an empty string") } + if strings.ToLower(shareName) != shareName { - return result, validation.NewError("shares.Client", "CreateSnapshot", "`shareName` must be a lower-cased string.") + return resp, fmt.Errorf("`shareName` must be a lower-cased string") } - if err := metadata.Validate(input.MetaData); err != nil { - return result, validation.NewError("shares.Client", "CreateSnapshot", fmt.Sprintf("`input.MetaData` is not valid: %s.", err)) + + if err = metadata.Validate(input.MetaData); err != nil { + return resp, fmt.Errorf("`input.MetaData` is not valid: %v", err) } - req, err := client.CreateSnapshotPreparer(ctx, accountName, shareName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "CreateSnapshot", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: snapShotCreateOptions{ + metaData: input.MetaData, + }, + Path: fmt.Sprintf("/%s", shareName), } - resp, err := client.CreateSnapshotSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "shares.Client", "CreateSnapshot", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.CreateSnapshotResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "CreateSnapshot", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } + if resp.HttpResponse != nil { + if resp.HttpResponse.Header != nil { + resp.SnapshotDateTime = resp.HttpResponse.Header.Get("x-ms-snapshot") + } + } return } -// CreateSnapshotPreparer prepares the CreateSnapshot request. -func (client Client) CreateSnapshotPreparer(ctx context.Context, accountName, shareName string, input CreateSnapshotInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "snapshot"), - "restype": autorest.Encode("query", "share"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - headers = metadata.SetIntoHeaders(headers, input.MetaData) - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) +type snapShotCreateOptions struct { + metaData map[string]string } -// CreateSnapshotSender sends the CreateSnapshot request. The method will close the -// http.Response Body if it receives an error. -func (client Client) CreateSnapshotSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (s snapShotCreateOptions) ToHeaders() *client.Headers { + headers := metadata.SetMetaDataHeaders(s.metaData) + return &headers } -// CreateSnapshotResponder handles the response to the CreateSnapshot request. The method always -// closes the http.Response Body. -func (client Client) CreateSnapshotResponder(resp *http.Response) (result CreateSnapshotResult, err error) { - result.SnapshotDateTime = resp.Header.Get("x-ms-snapshot") - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} +func (s snapShotCreateOptions) ToOData() *odata.Query { + return nil +} - return +func (s snapShotCreateOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "share") + out.Append("comp", "snapshot") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/snapshot_delete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/snapshot_delete.go index 1f5d665cb104..bf3ccd6719a6 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/snapshot_delete.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/snapshot_delete.go @@ -2,93 +2,75 @@ package shares import ( "context" + "fmt" "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) +type DeleteSnapshotResponse struct { + HttpResponse *client.Response +} + // DeleteSnapshot deletes the specified Snapshot of a Storage Share -func (client Client) DeleteSnapshot(ctx context.Context, accountName, shareName string, shareSnapshot string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("shares.Client", "DeleteSnapshot", "`accountName` cannot be an empty string.") - } +func (c Client) DeleteSnapshot(ctx context.Context, accountName, shareName string, shareSnapshot string) (resp DeleteSnapshotResponse, err error) { + if shareName == "" { - return result, validation.NewError("shares.Client", "DeleteSnapshot", "`shareName` cannot be an empty string.") + return resp, fmt.Errorf("`shareName` cannot be an empty string") } + if strings.ToLower(shareName) != shareName { - return result, validation.NewError("shares.Client", "DeleteSnapshot", "`shareName` must be a lower-cased string.") + return resp, fmt.Errorf("`shareName` must be a lower-cased string") } + if shareSnapshot == "" { - return result, validation.NewError("shares.Client", "DeleteSnapshot", "`shareSnapshot` cannot be an empty string.") + return resp, fmt.Errorf("`shareSnapshot` cannot be an empty string") } - req, err := client.DeleteSnapshotPreparer(ctx, accountName, shareName, shareSnapshot) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "DeleteSnapshot", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusAccepted, + }, + HttpMethod: http.MethodDelete, + OptionsObject: snapShotDeleteOptions{ + shareSnapShot: shareSnapshot, + }, + Path: fmt.Sprintf("/%s", shareName), } - resp, err := client.DeleteSnapshotSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "shares.Client", "DeleteSnapshot", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.DeleteSnapshotResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "DeleteSnapshot", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// DeleteSnapshotPreparer prepares the DeleteSnapshot request. -func (client Client) DeleteSnapshotPreparer(ctx context.Context, accountName, shareName string, shareSnapshot string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("path", "share"), - "sharesnapshot": autorest.Encode("query", shareSnapshot), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsDelete(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) +type snapShotDeleteOptions struct { + shareSnapShot string } -// DeleteSnapshotSender sends the DeleteSnapshot request. The method will close the -// http.Response Body if it receives an error. -func (client Client) DeleteSnapshotSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (s snapShotDeleteOptions) ToHeaders() *client.Headers { + return nil } -// DeleteSnapshotResponder handles the response to the DeleteSnapshot request. The method always -// closes the http.Response Body. -func (client Client) DeleteSnapshotResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusAccepted), - autorest.ByClosing()) - result = autorest.Response{Response: resp} +func (s snapShotDeleteOptions) ToOData() *odata.Query { + return nil +} - return +func (s snapShotDeleteOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "share") + out.Append("sharesnapshot", s.shareSnapShot) + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/snapshot_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/snapshot_get.go index 2cf5f16f618e..f4a12e9f0cdc 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/snapshot_get.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/snapshot_get.go @@ -2,104 +2,87 @@ package shares import ( "context" + "fmt" "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" "github.com/tombuildsstuff/giovanni/storage/internal/metadata" ) -type GetSnapshotPropertiesResult struct { - autorest.Response +type GetSnapshotPropertiesResponse struct { + HttpResponse *client.Response MetaData map[string]string } +type GetSnapshotPropertiesInput struct { + snapshotShare string +} + // GetSnapshot gets information about the specified Snapshot of the specified Storage Share -func (client Client) GetSnapshot(ctx context.Context, accountName, shareName, snapshotShare string) (result GetSnapshotPropertiesResult, err error) { - if accountName == "" { - return result, validation.NewError("shares.Client", "GetSnapshot", "`accountName` cannot be an empty string.") - } +func (c Client) GetSnapshot(ctx context.Context, shareName string, input GetSnapshotPropertiesInput) (resp GetSnapshotPropertiesResponse, err error) { if shareName == "" { - return result, validation.NewError("shares.Client", "GetSnapshot", "`shareName` cannot be an empty string.") + return resp, fmt.Errorf("`shareName` cannot be an empty string") } + if strings.ToLower(shareName) != shareName { - return result, validation.NewError("shares.Client", "GetSnapshot", "`shareName` must be a lower-cased string.") + return resp, fmt.Errorf("`shareName` must be a lower-cased string") } - if snapshotShare == "" { - return result, validation.NewError("shares.Client", "GetSnapshot", "`snapshotShare` cannot be an empty string.") + + if input.snapshotShare == "" { + return resp, fmt.Errorf("`snapshotShare` cannot be an empty string") } - req, err := client.GetSnapshotPreparer(ctx, accountName, shareName, snapshotShare) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "GetSnapshot", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: snapShotGetOptions{ + snapshotShare: input.snapshotShare, + }, + Path: fmt.Sprintf("/%s", shareName), } - resp, err := client.GetSnapshotSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "shares.Client", "GetSnapshot", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.GetSnapshotResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "GetSnapshot", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } - return -} - -// GetSnapshotPreparer prepares the GetSnapshot request. -func (client Client) GetSnapshotPreparer(ctx context.Context, accountName, shareName, snapshotShare string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), + if resp.HttpResponse != nil { + if resp.HttpResponse.Header != nil { + resp.MetaData = metadata.ParseFromHeaders(resp.HttpResponse.Header) + } } - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("query", "share"), - "snapshot": autorest.Encode("query", snapshotShare), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + return } -// GetSnapshotSender sends the GetSnapshot request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetSnapshotSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +type snapShotGetOptions struct { + snapshotShare string } -// GetSnapshotResponder handles the response to the GetSnapshot request. The method always -// closes the http.Response Body. -func (client Client) GetSnapshotResponder(resp *http.Response) (result GetSnapshotPropertiesResult, err error) { - if resp.Header != nil { - result.MetaData = metadata.ParseFromHeaders(resp.Header) - } +func (s snapShotGetOptions) ToHeaders() *client.Headers { + return nil +} - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} +func (s snapShotGetOptions) ToOData() *odata.Query { + return nil +} - return +func (s snapShotGetOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "share") + out.Append("snapshot", s.snapshotShare) + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/stats.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/stats.go index 3539eccbcd0e..23e48afe4043 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/stats.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/stats.go @@ -2,17 +2,16 @@ package shares import ( "context" + "fmt" "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) -type GetStatsResult struct { - autorest.Response +type GetStatsResponse struct { + HttpResponse *client.Response // The approximate size of the data stored on the share. // Note that this value may not include all recently created or recently resized files. @@ -20,81 +19,59 @@ type GetStatsResult struct { } // GetStats returns information about the specified Storage Share -func (client Client) GetStats(ctx context.Context, accountName, shareName string) (result GetStatsResult, err error) { - if accountName == "" { - return result, validation.NewError("shares.Client", "GetStats", "`accountName` cannot be an empty string.") - } +func (c Client) GetStats(ctx context.Context, shareName string) (resp GetStatsResponse, err error) { if shareName == "" { - return result, validation.NewError("shares.Client", "GetStats", "`shareName` cannot be an empty string.") + return resp, fmt.Errorf("`shareName` cannot be an empty string") } + if strings.ToLower(shareName) != shareName { - return result, validation.NewError("shares.Client", "GetStats", "`shareName` must be a lower-cased string.") + return resp, fmt.Errorf("`shareName` must be a lower-cased string") } - req, err := client.GetStatsPreparer(ctx, accountName, shareName) - if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "GetStats", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: statsOptions{}, + Path: shareName, } - resp, err := client.GetStatsSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "shares.Client", "GetStats", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.GetStatsResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "shares.Client", "GetStats", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } + if resp.HttpResponse != nil { + err = resp.HttpResponse.Unmarshal(&resp) + if err != nil { + return resp, fmt.Errorf("unmarshalling response: %v", err) + } + } return } -// GetStatsPreparer prepares the GetStats request. -func (client Client) GetStatsPreparer(ctx context.Context, accountName, shareName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "shareName": autorest.Encode("path", shareName), - } - - queryParameters := map[string]interface{}{ - "restype": autorest.Encode("query", "share"), - "comp": autorest.Encode("query", "stats"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } +type statsOptions struct{} - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetFileEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{shareName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) +func (s statsOptions) ToHeaders() *client.Headers { + return nil } -// GetStatsSender sends the GetStats request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetStatsSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (s statsOptions) ToOData() *odata.Query { + return nil } -// GetStatsResponder handles the response to the GetStats request. The method always -// closes the http.Response Body. -func (client Client) GetStatsResponder(resp *http.Response) (result GetStatsResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingXML(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return +func (s statsOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "share") + out.Append("comp", "stats") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/version.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/version.go index 653693959b6f..a3c5b6d50170 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/version.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/file/shares/version.go @@ -1,14 +1,4 @@ package shares -import ( - "fmt" - - "github.com/tombuildsstuff/giovanni/version" -) - -// APIVersion is the version of the API used for all Storage API Operations -const APIVersion = "2020-08-04" - -func UserAgent() string { - return fmt.Sprintf("tombuildsstuff/giovanni/%s storage/%s", version.Number, APIVersion) -} +const apiVersion = "2020-08-04" +const componentName = "file/shares" diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/README.md b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/README.md index b8b84a3799a8..c423c712a15a 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/README.md +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/README.md @@ -15,9 +15,8 @@ package main import ( "context" "fmt" - "time" - - "github.com/Azure/go-autorest/autorest" + + "github.com/hashicorp/go-azure-sdk/sdk/auth" "github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues" ) @@ -25,16 +24,27 @@ func Example() error { accountName := "storageaccount1" storageAccountKey := "ABC123...." queueName := "myqueue" - - storageAuth := autorest.NewSharedKeyLiteAuthorizer(accountName, storageAccountKey) - queuesClient := queues.New() - queuesClient.Client.Authorizer = storageAuth + domainSuffix := "core.windows.net" + + auth, err := auth.NewSharedKeyAuthorizer(accountName, storageAccountKey, auth.SharedKey) + if err != nil { + return fmt.Errorf("building SharedKey authorizer: %+v", err) + } + + queuesClient, err := queues.NewWithBaseUri(fmt.Sprintf("https://%s.queue.%s", accountName, domainSuffix)) + if err != nil { + return fmt.Errorf("building client for environment: %+v", err) + } + queuesClient.Client.WithAuthorizer(auth) ctx := context.TODO() metadata := map[string]string{ "hello": "world", } - if _, err := queuesClient.Create(ctx, accountName, queueName, metadata); err != nil { + input := queues.CreateInput{ + Metadata: metadata, + } + if _, err := queuesClient.Create(ctx, queueName, input); err != nil { return fmt.Errorf("Error creating Queue: %s", err) } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/api.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/api.go index e4c14220b68c..e051453e47f0 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/api.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/api.go @@ -2,16 +2,14 @@ package queues import ( "context" - - "github.com/Azure/go-autorest/autorest" ) type StorageQueue interface { - Delete(ctx context.Context, accountName, queueName string) (result autorest.Response, err error) - GetMetaData(ctx context.Context, accountName, queueName string) (result GetMetaDataResult, err error) - SetMetaData(ctx context.Context, accountName, queueName string, metaData map[string]string) (result autorest.Response, err error) - Create(ctx context.Context, accountName, queueName string, metaData map[string]string) (result autorest.Response, err error) - GetResourceID(accountName, queueName string) string - SetServiceProperties(ctx context.Context, accountName string, properties StorageServiceProperties) (result autorest.Response, err error) - GetServiceProperties(ctx context.Context, accountName string) (result StorageServicePropertiesResponse, err error) + Delete(ctx context.Context, queueName string) (DeleteResponse, error) + GetMetaData(ctx context.Context, queueName string) (GetMetaDataResponse, error) + SetMetaData(ctx context.Context, queueName string, input SetMetaDataInput) (SetMetaDataResponse, error) + Create(ctx context.Context, queueName string, input CreateInput) (CreateResponse, error) + GetResourceManagerResourceID(subscriptionID, resourceGroup, accountName, queueName string) string + SetServiceProperties(ctx context.Context, input SetStorageServicePropertiesInput) (SetStorageServicePropertiesResponse, error) + GetServiceProperties(ctx context.Context) (GetStorageServicePropertiesResponse, error) } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/client.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/client.go index 2f8008582b93..40aa674bb2c0 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/client.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/client.go @@ -1,25 +1,24 @@ package queues import ( - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" + "fmt" + + "github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/storage" ) // Client is the base client for Queue Storage Shares. -type Client struct { - autorest.Client - BaseURI string -} -// New creates an instance of the Client client. -func New() Client { - return NewWithEnvironment(azure.PublicCloud) +// Client is the base client for Messages. +type Client struct { + Client *storage.BaseClient } -// NewWithEnvironment creates an instance of the Client client. -func NewWithEnvironment(environment azure.Environment) Client { - return Client{ - Client: autorest.NewClientWithUserAgent(UserAgent()), - BaseURI: environment.StorageEndpointSuffix, +func NewWithBaseUri(baseUri string) (*Client, error) { + baseClient, err := storage.NewBaseClient(baseUri, componentName, apiVersion) + if err != nil { + return nil, fmt.Errorf("building base client: %+v", err) } + return &Client{ + Client: baseClient, + }, nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/create.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/create.go index f18910a88d9e..d156052ca70d 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/create.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/create.go @@ -6,87 +6,78 @@ import ( "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" "github.com/tombuildsstuff/giovanni/storage/internal/metadata" ) +type CreateInput struct { + MetaData map[string]string +} + +type CreateResponse struct { + HttpResponse *client.Response +} + // Create creates the specified Queue within the specified Storage Account -func (client Client) Create(ctx context.Context, accountName, queueName string, metaData map[string]string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("queues.Client", "Create", "`accountName` cannot be an empty string.") - } +func (c Client) Create(ctx context.Context, queueName string, input CreateInput) (resp CreateResponse, err error) { + if queueName == "" { - return result, validation.NewError("queues.Client", "Create", "`queueName` cannot be an empty string.") + return resp, fmt.Errorf("`queueName` cannot be an empty string") } + if strings.ToLower(queueName) != queueName { - return result, validation.NewError("queues.Client", "Create", "`queueName` must be a lower-cased string.") + return resp, fmt.Errorf("`queueName` must be a lower-cased string") } - if err := metadata.Validate(metaData); err != nil { - return result, validation.NewError("queues.Client", "Create", fmt.Sprintf("`metadata` is not valid: %s.", err)) + + if err := metadata.Validate(input.MetaData); err != nil { + return resp, fmt.Errorf("`metadata` is not valid: %s", err) } - req, err := client.CreatePreparer(ctx, accountName, queueName, metaData) - if err != nil { - err = autorest.NewErrorWithError(err, "queues.Client", "Create", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusCreated, + }, + HttpMethod: http.MethodPut, + OptionsObject: createOptions{ + metadata: input.MetaData, + }, + Path: fmt.Sprintf("/%s", queueName), } - resp, err := client.CreateSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "queues.Client", "Create", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.CreateResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "queues.Client", "Create", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// CreatePreparer prepares the Create request. -func (client Client) CreatePreparer(ctx context.Context, accountName string, queueName string, metaData map[string]string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "queueName": autorest.Encode("path", queueName), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } +type createOptions struct { + metadata map[string]string +} - headers = metadata.SetIntoHeaders(headers, metaData) +func (c createOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetQueueEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{queueName}", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + if len(c.metadata) > 0 { + headers.Merge(metadata.SetMetaDataHeaders(c.metadata)) + } + return headers } -// CreateSender sends the Create request. The method will close the -// http.Response Body if it receives an error. -func (client Client) CreateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (c createOptions) ToOData() *odata.Query { + return nil } -// CreateResponder handles the response to the Create request. The method always -// closes the http.Response Body. -func (client Client) CreateResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusCreated), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return +func (c createOptions) ToQuery() *client.QueryParams { + return nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/delete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/delete.go index 5f705959c446..39d5d64fa059 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/delete.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/delete.go @@ -2,84 +2,49 @@ package queues import ( "context" + "fmt" "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" ) +type DeleteResponse struct { + HttpResponse *client.Response +} + // Delete deletes the specified Queue within the specified Storage Account -func (client Client) Delete(ctx context.Context, accountName, queueName string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("queues.Client", "Delete", "`accountName` cannot be an empty string.") - } +func (c Client) Delete(ctx context.Context, queueName string) (resp DeleteResponse, err error) { + if queueName == "" { - return result, validation.NewError("queues.Client", "Delete", "`queueName` cannot be an empty string.") + return resp, fmt.Errorf("`queueName` cannot be an empty string") } + if strings.ToLower(queueName) != queueName { - return result, validation.NewError("queues.Client", "Delete", "`queueName` must be a lower-cased string.") + return resp, fmt.Errorf("`queueName` must be a lower-cased string") } - req, err := client.DeletePreparer(ctx, accountName, queueName) - if err != nil { - err = autorest.NewErrorWithError(err, "queues.Client", "Delete", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusNoContent, + }, + HttpMethod: http.MethodDelete, + OptionsObject: nil, + Path: fmt.Sprintf("/%s", queueName), } - resp, err := client.DeleteSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "queues.Client", "Delete", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.DeleteResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "queues.Client", "Delete", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } - -// DeletePreparer prepares the Delete request. -func (client Client) DeletePreparer(ctx context.Context, accountName string, queueName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "queueName": autorest.Encode("path", queueName), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsDelete(), - autorest.WithBaseURL(endpoints.GetQueueEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{queueName}", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client Client) DeleteSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client Client) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusNoContent), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/metadata_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/metadata_get.go index 9c230b613ad3..14c32d64d0f5 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/metadata_get.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/metadata_get.go @@ -2,100 +2,75 @@ package queues import ( "context" + "fmt" "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" "github.com/tombuildsstuff/giovanni/storage/internal/metadata" ) -type GetMetaDataResult struct { - autorest.Response +type GetMetaDataResponse struct { + HttpResponse *client.Response MetaData map[string]string } // GetMetaData returns the metadata for this Queue -func (client Client) GetMetaData(ctx context.Context, accountName, queueName string) (result GetMetaDataResult, err error) { - if accountName == "" { - return result, validation.NewError("queues.Client", "GetMetaData", "`accountName` cannot be an empty string.") - } +func (c Client) GetMetaData(ctx context.Context, queueName string) (resp GetMetaDataResponse, err error) { + if queueName == "" { - return result, validation.NewError("queues.Client", "GetMetaData", "`queueName` cannot be an empty string.") + return resp, fmt.Errorf("`queueName` cannot be an empty string") } + if strings.ToLower(queueName) != queueName { - return result, validation.NewError("queues.Client", "GetMetaData", "`queueName` must be a lower-cased string.") + return resp, fmt.Errorf("`queueName` must be a lower-cased string") } - req, err := client.GetMetaDataPreparer(ctx, accountName, queueName) - if err != nil { - err = autorest.NewErrorWithError(err, "queues.Client", "GetMetaData", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: getMetaDataOptions{}, + Path: fmt.Sprintf("/%s", queueName), } - resp, err := client.GetMetaDataSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "queues.Client", "GetMetaData", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.GetMetaDataResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "queues.Client", "GetMetaData", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } - return -} - -// GetMetaDataPreparer prepares the GetMetaData request. -func (client Client) GetMetaDataPreparer(ctx context.Context, accountName, queueName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "queueName": autorest.Encode("path", queueName), + if resp.HttpResponse != nil { + if resp.HttpResponse.Header != nil { + resp.MetaData = metadata.ParseFromHeaders(resp.HttpResponse.Header) + } } - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("path", "metadata"), - } + return +} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } +type getMetaDataOptions struct{} - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetQueueEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{queueName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) +func (g getMetaDataOptions) ToHeaders() *client.Headers { + return nil } -// GetMetaDataSender sends the GetMetaData request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetMetaDataSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (g getMetaDataOptions) ToOData() *odata.Query { + return nil } -// GetMetaDataResponder handles the response to the GetMetaData request. The method always -// closes the http.Response Body. -func (client Client) GetMetaDataResponder(resp *http.Response) (result GetMetaDataResult, err error) { - if resp != nil { - result.MetaData = metadata.ParseFromHeaders(resp.Header) - } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return +func (g getMetaDataOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "metadata") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/metadata_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/metadata_set.go index 51154a5c4334..ea8eac3192da 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/metadata_set.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/metadata_set.go @@ -6,92 +6,77 @@ import ( "net/http" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" "github.com/tombuildsstuff/giovanni/storage/internal/metadata" ) +type SetMetaDataResponse struct { + HttpResponse *client.Response +} + +type SetMetaDataInput struct { + MetaData map[string]string +} + // SetMetaData returns the metadata for this Queue -func (client Client) SetMetaData(ctx context.Context, accountName, queueName string, metaData map[string]string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("queues.Client", "SetMetaData", "`accountName` cannot be an empty string.") - } +func (c Client) SetMetaData(ctx context.Context, queueName string, input SetMetaDataInput) (resp SetMetaDataResponse, err error) { + if queueName == "" { - return result, validation.NewError("queues.Client", "SetMetaData", "`queueName` cannot be an empty string.") + return resp, fmt.Errorf("`queueName` cannot be an empty string") } + if strings.ToLower(queueName) != queueName { - return result, validation.NewError("queues.Client", "SetMetaData", "`queueName` must be a lower-cased string.") + return resp, fmt.Errorf("`queueName` must be a lower-cased string") } - if err := metadata.Validate(metaData); err != nil { - return result, validation.NewError("queues.Client", "SetMetaData", fmt.Sprintf("`metadata` is not valid: %s.", err)) + + if err := metadata.Validate(input.MetaData); err != nil { + return resp, fmt.Errorf("`metadata` is not valid: %v", err) } - req, err := client.SetMetaDataPreparer(ctx, accountName, queueName, metaData) - if err != nil { - err = autorest.NewErrorWithError(err, "queues.Client", "SetMetaData", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusNoContent, + }, + HttpMethod: http.MethodPut, + OptionsObject: setMetaDataOptions{ + metadata: input.MetaData, + }, + Path: fmt.Sprintf("/%s", queueName), } - resp, err := client.SetMetaDataSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "queues.Client", "SetMetaData", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.SetMetaDataResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "queues.Client", "SetMetaData", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// SetMetaDataPreparer prepares the SetMetaData request. -func (client Client) SetMetaDataPreparer(ctx context.Context, accountName, queueName string, metaData map[string]string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "queueName": autorest.Encode("path", queueName), - } - - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("path", "metadata"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - headers = metadata.SetIntoHeaders(headers, metaData) - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetQueueEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{queueName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) +type setMetaDataOptions struct { + metadata map[string]string } -// SetMetaDataSender sends the SetMetaData request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SetMetaDataSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (s setMetaDataOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Merge(metadata.SetMetaDataHeaders(s.metadata)) + return headers } -// SetMetaDataResponder handles the response to the SetMetaData request. The method always -// closes the http.Response Body. -func (client Client) SetMetaDataResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusNoContent), - autorest.ByClosing()) - result = autorest.Response{Response: resp} +func (s setMetaDataOptions) ToOData() *odata.Query { + return nil +} - return +func (s setMetaDataOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "metadata") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/properties_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/properties_get.go index a0e51ad34354..b2ea774e5534 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/properties_get.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/properties_get.go @@ -2,85 +2,66 @@ package queues import ( "context" + "fmt" "net/http" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) -type StorageServicePropertiesResponse struct { +type GetStorageServicePropertiesResponse struct { StorageServiceProperties - autorest.Response + HttpResponse *client.Response } -// SetServiceProperties gets the properties for this queue -func (client Client) GetServiceProperties(ctx context.Context, accountName string) (result StorageServicePropertiesResponse, err error) { - if accountName == "" { - return result, validation.NewError("queues.Client", "GetServiceProperties", "`accountName` cannot be an empty string.") +// GetServiceProperties gets the properties for this queue +func (c Client) GetServiceProperties(ctx context.Context) (resp GetStorageServicePropertiesResponse, err error) { + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: getStorageServicePropertiesOptions{}, + Path: "/", } - req, err := client.GetServicePropertiesPreparer(ctx, accountName) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - err = autorest.NewErrorWithError(err, "queues.Client", "GetServiceProperties", nil, "Failure preparing request") + err = fmt.Errorf("building request: %+v", err) return } - resp, err := client.GetServicePropertiesSender(req) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "queues.Client", "GetServiceProperties", resp, "Failure sending request") + err = fmt.Errorf("executing request: %+v", err) return } - result, err = client.GetServicePropertiesResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "queues.Client", "GetServiceProperties", resp, "Failure responding to request") - return + if resp.HttpResponse != nil { + err = resp.HttpResponse.Unmarshal(&resp) + if err != nil { + return resp, fmt.Errorf("unmarshalling respnse: %v", err) + } } return } -// GetServicePropertiesPreparer prepares the GetServiceProperties request. -func (client Client) GetServicePropertiesPreparer(ctx context.Context, accountName string) (*http.Request, error) { - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("path", "properties"), - "restype": autorest.Encode("path", "service"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } +type getStorageServicePropertiesOptions struct{} - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetQueueEndpoint(client.BaseURI, accountName)), - autorest.WithPath("/"), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) +func (g getStorageServicePropertiesOptions) ToHeaders() *client.Headers { + return nil } -// GetServicePropertiesSender sends the GetServiceProperties request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetServicePropertiesSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (g getStorageServicePropertiesOptions) ToOData() *odata.Query { + return nil } -// GetServicePropertiesResponder handles the response to the GetServiceProperties request. The method always -// closes the http.Response Body. -func (client Client) GetServicePropertiesResponder(resp *http.Response) (result StorageServicePropertiesResponse, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingXML(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return +func (g getStorageServicePropertiesOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "properties") + out.Append("restype", "service") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/properties_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/properties_set.go index 33dd40b3da1f..744bd9767ed1 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/properties_set.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/properties_set.go @@ -1,81 +1,76 @@ package queues import ( + "bytes" "context" + "encoding/xml" + "fmt" + "io" "net/http" + "strconv" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) +type SetStorageServicePropertiesResponse struct { + HttpResponse *client.Response +} + +type SetStorageServicePropertiesInput struct { + Properties StorageServiceProperties +} + // SetServiceProperties sets the properties for this queue -func (client Client) SetServiceProperties(ctx context.Context, accountName string, properties StorageServiceProperties) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("queues.Client", "SetServiceProperties", "`accountName` cannot be an empty string.") +func (c Client) SetServiceProperties(ctx context.Context, input SetStorageServicePropertiesInput) (resp SetStorageServicePropertiesResponse, err error) { + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusAccepted, + }, + HttpMethod: http.MethodPut, + OptionsObject: setStorageServicePropertiesOptions{}, + Path: "/", } - req, err := client.SetServicePropertiesPreparer(ctx, accountName, properties) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - err = autorest.NewErrorWithError(err, "queues.Client", "SetServiceProperties", nil, "Failure preparing request") + err = fmt.Errorf("building request: %+v", err) return } - resp, err := client.SetServicePropertiesSender(req) + marshalledProps, err := xml.Marshal(&input.Properties) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "queues.Client", "SetServiceProperties", resp, "Failure sending request") - return + return resp, fmt.Errorf("marshalling request: %v", err) } + body := xml.Header + string(marshalledProps) + req.Body = io.NopCloser(bytes.NewReader([]byte(body))) + req.ContentLength = int64(len(body)) + req.Header.Set("Content-Length", strconv.Itoa(len(body))) - result, err = client.SetServicePropertiesResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "queues.Client", "SetServiceProperties", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// SetServicePropertiesPreparer prepares the SetServiceProperties request. -func (client Client) SetServicePropertiesPreparer(ctx context.Context, accountName string, properties StorageServiceProperties) (*http.Request, error) { - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("path", "properties"), - "restype": autorest.Encode("path", "service"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } +type setStorageServicePropertiesOptions struct{} - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetQueueEndpoint(client.BaseURI, accountName)), - autorest.WithPath("/"), - autorest.WithQueryParameters(queryParameters), - autorest.WithXML(properties), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) +func (s setStorageServicePropertiesOptions) ToHeaders() *client.Headers { + return nil } -// SetServicePropertiesSender sends the SetServiceProperties request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SetServicePropertiesSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (s setStorageServicePropertiesOptions) ToOData() *odata.Query { + return nil } -// SetServicePropertiesResponder handles the response to the SetServiceProperties request. The method always -// closes the http.Response Body. -func (client Client) SetServicePropertiesResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusAccepted), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return +func (s setStorageServicePropertiesOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("restype", "service") + out.Append("comp", "properties") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/resource_id.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/resource_id.go index 912923abca0d..455319a23308 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/resource_id.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/resource_id.go @@ -5,42 +5,77 @@ import ( "net/url" "strings" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" + "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts" ) -// GetResourceID returns the Resource ID for the given Queue +// GetResourceManagerResourceID returns the Resource Manager ID for the given Queue // This can be useful when, for example, you're using this as a unique identifier -func (client Client) GetResourceID(accountName, queueName string) string { - domain := endpoints.GetQueueEndpoint(client.BaseURI, accountName) - return fmt.Sprintf("%s/%s", domain, queueName) +func (c Client) GetResourceManagerResourceID(subscriptionID, resourceGroup, accountName, queueName string) string { + fmtStr := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Storage/storageAccounts/%s/queueServices/default/queues/%s" + return fmt.Sprintf(fmtStr, subscriptionID, resourceGroup, accountName, queueName) } -type ResourceID struct { - AccountName string - QueueName string +// TODO: update this to implement `resourceids.ResourceId` once +// https://github.com/hashicorp/go-azure-helpers/issues/187 is fixed +var _ resourceids.Id = QueueId{} + +type QueueId struct { + // AccountId specifies the ID of the Storage Account where this Queue exists. + AccountId accounts.AccountId + + // QueueName specifies the name of this Queue. + QueueName string +} + +func NewQueueID(accountId accounts.AccountId, queueName string) QueueId { + return QueueId{ + AccountId: accountId, + QueueName: queueName, + } +} + +func (b QueueId) ID() string { + return fmt.Sprintf("%s/%s", b.AccountId.ID(), b.QueueName) } -// ParseResourceID parses the Resource ID and returns an Object which -// can be used to interact with a Queue within a Storage Account -func ParseResourceID(id string) (*ResourceID, error) { +func (b QueueId) String() string { + components := []string{ + fmt.Sprintf("Account %q", b.AccountId.String()), + } + return fmt.Sprintf("Queue %q (%s)", b.QueueName, strings.Join(components, " / ")) +} + +// ParseQueueID parses `input` into a Queue ID using a known `domainSuffix` +func ParseQueueID(input, domainSuffix string) (*QueueId, error) { // example: https://foo.queue.core.windows.net/Bar - if id == "" { - return nil, fmt.Errorf("`id` was empty") + if input == "" { + return nil, fmt.Errorf("`input` was empty") } - uri, err := url.Parse(id) + account, err := accounts.ParseAccountID(input, domainSuffix) if err != nil { - return nil, fmt.Errorf("Error parsing ID as a URL: %s", err) + return nil, fmt.Errorf("parsing account %q: %+v", input, err) } - accountName, err := endpoints.GetAccountNameFromEndpoint(uri.Host) + if account.SubDomainType != accounts.QueueSubDomainType { + return nil, fmt.Errorf("expected the subdomain type to be %q but got %q", string(accounts.QueueSubDomainType), string(account.SubDomainType)) + } + + uri, err := url.Parse(input) if err != nil { - return nil, fmt.Errorf("Error parsing Account Name: %s", err) + return nil, fmt.Errorf("parsing %q as a uri: %+v", input, err) + } + + path := strings.TrimPrefix(uri.Path, "/") + segments := strings.Split(path, "/") + if len(segments) != 1 { + return nil, fmt.Errorf("expected the path to contain 1 segment but got %d", len(segments)) } queueName := strings.TrimPrefix(uri.Path, "/") - return &ResourceID{ - AccountName: *accountName, - QueueName: queueName, + return &QueueId{ + AccountId: *account, + QueueName: queueName, }, nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/version.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/version.go index 9d3e68949fec..10937c5727d3 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/version.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues/version.go @@ -1,14 +1,5 @@ package queues -import ( - "fmt" - - "github.com/tombuildsstuff/giovanni/version" -) - // APIVersion is the version of the API used for all Storage API Operations -const APIVersion = "2020-08-04" - -func UserAgent() string { - return fmt.Sprintf("tombuildsstuff/giovanni/%s storage/%s", version.Number, APIVersion) -} +const apiVersion = "2020-08-04" +const componentName = "queue/queues" diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/README.md b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/README.md index e59b5a28335a..91c2096396f4 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/README.md +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/README.md @@ -14,9 +14,8 @@ package main import ( "context" "fmt" - "time" - - "github.com/Azure/go-autorest/autorest" + + "github.com/hashicorp/go-azure-sdk/sdk/auth" "github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities" ) @@ -24,10 +23,18 @@ func Example() error { accountName := "storageaccount1" storageAccountKey := "ABC123...." tableName := "mytable" - - storageAuth := autorest.NewSharedKeyLiteTableAuthorizer(accountName, storageAccountKey) - entitiesClient := entities.New() - entitiesClient.Client.Authorizer = storageAuth + domainSuffix := "core.windows.net" + + auth, err := auth.NewSharedKeyAuthorizer(accountName, storageAccountKey, auth.SharedKeyTable) + if err != nil { + return fmt.Errorf("building SharedKey authorizer: %+v", err) + } + + entitiesClient, err := entities.NewWithBaseUri(fmt.Sprintf("https://%s.table.%s", accountName, domainSuffix)) + if err != nil { + return fmt.Errorf("building client for environment: %+v", err) + } + entitiesClient.Client.WithAuthorizer(auth) ctx := context.TODO() input := entities.InsertEntityInput{ @@ -39,7 +46,7 @@ func Example() error { "artist": "Sigrid", }, } - if _, err := entitiesClient.Insert(ctx, accountName, tableName, input); err != nil { + if _, err := entitiesClient.Insert(ctx, tableName, input); err != nil { return fmt.Errorf("Error creating Entity: %s", err) } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/api.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/api.go index d4d20a723457..bb0e9809e3c9 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/api.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/api.go @@ -2,16 +2,13 @@ package entities import ( "context" - - "github.com/Azure/go-autorest/autorest" ) type StorageTableEntity interface { - Delete(ctx context.Context, accountName, tableName string, input DeleteEntityInput) (result autorest.Response, err error) - Insert(ctx context.Context, accountName, tableName string, input InsertEntityInput) (result autorest.Response, err error) - InsertOrReplace(ctx context.Context, accountName, tableName string, input InsertOrReplaceEntityInput) (result autorest.Response, err error) - InsertOrMerge(ctx context.Context, accountName, tableName string, input InsertOrMergeEntityInput) (result autorest.Response, err error) - Query(ctx context.Context, accountName, tableName string, input QueryEntitiesInput) (result QueryEntitiesResult, err error) - Get(ctx context.Context, accountName, tableName string, input GetEntityInput) (result GetEntityResult, err error) - GetResourceID(accountName, tableName, partitionKey, rowKey string) string + Delete(ctx context.Context, tableName string, input DeleteEntityInput) (resp DeleteEntityResponse, err error) + Insert(ctx context.Context, tableName string, input InsertEntityInput) (resp InsertResponse, err error) + InsertOrReplace(ctx context.Context, tableName string, input InsertOrReplaceEntityInput) (resp InsertOrReplaceResponse, err error) + InsertOrMerge(ctx context.Context, tableName string, input InsertOrMergeEntityInput) (resp InsertOrMergeResponse, err error) + Query(ctx context.Context, tableName string, input QueryEntitiesInput) (resp QueryEntitiesResponse, err error) + Get(ctx context.Context, tableName string, input GetEntityInput) (resp GetEntityResponse, err error) } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/client.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/client.go index 17e9d759fb9e..d1182ea25f6a 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/client.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/client.go @@ -1,25 +1,23 @@ package entities import ( - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" + "fmt" + + "github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/storage" ) // Client is the base client for Table Storage Shares. type Client struct { - autorest.Client - BaseURI string -} - -// New creates an instance of the Client client. -func New() Client { - return NewWithEnvironment(azure.PublicCloud) + Client *storage.BaseClient } -// NewWithEnvironment creates an instance of the Client client. -func NewWithEnvironment(environment azure.Environment) Client { - return Client{ - Client: autorest.NewClientWithUserAgent(UserAgent()), - BaseURI: environment.StorageEndpointSuffix, +func NewWithBaseUri(baseUri string) (*Client, error) { + baseClient, err := storage.NewBaseClient(baseUri, componentName, apiVersion) + if err != nil { + return nil, fmt.Errorf("building base client: %+v", err) } + + return &Client{ + Client: baseClient, + }, nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/delete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/delete.go index 83e9188e5e9e..05d09b3ce32e 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/delete.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/delete.go @@ -2,12 +2,11 @@ package entities import ( "context" + "fmt" "net/http" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type DeleteEntityInput struct { @@ -20,80 +19,62 @@ type DeleteEntityInput struct { PartitionKey string } +type DeleteEntityResponse struct { + HttpResponse *client.Response +} + // Delete deletes an existing entity in a table. -func (client Client) Delete(ctx context.Context, accountName, tableName string, input DeleteEntityInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("entities.Client", "Delete", "`accountName` cannot be an empty string.") - } +func (c Client) Delete(ctx context.Context, tableName string, input DeleteEntityInput) (resp DeleteEntityResponse, err error) { + if tableName == "" { - return result, validation.NewError("entities.Client", "Delete", "`tableName` cannot be an empty string.") + return resp, fmt.Errorf("`tableName` cannot be an empty string") } + if input.PartitionKey == "" { - return result, validation.NewError("entities.Client", "Delete", "`input.PartitionKey` cannot be an empty string.") + return resp, fmt.Errorf("`input.PartitionKey` cannot be an empty string") } + if input.RowKey == "" { - return result, validation.NewError("entities.Client", "Delete", "`input.RowKey` cannot be an empty string.") + return resp, fmt.Errorf("`input.RowKey` cannot be an empty string") } - req, err := client.DeletePreparer(ctx, accountName, tableName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "entities.Client", "Delete", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/json", + ExpectedStatusCodes: []int{ + http.StatusNoContent, + }, + HttpMethod: http.MethodDelete, + OptionsObject: deleteEntitiesOptions{}, + Path: fmt.Sprintf("/%s(PartitionKey='%s', RowKey='%s')", tableName, input.PartitionKey, input.RowKey), } - resp, err := client.DeleteSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "entities.Client", "Delete", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.DeleteResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "entities.Client", "Delete", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } - return } -// DeletePreparer prepares the Delete request. -func (client Client) DeletePreparer(ctx context.Context, accountName, tableName string, input DeleteEntityInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "tableName": autorest.Encode("path", tableName), - "partitionKey": autorest.Encode("path", input.PartitionKey), - "rowKey": autorest.Encode("path", input.RowKey), - } +type deleteEntitiesOptions struct{} - headers := map[string]interface{}{ - // TODO: support for eTags - "If-Match": "*", - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(endpoints.GetTableEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{tableName}(PartitionKey='{partitionKey}', RowKey='{rowKey}')", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) +func (d deleteEntitiesOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("Accept", "application/json") + headers.Append("If-Match", "*") + return headers } -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client Client) DeleteSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (d deleteEntitiesOptions) ToOData() *odata.Query { + return nil } -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client Client) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusNoContent), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return +func (d deleteEntitiesOptions) ToQuery() *client.QueryParams { + return nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/get.go index bdb40180b54d..14cd5ad38d04 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/get.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/get.go @@ -5,10 +5,8 @@ import ( "fmt" "net/http" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type GetEntityInput struct { @@ -19,90 +17,76 @@ type GetEntityInput struct { MetaDataLevel MetaDataLevel } -type GetEntityResult struct { - autorest.Response +type GetEntityResponse struct { + HttpResponse *client.Response Entity map[string]interface{} } // Get queries entities in a table and includes the $filter and $select options. -func (client Client) Get(ctx context.Context, accountName, tableName string, input GetEntityInput) (result GetEntityResult, err error) { - if accountName == "" { - return result, validation.NewError("entities.Client", "Get", "`accountName` cannot be an empty string.") - } +func (c Client) Get(ctx context.Context, tableName string, input GetEntityInput) (resp GetEntityResponse, err error) { if tableName == "" { - return result, validation.NewError("entities.Client", "Get", "`tableName` cannot be an empty string.") + return resp, fmt.Errorf("`tableName` cannot be an empty string") } + if input.PartitionKey == "" { - return result, validation.NewError("entities.Client", "Get", "`input.PartitionKey` cannot be an empty string.") + return resp, fmt.Errorf("`input.PartitionKey` cannot be an empty string") } + if input.RowKey == "" { - return result, validation.NewError("entities.Client", "Get", "`input.RowKey` cannot be an empty string.") + return resp, fmt.Errorf("`input.RowKey` cannot be an empty string") } - req, err := client.GetPreparer(ctx, accountName, tableName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "entities.Client", "Get", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: getEntitiesOptions{ + MetaDataLevel: input.MetaDataLevel, + }, + Path: fmt.Sprintf("/%s(PartitionKey='%s', RowKey='%s')", tableName, input.PartitionKey, input.RowKey), } - resp, err := client.GetSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "entities.Client", "Get", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.GetResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "entities.Client", "Get", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } + if resp.HttpResponse != nil { + if resp.HttpResponse.Body != nil { + err = resp.HttpResponse.Unmarshal(&resp.Entity) + if err != nil { + return resp, fmt.Errorf("unmarshalling response: %+v", err) + } + } + } return } -// GetPreparer prepares the Get request. -func (client Client) GetPreparer(ctx context.Context, accountName, tableName string, input GetEntityInput) (*http.Request, error) { - - pathParameters := map[string]interface{}{ - "tableName": autorest.Encode("path", tableName), - "partitionKey": autorest.Encode("path", input.PartitionKey), - "rowKey": autorest.Encode("path", input.RowKey), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "Accept": fmt.Sprintf("application/json;odata=%s", input.MetaDataLevel), - "DataServiceVersion": "3.0;NetFx", - "MaxDataServiceVersion": "3.0;NetFx", - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetTableEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{tableName}(PartitionKey='{partitionKey}',RowKey='{rowKey}')", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) +type getEntitiesOptions struct { + MetaDataLevel MetaDataLevel } -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (g getEntitiesOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("Accept", fmt.Sprintf("application/json;odata=%s", g.MetaDataLevel)) + headers.Append("DataServiceVersion", "3.0;NetFx") + headers.Append("MaxDataServiceVersion", "3.0;NetFx") + return headers } -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client Client) GetResponder(resp *http.Response) (result GetEntityResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result.Entity), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} +func (g getEntitiesOptions) ToOData() *odata.Query { + return nil +} - return +func (g getEntitiesOptions) ToQuery() *client.QueryParams { + return nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/insert.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/insert.go index 92b05cef5499..315b7ce5b653 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/insert.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/insert.go @@ -5,10 +5,8 @@ import ( "fmt" "net/http" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type InsertEntityInput struct { @@ -29,84 +27,74 @@ type InsertEntityInput struct { PartitionKey string } +type InsertResponse struct { + HttpResponse *client.Response +} + // Insert inserts a new entity into a table. -func (client Client) Insert(ctx context.Context, accountName, tableName string, input InsertEntityInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("entities.Client", "Insert", "`accountName` cannot be an empty string.") - } +func (c Client) Insert(ctx context.Context, tableName string, input InsertEntityInput) (resp InsertResponse, err error) { if tableName == "" { - return result, validation.NewError("entities.Client", "Insert", "`tableName` cannot be an empty string.") + return resp, fmt.Errorf("`tableName` cannot be an empty string") } + if input.PartitionKey == "" { - return result, validation.NewError("entities.Client", "Insert", "`input.PartitionKey` cannot be an empty string.") + return resp, fmt.Errorf("`input.PartitionKey` cannot be an empty string") } + if input.RowKey == "" { - return result, validation.NewError("entities.Client", "Insert", "`input.RowKey` cannot be an empty string.") + return resp, fmt.Errorf("`input.RowKey` cannot be an empty string") } - req, err := client.InsertPreparer(ctx, accountName, tableName, input) + opts := client.RequestOptions{ + ContentType: "application/json", + ExpectedStatusCodes: []int{ + http.StatusNoContent, + }, + HttpMethod: http.MethodPost, + OptionsObject: insertOptions{ + MetaDataLevel: input.MetaDataLevel, + }, + Path: fmt.Sprintf("/%s", tableName), + } + + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - err = autorest.NewErrorWithError(err, "entities.Client", "Insert", nil, "Failure preparing request") + err = fmt.Errorf("building request: %+v", err) return } - resp, err := client.InsertSender(req) + input.Entity["PartitionKey"] = input.PartitionKey + input.Entity["RowKey"] = input.RowKey + + err = req.Marshal(&input.Entity) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "entities.Client", "Insert", resp, "Failure sending request") - return + return resp, fmt.Errorf("marshalling request: %v", err) } - result, err = client.InsertResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "entities.Client", "Insert", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// InsertPreparer prepares the Insert request. -func (client Client) InsertPreparer(ctx context.Context, accountName, tableName string, input InsertEntityInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "tableName": autorest.Encode("path", tableName), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "Accept": fmt.Sprintf("application/json;odata=%s", input.MetaDataLevel), - "Prefer": "return-no-content", - } - - input.Entity["PartitionKey"] = input.PartitionKey - input.Entity["RowKey"] = input.RowKey - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json"), - autorest.AsPost(), - autorest.WithBaseURL(endpoints.GetTableEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{tableName}", pathParameters), - autorest.WithJSON(input.Entity), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) +type insertOptions struct { + MetaDataLevel MetaDataLevel } -// InsertSender sends the Insert request. The method will close the -// http.Response Body if it receives an error. -func (client Client) InsertSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (i insertOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("Accept", fmt.Sprintf("application/json;odata=%s", i.MetaDataLevel)) + headers.Append("Prefer", "return-no-content") + return headers } -// InsertResponder handles the response to the Insert request. The method always -// closes the http.Response Body. -func (client Client) InsertResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusNoContent), - autorest.ByClosing()) - result = autorest.Response{Response: resp} +func (i insertOptions) ToOData() *odata.Query { + return nil +} - return +func (i insertOptions) ToQuery() *client.QueryParams { + return nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/insert_or_merge.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/insert_or_merge.go index 1fb4ed3df164..27cae93239bf 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/insert_or_merge.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/insert_or_merge.go @@ -2,12 +2,11 @@ package entities import ( "context" + "fmt" "net/http" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type InsertOrMergeEntityInput struct { @@ -25,84 +24,71 @@ type InsertOrMergeEntityInput struct { PartitionKey string } +type InsertOrMergeResponse struct { + HttpResponse *client.Response +} + // InsertOrMerge updates an existing entity or inserts a new entity if it does not exist in the table. // Because this operation can insert or update an entity, it is also known as an upsert operation. -func (client Client) InsertOrMerge(ctx context.Context, accountName, tableName string, input InsertOrMergeEntityInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("entities.Client", "InsertOrMerge", "`accountName` cannot be an empty string.") - } +func (c Client) InsertOrMerge(ctx context.Context, tableName string, input InsertOrMergeEntityInput) (resp InsertOrMergeResponse, err error) { if tableName == "" { - return result, validation.NewError("entities.Client", "InsertOrMerge", "`tableName` cannot be an empty string.") + return resp, fmt.Errorf("`tableName` cannot be an empty string") } + if input.PartitionKey == "" { - return result, validation.NewError("entities.Client", "InsertOrMerge", "`input.PartitionKey` cannot be an empty string.") + return resp, fmt.Errorf("`input.PartitionKey` cannot be an empty string") } + if input.RowKey == "" { - return result, validation.NewError("entities.Client", "InsertOrMerge", "`input.RowKey` cannot be an empty string.") + return resp, fmt.Errorf("`input.RowKey` cannot be an empty string") + } + + opts := client.RequestOptions{ + ContentType: "application/json", + ExpectedStatusCodes: []int{ + http.StatusNoContent, + }, + HttpMethod: "MERGE", + OptionsObject: insertOrMergeOptions{}, + Path: fmt.Sprintf("/%s(PartitionKey='%s', RowKey='%s')", tableName, input.PartitionKey, input.RowKey), } - req, err := client.InsertOrMergePreparer(ctx, accountName, tableName, input) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - err = autorest.NewErrorWithError(err, "entities.Client", "InsertOrMerge", nil, "Failure preparing request") + err = fmt.Errorf("building request: %+v", err) return } - resp, err := client.InsertOrMergeSender(req) + input.Entity["PartitionKey"] = input.PartitionKey + input.Entity["RowKey"] = input.RowKey + + err = req.Marshal(&input.Entity) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "entities.Client", "InsertOrMerge", resp, "Failure sending request") - return + return resp, fmt.Errorf("marshalling request: %v", err) } - result, err = client.InsertOrMergeResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "entities.Client", "InsertOrMerge", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// InsertOrMergePreparer prepares the InsertOrMerge request. -func (client Client) InsertOrMergePreparer(ctx context.Context, accountName, tableName string, input InsertOrMergeEntityInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "tableName": autorest.Encode("path", tableName), - "partitionKey": autorest.Encode("path", input.PartitionKey), - "rowKey": autorest.Encode("path", input.RowKey), - } +type insertOrMergeOptions struct{} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "Accept": "application/json", - "Prefer": "return-no-content", - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json"), - autorest.AsMerge(), - autorest.WithBaseURL(endpoints.GetTableEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{tableName}(PartitionKey='{partitionKey}', RowKey='{rowKey}')", pathParameters), - autorest.WithJSON(input.Entity), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) +func (i insertOrMergeOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("Accept", "application/json") + headers.Append("Prefer", "return-no-content") + return headers } -// InsertOrMergeSender sends the InsertOrMerge request. The method will close the -// http.Response Body if it receives an error. -func (client Client) InsertOrMergeSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (i insertOrMergeOptions) ToOData() *odata.Query { + return nil } -// InsertOrMergeResponder handles the response to the InsertOrMerge request. The method always -// closes the http.Response Body. -func (client Client) InsertOrMergeResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusNoContent), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return +func (i insertOrMergeOptions) ToQuery() *client.QueryParams { + return nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/insert_or_replace.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/insert_or_replace.go index 036ba5de5fe7..6f97eb624b7d 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/insert_or_replace.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/insert_or_replace.go @@ -2,12 +2,11 @@ package entities import ( "context" + "fmt" "net/http" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type InsertOrReplaceEntityInput struct { @@ -25,84 +24,71 @@ type InsertOrReplaceEntityInput struct { PartitionKey string } +type InsertOrReplaceResponse struct { + HttpResponse *client.Response +} + // InsertOrReplace replaces an existing entity or inserts a new entity if it does not exist in the table. // Because this operation can insert or update an entity, it is also known as an upsert operation. -func (client Client) InsertOrReplace(ctx context.Context, accountName, tableName string, input InsertOrReplaceEntityInput) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("entities.Client", "InsertOrReplace", "`accountName` cannot be an empty string.") - } +func (c Client) InsertOrReplace(ctx context.Context, tableName string, input InsertOrReplaceEntityInput) (resp InsertOrReplaceResponse, err error) { if tableName == "" { - return result, validation.NewError("entities.Client", "InsertOrReplace", "`tableName` cannot be an empty string.") + return resp, fmt.Errorf("`tableName` cannot be an empty string") } + if input.PartitionKey == "" { - return result, validation.NewError("entities.Client", "InsertOrReplace", "`input.PartitionKey` cannot be an empty string.") + return resp, fmt.Errorf("`input.PartitionKey` cannot be an empty string") } + if input.RowKey == "" { - return result, validation.NewError("entities.Client", "InsertOrReplace", "`input.RowKey` cannot be an empty string.") + return resp, fmt.Errorf("`input.RowKey` cannot be an empty string") + } + + opts := client.RequestOptions{ + ContentType: "application/json", + ExpectedStatusCodes: []int{ + http.StatusNoContent, + }, + HttpMethod: "MERGE", + OptionsObject: insertOrReplaceOptions{}, + Path: fmt.Sprintf("/%s(PartitionKey='%s', RowKey='%s')", tableName, input.PartitionKey, input.RowKey), } - req, err := client.InsertOrReplacePreparer(ctx, accountName, tableName, input) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - err = autorest.NewErrorWithError(err, "entities.Client", "InsertOrReplace", nil, "Failure preparing request") + err = fmt.Errorf("building request: %+v", err) return } - resp, err := client.InsertOrReplaceSender(req) + input.Entity["PartitionKey"] = input.PartitionKey + input.Entity["RowKey"] = input.RowKey + + err = req.Marshal(&input.Entity) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "entities.Client", "InsertOrReplace", resp, "Failure sending request") - return + return resp, fmt.Errorf("marshalling request: %v", err) } - result, err = client.InsertOrReplaceResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "entities.Client", "InsertOrReplace", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// InsertOrReplacePreparer prepares the InsertOrReplace request. -func (client Client) InsertOrReplacePreparer(ctx context.Context, accountName, tableName string, input InsertOrReplaceEntityInput) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "tableName": autorest.Encode("path", tableName), - "partitionKey": autorest.Encode("path", input.PartitionKey), - "rowKey": autorest.Encode("path", input.RowKey), - } +type insertOrReplaceOptions struct{} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "Accept": "application/json", - "Prefer": "return-no-content", - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json"), - autorest.AsMerge(), - autorest.WithBaseURL(endpoints.GetTableEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{tableName}(PartitionKey='{partitionKey}', RowKey='{rowKey}')", pathParameters), - autorest.WithJSON(input.Entity), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) +func (i insertOrReplaceOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("Accept", "application/json") + headers.Append("Prefer", "return-no-content") + return headers } -// InsertOrReplaceSender sends the InsertOrReplace request. The method will close the -// http.Response Body if it receives an error. -func (client Client) InsertOrReplaceSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (i insertOrReplaceOptions) ToOData() *odata.Query { + return nil } -// InsertOrReplaceResponder handles the response to the InsertOrReplace request. The method always -// closes the http.Response Body. -func (client Client) InsertOrReplaceResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusNoContent), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return +func (i insertOrReplaceOptions) ToQuery() *client.QueryParams { + return nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/query.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/query.go index c1ba3706be7d..9137401377df 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/query.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/query.go @@ -4,12 +4,11 @@ import ( "context" "fmt" "net/http" + "strconv" "strings" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type QueryEntitiesInput struct { @@ -35,8 +34,8 @@ type QueryEntitiesInput struct { NextRowKey *string } -type QueryEntitiesResult struct { - autorest.Response +type QueryEntitiesResponse struct { + HttpResponse *client.Response NextPartitionKey string NextRowKey string @@ -46,117 +45,98 @@ type QueryEntitiesResult struct { } // Query queries entities in a table and includes the $filter and $select options. -func (client Client) Query(ctx context.Context, accountName, tableName string, input QueryEntitiesInput) (result QueryEntitiesResult, err error) { - if accountName == "" { - return result, validation.NewError("entities.Client", "Query", "`accountName` cannot be an empty string.") - } +func (c Client) Query(ctx context.Context, tableName string, input QueryEntitiesInput) (resp QueryEntitiesResponse, err error) { if tableName == "" { - return result, validation.NewError("entities.Client", "Query", "`tableName` cannot be an empty string.") + return resp, fmt.Errorf("`tableName` cannot be an empty string") } - req, err := client.QueryPreparer(ctx, accountName, tableName, input) - if err != nil { - err = autorest.NewErrorWithError(err, "entities.Client", "Query", nil, "Failure preparing request") - return + additionalParameters := make([]string, 0) + if input.PartitionKey != "" { + additionalParameters = append(additionalParameters, "PartitionKey='%s'", input.PartitionKey) + } + + if input.RowKey != "" { + additionalParameters = append(additionalParameters, "RowKey='%s'", input.RowKey) + } + + path := fmt.Sprintf("/%s", tableName) + if len(additionalParameters) > 0 { + path += fmt.Sprintf("(%s)", strings.Join(additionalParameters, ",")) } - resp, err := client.QuerySender(req) + opts := client.RequestOptions{ + ContentType: "application/json", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: queryOptions{ + input: input, + }, + Path: path, + } + + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "entities.Client", "Query", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.QueryResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "entities.Client", "Query", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } + if resp.HttpResponse != nil { + if resp.HttpResponse.Body != nil { + err = resp.HttpResponse.Unmarshal(&resp) + if err != nil { + return resp, fmt.Errorf("unmarshalling response: %v", err) + } + } + } + return } -// QueryPreparer prepares the Query request. -func (client Client) QueryPreparer(ctx context.Context, accountName, tableName string, input QueryEntitiesInput) (*http.Request, error) { - - pathParameters := map[string]interface{}{ - "tableName": autorest.Encode("path", tableName), - "additionalParameters": "", - } - - //PartitionKey='',RowKey='' - additionalParams := make([]string, 0) - if input.PartitionKey != "" { - additionalParams = append(additionalParams, fmt.Sprintf("PartitionKey='%s'", input.PartitionKey)) - } - if input.RowKey != "" { - additionalParams = append(additionalParams, fmt.Sprintf("RowKey='%s'", input.RowKey)) - } - if len(additionalParams) > 0 { - pathParameters["additionalParameters"] = autorest.Encode("path", strings.Join(additionalParams, ",")) - } +type queryOptions struct { + input QueryEntitiesInput +} - queryParameters := map[string]interface{}{} +func (q queryOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("Accept", fmt.Sprintf("application/json;odata=%s", q.input.MetaDataLevel)) + headers.Append("DataServiceVersion", "3.0;NetFx") + headers.Append("MaxDataServiceVersion", "3.0;NetFx") + return headers +} - if input.Filter != nil { - queryParameters["$filter"] = autorest.Encode("query", *input.Filter) - } +func (q queryOptions) ToOData() *odata.Query { + return nil +} - if input.PropertyNamesToSelect != nil { - queryParameters["$select"] = autorest.Encode("query", strings.Join(*input.PropertyNamesToSelect, ",")) - } +func (q queryOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} - if input.Top != nil { - queryParameters["$top"] = autorest.Encode("query", *input.Top) + if q.input.Filter != nil { + out.Append("$filter", *q.input.Filter) } - if input.NextPartitionKey != nil { - queryParameters["NextPartitionKey"] = *input.NextPartitionKey + if q.input.PropertyNamesToSelect != nil { + out.Append("$select", strings.Join(*q.input.PropertyNamesToSelect, ",")) } - if input.NextRowKey != nil { - queryParameters["NextRowKey"] = *input.NextRowKey + if q.input.Top != nil { + out.Append("$top", strconv.Itoa(*q.input.Top)) } - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "Accept": fmt.Sprintf("application/json;odata=%s", input.MetaDataLevel), - "DataServiceVersion": "3.0;NetFx", - "MaxDataServiceVersion": "3.0;NetFx", + if q.input.NextPartitionKey != nil { + out.Append("NextPartitionKey", *q.input.NextPartitionKey) } - // GET /myaccount/Customers()?$filter=(Rating%20ge%203)%20and%20(Rating%20le%206)&$select=PartitionKey,RowKey,Address,CustomerSince - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetTableEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{tableName}({additionalParameters})", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// QuerySender sends the Query request. The method will close the -// http.Response Body if it receives an error. -func (client Client) QuerySender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// QueryResponder handles the response to the Query request. The method always -// closes the http.Response Body. -func (client Client) QueryResponder(resp *http.Response) (result QueryEntitiesResult, err error) { - if resp != nil && resp.Header != nil { - result.NextPartitionKey = resp.Header.Get("x-ms-continuation-NextPartitionKey") - result.NextRowKey = resp.Header.Get("x-ms-continuation-NextRowKey") + if q.input.NextRowKey != nil { + out.Append("NextRowKey", *q.input.NextRowKey) } - - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/resource_id.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/resource_id.go index 249671dc91bf..4e7240264828 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/resource_id.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/resource_id.go @@ -5,87 +5,118 @@ import ( "net/url" "strings" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" + "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts" ) -// GetResourceID returns the Resource ID for the given Entity -// This can be useful when, for example, you're using this as a unique identifier -func (client Client) GetResourceID(accountName, tableName, partitionKey, rowKey string) string { - domain := endpoints.GetTableEndpoint(client.BaseURI, accountName) - return fmt.Sprintf("%s/%s(PartitionKey='%s',RowKey='%s')", domain, tableName, partitionKey, rowKey) -} +// TODO: update this to implement `resourceids.ResourceId` once +// https://github.com/hashicorp/go-azure-helpers/issues/187 is fixed +var _ resourceids.Id = EntityId{} + +type EntityId struct { + // AccountId specifies the ID of the Storage Account where this Entity exists. + AccountId accounts.AccountId -type ResourceID struct { - AccountName string - TableName string + // TableName specifies the name of the Table where this Entity exists. + TableName string + + // PartitionKey specifies the Partition Key for this Entity. PartitionKey string - RowKey string + + // RowKey specifies the Row Key for this Entity. + RowKey string } -// ParseResourceID parses the specified Resource ID and returns an object which -// can be used to look up the specified Entity within the specified Table -func ParseResourceID(id string) (*ResourceID, error) { - // example: https://account1.table.core.chinacloudapi.cn/table1(PartitionKey='partition1',RowKey='row1') - if id == "" { - return nil, fmt.Errorf("`id` was empty") +func NewEntityID(accountId accounts.AccountId, tableName, partitionKey, rowKey string) EntityId { + return EntityId{ + AccountId: accountId, + TableName: tableName, + PartitionKey: partitionKey, + RowKey: rowKey, } +} + +func (b EntityId) ID() string { + return fmt.Sprintf("%s/%s(PartitionKey='%s',RowKey='%s')", b.AccountId.ID(), b.TableName, b.PartitionKey, b.RowKey) +} + +func (b EntityId) String() string { + components := []string{ + fmt.Sprintf("Partition Key %q", b.PartitionKey), + fmt.Sprintf("Row Key %q", b.RowKey), + fmt.Sprintf("Table Name %q", b.TableName), + fmt.Sprintf("Account %q", b.AccountId.String()), + } + return fmt.Sprintf("Entity (%s)", strings.Join(components, " / ")) +} - uri, err := url.Parse(id) +// ParseEntityID parses `input` into a Entity ID using a known `domainSuffix` +func ParseEntityID(input, domainSuffix string) (*EntityId, error) { + // example: https://foo.table.core.windows.net/Bar1(PartitionKey='partition1',RowKey='row1') + if input == "" { + return nil, fmt.Errorf("`input` was empty") + } + + account, err := accounts.ParseAccountID(input, domainSuffix) if err != nil { - return nil, fmt.Errorf("Error parsing ID as a URL: %s", err) + return nil, fmt.Errorf("parsing account %q: %+v", input, err) + } + + if account.SubDomainType != accounts.TableSubDomainType { + return nil, fmt.Errorf("expected the subdomain type to be %q but got %q", string(accounts.TableSubDomainType), string(account.SubDomainType)) } - accountName, err := endpoints.GetAccountNameFromEndpoint(uri.Host) + uri, err := url.Parse(input) if err != nil { - return nil, fmt.Errorf("Error parsing Account Name: %s", err) + return nil, fmt.Errorf("parsing %q as a uri: %+v", input, err) } - // assume there a `Table('')` path := strings.TrimPrefix(uri.Path, "/") - if !strings.Contains(uri.Path, "(") || !strings.HasSuffix(uri.Path, ")") { - return nil, fmt.Errorf("Expected the Table Name to be in the format `tables(PartitionKey='',RowKey='')` but got %q", path) + segments := strings.Split(path, "/") + if len(segments) != 1 { + return nil, fmt.Errorf("expected the path to contain 1 segment but got %d", len(segments)) } - // NOTE: honestly this could probably be a RegEx, but this seemed like the simplest way to - // allow these two fields to be specified in either order - indexOfBracket := strings.IndexByte(path, '(') - tableName := path[0:indexOfBracket] - - // trim off the brackets - temp := strings.TrimPrefix(path, fmt.Sprintf("%s(", tableName)) - temp = strings.TrimSuffix(temp, ")") - - dictionary := strings.Split(temp, ",") - partitionKey := "" - rowKey := "" - for _, v := range dictionary { - split := strings.Split(v, "=") - if len(split) != 2 { - return nil, fmt.Errorf("Expected 2 segments but got %d for %q", len(split), v) - } - - key := split[0] - value := strings.TrimSuffix(strings.TrimPrefix(split[1], "'"), "'") - if strings.EqualFold(key, "PartitionKey") { - partitionKey = value - } else if strings.EqualFold(key, "RowKey") { - rowKey = value - } else { - return nil, fmt.Errorf("Unexpected Key %q", key) - } + // Tables and Table Entities are similar with table being `table1` and entities + // being `table1(PartitionKey='samplepartition',RowKey='samplerow')` so we need to validate this is a table + key := strings.TrimPrefix(uri.Path, "/") + if !strings.Contains(key, "(") || !strings.HasSuffix(key, ")") { + return nil, fmt.Errorf("expected the path to be an entity name but got a table name %q", key) } - if partitionKey == "" { - return nil, fmt.Errorf("Expected a PartitionKey but didn't get one") - } - if rowKey == "" { - return nil, fmt.Errorf("Expected a RowKey but didn't get one") + indexOfFirstBracket := strings.Index(key, "(") + tableName := key[0:indexOfFirstBracket] + componentString := key[indexOfFirstBracket:] + componentString = strings.TrimPrefix(componentString, "(") + componentString = strings.TrimSuffix(componentString, ")") + components := strings.Split(componentString, ",") + if len(components) != 2 { + return nil, fmt.Errorf("expected the path to be an entity name but got %q", key) } - return &ResourceID{ - AccountName: *accountName, + partitionKey := parseValueFromKey(components[0], "PartitionKey") + rowKey := parseValueFromKey(components[1], "RowKey") + return &EntityId{ + AccountId: *account, TableName: tableName, - PartitionKey: partitionKey, - RowKey: rowKey, + PartitionKey: *partitionKey, + RowKey: *rowKey, }, nil } + +func parseValueFromKey(input, expectedKey string) *string { + components := strings.Split(input, "=") + if len(components) != 2 { + return nil + } + key := components[0] + value := components[1] + if key != expectedKey { + return nil + } + + // the value is surrounded in single quotes, remove those + value = strings.TrimPrefix(value, "'") + value = strings.TrimSuffix(value, "'") + return &value +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/version.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/version.go index 6270953c7923..13d95b5bcd29 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/version.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities/version.go @@ -1,14 +1,4 @@ package entities -import ( - "fmt" - - "github.com/tombuildsstuff/giovanni/version" -) - -// APIVersion is the version of the API used for all Storage API Operations -const APIVersion = "2020-08-04" - -func UserAgent() string { - return fmt.Sprintf("tombuildsstuff/giovanni/%s storage/%s", version.Number, APIVersion) -} +const apiVersion = "2020-08-04" +const componentName = "table/entities" diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/README.md b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/README.md index 40ec34959a79..2ef66210193c 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/README.md +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/README.md @@ -14,9 +14,8 @@ package main import ( "context" "fmt" - "time" - - "github.com/Azure/go-autorest/autorest" + + "github.com/hashicorp/go-azure-sdk/sdk/auth" "github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables" ) @@ -24,13 +23,20 @@ func Example() error { accountName := "storageaccount1" storageAccountKey := "ABC123...." tableName := "mytable" - - storageAuth := autorest.NewSharedKeyLiteTableAuthorizer(accountName, storageAccountKey) - tablesClient := tables.New() - tablesClient.Client.Authorizer = storageAuth + domainSuffix := "core.windows.net" + + auth, err := auth.NewSharedKeyAuthorizer(accountName, storageAccountKey, auth.SharedKeyTable) + if err != nil { + return fmt.Errorf("building SharedKey authorizer: %+v", err) + } + tablesClient, err := tables.NewWithBaseUri(fmt.Sprintf("https://%s.table.%s", accountName, domainSuffix)) + if err != nil { + return fmt.Errorf("building client for environment: %+v", err) + } + tablesClient.Client.WithAuthorizer(auth) ctx := context.TODO() - if _, err := tablesClient.Insert(ctx, accountName, tableName); err != nil { + if _, err := tablesClient.Create(ctx, tableName); err != nil { return fmt.Errorf("Error creating Table: %s", err) } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/acl_get.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/acl_get.go index 0ef00006530f..d927d38f9c90 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/acl_get.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/acl_get.go @@ -2,92 +2,72 @@ package tables import ( "context" + "fmt" "net/http" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) -type GetACLResult struct { - autorest.Response +type GetACLResponse struct { + HttpResponse *client.Response SignedIdentifiers []SignedIdentifier `xml:"SignedIdentifier"` } // GetACL returns the Access Control List for the specified Table -func (client Client) GetACL(ctx context.Context, accountName, tableName string) (result GetACLResult, err error) { - if accountName == "" { - return result, validation.NewError("tables.Client", "GetACL", "`accountName` cannot be an empty string.") - } +func (c Client) GetACL(ctx context.Context, tableName string) (resp GetACLResponse, err error) { + if tableName == "" { - return result, validation.NewError("tables.Client", "GetACL", "`tableName` cannot be an empty string.") + return resp, fmt.Errorf("`tableName` cannot be an empty string") } - req, err := client.GetACLPreparer(ctx, accountName, tableName) - if err != nil { - err = autorest.NewErrorWithError(err, "tables.Client", "GetACL", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: getAclTableOptions{}, + Path: fmt.Sprintf("/%s", tableName), } - resp, err := client.GetACLSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "tables.Client", "GetACL", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.GetACLResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "tables.Client", "GetACL", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } - return -} - -// GetACLPreparer prepares the GetACL request. -func (client Client) GetACLPreparer(ctx context.Context, accountName, tableName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "tableName": autorest.Encode("path", tableName), + if resp.HttpResponse != nil { + if resp.HttpResponse.Body != nil { + err = resp.HttpResponse.Unmarshal(&resp) + if err != nil { + return resp, fmt.Errorf("unmarshalling response body: %v", err) + } + } } - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "acl"), - } + return +} - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } +type getAclTableOptions struct{} - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetTableEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{tableName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) +func (g getAclTableOptions) ToHeaders() *client.Headers { + return nil } -// GetACLSender sends the GetACL request. The method will close the -// http.Response Body if it receives an error. -func (client Client) GetACLSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (g getAclTableOptions) ToOData() *odata.Query { + return nil } -// GetACLResponder handles the response to the GetACL request. The method always -// closes the http.Response Body. -func (client Client) GetACLResponder(resp *http.Response) (result GetACLResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingXML(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return +func (g getAclTableOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "acl") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/acl_set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/acl_set.go index c26bffc834d1..9ff4ad0e0a1e 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/acl_set.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/acl_set.go @@ -3,12 +3,11 @@ package tables import ( "context" "encoding/xml" + "fmt" "net/http" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type setAcl struct { @@ -17,82 +16,58 @@ type setAcl struct { XMLName xml.Name `xml:"SignedIdentifiers"` } +type SetACLResponse struct { + HttpResponse *client.Response +} + // SetACL sets the specified Access Control List for the specified Table -func (client Client) SetACL(ctx context.Context, accountName, tableName string, acls []SignedIdentifier) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("tables.Client", "SetACL", "`accountName` cannot be an empty string.") - } +func (c Client) SetACL(ctx context.Context, tableName string, acls []SignedIdentifier) (resp SetACLResponse, err error) { if tableName == "" { - return result, validation.NewError("tables.Client", "SetACL", "`tableName` cannot be an empty string.") + return resp, fmt.Errorf("`tableName` cannot be an empty string") + } + + opts := client.RequestOptions{ + ContentType: "application/xml; charset=utf-8", + ExpectedStatusCodes: []int{ + http.StatusNoContent, + }, + HttpMethod: http.MethodPut, + OptionsObject: setAclTableOptions{}, + Path: fmt.Sprintf("/%s", tableName), } - req, err := client.SetACLPreparer(ctx, accountName, tableName, acls) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - err = autorest.NewErrorWithError(err, "tables.Client", "SetACL", nil, "Failure preparing request") + err = fmt.Errorf("building request: %+v", err) return } - resp, err := client.SetACLSender(req) + err = req.Marshal(setAcl{SignedIdentifiers: acls}) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "tables.Client", "SetACL", resp, "Failure sending request") - return + return resp, fmt.Errorf("marshalling request: %+v", err) } - result, err = client.SetACLResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "tables.Client", "SetACL", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// SetACLPreparer prepares the SetACL request. -func (client Client) SetACLPreparer(ctx context.Context, accountName, tableName string, acls []SignedIdentifier) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "tableName": autorest.Encode("path", tableName), - } +type setAclTableOptions struct{} - queryParameters := map[string]interface{}{ - "comp": autorest.Encode("query", "acl"), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - } - - input := setAcl{ - SignedIdentifiers: acls, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/xml; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(endpoints.GetTableEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/{tableName}", pathParameters), - autorest.WithQueryParameters(queryParameters), - autorest.WithHeaders(headers), - autorest.WithXML(&input)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) +func (s setAclTableOptions) ToHeaders() *client.Headers { + return nil } -// SetACLSender sends the SetACL request. The method will close the -// http.Response Body if it receives an error. -func (client Client) SetACLSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (s setAclTableOptions) ToOData() *odata.Query { + return nil } -// SetACLResponder handles the response to the SetACL request. The method always -// closes the http.Response Body. -func (client Client) SetACLResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusNoContent), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return +func (s setAclTableOptions) ToQuery() *client.QueryParams { + out := &client.QueryParams{} + out.Append("comp", "acl") + return out } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/api.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/api.go index d869819ff21e..75c1de621410 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/api.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/api.go @@ -2,16 +2,14 @@ package tables import ( "context" - - "github.com/Azure/go-autorest/autorest" ) type StorageTable interface { - Delete(ctx context.Context, accountName, tableName string) (result autorest.Response, err error) - Exists(ctx context.Context, accountName, tableName string) (result autorest.Response, err error) - GetACL(ctx context.Context, accountName, tableName string) (result GetACLResult, err error) - Create(ctx context.Context, accountName, tableName string) (result autorest.Response, err error) - GetResourceID(accountName, tableName string) string - Query(ctx context.Context, accountName string, metaDataLevel MetaDataLevel) (result GetResult, err error) - SetACL(ctx context.Context, accountName, tableName string, acls []SignedIdentifier) (result autorest.Response, err error) + Delete(ctx context.Context, tableName string) (resp DeleteTableResponse, err error) + Exists(ctx context.Context, tableName string) (resp TableExistsResponse, err error) + GetACL(ctx context.Context, tableName string) (resp GetACLResponse, err error) + Create(ctx context.Context, tableName string) (resp CreateTableResponse, err error) + GetResourceManagerResourceID(subscriptionID, resourceGroup, accountName, tableName string) string + Query(ctx context.Context, input QueryInput) (resp GetResponse, err error) + SetACL(ctx context.Context, tableName string, acls []SignedIdentifier) (resp SetACLResponse, err error) } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/client.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/client.go index 56724b9202c9..31e53c5a6c68 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/client.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/client.go @@ -1,25 +1,23 @@ package tables import ( - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" + "fmt" + + "github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/storage" ) // Client is the base client for Table Storage Shares. type Client struct { - autorest.Client - BaseURI string -} - -// New creates an instance of the Client client. -func New() Client { - return NewWithEnvironment(azure.PublicCloud) + Client *storage.BaseClient } -// NewWithEnvironment creates an instance of the Client client. -func NewWithEnvironment(environment azure.Environment) Client { - return Client{ - Client: autorest.NewClientWithUserAgent(UserAgent()), - BaseURI: environment.StorageEndpointSuffix, +func NewWithBaseUri(baseUri string) (*Client, error) { + baseClient, err := storage.NewBaseClient(baseUri, componentName, apiVersion) + if err != nil { + return nil, fmt.Errorf("building base client: %+v", err) } + + return &Client{ + Client: baseClient, + }, nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/create.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/create.go index 561f57460daf..feeebe40052f 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/create.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/create.go @@ -2,89 +2,70 @@ package tables import ( "context" + "fmt" "net/http" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) type createTableRequest struct { TableName string `json:"TableName"` } +type CreateTableResponse struct { + HttpResponse *client.Response +} + // Create creates a new table in the storage account. -func (client Client) Create(ctx context.Context, accountName, tableName string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("tables.Client", "Create", "`accountName` cannot be an empty string.") - } +func (c Client) Create(ctx context.Context, tableName string) (resp CreateTableResponse, err error) { if tableName == "" { - return result, validation.NewError("tables.Client", "Create", "`tableName` cannot be an empty string.") + return resp, fmt.Errorf("`tableName` cannot be an empty string") } - req, err := client.CreatePreparer(ctx, accountName, tableName) + opts := client.RequestOptions{ + ContentType: "application/json", + ExpectedStatusCodes: []int{ + http.StatusNoContent, + }, + HttpMethod: http.MethodPost, + OptionsObject: createTableOptions{}, + Path: "/Tables", + } + + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - err = autorest.NewErrorWithError(err, "tables.Client", "Create", nil, "Failure preparing request") + err = fmt.Errorf("building request: %+v", err) return } - resp, err := client.CreateSender(req) + err = req.Marshal(&createTableRequest{TableName: tableName}) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "tables.Client", "Create", resp, "Failure sending request") - return + return resp, fmt.Errorf("marshalling request") } - result, err = client.CreateResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "tables.Client", "Create", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// CreatePreparer prepares the Create request. -func (client Client) CreatePreparer(ctx context.Context, accountName, tableName string) (*http.Request, error) { - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - // NOTE: we could support returning metadata here, but it doesn't appear to be directly useful - // vs making a request using the Get methods as-necessary? - "Accept": "application/json;odata=nometadata", - "Prefer": "return-no-content", - } - - body := createTableRequest{ - TableName: tableName, - } +type createTableOptions struct{} - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json"), - autorest.AsPost(), - autorest.WithBaseURL(endpoints.GetTableEndpoint(client.BaseURI, accountName)), - autorest.WithPath("/Tables"), - autorest.WithJSON(body), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) +func (c createTableOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("Accept", "application/json;odata=nometadata") + headers.Append("Prefer", "return-no-content") + return headers } -// CreateSender sends the Create request. The method will close the -// http.Response Body if it receives an error. -func (client Client) CreateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (c createTableOptions) ToOData() *odata.Query { + return nil } -// CreateResponder handles the response to the Create request. The method always -// closes the http.Response Body. -func (client Client) CreateResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusNoContent), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return +func (c createTableOptions) ToQuery() *client.QueryParams { + return nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/delete.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/delete.go index 5b5ec86d9ca9..3a2817f48282 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/delete.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/delete.go @@ -2,78 +2,61 @@ package tables import ( "context" + "fmt" "net/http" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) +type DeleteTableResponse struct { + HttpResponse *client.Response +} + // Delete deletes the specified table and any data it contains. -func (client Client) Delete(ctx context.Context, accountName, tableName string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("tables.Client", "Delete", "`accountName` cannot be an empty string.") - } +func (c Client) Delete(ctx context.Context, tableName string) (resp DeleteTableResponse, err error) { if tableName == "" { - return result, validation.NewError("tables.Client", "Delete", "`tableName` cannot be an empty string.") + return resp, fmt.Errorf("`tableName` cannot be an empty string") } - req, err := client.DeletePreparer(ctx, accountName, tableName) - if err != nil { - err = autorest.NewErrorWithError(err, "tables.Client", "Delete", nil, "Failure preparing request") - return + opts := client.RequestOptions{ + ContentType: "application/json", + ExpectedStatusCodes: []int{ + http.StatusNoContent, + }, + HttpMethod: http.MethodDelete, + OptionsObject: deleteOptions{}, + Path: fmt.Sprintf("/Tables('%s')", tableName), } - resp, err := client.DeleteSender(req) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "tables.Client", "Delete", resp, "Failure sending request") + err = fmt.Errorf("building request: %+v", err) return } - result, err = client.DeleteResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "tables.Client", "Delete", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// DeletePreparer prepares the Delete request. -func (client Client) DeletePreparer(ctx context.Context, accountName, tableName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "tableName": autorest.Encode("path", tableName), - } - - // NOTE: whilst the API documentation says that API Version is Optional - // apparently specifying it causes an "invalid content type" to always be returned - // as such we omit it here :shrug: - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(endpoints.GetTableEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/Tables('{tableName}')", pathParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) +type deleteOptions struct { } -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client Client) DeleteSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (d deleteOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("Accept", "application/json") + return headers } -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client Client) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusNoContent), - autorest.ByClosing()) - result = autorest.Response{Response: resp} +func (d deleteOptions) ToOData() *odata.Query { + return nil +} - return +func (d deleteOptions) ToQuery() *client.QueryParams { + return nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/exists.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/exists.go index 6abe4f0bbd42..1497695cf03f 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/exists.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/exists.go @@ -2,85 +2,65 @@ package tables import ( "context" + "fmt" "net/http" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) +type TableExistsResponse struct { + HttpResponse *client.Response +} + // Exists checks that the specified table exists -func (client Client) Exists(ctx context.Context, accountName, tableName string) (result autorest.Response, err error) { - if accountName == "" { - return result, validation.NewError("tables.Client", "Exists", "`accountName` cannot be an empty string.") - } +func (c Client) Exists(ctx context.Context, tableName string) (resp TableExistsResponse, err error) { if tableName == "" { - return result, validation.NewError("tables.Client", "Exists", "`tableName` cannot be an empty string.") + return resp, fmt.Errorf("`tableName` cannot be an empty string") } - req, err := client.ExistsPreparer(ctx, accountName, tableName) + opts := client.RequestOptions{ + ContentType: "application/json", + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: tableExistsOptions{}, + Path: fmt.Sprintf("/Tables('%s')", tableName), + } + + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - err = autorest.NewErrorWithError(err, "tables.Client", "Exists", nil, "Failure preparing request") + err = fmt.Errorf("building request: %+v", err) return } - resp, err := client.ExistsSender(req) + err = req.Marshal(&createTableRequest{TableName: tableName}) if err != nil { - result = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "tables.Client", "Exists", resp, "Failure sending request") - return + return resp, fmt.Errorf("marshalling request") } - result, err = client.ExistsResponder(resp) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - err = autorest.NewErrorWithError(err, "tables.Client", "Exists", resp, "Failure responding to request") + err = fmt.Errorf("executing request: %+v", err) return } return } -// ExistsPreparer prepares the Exists request. -func (client Client) ExistsPreparer(ctx context.Context, accountName, tableName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "tableName": autorest.Encode("path", tableName), - } - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "Accept": "application/json;odata=nometadata", - } +type tableExistsOptions struct{} - // NOTE: whilst the API documentation says that API Version is Optional - // apparently specifying it causes an "invalid content type" to always be returned - // as such we omit it here :shrug: - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.AsContentType("application/json"), - autorest.WithBaseURL(endpoints.GetTableEndpoint(client.BaseURI, accountName)), - autorest.WithPathParameters("/Tables('{tableName}')", pathParameters), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) +func (t tableExistsOptions) ToHeaders() *client.Headers { + headers := &client.Headers{} + headers.Append("Accept", "application/json;odata=nometadata") + return headers } -// ExistsSender sends the Exists request. The method will close the -// http.Response Body if it receives an error. -func (client Client) ExistsSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (t tableExistsOptions) ToOData() *odata.Query { + return nil } -// ExistsResponder handles the response to the Exists request. The method always -// closes the http.Response Body. -func (client Client) ExistsResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByClosing()) - result = autorest.Response{Response: resp} - - return +func (t tableExistsOptions) ToQuery() *client.QueryParams { + return nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/query.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/query.go index 475370f0cbd5..9a15de8d0fa7 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/query.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/query.go @@ -5,83 +5,76 @@ import ( "fmt" "net/http" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/validation" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-sdk/sdk/client" + "github.com/hashicorp/go-azure-sdk/sdk/odata" ) -type GetResult struct { - autorest.Response +type GetResponse struct { + HttpResponse *client.Response MetaData string `json:"odata.metadata,omitempty"` Tables []GetResultItem `json:"value"` } +type QueryInput struct { + MetaDataLevel MetaDataLevel +} + // Query returns a list of tables under the specified account. -func (client Client) Query(ctx context.Context, accountName string, metaDataLevel MetaDataLevel) (result GetResult, err error) { - if accountName == "" { - return result, validation.NewError("tables.Client", "Query", "`accountName` cannot be an empty string.") +func (c Client) Query(ctx context.Context, input QueryInput) (resp GetResponse, err error) { + + opts := client.RequestOptions{ + ExpectedStatusCodes: []int{ + http.StatusOK, + }, + HttpMethod: http.MethodGet, + OptionsObject: queryOptions{ + metaDataLevel: input.MetaDataLevel, + }, + Path: "/Tables", } - req, err := client.QueryPreparer(ctx, accountName, metaDataLevel) + req, err := c.Client.NewRequest(ctx, opts) if err != nil { - err = autorest.NewErrorWithError(err, "tables.Client", "Query", nil, "Failure preparing request") + err = fmt.Errorf("building request: %+v", err) return } - resp, err := client.QuerySender(req) + resp.HttpResponse, err = req.Execute(ctx) if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "tables.Client", "Query", resp, "Failure sending request") + err = fmt.Errorf("executing request: %+v", err) return } - result, err = client.QueryResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "tables.Client", "Query", resp, "Failure responding to request") - return + if resp.HttpResponse != nil { + if resp.HttpResponse.Body != nil { + err = resp.HttpResponse.Unmarshal(&resp) + if err != nil { + return resp, fmt.Errorf("unmarshalling response: %v", err) + } + } } return } -// QueryPreparer prepares the Query request. -func (client Client) QueryPreparer(ctx context.Context, accountName string, metaDataLevel MetaDataLevel) (*http.Request, error) { +type queryOptions struct { + metaDataLevel MetaDataLevel +} + +func (q queryOptions) ToHeaders() *client.Headers { // NOTE: whilst this supports ContinuationTokens and 'Top' // it appears that 'Skip' returns a '501 Not Implemented' // as such, we intentionally don't support those right now - - headers := map[string]interface{}{ - "x-ms-version": APIVersion, - "Accept": fmt.Sprintf("application/json;odata=%s", metaDataLevel), - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(endpoints.GetTableEndpoint(client.BaseURI, accountName)), - autorest.WithPath("/Tables"), - autorest.WithHeaders(headers)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) + headers := &client.Headers{} + headers.Append("Accept", fmt.Sprintf("application/json;odata=%s", q.metaDataLevel)) + return headers } -// QuerySender sends the Query request. The method will close the -// http.Response Body if it receives an error. -func (client Client) QuerySender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) +func (q queryOptions) ToOData() *odata.Query { + return nil } -// QueryResponder handles the response to the Query request. The method always -// closes the http.Response Body. -func (client Client) QueryResponder(resp *http.Response) (result GetResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - - return +func (q queryOptions) ToQuery() *client.QueryParams { + return nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/resource_id.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/resource_id.go index 4ceae10150e0..2dbc4c948c5b 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/resource_id.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/resource_id.go @@ -5,50 +5,82 @@ import ( "net/url" "strings" - "github.com/tombuildsstuff/giovanni/storage/internal/endpoints" + "github.com/hashicorp/go-azure-helpers/resourcemanager/resourceids" + "github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts" ) -// GetResourceID returns the Resource ID for the given Table +// GetResourceManagerResourceID returns the Resource ID for the given Table // This can be useful when, for example, you're using this as a unique identifier -func (client Client) GetResourceID(accountName, tableName string) string { - domain := endpoints.GetTableEndpoint(client.BaseURI, accountName) - return fmt.Sprintf("%s/Tables('%s')", domain, tableName) +func (c Client) GetResourceManagerResourceID(subscriptionID, resourceGroup, accountName, tableName string) string { + fmtStr := "/subscriptions/%s/resourceGroups/%s/providers/Microsoft.Storage/storageAccounts/%s/tableServices/default/tables/%s" + return fmt.Sprintf(fmtStr, subscriptionID, resourceGroup, accountName, tableName) } -type ResourceID struct { - AccountName string - TableName string +// TODO: update this to implement `resourceids.ResourceId` once +// https://github.com/hashicorp/go-azure-helpers/issues/187 is fixed +var _ resourceids.Id = TableId{} + +type TableId struct { + // AccountId specifies the ID of the Storage Account where this Table exists. + AccountId accounts.AccountId + + // TableName specifies the name of this Table. + TableName string } -// ParseResourceID parses the Resource ID and returns an object which -// can be used to interact with the Table within the specified Storage Account -func ParseResourceID(id string) (*ResourceID, error) { - // example: https://foo.table.core.windows.net/Table('foo') - if id == "" { - return nil, fmt.Errorf("`id` was empty") +func NewTableID(accountId accounts.AccountId, tableName string) TableId { + return TableId{ + AccountId: accountId, + TableName: tableName, } +} - uri, err := url.Parse(id) +func (b TableId) ID() string { + return fmt.Sprintf("%s/%s", b.AccountId.ID(), b.TableName) +} + +func (b TableId) String() string { + components := []string{ + fmt.Sprintf("Account %q", b.AccountId.String()), + } + return fmt.Sprintf("Table %q (%s)", b.TableName, strings.Join(components, " / ")) +} + +// ParseTableID parses `input` into a Table ID using a known `domainSuffix` +func ParseTableID(input, domainSuffix string) (*TableId, error) { + // example: https://foo.table.core.windows.net/Bar + if input == "" { + return nil, fmt.Errorf("`input` was empty") + } + + account, err := accounts.ParseAccountID(input, domainSuffix) if err != nil { - return nil, fmt.Errorf("Error parsing ID as a URL: %s", err) + return nil, fmt.Errorf("parsing account %q: %+v", input, err) } - accountName, err := endpoints.GetAccountNameFromEndpoint(uri.Host) + if account.SubDomainType != accounts.TableSubDomainType { + return nil, fmt.Errorf("expected the subdomain type to be %q but got %q", string(accounts.TableSubDomainType), string(account.SubDomainType)) + } + + uri, err := url.Parse(input) if err != nil { - return nil, fmt.Errorf("Error parsing Account Name: %s", err) + return nil, fmt.Errorf("parsing %q as a uri: %+v", input, err) } - // assume there a `Table('')` path := strings.TrimPrefix(uri.Path, "/") - if !strings.HasPrefix(path, "Tables('") || !strings.HasSuffix(path, "')") { - return nil, fmt.Errorf("Expected the Table Name to be in the format `Tables('name')` but got %q", path) + segments := strings.Split(path, "/") + if len(segments) != 1 { + return nil, fmt.Errorf("expected the path to contain 1 segment but got %d", len(segments)) } - // strip off the `Table('')` - tableName := strings.TrimPrefix(uri.Path, "/Tables('") - tableName = strings.TrimSuffix(tableName, "')") - return &ResourceID{ - AccountName: *accountName, - TableName: tableName, + // Tables and Table Entities are similar with table being `table1` and entities + // being `table1(PartitionKey='samplepartition',RowKey='samplerow')` so we need to validate this is a table + tableName := strings.TrimPrefix(uri.Path, "/") + if strings.Contains(tableName, "(") || strings.Contains(tableName, ")") { + return nil, fmt.Errorf("expected the path to a table name and not an entity name but got %q", tableName) + } + return &TableId{ + AccountId: *account, + TableName: tableName, }, nil } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/version.go b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/version.go index 05a61a8a7c9d..3e0363fc361e 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/version.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables/version.go @@ -1,14 +1,4 @@ package tables -import ( - "fmt" - - "github.com/tombuildsstuff/giovanni/version" -) - -// APIVersion is the version of the API used for all Storage API Operations -const APIVersion = "2020-08-04" - -func UserAgent() string { - return fmt.Sprintf("tombuildsstuff/giovanni/%s storage/%s", version.Number, APIVersion) -} +const apiVersion = "2020-08-04" +const componentName = "table/tables" diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/internal/endpoints/endpoints.go b/vendor/github.com/tombuildsstuff/giovanni/storage/internal/endpoints/endpoints.go deleted file mode 100644 index 2c58e8f69b03..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/internal/endpoints/endpoints.go +++ /dev/null @@ -1,39 +0,0 @@ -package endpoints - -import ( - "fmt" - "strings" -) - -func GetAccountNameFromEndpoint(endpoint string) (*string, error) { - segments := strings.Split(endpoint, ".") - if len(segments) == 0 { - return nil, fmt.Errorf("The Endpoint contained no segments") - } - return &segments[0], nil -} - -// GetBlobEndpoint returns the endpoint for Blob API Operations on this storage account -func GetBlobEndpoint(baseUri string, accountName string) string { - return fmt.Sprintf("https://%s.blob.%s", accountName, baseUri) -} - -// GetDataLakeStoreEndpoint returns the endpoint for Data Lake Store API Operations on this storage account -func GetDataLakeStoreEndpoint(baseUri string, accountName string) string { - return fmt.Sprintf("https://%s.dfs.%s", accountName, baseUri) -} - -// GetFileEndpoint returns the endpoint for File Share API Operations on this storage account -func GetFileEndpoint(baseUri string, accountName string) string { - return fmt.Sprintf("https://%s.file.%s", accountName, baseUri) -} - -// GetQueueEndpoint returns the endpoint for Queue API Operations on this storage account -func GetQueueEndpoint(baseUri string, accountName string) string { - return fmt.Sprintf("https://%s.queue.%s", accountName, baseUri) -} - -// GetTableEndpoint returns the endpoint for Table API Operations on this storage account -func GetTableEndpoint(baseUri string, accountName string) string { - return fmt.Sprintf("https://%s.table.%s", accountName, baseUri) -} diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/internal/metadata/parse.go b/vendor/github.com/tombuildsstuff/giovanni/storage/internal/metadata/parse.go index 1880d409a7db..038b12c4f5e2 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/internal/metadata/parse.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/internal/metadata/parse.go @@ -8,13 +8,16 @@ import ( // ParseFromHeaders parses the meta data from the headers func ParseFromHeaders(headers http.Header) map[string]string { metaData := make(map[string]string, 0) + prefix := "x-ms-meta-" for k, v := range headers { key := strings.ToLower(k) - prefix := "x-ms-meta-" if !strings.HasPrefix(key, prefix) { continue } + // TODO: update this to support case-insensitive headers when the base layer is changed to `hashicorp/go-azure-sdk` + // (e.g. trim off the first 10 characters, but this can't be done until the base layer is updated, since + // `Azure/go-autorest` canonicalizes the header keys) key = strings.TrimPrefix(key, prefix) metaData[key] = v[0] } diff --git a/vendor/github.com/tombuildsstuff/giovanni/storage/internal/metadata/set.go b/vendor/github.com/tombuildsstuff/giovanni/storage/internal/metadata/set.go index d88fbd766b63..6006159f78cf 100644 --- a/vendor/github.com/tombuildsstuff/giovanni/storage/internal/metadata/set.go +++ b/vendor/github.com/tombuildsstuff/giovanni/storage/internal/metadata/set.go @@ -1,6 +1,10 @@ package metadata -import "fmt" +import ( + "fmt" + + "github.com/hashicorp/go-azure-sdk/sdk/client" +) // SetIntoHeaders sets the provided MetaData into the headers func SetIntoHeaders(headers map[string]interface{}, metaData map[string]string) map[string]interface{} { @@ -11,3 +15,13 @@ func SetIntoHeaders(headers map[string]interface{}, metaData map[string]string) return headers } + +// SetMetaDataHeaders sets the provided MetaData into the headers +func SetMetaDataHeaders(metaData map[string]string) client.Headers { + headers := client.Headers{} + for k, v := range metaData { + key := fmt.Sprintf("x-ms-meta-%s", k) + headers.Append(key, v) + } + return headers +} diff --git a/vendor/github.com/tombuildsstuff/giovanni/version/version.go b/vendor/github.com/tombuildsstuff/giovanni/version/version.go deleted file mode 100644 index 45a0da69aa76..000000000000 --- a/vendor/github.com/tombuildsstuff/giovanni/version/version.go +++ /dev/null @@ -1,3 +0,0 @@ -package version - -const Number = "v0.17.0" diff --git a/vendor/modules.txt b/vendor/modules.txt index 2a91e89b71f1..9d0943660ca1 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -131,7 +131,7 @@ github.com/google/go-cmp/cmp/internal/diff github.com/google/go-cmp/cmp/internal/flags github.com/google/go-cmp/cmp/internal/function github.com/google/go-cmp/cmp/internal/value -# github.com/google/uuid v1.3.1 +# github.com/google/uuid v1.4.0 ## explicit github.com/google/uuid # github.com/hashicorp/errwrap v1.1.0 @@ -1016,6 +1016,8 @@ github.com/hashicorp/go-azure-sdk/sdk/auth github.com/hashicorp/go-azure-sdk/sdk/auth/autorest github.com/hashicorp/go-azure-sdk/sdk/claims github.com/hashicorp/go-azure-sdk/sdk/client +github.com/hashicorp/go-azure-sdk/sdk/client/dataplane +github.com/hashicorp/go-azure-sdk/sdk/client/dataplane/storage github.com/hashicorp/go-azure-sdk/sdk/client/msgraph github.com/hashicorp/go-azure-sdk/sdk/client/pollers github.com/hashicorp/go-azure-sdk/sdk/client/resourcemanager @@ -1203,8 +1205,8 @@ github.com/rickb777/plural # github.com/sergi/go-diff v1.2.0 ## explicit; go 1.12 github.com/sergi/go-diff/diffmatchpatch -# github.com/tombuildsstuff/giovanni v0.20.0 -## explicit; go 1.13 +# github.com/tombuildsstuff/giovanni v0.22.0 +## explicit; go 1.21 github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/accounts github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/blobs github.com/tombuildsstuff/giovanni/storage/2020-08-04/blob/containers @@ -1217,9 +1219,7 @@ github.com/tombuildsstuff/giovanni/storage/2020-08-04/queue/queues github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/entities github.com/tombuildsstuff/giovanni/storage/2020-08-04/table/tables github.com/tombuildsstuff/giovanni/storage/accesscontrol -github.com/tombuildsstuff/giovanni/storage/internal/endpoints github.com/tombuildsstuff/giovanni/storage/internal/metadata -github.com/tombuildsstuff/giovanni/version # github.com/tombuildsstuff/kermit v0.20230703.1101016 ## explicit; go 1.18 github.com/tombuildsstuff/kermit/sdk/appconfiguration/1.0/appconfiguration