├── LICENSE ├── README.md ├── go.mod ├── go.sum └── main.go /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License, version 2.0 2 | 3 | 1. Definitions 4 | 5 | 1.1. “Contributor” 6 | 7 | means each individual or legal entity that creates, contributes to the 8 | creation of, or owns Covered Software. 9 | 10 | 1.2. “Contributor Version” 11 | 12 | means the combination of the Contributions of others (if any) used by a 13 | Contributor and that particular Contributor’s Contribution. 14 | 15 | 1.3. “Contribution” 16 | 17 | means Covered Software of a particular Contributor. 18 | 19 | 1.4. “Covered Software” 20 | 21 | means Source Code Form to which the initial Contributor has attached the 22 | notice in Exhibit A, the Executable Form of such Source Code Form, and 23 | Modifications of such Source Code Form, in each case including portions 24 | thereof. 25 | 26 | 1.5. “Incompatible With Secondary Licenses” 27 | means 28 | 29 | a. that the initial Contributor has attached the notice described in 30 | Exhibit B to the Covered Software; or 31 | 32 | b. that the Covered Software was made available under the terms of version 33 | 1.1 or earlier of the License, but not also under the terms of a 34 | Secondary License. 35 | 36 | 1.6. “Executable Form” 37 | 38 | means any form of the work other than Source Code Form. 39 | 40 | 1.7. “Larger Work” 41 | 42 | means a work that combines Covered Software with other material, in a separate 43 | file or files, that is not Covered Software. 44 | 45 | 1.8. “License” 46 | 47 | means this document. 48 | 49 | 1.9. “Licensable” 50 | 51 | means having the right to grant, to the maximum extent possible, whether at the 52 | time of the initial grant or subsequently, any and all of the rights conveyed by 53 | this License. 54 | 55 | 1.10. “Modifications” 56 | 57 | means any of the following: 58 | 59 | a. any file in Source Code Form that results from an addition to, deletion 60 | from, or modification of the contents of Covered Software; or 61 | 62 | b. any new file in Source Code Form that contains any Covered Software. 63 | 64 | 1.11. “Patent Claims” of a Contributor 65 | 66 | means any patent claim(s), including without limitation, method, process, 67 | and apparatus claims, in any patent Licensable by such Contributor that 68 | would be infringed, but for the grant of the License, by the making, 69 | using, selling, offering for sale, having made, import, or transfer of 70 | either its Contributions or its Contributor Version. 71 | 72 | 1.12. “Secondary License” 73 | 74 | means either the GNU General Public License, Version 2.0, the GNU Lesser 75 | General Public License, Version 2.1, the GNU Affero General Public 76 | License, Version 3.0, or any later versions of those licenses. 77 | 78 | 1.13. “Source Code Form” 79 | 80 | means the form of the work preferred for making modifications. 81 | 82 | 1.14. “You” (or “Your”) 83 | 84 | means an individual or a legal entity exercising rights under this 85 | License. For legal entities, “You” includes any entity that controls, is 86 | controlled by, or is under common control with You. For purposes of this 87 | definition, “control” means (a) the power, direct or indirect, to cause 88 | the direction or management of such entity, whether by contract or 89 | otherwise, or (b) ownership of more than fifty percent (50%) of the 90 | outstanding shares or beneficial ownership of such entity. 91 | 92 | 93 | 2. License Grants and Conditions 94 | 95 | 2.1. Grants 96 | 97 | Each Contributor hereby grants You a world-wide, royalty-free, 98 | non-exclusive license: 99 | 100 | a. under intellectual property rights (other than patent or trademark) 101 | Licensable by such Contributor to use, reproduce, make available, 102 | modify, display, perform, distribute, and otherwise exploit its 103 | Contributions, either on an unmodified basis, with Modifications, or as 104 | part of a Larger Work; and 105 | 106 | b. under Patent Claims of such Contributor to make, use, sell, offer for 107 | sale, have made, import, and otherwise transfer either its Contributions 108 | or its Contributor Version. 109 | 110 | 2.2. Effective Date 111 | 112 | The licenses granted in Section 2.1 with respect to any Contribution become 113 | effective for each Contribution on the date the Contributor first distributes 114 | such Contribution. 115 | 116 | 2.3. Limitations on Grant Scope 117 | 118 | The licenses granted in this Section 2 are the only rights granted under this 119 | License. No additional rights or licenses will be implied from the distribution 120 | or licensing of Covered Software under this License. Notwithstanding Section 121 | 2.1(b) above, no patent license is granted by a Contributor: 122 | 123 | a. for any code that a Contributor has removed from Covered Software; or 124 | 125 | b. for infringements caused by: (i) Your and any other third party’s 126 | modifications of Covered Software, or (ii) the combination of its 127 | Contributions with other software (except as part of its Contributor 128 | Version); or 129 | 130 | c. under Patent Claims infringed by Covered Software in the absence of its 131 | Contributions. 132 | 133 | This License does not grant any rights in the trademarks, service marks, or 134 | logos of any Contributor (except as may be necessary to comply with the 135 | notice requirements in Section 3.4). 136 | 137 | 2.4. Subsequent Licenses 138 | 139 | No Contributor makes additional grants as a result of Your choice to 140 | distribute the Covered Software under a subsequent version of this License 141 | (see Section 10.2) or under the terms of a Secondary License (if permitted 142 | under the terms of Section 3.3). 143 | 144 | 2.5. Representation 145 | 146 | Each Contributor represents that the Contributor believes its Contributions 147 | are its original creation(s) or it has sufficient rights to grant the 148 | rights to its Contributions conveyed by this License. 149 | 150 | 2.6. Fair Use 151 | 152 | This License is not intended to limit any rights You have under applicable 153 | copyright doctrines of fair use, fair dealing, or other equivalents. 154 | 155 | 2.7. Conditions 156 | 157 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in 158 | Section 2.1. 159 | 160 | 161 | 3. Responsibilities 162 | 163 | 3.1. Distribution of Source Form 164 | 165 | All distribution of Covered Software in Source Code Form, including any 166 | Modifications that You create or to which You contribute, must be under the 167 | terms of this License. You must inform recipients that the Source Code Form 168 | of the Covered Software is governed by the terms of this License, and how 169 | they can obtain a copy of this License. You may not attempt to alter or 170 | restrict the recipients’ rights in the Source Code Form. 171 | 172 | 3.2. Distribution of Executable Form 173 | 174 | If You distribute Covered Software in Executable Form then: 175 | 176 | a. such Covered Software must also be made available in Source Code Form, 177 | as described in Section 3.1, and You must inform recipients of the 178 | Executable Form how they can obtain a copy of such Source Code Form by 179 | reasonable means in a timely manner, at a charge no more than the cost 180 | of distribution to the recipient; and 181 | 182 | b. You may distribute such Executable Form under the terms of this License, 183 | or sublicense it under different terms, provided that the license for 184 | the Executable Form does not attempt to limit or alter the recipients’ 185 | rights in the Source Code Form under this License. 186 | 187 | 3.3. Distribution of a Larger Work 188 | 189 | You may create and distribute a Larger Work under terms of Your choice, 190 | provided that You also comply with the requirements of this License for the 191 | Covered Software. If the Larger Work is a combination of Covered Software 192 | with a work governed by one or more Secondary Licenses, and the Covered 193 | Software is not Incompatible With Secondary Licenses, this License permits 194 | You to additionally distribute such Covered Software under the terms of 195 | such Secondary License(s), so that the recipient of the Larger Work may, at 196 | their option, further distribute the Covered Software under the terms of 197 | either this License or such Secondary License(s). 198 | 199 | 3.4. Notices 200 | 201 | You may not remove or alter the substance of any license notices (including 202 | copyright notices, patent notices, disclaimers of warranty, or limitations 203 | of liability) contained within the Source Code Form of the Covered 204 | Software, except that You may alter any license notices to the extent 205 | required to remedy known factual inaccuracies. 206 | 207 | 3.5. Application of Additional Terms 208 | 209 | You may choose to offer, and to charge a fee for, warranty, support, 210 | indemnity or liability obligations to one or more recipients of Covered 211 | Software. However, You may do so only on Your own behalf, and not on behalf 212 | of any Contributor. You must make it absolutely clear that any such 213 | warranty, support, indemnity, or liability obligation is offered by You 214 | alone, and You hereby agree to indemnify every Contributor for any 215 | liability incurred by such Contributor as a result of warranty, support, 216 | indemnity or liability terms You offer. You may include additional 217 | disclaimers of warranty and limitations of liability specific to any 218 | jurisdiction. 219 | 220 | 4. Inability to Comply Due to Statute or Regulation 221 | 222 | If it is impossible for You to comply with any of the terms of this License 223 | with respect to some or all of the Covered Software due to statute, judicial 224 | order, or regulation then You must: (a) comply with the terms of this License 225 | to the maximum extent possible; and (b) describe the limitations and the code 226 | they affect. Such description must be placed in a text file included with all 227 | distributions of the Covered Software under this License. Except to the 228 | extent prohibited by statute or regulation, such description must be 229 | sufficiently detailed for a recipient of ordinary skill to be able to 230 | understand it. 231 | 232 | 5. Termination 233 | 234 | 5.1. The rights granted under this License will terminate automatically if You 235 | fail to comply with any of its terms. However, if You become compliant, 236 | then the rights granted under this License from a particular Contributor 237 | are reinstated (a) provisionally, unless and until such Contributor 238 | explicitly and finally terminates Your grants, and (b) on an ongoing basis, 239 | if such Contributor fails to notify You of the non-compliance by some 240 | reasonable means prior to 60 days after You have come back into compliance. 241 | Moreover, Your grants from a particular Contributor are reinstated on an 242 | ongoing basis if such Contributor notifies You of the non-compliance by 243 | some reasonable means, this is the first time You have received notice of 244 | non-compliance with this License from such Contributor, and You become 245 | compliant prior to 30 days after Your receipt of the notice. 246 | 247 | 5.2. If You initiate litigation against any entity by asserting a patent 248 | infringement claim (excluding declaratory judgment actions, counter-claims, 249 | and cross-claims) alleging that a Contributor Version directly or 250 | indirectly infringes any patent, then the rights granted to You by any and 251 | all Contributors for the Covered Software under Section 2.1 of this License 252 | shall terminate. 253 | 254 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user 255 | license agreements (excluding distributors and resellers) which have been 256 | validly granted by You or Your distributors under this License prior to 257 | termination shall survive termination. 258 | 259 | 6. Disclaimer of Warranty 260 | 261 | Covered Software is provided under this License on an “as is” basis, without 262 | warranty of any kind, either expressed, implied, or statutory, including, 263 | without limitation, warranties that the Covered Software is free of defects, 264 | merchantable, fit for a particular purpose or non-infringing. The entire 265 | risk as to the quality and performance of the Covered Software is with You. 266 | Should any Covered Software prove defective in any respect, You (not any 267 | Contributor) assume the cost of any necessary servicing, repair, or 268 | correction. This disclaimer of warranty constitutes an essential part of this 269 | License. No use of any Covered Software is authorized under this License 270 | except under this disclaimer. 271 | 272 | 7. Limitation of Liability 273 | 274 | Under no circumstances and under no legal theory, whether tort (including 275 | negligence), contract, or otherwise, shall any Contributor, or anyone who 276 | distributes Covered Software as permitted above, be liable to You for any 277 | direct, indirect, special, incidental, or consequential damages of any 278 | character including, without limitation, damages for lost profits, loss of 279 | goodwill, work stoppage, computer failure or malfunction, or any and all 280 | other commercial damages or losses, even if such party shall have been 281 | informed of the possibility of such damages. This limitation of liability 282 | shall not apply to liability for death or personal injury resulting from such 283 | party’s negligence to the extent applicable law prohibits such limitation. 284 | Some jurisdictions do not allow the exclusion or limitation of incidental or 285 | consequential damages, so this exclusion and limitation may not apply to You. 286 | 287 | 8. Litigation 288 | 289 | Any litigation relating to this License may be brought only in the courts of 290 | a jurisdiction where the defendant maintains its principal place of business 291 | and such litigation shall be governed by laws of that jurisdiction, without 292 | reference to its conflict-of-law provisions. Nothing in this Section shall 293 | prevent a party’s ability to bring cross-claims or counter-claims. 294 | 295 | 9. Miscellaneous 296 | 297 | This License represents the complete agreement concerning the subject matter 298 | hereof. If any provision of this License is held to be unenforceable, such 299 | provision shall be reformed only to the extent necessary to make it 300 | enforceable. Any law or regulation which provides that the language of a 301 | contract shall be construed against the drafter shall not be used to construe 302 | this License against a Contributor. 303 | 304 | 305 | 10. Versions of the License 306 | 307 | 10.1. New Versions 308 | 309 | Mozilla Foundation is the license steward. Except as provided in Section 310 | 10.3, no one other than the license steward has the right to modify or 311 | publish new versions of this License. Each version will be given a 312 | distinguishing version number. 313 | 314 | 10.2. Effect of New Versions 315 | 316 | You may distribute the Covered Software under the terms of the version of 317 | the License under which You originally received the Covered Software, or 318 | under the terms of any subsequent version published by the license 319 | steward. 320 | 321 | 10.3. Modified Versions 322 | 323 | If you create software not governed by this License, and you want to 324 | create a new license for such software, you may create and use a modified 325 | version of this License if you rename the license and remove any 326 | references to the name of the license steward (except to note that such 327 | modified license differs from this License). 328 | 329 | 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses 330 | If You choose to distribute Source Code Form that is Incompatible With 331 | Secondary Licenses under the terms of this version of the License, the 332 | notice described in Exhibit B of this License must be attached. 333 | 334 | Exhibit A - Source Code Form License Notice 335 | 336 | This Source Code Form is subject to the 337 | terms of the Mozilla Public License, v. 338 | 2.0. If a copy of the MPL was not 339 | distributed with this file, You can 340 | obtain one at 341 | http://mozilla.org/MPL/2.0/. 342 | 343 | If it is not possible or desirable to put the notice in a particular file, then 344 | You may include the notice in a location (such as a LICENSE file in a relevant 345 | directory) where a recipient would be likely to look for such a notice. 346 | 347 | You may add additional accurate notices of copyright ownership. 348 | 349 | Exhibit B - “Incompatible With Secondary Licenses” Notice 350 | 351 | This Source Code Form is “Incompatible 352 | With Secondary Licenses”, as defined by 353 | the Mozilla Public License, v. 2.0. 354 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # `terraform-clean-syntax` 2 | 3 | > **NOTE:** The changes made by this tool were integrated into Terraform's own `terraform fmt` in Terraform v0.14.0, so the functionality in this repository will see no further changes. 4 | 5 | `terraform-clean-syntax` is a simple command line tool for performing some 6 | small syntax cleanup steps on Terraform `.tf` configuration files 7 | automatically. 8 | 9 | Specifically, it currently knows how to clean up the following: 10 | 11 | * Argument values that are just a single template interpolation, like 12 | `"${foo}"`, are simplified to the equivalent `foo`. 13 | * Variable type constraints using the legacy forms from Terraform 0.11, like 14 | `"string"`, `"list"`, or `"map"`, are replaced with their modern type 15 | constraint expressions `string`, `list(string)` and `map(string)`. 16 | 17 | The two changes listed above will both silence some (though not all) of the 18 | syntax deprecation warnings emitted by Terraform 0.12.14 and later. This program 19 | is conservative, so it may skip certain opportunities for cleanup if they are 20 | too complex for it to be sure that the change is safe. 21 | 22 | The built in `terraform fmt` command in Terraform doesn't perform these cleanups 23 | automatically at the time of writing, because the Terraform team worried that 24 | this would make it difficult for folks to continue maintaining modules that 25 | are cross-compatible with both Terraform 0.11 and 0.12. The cleanups made by 26 | this program will render a configuration incompatible with Terraform 0.11, 27 | so this program should not be used on any module that must retain Terraform 0.11 28 | compatibility. 29 | 30 | ## Usage 31 | 32 | After compiling the program using Go 1.12 or later, run it with a single 33 | argument that is a file or directory to apply rewriting to: 34 | 35 | ``` 36 | terraform-clean-syntax . 37 | ``` 38 | 39 | If given a directory, `terraform-clean-syntax` will visit all of the `.tf` 40 | files in the directory and recursively search any directories within it. 41 | 42 | If given a single file, `terraform-clean-syntax` will process that file only 43 | if its name has the suffix `.tf`. 44 | 45 | This program rewrites configuration files in-place, so it's best to make sure 46 | your version control work tree is clean before running so that you can clearly 47 | see which changes it is proposing and discard those changes if desired. 48 | 49 | This program is a best-effort static analysis tool and it doesn't have intimate 50 | understanding of Terraform language syntax, so be sure to review the changes it 51 | proposes and test your resulting configuration with `terraform validate` and/or 52 | `terraform plan` before merging the changes into your codebase. 53 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/apparentlymart/terraform-clean-syntax 2 | 3 | go 1.12 4 | 5 | require ( 6 | github.com/hashicorp/hcl/v2 v2.5.1 7 | github.com/spf13/pflag v1.0.5 8 | ) 9 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/agext/levenshtein v1.2.1 h1:QmvMAjj2aEICytGiWzmxoE0x2KZvE0fvmqMOfy2tjT8= 2 | github.com/agext/levenshtein v1.2.1/go.mod h1:JEDfjyjHDjOF/1e4FlBE/PkbqA9OfWu2ki2W0IB5558= 3 | github.com/apparentlymart/go-dump v0.0.0-20180507223929-23540a00eaa3/go.mod h1:oL81AME2rN47vu18xqj1S1jPIPuN7afo62yKTNn3XMM= 4 | github.com/apparentlymart/go-textseg v1.0.0 h1:rRmlIsPEEhUTIKQb7T++Nz/A5Q6C9IuX2wFoYVvnCs0= 5 | github.com/apparentlymart/go-textseg v1.0.0/go.mod h1:z96Txxhf3xSFMPmb5X/1W05FF/Nj9VFpLOpjS5yuumk= 6 | github.com/apparentlymart/go-textseg/v12 v12.0.0 h1:bNEQyAGak9tojivJNkoqWErVCQbjdL7GzRt3F8NvfJ0= 7 | github.com/apparentlymart/go-textseg/v12 v12.0.0/go.mod h1:S/4uRK2UtaQttw1GenVJEynmyUenKwP++x/+DdGV/Ec= 8 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 9 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 10 | github.com/go-test/deep v1.0.3 h1:ZrJSEWsXzPOxaZnFteGEfooLba+ju3FYIbOrS+rQd68= 11 | github.com/go-test/deep v1.0.3/go.mod h1:wGDj63lr65AM2AQyKZd/NYHGb0R+1RLqB8NKt3aSFNA= 12 | github.com/golang/protobuf v1.1.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 13 | github.com/google/go-cmp v0.3.1 h1:Xye71clBPdm5HgqGwUkwhbynsUJZhDbS20FvLhQ2izg= 14 | github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= 15 | github.com/hashicorp/hcl/v2 v2.5.1 h1:5ytFZykUu2/4U59ogd2f+XZdi9+6oC/Tv5WzsH6fIDA= 16 | github.com/hashicorp/hcl/v2 v2.5.1/go.mod h1:bQTN5mpo+jewjJgh8jr0JUguIi7qPHUF6yIfAEN3jqY= 17 | github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= 18 | github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= 19 | github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= 20 | github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= 21 | github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= 22 | github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348 h1:MtvEpTB6LX3vkb4ax0b5D2DHbNAUsen0Gx5wZoq3lV4= 23 | github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348/go.mod h1:B69LEHPfb2qLo0BaaOLcbitczOKLWTsrBG9LczfCD4k= 24 | github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7 h1:DpOJ2HYzCv8LZP15IdmG+YdwD2luVPHITV96TkirNBM= 25 | github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= 26 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 27 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 28 | github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ= 29 | github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= 30 | github.com/spf13/pflag v1.0.2/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= 31 | github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= 32 | github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= 33 | github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= 34 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= 35 | github.com/vmihailenco/msgpack v3.3.3+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= 36 | github.com/zclconf/go-cty v1.2.0 h1:sPHsy7ADcIZQP3vILvTjrh74ZA175TFP5vqiNK1UmlI= 37 | github.com/zclconf/go-cty v1.2.0/go.mod h1:hOPWgoHbaTUnI5k4D2ld+GRpFJSCe6bCM7m1q/N4PQ8= 38 | golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 39 | golang.org/x/crypto v0.0.0-20190426145343-a29dc8fdc734/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= 40 | golang.org/x/net v0.0.0-20180811021610-c39426892332/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 41 | golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= 42 | golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 43 | golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 44 | golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 45 | golang.org/x/sys v0.0.0-20190502175342-a43fa875dd82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 46 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 47 | golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= 48 | golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= 49 | golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= 50 | google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= 51 | gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 52 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "io/ioutil" 7 | "log" 8 | "os" 9 | "path/filepath" 10 | "runtime/debug" 11 | "strings" 12 | 13 | "github.com/hashicorp/hcl/v2" 14 | "github.com/hashicorp/hcl/v2/hclsyntax" 15 | "github.com/hashicorp/hcl/v2/hclwrite" 16 | flag "github.com/spf13/pflag" 17 | ) 18 | 19 | func main() { 20 | flag.Usage = func() { 21 | os.Stderr.WriteString("Usage: terraform-clean-syntax \n") 22 | } 23 | 24 | flag.Parse() 25 | args := flag.Args() 26 | if len(args) < 1 { 27 | flag.Usage() 28 | os.Exit(1) 29 | } 30 | 31 | for _, arg := range args { 32 | processItem(arg) 33 | } 34 | } 35 | 36 | func processItem(fn string) { 37 | fn = filepath.Clean(fn) 38 | 39 | info, err := os.Lstat(fn) 40 | if err != nil { 41 | log.Printf("Failed to stat %q: %s\n", fn, err) 42 | return 43 | } 44 | 45 | if info.IsDir() { 46 | if info.Name() != "." && info.Name() != ".." && strings.HasPrefix(info.Name(), ".") { 47 | return 48 | } 49 | processDir(fn) 50 | } else { 51 | if !info.Mode().IsRegular() { 52 | log.Printf("Skipping %q: not a regular file or directory", fn) 53 | } 54 | if !strings.HasSuffix(fn, ".tf") { 55 | return 56 | } 57 | processFile(fn, info.Mode()) 58 | } 59 | } 60 | 61 | func processDir(fn string) { 62 | entries, err := ioutil.ReadDir(fn) 63 | if err != nil { 64 | log.Printf("Failed to read directory %q: %s", fn, err) 65 | return 66 | } 67 | 68 | for _, entry := range entries { 69 | processItem(filepath.Join(fn, entry.Name())) 70 | } 71 | } 72 | 73 | func processFile(fn string, mode os.FileMode) { 74 | src, err := ioutil.ReadFile(fn) 75 | if err != nil { 76 | log.Printf("Failed to read file %q: %s", fn, err) 77 | return 78 | } 79 | 80 | defer func() { 81 | if r := recover(); r != nil { 82 | fmt.Printf("Recovered in processFile while processing %s: %#v\n%s", fn, r, debug.Stack()) 83 | } 84 | }() 85 | 86 | f, diags := hclwrite.ParseConfig(src, fn, hcl.Pos{Line: 1, Column: 1}) 87 | if diags.HasErrors() { 88 | for _, diag := range diags { 89 | if diag.Subject != nil { 90 | log.Printf("[%s:%d] %s: %s", diag.Subject.Filename, diag.Subject.Start.Line, diag.Summary, diag.Detail) 91 | } else { 92 | log.Printf("%s: %s", diag.Summary, diag.Detail) 93 | } 94 | } 95 | return 96 | } 97 | 98 | cleanFile(f) 99 | 100 | newSrc := f.Bytes() 101 | if bytes.Equal(newSrc, src) { 102 | // No changes 103 | return 104 | } 105 | 106 | // TODO: Write the new file to disk in place of the old one 107 | err = ioutil.WriteFile(fn, newSrc, mode) 108 | if err != nil { 109 | log.Printf("Failed to write to %q: %s", fn, err) 110 | log.Printf("WARNING: File %q may be left with only partial content", fn) 111 | return 112 | } 113 | log.Printf("Made changes: %s", fn) 114 | } 115 | 116 | func cleanFile(f *hclwrite.File) { 117 | cleanBody(f.Body(), nil) 118 | } 119 | 120 | func cleanBody(body *hclwrite.Body, inBlocks []string) { 121 | attrs := body.Attributes() 122 | for name, attr := range attrs { 123 | var cleanedExprTokens hclwrite.Tokens 124 | tokens := attr.Expr().BuildTokens(nil) 125 | if len(inBlocks) == 1 { 126 | inBlock := inBlocks[0] 127 | if inBlock == "variable" && name == "type" { 128 | cleanedExprTokens = cleanTypeExpr(tokens) 129 | body.SetAttributeRaw(name, cleanedExprTokens) 130 | continue 131 | } else if (inBlock == "resource" || inBlock == "data") && name == "provider" { 132 | cleanedExprTokens = cleanProviderExpr(tokens) 133 | body.SetAttributeRaw(name, cleanedExprTokens) 134 | continue 135 | } 136 | } 137 | cleanedExprTokens = cleanValueExpr(tokens) 138 | body.SetAttributeRaw(name, cleanedExprTokens) 139 | } 140 | 141 | blocks := body.Blocks() 142 | for _, block := range blocks { 143 | inBlocks := append(inBlocks, block.Type()) 144 | cleanBody(block.Body(), inBlocks) 145 | } 146 | } 147 | 148 | func cleanValueExpr(tokens hclwrite.Tokens) hclwrite.Tokens { 149 | if len(tokens) < 5 { 150 | // Can't possibly be a "${ ... }" sequence without at least enough 151 | // tokens for the delimiters and one token inside them. 152 | return tokens 153 | } 154 | oQuote := tokens[0] 155 | oBrace := tokens[1] 156 | cBrace := tokens[len(tokens)-2] 157 | cQuote := tokens[len(tokens)-1] 158 | if oQuote.Type != hclsyntax.TokenOQuote || oBrace.Type != hclsyntax.TokenTemplateInterp || cBrace.Type != hclsyntax.TokenTemplateSeqEnd || cQuote.Type != hclsyntax.TokenCQuote { 159 | // Not an interpolation sequence at all, then. 160 | return tokens 161 | } 162 | 163 | inside := tokens[2 : len(tokens)-2] 164 | 165 | // We're only interested in sequences that are provable to be single 166 | // interpolation sequences, which we'll determine by hunting inside 167 | // the interior tokens for any other interpolation sequences. This is 168 | // likely to produce false negatives sometimes, but that's better than 169 | // false positives and we're mainly interested in catching the easy cases 170 | // here. 171 | quotes := 0 172 | for _, token := range inside { 173 | if token.Type == hclsyntax.TokenOQuote { 174 | quotes++ 175 | continue 176 | } 177 | if token.Type == hclsyntax.TokenCQuote { 178 | quotes-- 179 | continue 180 | } 181 | if quotes > 0 { 182 | // Interpolation sequences inside nested quotes are okay, because 183 | // they are part of a nested expression. 184 | // "${foo("${bar}")}" 185 | continue 186 | } 187 | if token.Type == hclsyntax.TokenTemplateInterp || token.Type == hclsyntax.TokenTemplateSeqEnd { 188 | // We've found another template delimiter within our interior 189 | // tokens, which suggests that we've found something like this: 190 | // "${foo}${bar}" 191 | // That isn't unwrappable, so we'll leave the whole expression alone. 192 | return tokens 193 | } 194 | } 195 | 196 | // If we got down here without an early return then this looks like 197 | // an unwrappable sequence, but we'll trim any leading and trailing 198 | // newlines that might result in an invalid result if we were to 199 | // naively trim something like this: 200 | // "${ 201 | // foo 202 | // }" 203 | return trimNewlines(inside) 204 | } 205 | 206 | func cleanProviderExpr(tokens hclwrite.Tokens) hclwrite.Tokens { 207 | if len(tokens) != 3 { 208 | // We're only interested in plain quoted strings, which consist 209 | // of the open and close quotes and a literal string token. 210 | return tokens 211 | } 212 | oQuote := tokens[0] 213 | strTok := tokens[1] 214 | cQuote := tokens[2] 215 | if oQuote.Type != hclsyntax.TokenOQuote || strTok.Type != hclsyntax.TokenQuotedLit || cQuote.Type != hclsyntax.TokenCQuote { 216 | // Not a quoted string sequence, then. 217 | return tokens 218 | } 219 | // HACK: Technically a provider.alias sequence ought to be three 220 | // separate tokens, because the dot is an operator, but only the 221 | // `Bytes` part of this is relevant to our output anyway so 222 | // we'll cheat and thus avoid the need to parse `strTok.Bytes. 223 | return hclwrite.Tokens{ 224 | { 225 | Type: hclsyntax.TokenIdent, 226 | Bytes: []byte(strTok.Bytes), 227 | }, 228 | } 229 | } 230 | 231 | func cleanTypeExpr(tokens hclwrite.Tokens) hclwrite.Tokens { 232 | if len(tokens) != 3 { 233 | // We're only interested in plain quoted strings, which consist 234 | // of the open and close quotes and a literal string token. 235 | return tokens 236 | } 237 | oQuote := tokens[0] 238 | strTok := tokens[1] 239 | cQuote := tokens[2] 240 | if oQuote.Type != hclsyntax.TokenOQuote || strTok.Type != hclsyntax.TokenQuotedLit || cQuote.Type != hclsyntax.TokenCQuote { 241 | // Not a quoted string sequence, then. 242 | return tokens 243 | } 244 | 245 | switch string(strTok.Bytes) { 246 | case "string": 247 | return hclwrite.Tokens{ 248 | { 249 | Type: hclsyntax.TokenIdent, 250 | Bytes: []byte("string"), 251 | }, 252 | } 253 | case "list": 254 | return hclwrite.Tokens{ 255 | { 256 | Type: hclsyntax.TokenIdent, 257 | Bytes: []byte("list"), 258 | }, 259 | { 260 | Type: hclsyntax.TokenOParen, 261 | Bytes: []byte("("), 262 | }, 263 | { 264 | Type: hclsyntax.TokenIdent, 265 | Bytes: []byte("string"), 266 | }, 267 | { 268 | Type: hclsyntax.TokenCParen, 269 | Bytes: []byte(")"), 270 | }, 271 | } 272 | case "map": 273 | return hclwrite.Tokens{ 274 | { 275 | Type: hclsyntax.TokenIdent, 276 | Bytes: []byte("map"), 277 | }, 278 | { 279 | Type: hclsyntax.TokenOParen, 280 | Bytes: []byte("("), 281 | }, 282 | { 283 | Type: hclsyntax.TokenIdent, 284 | Bytes: []byte("string"), 285 | }, 286 | { 287 | Type: hclsyntax.TokenCParen, 288 | Bytes: []byte(")"), 289 | }, 290 | } 291 | default: 292 | // Something else we're not expecting, then. 293 | return tokens 294 | } 295 | } 296 | 297 | func trimNewlines(tokens hclwrite.Tokens) hclwrite.Tokens { 298 | if len(tokens) == 0 { 299 | return nil 300 | } 301 | var start, end int 302 | for start = 0; start < len(tokens); start++ { 303 | if tokens[start].Type != hclsyntax.TokenNewline { 304 | break 305 | } 306 | } 307 | for end = len(tokens); end > 0; end-- { 308 | if tokens[end-1].Type != hclsyntax.TokenNewline { 309 | break 310 | } 311 | } 312 | return tokens[start:end] 313 | } 314 | --------------------------------------------------------------------------------