├── .github ├── ISSUE_TEMPLATE │ ├── BUG_REPORT.md │ ├── FEATURE_REQUEST.md │ └── QUESTION.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ ├── publish.yml │ └── test.yml ├── .gitignore ├── .swift-format.json ├── .swift-mod.yml ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE ├── Makefile ├── Package.resolved ├── Package.swift ├── README.md ├── Sources ├── SwiftModCommands │ ├── Arguments.swift │ ├── Configuration │ │ ├── Configuration+AllRules.swift │ │ ├── Configuration+Codable.swift │ │ └── Configuration+Template.swift │ ├── InitCommand.swift │ ├── RulesCommand.swift │ ├── RunCommand.swift │ └── Runners │ │ ├── InitCommandRunner.swift │ │ ├── RulesCommandRunner.swift │ │ └── RunCommandRunner.swift ├── SwiftModCore │ ├── Configuration.swift │ ├── ConfigurationError.swift │ ├── Extensions │ │ ├── DeclModifierListSyntaxExtensions.swift │ │ ├── DecodingErrorExtensions.swift │ │ ├── IdentifierPatternSyntaxExtensions.swift │ │ ├── IndentExtensions.swift │ │ ├── OptionalExtensions.swift │ │ ├── SequenceExtensions.swift │ │ ├── StringExtensions.swift │ │ ├── SyntaxCollection.swift │ │ ├── TokenKindExtensions.swift │ │ ├── TokenSyntaxExtensions.swift │ │ ├── TriviaExtensions.swift │ │ ├── TypeSyntaxExtensions.swift │ │ └── VariableDeclSyntaxExtensions.swift │ ├── Format.swift │ ├── Helpers │ │ ├── Atomic.swift │ │ ├── DecoderInterceptor.swift │ │ ├── DirectoryIterator.swift │ │ ├── DynamicCondingKey.swift │ │ ├── DynamicEncodable.swift │ │ ├── FileManager.swift │ │ ├── InteractiveWriter.swift │ │ ├── Measure.swift │ │ ├── RulePipeline.swift │ │ ├── Stack.swift │ │ └── SwiftFileIterator.swift │ ├── Indent.swift │ ├── RuleDefinition.swift │ ├── RuleDescription.swift │ ├── RulePriority.swift │ └── RuleSyntaxRewriter.swift ├── SwiftModRules │ ├── DefaultAccessLevelRule.swift │ └── DefaultMemberwiseInitializerRule.swift └── swift-mod │ └── SwiftMod.swift ├── Tests ├── SwiftModCommandsTests │ ├── Configuration+CodableTests.swift │ ├── InitCommandRunnerTests.swift │ ├── RulesCommandRunnerTests.swift │ └── RunCommandRunnerTests.swift ├── SwiftModCoreTests │ └── RuleSyntaxRewriterTests.swift └── SwiftModRulesTests │ ├── DefaultAccessLevelRuleTests.swift │ ├── DefaultMemberwiseInitializerRuleTests.swift │ └── Helpers.swift └── Tools ├── Package.resolved └── Package.swift /.github/ISSUE_TEMPLATE/BUG_REPORT.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug Report 3 | about: Create a bug report. 4 | --- 5 | 6 | ## Checklist 7 | 8 | - [ ] Reviewed the README. 9 | - [ ] Searched existing issues to make sure not duplicated. 10 | 11 | ## Description 12 | 13 | 14 | ## Current Behavior 15 | 16 | 17 | ## Expected Behavior 18 | 19 | 20 | ## Steps to Reproduce 21 | 22 | 1. 23 | 2. 24 | 25 | ## Reproducible Demo 26 | 27 | 28 | ## Environments 29 | 30 | - Tool version: 31 | 32 | - Swift version: 33 | 34 | - OS version: 35 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/FEATURE_REQUEST.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature Request 3 | about: Create a feature request. 4 | --- 5 | 6 | ## Checklist 7 | 8 | - [ ] Reviewed the README. 9 | - [ ] Searched existing issues to make sure not duplicated. 10 | 11 | ## Motivation and Context 12 | 13 | 14 | ## Description 15 | 16 | 17 | ## Proposed Solution 18 | 19 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/QUESTION.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Question 3 | about: Create a bug question. 4 | --- 5 | 6 | ## Checklist 7 | 8 | - [ ] Reviewed the README. 9 | - [ ] Searched existing issues to make sure not duplicated. 10 | 11 | ## Description 12 | 13 | 14 | ## Environment 15 | 16 | - Tool version: 17 | 18 | - Swift version: 19 | 20 | - OS version: 21 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## Checklist 2 | 3 | - [ ] All tests are passed. 4 | - [ ] Added tests. 5 | - [ ] Searched existing issues to make sure not duplicated. 6 | 7 | ## Motivation and Context 8 | 9 | 10 | ## Description 11 | 12 | 13 | ## Related Issue 14 | 15 | 16 | ## Impact on Existing Code 17 | 18 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: publish 2 | on: 3 | release: 4 | types: [published] 5 | 6 | jobs: 7 | publish: 8 | name: Publish 9 | runs-on: macos-14 10 | strategy: 11 | matrix: 12 | xcode_version: 13 | - "15.4" 14 | env: 15 | DEVELOPER_DIR: /Applications/Xcode_${{ matrix.xcode_version }}.app 16 | steps: 17 | - name: Checkout 18 | uses: actions/checkout@v2 19 | - name: Upload Zip 20 | run: make upload-zip 21 | env: 22 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 23 | GITHUB_RELEASE_ID: ${{ github.event.release.id }} 24 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: test 2 | on: 3 | pull_request: 4 | push: 5 | branches: 6 | - master 7 | workflow_dispatch: 8 | 9 | jobs: 10 | linux: 11 | name: Test on Linux 12 | runs-on: ubuntu-22.04 13 | container: 14 | image: swift:5.10 15 | steps: 16 | - uses: actions/checkout@v2 17 | - name: Show Environments 18 | run: swift --version 19 | - name: Install missing dependencies in ubuntu 20 | run: | 21 | apt-get update --assume-yes 22 | apt-get install --assume-yes libsqlite3-dev libncurses-dev make 23 | - name: Validate Source Code 24 | run: make autocorrect && [ -z "$(git status --porcelain)" ] 25 | - name: Run Test 26 | run: make test 27 | macOS: 28 | name: Test on macOS 29 | runs-on: macos-14 30 | strategy: 31 | matrix: 32 | xcode_version: 33 | - "15.4" 34 | env: 35 | DEVELOPER_DIR: /Applications/Xcode_${{ matrix.xcode_version }}.app 36 | steps: 37 | - uses: actions/checkout@v2 38 | - name: Show Environments 39 | run: | 40 | swift --version 41 | xcodebuild -version 42 | - name: Run Test 43 | run: make test 44 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | .build 3 | /*.xcodeproj 4 | xcuserdata/ 5 | .tmp 6 | .swiftpm/ 7 | swift-mod.zip 8 | -------------------------------------------------------------------------------- /.swift-format.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": 1, 3 | "indentConditionalCompilationBlocks": true, 4 | "lineBreakBeforeControlFlowKeywords": true, 5 | "lineBreakBeforeEachArgument": true, 6 | "lineBreakBeforeEachGenericRequirement": false, 7 | "lineLength": 200, 8 | "maximumBlankLines": 1, 9 | "prioritizeKeepingFunctionOutputTogether": false, 10 | "respectsExistingLineBreaks": true, 11 | "tabWidth": 8, 12 | "indentation": { 13 | "spaces": 4 14 | }, 15 | "rules": { 16 | "AllPublicDeclarationsHaveDocumentation": false, 17 | "AlwaysUseLowerCamelCase": true, 18 | "AmbiguousTrailingClosureOverload": true, 19 | "BeginDocumentationCommentWithOneLineSummary": true, 20 | "DoNotUseSemicolons": true, 21 | "DontRepeatTypeInStaticProperties": true, 22 | "FullyIndirectEnum": true, 23 | "GroupNumericLiterals": true, 24 | "IdentifiersMustBeASCII": true, 25 | "NeverForceUnwrap": false, 26 | "NeverUseForceTry": false, 27 | "NeverUseImplicitlyUnwrappedOptionals": true, 28 | "NoAccessLevelOnExtensionDeclaration": false, 29 | "NoBlockComments": true, 30 | "NoCasesWithOnlyFallthrough": true, 31 | "NoEmptyTrailingClosureParentheses": true, 32 | "NoLabelsInCasePatterns": true, 33 | "NoLeadingUnderscores": true, 34 | "NoParensAroundConditions": true, 35 | "NoVoidReturnOnFunctionSignature": true, 36 | "OneCasePerLine": true, 37 | "OneVariableDeclarationPerLine": true, 38 | "OnlyOneTrailingClosureArgument": true, 39 | "OrderedImports": true, 40 | "ReturnVoidInsteadOfEmptyTuple": true, 41 | "UseLetInEveryBoundCaseVariable": false, 42 | "UseShorthandTypeNames": true, 43 | "UseSingleLinePropertyGetter": true, 44 | "UseSynthesizedInitializer": true, 45 | "UseTripleSlashForDocumentationComments": true, 46 | "ValidateDocumentationComments": true 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /.swift-mod.yml: -------------------------------------------------------------------------------- 1 | format: 2 | indent: 4 3 | lineBreakBeforeEachArgument: true 4 | 5 | rules: 6 | defaultAccessLevel: 7 | accessLevel: openOrPublic 8 | implicitInternal: true 9 | 10 | defaultMemberwiseInitializer: 11 | implicitInitializer: true 12 | implicitInternal: true 13 | ignoreClassesWithInheritance: true 14 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at [INSERT EMAIL ADDRESS]. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | ## Issue 4 | 5 | Feel free to open the issue for your feature request or founded bugs. 6 | Please make sure not already reported in existing issues before you open an issue. 7 | Prefer include as much information as possible in the issue template. 8 | 9 | ## Pull Request 10 | 11 | Before submitting the pull request, please make sure you have tested your changes. 12 | We wrote some `make` command to validate and format your codes. 13 | Please run following command before you submit a pull-request. 14 | 15 | ```sh 16 | make autocorrect 17 | ``` 18 | 19 | ## [Developer's Certificate of Origin 1.1](https://elinux.org/Developer_Certificate_Of_Origin) 20 | 21 | By making a contribution to this project, I certify that: 22 | 23 | (a) The contribution was created in whole or in part by me and I have the right to submit it under the open source license indicated in the file; or 24 | 25 | (b) The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same open source license (unless I am permitted to submit under a different license), as indicated in the file; or 26 | 27 | (c) The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it. 28 | 29 | (d) I understand and agree that this project and the contribution are public and that a record of the contribution (including all personal information I submit with it, including my sign-off) is maintained indefinitely and may be redistributed consistent with this project or the open source license(s) involved. 30 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | SWIFT_FORMAT_PATHS := Sources $(shell find Tests -type f -name "*.swift") 2 | SWIFT_MOD_PATHS := $(shell find Sources -type f -name "*.swift" -not -path "Sources/swift-mod/*") 3 | SWIFT_BUILD_FLAGS := -c release --disable-sandbox 4 | TOOL_NAME := swift-mod 5 | XCODE_DEFAULT_TOOLCHAIN := /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain 6 | GITHUB_REPO := ra1028/$(TOOL_NAME) 7 | DOCKER_IMAGE_NAME := swift:5.10 8 | 9 | ifeq ($(shell uname), Darwin) 10 | SWIFT_BUILD_FLAGS += --arch arm64 --arch x86_64 11 | endif 12 | 13 | TOOL_BIN_DIR := $(shell swift build $(SWIFT_BUILD_FLAGS) --show-bin-path) 14 | TOOL_BIN := $(TOOL_BIN_DIR)/$(TOOL_NAME) 15 | 16 | .PHONY: $(MAKECMDGOALS) 17 | 18 | build: 19 | swift build $(SWIFT_BUILD_FLAGS) 20 | @echo $(TOOL_BIN) 21 | 22 | test: 23 | swift test -c release --parallel 24 | 25 | mod: 26 | swift run -c release swift-mod $(SWIFT_MOD_PATHS) 27 | 28 | format: 29 | swift run -c release --package-path ./Tools -- swift-format format --configuration .swift-format.json -i -r $(SWIFT_FORMAT_PATHS) 30 | 31 | lint: 32 | swift run -c release --package-path ./Tools -- swift-format lint --configuration .swift-format.json -r $(SWIFT_FORMAT_PATHS) 33 | 34 | autocorrect: mod format lint 35 | 36 | ubuntu-deps: 37 | apt-get update --assume-yes 38 | apt-get install --assume-yes libsqlite3-dev libncurses-dev 39 | 40 | docker-test: 41 | docker run -v `pwd`:`pwd` -w `pwd` --rm $(DOCKER_IMAGE_NAME) make ubuntu-deps test 42 | 43 | zip: build 44 | install_name_tool -add_rpath @loader_path -add_rpath $(XCODE_DEFAULT_TOOLCHAIN)/usr/lib/swift/macosx $(TOOL_BIN) 2>/dev/null || true 45 | rm -f $(TOOL_NAME).zip 46 | zip -j $(TOOL_NAME).zip $(TOOL_BIN) LICENSE 47 | 48 | upload-zip: zip 49 | @[ -n "$(GITHUB_TOKEN)" ] || (echo "\nERROR: Make sure setting environment variable 'GITHUB_TOKEN'." && exit 1) 50 | @[ -n "$(GITHUB_RELEASE_ID)" ] || (echo "\nERROR: Make sure setting environment variable 'GITHUB_RELEASE_ID'." && exit 1) 51 | curl -sSL -X POST \ 52 | -H "Authorization: token $(GITHUB_TOKEN)" \ 53 | -H "Content-Type: application/zip" \ 54 | --upload-file "./$(TOOL_NAME).zip" "https://uploads.github.com/repos/$(GITHUB_REPO)/releases/$(GITHUB_RELEASE_ID)/assets?name=$(TOOL_NAME).zip" 55 | -------------------------------------------------------------------------------- /Package.resolved: -------------------------------------------------------------------------------- 1 | { 2 | "originHash" : "49d24ece49d7491e223d2db9c9de55a04e033203d984a1aef05c176f2baee5a8", 3 | "pins" : [ 4 | { 5 | "identity" : "swift-argument-parser", 6 | "kind" : "remoteSourceControl", 7 | "location" : "https://github.com/apple/swift-argument-parser.git", 8 | "state" : { 9 | "revision" : "41982a3656a71c768319979febd796c6fd111d5c", 10 | "version" : "1.5.0" 11 | } 12 | }, 13 | { 14 | "identity" : "swift-syntax", 15 | "kind" : "remoteSourceControl", 16 | "location" : "https://github.com/swiftlang/swift-syntax.git", 17 | "state" : { 18 | "revision" : "2bc86522d115234d1f588efe2bcb4ce4be8f8b82", 19 | "version" : "510.0.3" 20 | } 21 | }, 22 | { 23 | "identity" : "swift-tools-support-core", 24 | "kind" : "remoteSourceControl", 25 | "location" : "https://github.com/swiftlang/swift-tools-support-core.git", 26 | "state" : { 27 | "revision" : "5b130e04cc939373c4713b91704b0c47ceb36170", 28 | "version" : "0.7.1" 29 | } 30 | }, 31 | { 32 | "identity" : "yams", 33 | "kind" : "remoteSourceControl", 34 | "location" : "https://github.com/jpsim/Yams.git", 35 | "state" : { 36 | "revision" : "3036ba9d69cf1fd04d433527bc339dc0dc75433d", 37 | "version" : "5.1.3" 38 | } 39 | } 40 | ], 41 | "version" : 3 42 | } 43 | -------------------------------------------------------------------------------- /Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version:5.10 2 | 3 | import PackageDescription 4 | 5 | let package = Package( 6 | name: "swift-mod", 7 | platforms: [ 8 | .macOS("10.15") 9 | ], 10 | products: [ 11 | .executable( 12 | name: "swift-mod", 13 | targets: ["swift-mod"] 14 | ) 15 | ], 16 | dependencies: [ 17 | .package(url: "https://github.com/apple/swift-argument-parser.git", exact: "1.5.0"), 18 | .package(url: "https://github.com/swiftlang/swift-syntax.git", exact: "510.0.3"), 19 | .package(url: "https://github.com/swiftlang/swift-tools-support-core.git", exact: "0.7.1"), 20 | .package(url: "https://github.com/jpsim/Yams.git", exact: "5.1.3") 21 | ], 22 | targets: [ 23 | .executableTarget( 24 | name: "swift-mod", 25 | dependencies: ["SwiftModCommands"] 26 | ), 27 | .target( 28 | name: "SwiftModCommands", 29 | dependencies: [ 30 | "SwiftModRules", 31 | .product(name: "ArgumentParser", package: "swift-argument-parser"), 32 | ] 33 | ), 34 | .testTarget( 35 | name: "SwiftModCommandsTests", 36 | dependencies: ["SwiftModCommands"] 37 | ), 38 | .target( 39 | name: "SwiftModRules", 40 | dependencies: ["SwiftModCore"] 41 | ), 42 | .testTarget( 43 | name: "SwiftModRulesTests", 44 | dependencies: ["SwiftModRules"] 45 | ), 46 | .target( 47 | name: "SwiftModCore", 48 | dependencies: [ 49 | .product(name: "SwiftParser", package: "swift-syntax"), 50 | .product(name: "SwiftToolsSupport-auto", package: "swift-tools-support-core"), 51 | "Yams", 52 | ] 53 | ), 54 | .testTarget( 55 | name: "SwiftModCoreTests", 56 | dependencies: ["SwiftModCore"] 57 | ), 58 | ], 59 | swiftLanguageVersions: [.v5] 60 | ) 61 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # swift-mod 2 | 3 | A tool for Swift code modification intermediating between code generation and formatting. 4 | 5 | [![swift](https://img.shields.io/badge/language-Swift5-orange.svg)](https://developer.apple.com/swift) 6 | [![release](https://img.shields.io/github/release/ra1028/swift-mod.svg)](https://github.com/ra1028/swift-mod/releases/latest) 7 | [![test](https://github.com/ra1028/swift-mod/workflows/GitHub%20Actions/badge.svg)](https://github.com/ra1028/swift-mod/actions) 8 | [![lincense](http://img.shields.io/badge/License-Apache%202.0-black.svg)](https://github.com/ra1028/swift-mod/blob/master/LICENSE) 9 | 10 | --- 11 | 12 | ## Overview 13 | 14 | `swift-mod` is a tool for Swift code modification that intermediating between code generator and formatter built on top of [apple/SwiftSyntax](https://github.com/apple/swift-syntax). 15 | It can generates boilerplate code, such as access control or memberwise initializers in modularized source code, taking into account the state of the [AST](https://en.wikipedia.org/wiki/Abstract_syntax_tree). 16 | You can improve your productivity for writing more advanced Swift codes by introducing `swift-mod`. 17 | 18 | ### Example 19 | 20 | - **Before** 21 | 22 | ```swift 23 | struct Avenger { 24 | var heroName: String 25 | internal var realName: String? 26 | } 27 | 28 | let avengers = [ 29 | Avenger(heroName: "Iron Man", realName: "Tony Stark"), 30 | Avenger(heroName: "Captain America", realName: "Steve Rogers"), 31 | Avenger(heroName: "Thor"), 32 | ] 33 | 34 | ``` 35 | 36 | - **After** 37 | 38 | ```diff 39 | + public struct Avenger { 40 | + public var heroName: String 41 | internal var realName: String? 42 | 43 | + public init( 44 | + heroName: String, 45 | + realName: String? = nil 46 | + ) { 47 | + self.heroName = heroName 48 | + self.realName = realName 49 | + } 50 | } 51 | 52 | + public let avengers = [ 53 | Avenger(heroName: "Iron Man", realName: "Tony Stark"), 54 | Avenger(heroName: "Captain America", realName: "Steve Rogers"), 55 | Avenger(heroName: "Thor"), 56 | ] 57 | ``` 58 | 59 | --- 60 | 61 | ## Getting Started 62 | 63 | 1. [Install `swift-mod`](#installation). 64 | 65 | 2. Generates configuration file. 66 | 67 | ```sh 68 | swift-mod init 69 | ``` 70 | 71 | 3. Check the all modification rules. 72 | 73 | ```sh 74 | swift-mod rules 75 | swift-mod rules --rule [RULE NAME] # Display more detailed rule description 76 | ``` 77 | 78 | 4. Edit your configuration file with an editor you like, refering to the [documentation](#configuration). 79 | 80 | 5. Run 81 | 82 | ```sh 83 | swift-mod 84 | ``` 85 | 86 | --- 87 | 88 | ## Command Usage 89 | 90 | ```sh 91 | swift-mod [COMMAND] [OPTIONS] 92 | ``` 93 | 94 | All commands can be display a usage by option `-h/--help`. 95 | 96 | - `run` (or not specified) 97 | 98 | ``` 99 | OVERVIEW: Runs modification. 100 | 101 | USAGE: swift-mod run [--mode ] [--configuration ] [ ...] 102 | 103 | ARGUMENTS: 104 | Zero or more input filenames. 105 | 106 | OPTIONS: 107 | -m, --mode Overrides running mode: modify|dry-run|check. (default: modify) 108 | -c, --configuration The path to a configuration file. 109 | -h, --help Show help information. 110 | ``` 111 | 112 | - `init` 113 | 114 | ``` 115 | OVERVIEW: Generates a modify configuration file. 116 | 117 | USAGE: swift-mod init [--output ] 118 | 119 | OPTIONS: 120 | -o, --output An output for the configuration file to be generated. 121 | -h, --help Show help information. 122 | ``` 123 | 124 | - `rules` 125 | 126 | ``` 127 | OVERVIEW: Display the list of rules. 128 | 129 | USAGE: swift-mod rules [--rule ] 130 | 131 | OPTIONS: 132 | -r, --rule A rule name to see detail. 133 | -h, --help Show help information. 134 | ``` 135 | 136 | --- 137 | 138 | ## Configuration 139 | 140 | Modification rules and targets are defines with YAML-formatted file. By default, it's searched by name `.swift-mod.yml`. 141 | Any file name is allowed with passing with option like follows: 142 | 143 | ```sh 144 | swift-mod --configuration 145 | ``` 146 | 147 | ### Example 148 | 149 | ```yaml 150 | format: 151 | indent: 4 152 | lineBreakBeforeEachArgument: true 153 | rules: 154 | defaultAccessLevel: 155 | accessLevel: openOrPublic 156 | implicitInternal: true 157 | defaultMemberwiseInitializer: 158 | implicitInitializer: false 159 | implicitInternal: true 160 | ignoreClassesWithInheritance: false 161 | ``` 162 | 163 | ### Format 164 | 165 | Determines the format setting in all rules. 166 | Format according to this setting only when changes occur. 167 | 168 | |KEY|VALUE|REQUIREMENT|DEFAULT| 169 | |:-|:-|:-|:-| 170 | |indent|The number of spaces, or `tab` by text|Optional|4| 171 | |lineBreakBeforeEachArgument|Indicating whether to insert new lines before each function argument|Optional|true| 172 | 173 | ### Rules 174 | 175 | #### Default Access Level 176 | 177 | |IDENTIFIER|OVERVIEW| 178 | |:-|:-| 179 | |defaultAccessLevel|Assigns the suitable access level to all declaration syntaxes if not present| 180 | 181 | |KEY|VALUE|REQUIREMENT|DEFAULT| 182 | |:-|:-|:-|:-| 183 | |accessLevel|\|openOrPublic\|public\|internal\|fileprivate\|private\||Required|| 184 | |implicitInternal|Indicating whether to omit the `internal` access level|Optional|true| 185 | 186 | ```swift 187 | struct Avenger { 188 | var heroName: String 189 | internal var realName: String? 190 | } 191 | ``` 192 | 193 | ```diff 194 | + public struct Avenger { 195 | + public var heroName: String 196 | internal var realName: String? 197 | } 198 | ``` 199 | 200 | #### Default Memberwise Initializer 201 | 202 | |IDENTIFIER|OVERVIEW| 203 | |:-|:-| 204 | |defaultMemberwiseInitializer|Defines a memberwise initializer according to the access level in the type declaration if not present| 205 | 206 | |KEY|VALUE|REQUIREMENT|DEFAULT| 207 | |:-|:-|:-|:-| 208 | |implicitInitializer|Indicating whether to omit the `internal` initializer in struct decalaration|Optional|false| 209 | |implicitInternal|Indicating whether to omit the `internal` access level|Optional|true| 210 | |ignoreClassesWithInheritance|Indicating whether to skip the classes having inheritance including protocol|Optional|false| 211 | 212 | ```swift 213 | struct Avenger { 214 | var heroName: String 215 | internal var realName: String? 216 | } 217 | ``` 218 | 219 | ```diff 220 | struct Avenger { 221 | var heroName: String 222 | internal var realName: String? 223 | 224 | + init( 225 | + heroName: String, 226 | + realName: String? = nil 227 | + ) { 228 | + self.heroName = heroName 229 | + self.realName = realName 230 | + } 231 | } 232 | ``` 233 | 234 | --- 235 | 236 | ### Ignoring Rules 237 | 238 | `swift-mod` allows users to suppress modification for node and its children by comment like below. 239 | 240 | - **Ignore all rules** 241 | 242 | `// swift-mod-ignore` 243 | 244 | ```swift 245 | // swift-mod-ignore 246 | struct Avenger { 247 | var heroName: String 248 | internal var realName: String? 249 | } 250 | ``` 251 | 252 | - **Ignore specific rule(s)** 253 | 254 | `// swift-mod-ignore: [COMMA DELIMITED RULE IDENTIFIERS]` 255 | 256 | ```swift 257 | // swift-mod-ignore: defaultAccessLevel, defaultMemberwiseInitializer 258 | struct Avenger { 259 | var heroName: String 260 | internal var realName: String? 261 | } 262 | ``` 263 | 264 | --- 265 | 266 | ## Installation 267 | 268 | ### [Swift Package Manager](https://github.com/apple/swift-package-manager) 269 | 270 | Add the following to the dependencies of your `Package.swift`: 271 | 272 | ```swift 273 | dependencies: [ 274 | .package(url: "https://github.com/ra1028/swift-mod.git", from: "swift-mod version"), 275 | ] 276 | ``` 277 | 278 | Run command: 279 | 280 | ```sh 281 | swift run -c release swift-mod [COMMAND] [OPTIONS] 282 | ``` 283 | 284 | ### [Mint](https://github.com/yonaskolb/Mint) 285 | 286 | Install with Mint by following command: 287 | 288 | ```sh 289 | mint install ra1028/swift-mod 290 | ``` 291 | 292 | Run command: 293 | 294 | ```sh 295 | mint run ra1028/swift-mod [COMMAND] [OPTIONS] 296 | ``` 297 | 298 | ### Using a pre-built binary 299 | 300 | You can also install swift-mod by downloading `swift-mod.zip` from the latest GitHub release. 301 | 302 | ### Swift Version Support 303 | 304 | `swift-mod` depends on [SwiftSyntax](https://github.com/apple/swift-syntax) version that matches the toolchain version in use. 305 | So you should use swift-mod version that built with compatible version of Swift you are using. 306 | 307 | |Swift Version|Last Supported `swift-mod` | 308 | |:------------|:-------------------------------| 309 | |5.1 |0.0.2 | 310 | |5.2 |0.0.4 | 311 | |5.3 |0.0.5 | 312 | |5.4 |0.0.6 | 313 | |5.5 |0.0.7 | 314 | |5.6 |0.1.0 | 315 | |5.7 |0.1.1 | 316 | |5.8 |0.2.0 | 317 | |5.9 |0.2.0 | 318 | |5.10 |0.2.1 | 319 | 320 | --- 321 | 322 | ## Development 323 | 324 | Pull requests, bug reports and feature requests are welcome 🚀. 325 | See [CONTRIBUTING.md](./CONTRIBUTING.md) file to learn how to contribute to swift-mod. 326 | 327 | Please validate and test your code before you submit your changes by following commands: 328 | 329 | ```sh 330 | make autocorrect # Modifying, formatting, linting codes and generating Linux XCTest manifests. 331 | make test 332 | ``` 333 | 334 | In addition, swift-mod supports running on Linux, so you should test by installing Docker and following command: 335 | 336 | ```sh 337 | make docker-test 338 | ``` 339 | 340 | --- 341 | 342 | ## License 343 | 344 | swift-mod is released under the [Apache 2.0 License](https://github.com/ra1028/swift-mod/blob/master/LICENSE). 345 | -------------------------------------------------------------------------------- /Sources/SwiftModCommands/Arguments.swift: -------------------------------------------------------------------------------- 1 | import ArgumentParser 2 | import TSCBasic 3 | 4 | public enum Mode: String, CaseIterable, ExpressibleByArgument { 5 | case modify 6 | case dryRun = "dry-run" 7 | case check 8 | } 9 | 10 | extension AbsolutePath: ExpressibleByArgument { 11 | public init?(argument: String) { 12 | if let cwd = localFileSystem.currentWorkingDirectory { 13 | try? self.init(validating: argument, relativeTo: cwd) 14 | } 15 | else { 16 | try? self.init(validating: argument) 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Sources/SwiftModCommands/Configuration/Configuration+AllRules.swift: -------------------------------------------------------------------------------- 1 | import SwiftModCore 2 | import SwiftModRules 3 | 4 | public extension Configuration { 5 | static let allRules: [AnyRule.Type] = [ 6 | DefaultAccessLevelRule.self, 7 | DefaultMemberwiseInitializerRule.self, 8 | ] 9 | } 10 | -------------------------------------------------------------------------------- /Sources/SwiftModCommands/Configuration/Configuration+Codable.swift: -------------------------------------------------------------------------------- 1 | import SwiftModCore 2 | import TSCBasic 3 | 4 | extension Configuration: Codable { 5 | private enum CodingKeys: CodingKey { 6 | case format 7 | case rules 8 | } 9 | 10 | public init(from decoder: Decoder) throws { 11 | let container = try decoder.container(keyedBy: CodingKeys.self) 12 | let format = try container.decodeIfPresent(Format.self, forKey: .format) 13 | let allRuleMap = Dictionary( 14 | uniqueKeysWithValues: Configuration.allRules.lazy.map { ($0.description.name, $0) } 15 | ) 16 | 17 | try self.init( 18 | format: format, 19 | rules: container.decode([String: DecoderInterceptor].self, forKey: .rules).map { rule, interceptor in 20 | guard let ruleType = allRuleMap[rule] else { 21 | throw ConfigurationError.invalidRuleName(rule) 22 | } 23 | 24 | do { 25 | return try ruleType.init(from: interceptor.decoder, format: format ?? .default) 26 | } 27 | catch { 28 | throw ConfigurationError.unexpectedRuleSetting(description: ruleType.description, error: error) 29 | } 30 | } 31 | ) 32 | } 33 | 34 | public func encode(to encoder: Encoder) throws { 35 | var container = encoder.container(keyedBy: CodingKeys.self) 36 | try container.encodeIfPresent(format, forKey: .format) 37 | var rulesContainer = container.nestedContainer(keyedBy: DynamicCondingKey.self, forKey: .rules) 38 | 39 | for rule in rules { 40 | let ruleEncodable = DynamicEncodable(encode: rule.encodeOptions) 41 | let key = DynamicCondingKey(type(of: rule).description.name) 42 | try rulesContainer.encode(ruleEncodable, forKey: key) 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Sources/SwiftModCommands/Configuration/Configuration+Template.swift: -------------------------------------------------------------------------------- 1 | import SwiftModCore 2 | import SwiftModRules 3 | import TSCBasic 4 | 5 | public extension Configuration { 6 | static let template: Configuration = { 7 | let format = Format( 8 | indent: .spaces(4), 9 | lineBreakBeforeEachArgument: true 10 | ) 11 | 12 | return Configuration( 13 | format: format, 14 | rules: [ 15 | DefaultAccessLevelRule( 16 | options: DefaultAccessLevelRule.Options( 17 | accessLevel: .openOrPublic, 18 | implicitInternal: true 19 | ), 20 | format: format 21 | ), 22 | DefaultMemberwiseInitializerRule( 23 | options: DefaultMemberwiseInitializerRule.Options( 24 | implicitInitializer: false, 25 | implicitInternal: true, 26 | ignoreClassesWithInheritance: false 27 | ), 28 | format: format 29 | ), 30 | ] 31 | ) 32 | }() 33 | } 34 | -------------------------------------------------------------------------------- /Sources/SwiftModCommands/InitCommand.swift: -------------------------------------------------------------------------------- 1 | import ArgumentParser 2 | import Foundation 3 | import TSCBasic 4 | 5 | public struct InitCommand: ParsableCommand { 6 | public static var configuration = CommandConfiguration( 7 | commandName: "init", 8 | abstract: "Generates a modify configuration file." 9 | ) 10 | 11 | @Option( 12 | name: .shortAndLong, 13 | help: "An output for the configuration file to be generated." 14 | ) 15 | private var output: AbsolutePath? 16 | 17 | public init() {} 18 | 19 | public func run() throws { 20 | let runner = InitCommandRunner( 21 | output: output, 22 | fileSystem: localFileSystem, 23 | fileManager: FileManager.default 24 | ) 25 | try runner.run() 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Sources/SwiftModCommands/RulesCommand.swift: -------------------------------------------------------------------------------- 1 | import ArgumentParser 2 | import SwiftModCore 3 | 4 | public struct RulesCommand: ParsableCommand { 5 | public static var configuration = CommandConfiguration( 6 | commandName: "rules", 7 | abstract: "Display the list of rules." 8 | ) 9 | 10 | @Option( 11 | name: .shortAndLong, 12 | help: "A rule name to see detail." 13 | ) 14 | private var rule: String? 15 | 16 | public init() {} 17 | 18 | public func run() throws { 19 | let runner = RulesCommandRunner( 20 | rule: rule, 21 | writer: InteractiveWriter.stdout 22 | ) 23 | try runner.run() 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Sources/SwiftModCommands/RunCommand.swift: -------------------------------------------------------------------------------- 1 | import ArgumentParser 2 | import Foundation 3 | import SwiftModCore 4 | import TSCBasic 5 | 6 | public struct RunCommand: ParsableCommand { 7 | public static var configuration = CommandConfiguration( 8 | commandName: "run", 9 | abstract: "Runs modification." 10 | ) 11 | 12 | @Option( 13 | name: .shortAndLong, 14 | help: "Overrides running mode: \(Mode.allCases.map(\.rawValue).joined(separator: "|"))." 15 | ) 16 | private var mode: Mode = .modify 17 | 18 | @Option( 19 | name: .shortAndLong, 20 | help: "The path to a configuration file." 21 | ) 22 | private var configuration: AbsolutePath? 23 | 24 | @Argument( 25 | help: "Zero or more input filenames." 26 | ) 27 | private var paths: [AbsolutePath] 28 | 29 | public init() {} 30 | 31 | public func run() throws { 32 | let runner = RunCommandRunner( 33 | configuration: configuration, 34 | mode: mode, 35 | paths: paths, 36 | fileSystem: localFileSystem, 37 | fileManager: FileManager.default, 38 | measure: Measure() 39 | ) 40 | try runner.run() 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Sources/SwiftModCommands/Runners/InitCommandRunner.swift: -------------------------------------------------------------------------------- 1 | import SwiftModCore 2 | import TSCBasic 3 | import Yams 4 | 5 | internal struct InitCommandRunner { 6 | enum Error: Swift.Error, CustomStringConvertible { 7 | case loadOutputPathFailed 8 | case writeFailed(path: AbsolutePath, error: Swift.Error) 9 | case alreadyExists(path: AbsolutePath) 10 | 11 | var description: String { 12 | switch self { 13 | case .loadOutputPathFailed: 14 | return "Could not load output path" 15 | 16 | case .writeFailed(let path, let error): 17 | return """ 18 | Could not write configuration at '\(path.prettyPath())' 19 | 20 | DETAILS: 21 | \(String(error).offsetBeforeEachLines(2)) 22 | """ 23 | 24 | case .alreadyExists(let path): 25 | return "A configuration file already exists at '\(path.prettyPath())'" 26 | } 27 | } 28 | } 29 | 30 | let output: AbsolutePath? 31 | let fileSystem: FileSystem 32 | let fileManager: FileManagerProtocol 33 | 34 | func run() throws { 35 | let outputPath = try output ?? fileSystem.currentWorkingDirectory.unwrapped(or: Error.loadOutputPathFailed) 36 | 37 | do { 38 | let outputPath = 39 | fileSystem.isDirectory(outputPath) 40 | ? outputPath.appending(component: Configuration.defaultFileName) 41 | : outputPath 42 | 43 | if fileSystem.exists(outputPath) { 44 | throw Error.alreadyExists(path: outputPath) 45 | } 46 | else { 47 | InteractiveWriter.stdout.write("Creating \(outputPath.prettyPath())\n") 48 | try fileSystem.createDirectory(outputPath.parentDirectory, recursive: true) 49 | fileManager.createFile(atPath: outputPath.pathString) 50 | } 51 | 52 | let configuration = Configuration.template 53 | let encoded = try YAMLEncoder().encode(configuration) 54 | try fileSystem.writeFileContents(outputPath) { buffer in 55 | buffer.write(encoded) 56 | } 57 | } 58 | catch let error as Error { 59 | throw error 60 | } 61 | catch { 62 | throw Error.writeFailed(path: outputPath, error: error) 63 | } 64 | 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Sources/SwiftModCommands/Runners/RulesCommandRunner.swift: -------------------------------------------------------------------------------- 1 | import SwiftModCore 2 | import Yams 3 | 4 | internal struct RulesCommandRunner { 5 | enum Error: Swift.Error, CustomStringConvertible { 6 | case unknownRuleSpecified(name: String) 7 | 8 | var description: String { 9 | switch self { 10 | case .unknownRuleSpecified(let name): 11 | return "Unknown rule name `\(name)` is specified" 12 | } 13 | } 14 | } 15 | 16 | let rule: String? 17 | let writer: InteractiveWriterProtocol 18 | 19 | func definitionLines(ruleName: String) throws -> [String] { 20 | guard let rule = Configuration.allRules.first(where: { $0.description.name == ruleName }) else { 21 | throw Error.unknownRuleSpecified(name: ruleName) 22 | } 23 | 24 | let description = rule.description 25 | let offset = 2 26 | 27 | return try [ 28 | "NAME:\n", 29 | description.name.offsetBeforeEachLines(offset), 30 | "\n\n", 31 | "OVERVIEW:\n", 32 | description.overview.offsetBeforeEachLines(offset), 33 | "\n\n", 34 | "EXAMPLE OPTIONS:\n", 35 | YAMLEncoder().encode(description.exampleOptions).offsetBeforeEachLines(offset), 36 | "\n", 37 | "EXAMPLE BEFORE:\n", 38 | description.exampleBefore.offsetBeforeEachLines(offset), 39 | "\n\n", 40 | "EXAMPLE AFTER:\n", 41 | description.exampleAfter.offsetBeforeEachLines(offset), 42 | "\n", 43 | ] 44 | } 45 | 46 | func overviewLines() -> [String] { 47 | let allRuleDescriptions = Configuration.allRules.map { $0.description } 48 | let maxIdentifierWidth = 49 | allRuleDescriptions.lazy 50 | .map { $0.name.count } 51 | .max() ?? 0 52 | 53 | return ["RULES:\n"] 54 | + allRuleDescriptions.flatMap { description in 55 | [ 56 | description.name 57 | .padding(toLength: maxIdentifierWidth + 4, withPad: " ", startingAt: 0) 58 | .offsetBeforeEachLines(2), 59 | description.overview, 60 | "\n", 61 | ] 62 | } 63 | } 64 | 65 | func run() throws { 66 | let lines = try rule.map(definitionLines) ?? overviewLines() 67 | 68 | for line in lines { 69 | writer.write(line) 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /Sources/SwiftModCommands/Runners/RunCommandRunner.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | import SwiftModCore 3 | import SwiftParser 4 | import SwiftSyntax 5 | import TSCBasic 6 | import Yams 7 | 8 | internal struct RunCommandRunner { 9 | enum Error: Swift.Error, CustomStringConvertible { 10 | case readOrParseFileFailed(path: AbsolutePath, error: Swift.Error) 11 | case writeFileContentsFailed(path: AbsolutePath, error: Swift.Error) 12 | case loadConfigurationFilePathFailed 13 | 14 | var description: String { 15 | switch self { 16 | case .readOrParseFileFailed(let path, let error): 17 | return """ 18 | Unable to parse file '\(path)'. 19 | 20 | DETAILS: 21 | \(String(error).offsetBeforeEachLines(2)) 22 | """ 23 | 24 | case .writeFileContentsFailed(let path, let error): 25 | return """ 26 | Unable to write file contents to '\(path)'. 27 | 28 | DETAILS: 29 | \(String(error).offsetBeforeEachLines(2)) 30 | """ 31 | 32 | case .loadConfigurationFilePathFailed: 33 | return "Could not load configuration file" 34 | } 35 | } 36 | } 37 | 38 | let configuration: AbsolutePath? 39 | let mode: Mode 40 | let paths: [AbsolutePath] 41 | let fileSystem: FileSystem 42 | let fileManager: FileManagerProtocol 43 | let measure: Measure 44 | 45 | func run() throws { 46 | let configurationPath = try configuration ?? fileSystem.currentWorkingDirectory.unwrapped(or: Error.loadConfigurationFilePathFailed) 47 | let configuration = try loadConfiguration(at: configurationPath) 48 | let results = try measure.run { () -> [ModifyResult] in 49 | return try [ 50 | modify(rules: configuration.rules) 51 | ] 52 | } 53 | 54 | let numberOfModifiedFiles = results.value.reduce(0) { $0 + $1.numberOfModifiedFiles } 55 | let numberOfTotalFiles = results.value.reduce(0) { $0 + $1.numberOfTotalFiles } 56 | let message = "\(numberOfModifiedFiles)/\(numberOfTotalFiles) file\(numberOfModifiedFiles > 1 ? "s" : "") in \(results.time.formattedString())\n" 57 | 58 | switch mode { 59 | case .modify: 60 | InteractiveWriter.stdout.write("Completed modification " + message, inColor: .green) 61 | 62 | case .dryRun: 63 | InteractiveWriter.stdout.write("Completed dry run modification " + message, inColor: .green) 64 | 65 | case .check: 66 | let isFailed = numberOfModifiedFiles > 0 67 | InteractiveWriter.stdout.write("Completed check modification " + message, inColor: isFailed ? .red : .green) 68 | } 69 | } 70 | } 71 | 72 | private extension RunCommandRunner { 73 | struct ModifyResult { 74 | var numberOfModifiedFiles = 0 75 | var numberOfTotalFiles = 0 76 | var errors = [Swift.Error]() 77 | } 78 | 79 | func modify(rules: [AnyRule]) throws -> ModifyResult { 80 | let pathIterator = SwiftFileIterator( 81 | fileSystem: fileSystem, 82 | fileManager: fileManager, 83 | paths: paths 84 | ) 85 | let pipeline = RulePipeline( 86 | rules.lazy 87 | .filter { $0.isEnabled } 88 | .sorted { type(of: $0).description.priority > type(of: $1).description.priority } 89 | ) 90 | let writer = InteractiveWriter.stdout 91 | writer.write("Applying rules ...") 92 | 93 | defer { writer.write(" done\n") } 94 | 95 | let result = Atomic(ModifyResult()) 96 | let group = DispatchGroup() 97 | let queue = DispatchQueue.global(qos: .userInitiated) 98 | 99 | for path in pathIterator { 100 | group.enter() 101 | queue.async(group: group) { 102 | defer { group.leave() } 103 | 104 | do { 105 | result.modify { $0.numberOfTotalFiles += 1 } 106 | 107 | let source: String 108 | let syntax: Syntax 109 | let modifiedSyntax: Syntax 110 | 111 | do { 112 | source = try self.fileSystem.readFileContents(path).cString 113 | syntax = Syntax(Parser.parse(source: source)) 114 | modifiedSyntax = pipeline.visit(syntax) 115 | } 116 | catch { 117 | throw Error.readOrParseFileFailed(path: path, error: error) 118 | } 119 | 120 | let modifiedSource = modifiedSyntax.description 121 | let isModified = source != modifiedSource 122 | 123 | if isModified && mode == .modify { 124 | try self.rewriteFileContents(path: path, modifiedSource: modifiedSource) 125 | } 126 | 127 | if isModified { 128 | result.modify { $0.numberOfModifiedFiles += 1 } 129 | } 130 | } 131 | catch { 132 | result.modify { $0.errors.append(error) } 133 | } 134 | } 135 | } 136 | 137 | group.wait() 138 | 139 | if let firstError = result.value.errors.first { 140 | throw firstError 141 | } 142 | 143 | return result.value 144 | } 145 | 146 | func rewriteFileContents(path: AbsolutePath, modifiedSource: String) throws { 147 | do { 148 | try fileSystem.writeFileContents(path) { stream in 149 | stream.write(modifiedSource) 150 | } 151 | } 152 | catch { 153 | throw Error.writeFileContentsFailed(path: path, error: error) 154 | } 155 | } 156 | 157 | func loadConfiguration(at path: AbsolutePath) throws -> Configuration { 158 | let path = 159 | fileSystem.isDirectory(path) 160 | ? path.appending(component: Configuration.defaultFileName) 161 | : path 162 | 163 | let yaml: String 164 | 165 | do { 166 | yaml = try fileSystem.readFileContents(path).cString 167 | } 168 | catch { 169 | throw ConfigurationError.loadFailed(path: path, error: error) 170 | } 171 | 172 | do { 173 | return try YAMLDecoder().decode(from: yaml) 174 | } 175 | catch let error as ConfigurationError { 176 | throw error 177 | } 178 | catch let error as DecodingError { 179 | throw ConfigurationError.decodeFailed(error: error.underlyingError ?? error) 180 | } 181 | catch { 182 | throw ConfigurationError.invalidSetting(error: error) 183 | } 184 | } 185 | } 186 | 187 | private extension Double { 188 | func formattedString() -> String { 189 | String(format: "%gs", (self * 100).rounded() / 100) 190 | } 191 | } 192 | -------------------------------------------------------------------------------- /Sources/SwiftModCore/Configuration.swift: -------------------------------------------------------------------------------- 1 | public struct Configuration { 2 | public static let defaultFileName = ".swift-mod.yml" 3 | 4 | public var format: Format? 5 | public var rules: [AnyRule] 6 | 7 | public init(format: Format?, rules: [AnyRule]) { 8 | self.format = format 9 | self.rules = rules 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Sources/SwiftModCore/ConfigurationError.swift: -------------------------------------------------------------------------------- 1 | import TSCBasic 2 | 3 | public enum ConfigurationError: Error, CustomStringConvertible { 4 | case invalidSetting(error: Error) 5 | case invalidRuleName(String) 6 | case decodeFailed(error: Error) 7 | case loadFailed(path: AbsolutePath, error: Error) 8 | case unexpectedFormatSetting(details: String) 9 | case unexpectedRuleSetting(description: RuleDescription, error: Error) 10 | 11 | public var description: String { 12 | switch self { 13 | case .invalidSetting(let error): 14 | return """ 15 | Configuration file has invalid setting. 16 | 17 | DETAILS: 18 | \(String(error).offsetBeforeEachLines(2)) 19 | """ 20 | 21 | case .invalidRuleName(let name): 22 | return "Configuration file contains an invalid rule '\(name)'" 23 | 24 | case .decodeFailed(let error): 25 | return """ 26 | Could not decode configuration file. 27 | 28 | DETAILS: 29 | \(String(error).offsetBeforeEachLines(2)) 30 | """ 31 | 32 | case .loadFailed(let path, let error): 33 | return """ 34 | Could not load configuration at '\(path.prettyPath())'. 35 | 36 | DETAILS: 37 | \(String(error).offsetBeforeEachLines(2)) 38 | """ 39 | 40 | case .unexpectedFormatSetting(let details): 41 | return """ 42 | Unexpected format setting is found. 43 | 44 | DETAILS: 45 | \(details.offsetBeforeEachLines(2)) 46 | """ 47 | 48 | case .unexpectedRuleSetting(let description, let error): 49 | return """ 50 | Unexpected rule setting is found in rule '\(description.name)'. 51 | 52 | DETAILS: 53 | \(String(error).offsetBeforeEachLines(2)) 54 | """ 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /Sources/SwiftModCore/Extensions/DeclModifierListSyntaxExtensions.swift: -------------------------------------------------------------------------------- 1 | import SwiftSyntax 2 | 3 | public extension DeclModifierListSyntax { 4 | var hasFinal: Bool { 5 | contains { $0.name.tokenKind == .keyword(.final) } 6 | } 7 | 8 | var hasStatic: Bool { 9 | contains { $0.name.tokenKind == .keyword(.static) } 10 | } 11 | 12 | var accessLevelModifier: DeclModifierSyntax? { 13 | first { modifier in 14 | switch modifier.name.tokenKind { 15 | case .keyword(.open), 16 | .keyword(.public), 17 | .keyword(.internal), 18 | .keyword(.fileprivate), 19 | .keyword(.private): 20 | return true 21 | 22 | default: 23 | return false 24 | } 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Sources/SwiftModCore/Extensions/DecodingErrorExtensions.swift: -------------------------------------------------------------------------------- 1 | public extension DecodingError { 2 | var underlyingError: Error? { 3 | switch self { 4 | case .typeMismatch(_, let context): 5 | return context.underlyingError 6 | 7 | case .valueNotFound(_, let context): 8 | return context.underlyingError 9 | 10 | case .keyNotFound(_, let context): 11 | return context.underlyingError 12 | 13 | case .dataCorrupted(let context): 14 | return context.underlyingError 15 | 16 | @unknown default: 17 | return nil 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Sources/SwiftModCore/Extensions/IdentifierPatternSyntaxExtensions.swift: -------------------------------------------------------------------------------- 1 | import SwiftSyntax 2 | 3 | public extension IdentifierPatternSyntax { 4 | func withoutBackticks() -> IdentifierPatternSyntax { 5 | IdentifierBackticksRemover() 6 | .visit(self) 7 | .as(Self.self)! 8 | } 9 | } 10 | 11 | private final class IdentifierBackticksRemover: SyntaxRewriter { 12 | override func visit(_ token: TokenSyntax) -> TokenSyntax { 13 | guard case .identifier(let text) = token.tokenKind else { 14 | return token 15 | } 16 | 17 | return token.with(\.tokenKind, .identifier(text.replacingOccurrences(of: "`", with: ""))) 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Sources/SwiftModCore/Extensions/IndentExtensions.swift: -------------------------------------------------------------------------------- 1 | import SwiftSyntax 2 | 3 | public extension Indent { 4 | var trivia: Trivia { 5 | switch self { 6 | case .spaces(let spaces): 7 | return .spaces(spaces) 8 | 9 | case .tab: 10 | return .tab 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Sources/SwiftModCore/Extensions/OptionalExtensions.swift: -------------------------------------------------------------------------------- 1 | public extension Optional { 2 | func unwrapped(or error: @autoclosure () -> Error) throws -> Wrapped { 3 | guard let wrapped = self else { 4 | throw error() 5 | } 6 | 7 | return wrapped 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Sources/SwiftModCore/Extensions/SequenceExtensions.swift: -------------------------------------------------------------------------------- 1 | public extension Sequence { 2 | var first: Element? { 3 | first { _ in true } 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /Sources/SwiftModCore/Extensions/StringExtensions.swift: -------------------------------------------------------------------------------- 1 | public extension String { 2 | init(_ any: Any) { 3 | self = "\(any)" 4 | } 5 | 6 | func offsetBeforeEachLines(_ offset: Int) -> String { 7 | let offsetString = String(repeating: " ", count: offset) 8 | return offsetString + replacingOccurrences(of: "\n", with: "\n\(offsetString)") 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Sources/SwiftModCore/Extensions/SyntaxCollection.swift: -------------------------------------------------------------------------------- 1 | import SwiftSyntax 2 | 3 | public extension SyntaxCollection { 4 | var isEmpty: Bool { 5 | count <= 0 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Sources/SwiftModCore/Extensions/TokenKindExtensions.swift: -------------------------------------------------------------------------------- 1 | import SwiftSyntax 2 | 3 | public extension TokenKind { 4 | var isOptional: Bool { 5 | self == .identifier("Optional") 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Sources/SwiftModCore/Extensions/TokenSyntaxExtensions.swift: -------------------------------------------------------------------------------- 1 | import SwiftSyntax 2 | 3 | public extension TokenSyntax { 4 | func appendingLeadingTrivia(_ trivia: Trivia, condition: Bool = true) -> TokenSyntax { 5 | withLeadingTrivia(leadingTrivia + trivia, condition: condition) 6 | } 7 | 8 | func appendingTrailingTrivia(_ trivia: Trivia, condition: Bool = true) -> TokenSyntax { 9 | withTrailingTrivia(trailingTrivia + trivia, condition: condition) 10 | } 11 | 12 | func withLeadingTrivia(_ leadingTrivia: Trivia, condition: Bool) -> TokenSyntax { 13 | if condition { 14 | return with(\.leadingTrivia, leadingTrivia) 15 | } 16 | else { 17 | return self 18 | } 19 | } 20 | 21 | func withTrailingTrivia(_ trailingTrivia: Trivia, condition: Bool) -> TokenSyntax { 22 | if condition { 23 | return with(\.trailingTrivia, trailingTrivia) 24 | } 25 | else { 26 | return self 27 | } 28 | } 29 | 30 | static func replacingTrivia( 31 | _ node: S, 32 | for token: TokenSyntax, 33 | leading: Trivia? = nil, 34 | trailing: Trivia? = nil 35 | ) -> S { 36 | TriviaReplacer(for: token, leading: leading, trailing: trailing) 37 | .rewrite(Syntax(node)) 38 | .as(S.self)! 39 | } 40 | 41 | static func movingLeadingTrivia( 42 | leading: L, 43 | for leadingToken: TokenSyntax, 44 | trailing: T, 45 | for trailingToken: TokenSyntax 46 | ) -> (leading: L, trailing: T) { 47 | let leading = replacingTrivia(leading, for: leadingToken, leading: trailingToken.leadingTrivia) 48 | let trailing = replacingTrivia(trailing, for: trailingToken, leading: []) 49 | return (leading, trailing) 50 | } 51 | } 52 | 53 | private final class TriviaReplacer: SyntaxRewriter { 54 | let token: TokenSyntax 55 | let leading: Trivia 56 | let trailing: Trivia 57 | 58 | init(for token: TokenSyntax, leading: Trivia?, trailing: Trivia?) { 59 | self.token = token 60 | self.leading = leading ?? token.leadingTrivia 61 | self.trailing = trailing ?? token.trailingTrivia 62 | } 63 | 64 | override func visit(_ token: TokenSyntax) -> TokenSyntax { 65 | guard token == self.token else { return token } 66 | 67 | return 68 | token 69 | .with(\.leadingTrivia, leading) 70 | .with(\.trailingTrivia, trailing) 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /Sources/SwiftModCore/Extensions/TriviaExtensions.swift: -------------------------------------------------------------------------------- 1 | import SwiftSyntax 2 | 3 | public extension Trivia { 4 | var numberOfNewlines: Int { 5 | reduce(0) { result, piece in 6 | switch piece { 7 | case .newlines(let count): 8 | return result + count 9 | 10 | default: 11 | return result 12 | } 13 | } 14 | } 15 | 16 | var indentation: Trivia { 17 | Trivia( 18 | pieces: filter { piece in 19 | switch piece { 20 | case .spaces, .tabs: 21 | return true 22 | 23 | default: 24 | return false 25 | } 26 | } 27 | ) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Sources/SwiftModCore/Extensions/TypeSyntaxExtensions.swift: -------------------------------------------------------------------------------- 1 | import SwiftSyntax 2 | 3 | public extension TypeSyntax { 4 | var isOptional: Bool { 5 | if let identifier = self.as(IdentifierTypeSyntax.self), identifier.name.tokenKind.isOptional { 6 | return true 7 | } 8 | else { 9 | return self.is(OptionalTypeSyntax.self) 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Sources/SwiftModCore/Extensions/VariableDeclSyntaxExtensions.swift: -------------------------------------------------------------------------------- 1 | import SwiftSyntax 2 | 3 | public extension VariableDeclSyntax { 4 | var identifier: IdentifierPatternSyntax? { 5 | bindings.lazy 6 | .compactMap { $0.pattern.as(IdentifierPatternSyntax.self) } 7 | .first 8 | } 9 | 10 | var typeAnnotation: TypeAnnotationSyntax? { 11 | bindings.lazy 12 | .compactMap { $0.typeAnnotation } 13 | .first 14 | } 15 | 16 | var value: ExprSyntax? { 17 | bindings.lazy 18 | .compactMap { $0.initializer?.value } 19 | .first 20 | } 21 | 22 | var hasAccessor: Bool { 23 | bindings.contains { $0.accessorBlock != nil } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Sources/SwiftModCore/Format.swift: -------------------------------------------------------------------------------- 1 | public struct Format: Codable, Equatable { 2 | private enum CodingKeys: String, CodingKey { 3 | case indent 4 | case lineBreakBeforeEachArgument 5 | } 6 | 7 | public static let `default` = Format(indent: nil, lineBreakBeforeEachArgument: nil) 8 | 9 | private var underlyingIndent: Indent? 10 | private var underlyingLineBreakBeforeEachArgument: Bool? 11 | 12 | public var indent: Indent { underlyingIndent ?? .spaces(4) } 13 | public var lineBreakBeforeEachArgument: Bool { underlyingLineBreakBeforeEachArgument ?? true } 14 | 15 | public init(indent: Indent?, lineBreakBeforeEachArgument: Bool?) { 16 | self.underlyingIndent = indent 17 | self.underlyingLineBreakBeforeEachArgument = lineBreakBeforeEachArgument 18 | } 19 | 20 | public init(from decoder: Decoder) throws { 21 | let container = try decoder.container(keyedBy: CodingKeys.self) 22 | let indent = try container.decodeIfPresent(Indent.self, forKey: .indent) 23 | let lineBreakBeforeEachArgument = try container.decodeIfPresent(Bool.self, forKey: .lineBreakBeforeEachArgument) 24 | 25 | self.init( 26 | indent: indent, 27 | lineBreakBeforeEachArgument: lineBreakBeforeEachArgument 28 | ) 29 | } 30 | 31 | public func encode(to encoder: Encoder) throws { 32 | var container = encoder.container(keyedBy: CodingKeys.self) 33 | try container.encodeIfPresent(underlyingIndent, forKey: .indent) 34 | try container.encodeIfPresent(underlyingLineBreakBeforeEachArgument, forKey: .lineBreakBeforeEachArgument) 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Sources/SwiftModCore/Helpers/Atomic.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | public final class Atomic { 4 | public var value: Value { 5 | get { modify { $0 } } 6 | set { modify { $0 = newValue } } 7 | } 8 | 9 | private let lock = NSLock() 10 | private var underlyingValue: Value 11 | 12 | public init(_ value: Value) { 13 | self.underlyingValue = value 14 | } 15 | 16 | @discardableResult 17 | public func withValue(_ action: (Value) throws -> T) rethrows -> T { 18 | lock.lock() 19 | defer { lock.unlock() } 20 | return try action(underlyingValue) 21 | } 22 | 23 | @discardableResult 24 | public func modify(_ action: (inout Value) throws -> T) rethrows -> T { 25 | lock.lock() 26 | defer { lock.unlock() } 27 | return try action(&underlyingValue) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Sources/SwiftModCore/Helpers/DecoderInterceptor.swift: -------------------------------------------------------------------------------- 1 | public struct DecoderInterceptor: Decodable { 2 | public let decoder: Decoder 3 | 4 | public init(from decoder: Decoder) throws { 5 | self.decoder = decoder 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Sources/SwiftModCore/Helpers/DirectoryIterator.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | import TSCBasic 3 | 4 | public protocol DirectoryEnumerable: AnyObject { 5 | func next() -> AbsolutePath? 6 | } 7 | 8 | public final class DirectoryIterator: DirectoryEnumerable, IteratorProtocol { 9 | private var rootPath: AbsolutePath? 10 | private let enumerator: FileManager.DirectoryEnumerator 11 | 12 | public init?(rootPath: AbsolutePath) { 13 | guard let enumerator = FileManager.default.enumerator(at: rootPath.asURL, includingPropertiesForKeys: [.pathKey], options: .skipsHiddenFiles) else { 14 | return nil 15 | } 16 | 17 | self.rootPath = rootPath 18 | self.enumerator = enumerator 19 | } 20 | 21 | public func next() -> AbsolutePath? { 22 | if let rootPath = rootPath { 23 | self.rootPath = nil 24 | return rootPath 25 | } 26 | 27 | guard let pathURL = enumerator.nextObject() as? URL else { 28 | return nil 29 | } 30 | 31 | return try? AbsolutePath(validating: pathURL.path) 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Sources/SwiftModCore/Helpers/DynamicCondingKey.swift: -------------------------------------------------------------------------------- 1 | public struct DynamicCondingKey: CodingKey { 2 | public var stringValue: String 3 | public var intValue: Int? { nil } 4 | 5 | public init?(intValue: Int) { nil } 6 | 7 | public init?(stringValue: String) { 8 | self.init(stringValue) 9 | } 10 | 11 | public init(_ stringValue: String) { 12 | self.stringValue = stringValue 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Sources/SwiftModCore/Helpers/DynamicEncodable.swift: -------------------------------------------------------------------------------- 1 | public struct DynamicEncodable: Encodable { 2 | private var internalEncode: (Encoder) throws -> Void 3 | 4 | public init(encode: @escaping (Encoder) throws -> Void) { 5 | self.internalEncode = encode 6 | } 7 | 8 | public func encode(to encoder: Encoder) throws { 9 | try internalEncode(encoder) 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Sources/SwiftModCore/Helpers/FileManager.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | import TSCBasic 3 | 4 | public protocol FileManagerProtocol: AnyObject { 5 | @discardableResult 6 | func createFile(atPath path: String) -> Bool 7 | 8 | func enumerator(at path: AbsolutePath) -> DirectoryEnumerable? 9 | } 10 | 11 | extension FileManager: FileManagerProtocol { 12 | @discardableResult 13 | public func createFile(atPath path: String) -> Bool { 14 | createFile(atPath: path, contents: nil) 15 | } 16 | 17 | public func enumerator(at path: AbsolutePath) -> DirectoryEnumerable? { 18 | DirectoryIterator(rootPath: path) 19 | } 20 | } 21 | 22 | public final class InMemoryFileManager: FileManagerProtocol { 23 | public let fileSystem: InMemoryFileSystem 24 | 25 | public init(fileSystem: InMemoryFileSystem = InMemoryFileSystem()) { 26 | self.fileSystem = fileSystem 27 | } 28 | 29 | public func createFile(atPath path: String) -> Bool { 30 | do { 31 | try fileSystem.writeFileContents(AbsolutePath(validating: path), bytes: ByteString()) 32 | return true 33 | } 34 | catch { 35 | return false 36 | } 37 | } 38 | 39 | public func enumerator(at path: AbsolutePath) -> DirectoryEnumerable? { 40 | final class InMemoryDirectoryIterator: DirectoryEnumerable { 41 | private var paths: [AbsolutePath] 42 | 43 | init(paths: [AbsolutePath] = []) { 44 | self.paths = paths 45 | } 46 | 47 | func next() -> AbsolutePath? { 48 | guard !paths.isEmpty else { 49 | return nil 50 | } 51 | 52 | return paths.removeFirst() 53 | } 54 | } 55 | 56 | func getRecursiveDirectoryContents(rootPath: AbsolutePath) -> [AbsolutePath] { 57 | guard let contents = try? fileSystem.getDirectoryContents(rootPath) else { 58 | return [] 59 | } 60 | 61 | return contents.sorted().flatMap { component -> [AbsolutePath] in 62 | let path = rootPath.appending(component: component) 63 | 64 | if fileSystem.isDirectory(path) { 65 | return [path] + getRecursiveDirectoryContents(rootPath: path) 66 | } 67 | else { 68 | return [path] 69 | } 70 | } 71 | } 72 | 73 | return InMemoryDirectoryIterator(paths: getRecursiveDirectoryContents(rootPath: path)) 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /Sources/SwiftModCore/Helpers/InteractiveWriter.swift: -------------------------------------------------------------------------------- 1 | import TSCBasic 2 | 3 | public protocol InteractiveWriterProtocol { 4 | func write(_ string: String, inColor color: TerminalController.Color, bold: Bool) 5 | } 6 | 7 | public extension InteractiveWriterProtocol { 8 | func write(_ string: String, inColor color: TerminalController.Color = .noColor, bold: Bool = false) { 9 | write(string, inColor: color, bold: bold) 10 | } 11 | } 12 | 13 | public final class InteractiveWriter: InteractiveWriterProtocol { 14 | public static let stdout = InteractiveWriter(stream: stdoutStream) 15 | public static let stderr = InteractiveWriter(stream: stderrStream) 16 | 17 | public let term: TerminalController? 18 | public let stream: OutputByteStream 19 | 20 | public init(stream: OutputByteStream) { 21 | self.term = TerminalController(stream: stream) 22 | self.stream = stream 23 | } 24 | 25 | public func write(_ string: String, inColor color: TerminalController.Color, bold: Bool) { 26 | if let term = term { 27 | term.write(string, inColor: color, bold: bold) 28 | } 29 | else { 30 | stream.send(string) 31 | stream.flush() 32 | } 33 | } 34 | } 35 | 36 | public final class InMemoryInteractiveWriter: InteractiveWriterProtocol { 37 | public struct Input: Equatable { 38 | public let string: String 39 | public let color: TerminalController.Color 40 | public let bold: Bool 41 | 42 | public init( 43 | string: String, 44 | color: TerminalController.Color, 45 | bold: Bool 46 | ) { 47 | self.string = string 48 | self.color = color 49 | self.bold = bold 50 | } 51 | } 52 | 53 | public var inputs = [Input]() 54 | 55 | public init() {} 56 | 57 | public func write(_ string: String, inColor color: TerminalController.Color, bold: Bool) { 58 | inputs.append(Input(string: string, color: color, bold: bold)) 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Sources/SwiftModCore/Helpers/Measure.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | public struct Measure { 4 | public var makeDate: () -> Date 5 | 6 | public init(_ makeDate: @escaping () -> Date = Date.init) { 7 | self.makeDate = makeDate 8 | } 9 | 10 | public func run(_ action: () throws -> T) rethrows -> (value: T, time: TimeInterval) { 11 | let startTime = makeDate() 12 | let result = try action() 13 | let endTime = makeDate() 14 | let time = endTime.timeIntervalSince(startTime) 15 | return (result, time) 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Sources/SwiftModCore/Helpers/RulePipeline.swift: -------------------------------------------------------------------------------- 1 | import SwiftSyntax 2 | 3 | public struct RulePipeline { 4 | private let rules: ContiguousArray 5 | 6 | public init(_ rules: S) where S.Element == Rule { 7 | self.rules = ContiguousArray(rules) 8 | } 9 | 10 | public func visit(_ node: Syntax) -> Syntax { 11 | rules.reduce(node) { node, rule in 12 | rule.rewriter().rewrite(node) 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Sources/SwiftModCore/Helpers/Stack.swift: -------------------------------------------------------------------------------- 1 | public struct Stack { 2 | private var buffer: ContiguousArray 3 | 4 | public var top: Element? { 5 | buffer.last 6 | } 7 | 8 | public init(_ buffer: S) where S.Element == Element { 9 | self.buffer = ContiguousArray(buffer) 10 | } 11 | 12 | public init() { 13 | self.init([]) 14 | } 15 | 16 | public mutating func push(_ element: Element) { 17 | buffer.append(element) 18 | } 19 | 20 | @discardableResult 21 | public mutating func pop() -> Element? { 22 | buffer.popLast() 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Sources/SwiftModCore/Helpers/SwiftFileIterator.swift: -------------------------------------------------------------------------------- 1 | import TSCBasic 2 | 3 | public final class SwiftFileIterator: Sequence, IteratorProtocol { 4 | public static let fileExtension = "swift" 5 | 6 | private let fileSystem: FileSystem 7 | private let fileManager: FileManagerProtocol 8 | private var pathIterator: Array.Iterator 9 | private var directoryIterator: DirectoryEnumerable? 10 | 11 | public init( 12 | fileSystem: FileSystem, 13 | fileManager: FileManagerProtocol, 14 | paths: [AbsolutePath] 15 | ) { 16 | self.fileSystem = fileSystem 17 | self.fileManager = fileManager 18 | self.pathIterator = paths.makeIterator() 19 | } 20 | 21 | public func next() -> AbsolutePath? { 22 | if let path = directoryIterator?.next() { 23 | return swiftFilePath(path) 24 | } 25 | else if let path = pathIterator.next() { 26 | if fileSystem.isDirectory(path) { 27 | directoryIterator = fileManager.enumerator(at: path) 28 | return next() 29 | } 30 | else if fileSystem.exists(path) { 31 | return swiftFilePath(path) 32 | } 33 | else { 34 | return next() 35 | } 36 | } 37 | else { 38 | return nil 39 | } 40 | } 41 | 42 | private func swiftFilePath(_ path: AbsolutePath) -> AbsolutePath? { 43 | guard fileSystem.isFile(path) && path.extension == Self.fileExtension else { 44 | return next() 45 | } 46 | 47 | return path 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Sources/SwiftModCore/Indent.swift: -------------------------------------------------------------------------------- 1 | public enum Indent: Codable, Equatable { 2 | case spaces(Int) 3 | case tab 4 | 5 | private static let tabText = "tab" 6 | 7 | public init(from decoder: Decoder) throws { 8 | let container = try decoder.singleValueContainer() 9 | 10 | if let spaces = try? container.decode(Int.self) { 11 | self = .spaces(spaces) 12 | } 13 | else if let tab = try? container.decode(String.self), tab == Self.tabText { 14 | self = .tab 15 | } 16 | else { 17 | throw DecodingError.dataCorruptedError( 18 | in: container, 19 | debugDescription: """ 20 | The value for indent should specify number of spaces. 21 | To use tab for indentation, specify tab by text. 22 | """ 23 | ) 24 | } 25 | } 26 | 27 | public func encode(to encoder: Encoder) throws { 28 | var container = encoder.singleValueContainer() 29 | 30 | switch self { 31 | case .spaces(let spaces): 32 | try container.encode(spaces) 33 | 34 | case .tab: 35 | try container.encode(Self.tabText) 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Sources/SwiftModCore/RuleDefinition.swift: -------------------------------------------------------------------------------- 1 | import SwiftSyntax 2 | 3 | public typealias RuleDefinition = Rule & RuleDefinable 4 | 5 | public protocol RuleDefinable: AnyRule { 6 | associatedtype Options 7 | 8 | // Can't compile with `associatedtype Rewriter: RuleSyntaxRewriter` 9 | associatedtype Rewriter: RuleSyntaxRewriterProtocol where Rewriter.Options == Options 10 | } 11 | 12 | public extension RuleDefinable { 13 | init( 14 | isEnabled: Bool? = nil, 15 | options: Options, 16 | format: Format 17 | ) { 18 | self.init( 19 | isEnabled: isEnabled ?? true, 20 | makeRewriter: { 21 | Rewriter( 22 | name: Self.description.name, 23 | options: options, 24 | format: format 25 | ) 26 | }, 27 | encodeOptions: { encoder in 28 | var container = encoder.container(keyedBy: CodingKeys.self) 29 | try container.encodeIfPresent(isEnabled, forKey: .isEnabled) 30 | try options.encode(to: encoder) 31 | } 32 | ) 33 | } 34 | 35 | init(from decoder: Decoder, format: Format) throws { 36 | let container = try decoder.container(keyedBy: CodingKeys.self) 37 | let isEnabled = try container.decodeIfPresent(Bool.self, forKey: .isEnabled) 38 | let options = try Options(from: decoder) 39 | 40 | self.init( 41 | isEnabled: isEnabled, 42 | options: options, 43 | format: format 44 | ) 45 | } 46 | } 47 | 48 | public protocol AnyRule: Rule { 49 | static var description: RuleDescription { get } 50 | 51 | init(from decoder: Decoder, format: Format) throws 52 | } 53 | 54 | open class Rule { 55 | public let isEnabled: Bool 56 | 57 | private let makeRewriter: () -> SyntaxRewriter 58 | private let encodeOptions: (Encoder) throws -> Void 59 | 60 | public required init( 61 | isEnabled: Bool = true, 62 | makeRewriter: @escaping () -> SyntaxRewriter, 63 | encodeOptions: @escaping (Encoder) throws -> Void 64 | ) { 65 | self.isEnabled = isEnabled 66 | self.makeRewriter = makeRewriter 67 | self.encodeOptions = encodeOptions 68 | } 69 | 70 | public final func rewriter() -> SyntaxRewriter { 71 | makeRewriter() 72 | } 73 | 74 | public final func encodeOptions(to encoder: Encoder) throws { 75 | try encodeOptions(encoder) 76 | } 77 | } 78 | 79 | private enum CodingKeys: String, CodingKey { 80 | case isEnabled = "enabled" 81 | } 82 | -------------------------------------------------------------------------------- /Sources/SwiftModCore/RuleDescription.swift: -------------------------------------------------------------------------------- 1 | public struct RuleDescription { 2 | public var name: String 3 | public var priority: RulePriority 4 | public var overview: String 5 | public var exampleOptions: DynamicEncodable 6 | public var exampleBefore: String 7 | public var exampleAfter: String 8 | 9 | public init( 10 | name: String, 11 | priority: RulePriority, 12 | overview: String, 13 | exampleOptions: Options, 14 | exampleBefore: String, 15 | exampleAfter: String 16 | ) { 17 | self.name = name 18 | self.priority = priority 19 | self.overview = overview 20 | self.exampleOptions = DynamicEncodable(encode: exampleOptions.encode) 21 | self.exampleBefore = exampleBefore 22 | self.exampleAfter = exampleAfter 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Sources/SwiftModCore/RulePriority.swift: -------------------------------------------------------------------------------- 1 | public struct RulePriority: RawRepresentable, Comparable { 2 | public var rawValue: Int 3 | 4 | public static let high = RulePriority(rawValue: 1000) 5 | public static let `default` = RulePriority(rawValue: 750) 6 | public static let low = RulePriority(rawValue: 500) 7 | 8 | public init(rawValue: Int) { 9 | self.rawValue = rawValue 10 | } 11 | 12 | public static func < (lhs: RulePriority, rhs: RulePriority) -> Bool { 13 | lhs.rawValue < rhs.rawValue 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Sources/SwiftModCore/RuleSyntaxRewriter.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | import SwiftSyntax 3 | 4 | private extension NSRegularExpression { 5 | static let ignoreRules = try! NSRegularExpression(pattern: #"^.*swift-mod-ignore(:\s+(([A-z0-9]+[,\s]*)+))?.*$"#) 6 | } 7 | 8 | public protocol RuleSyntaxRewriterProtocol: SyntaxRewriter { 9 | associatedtype Options: Codable 10 | 11 | init(name: String, options: Options, format: Format) 12 | } 13 | 14 | open class RuleSyntaxRewriter: SyntaxRewriter, RuleSyntaxRewriterProtocol { 15 | public let name: String 16 | public let options: Options 17 | public let format: Format 18 | 19 | public required init(name: String, options: Options, format: Format) { 20 | self.name = name 21 | self.options = options 22 | self.format = format 23 | } 24 | 25 | public final override func visitAny(_ node: Syntax) -> Syntax? { 26 | // Whether to extract ignore options from comments 27 | let shouldExtractNode = node.is(MemberBlockItemSyntax.self) || node.is(CodeBlockItemSyntax.self) 28 | 29 | guard shouldExtractNode, let leadingTrivia = node.firstToken(viewMode: .sourceAccurate)?.leadingTrivia else { 30 | return nil 31 | } 32 | 33 | for piece in leadingTrivia { 34 | let comment: String 35 | 36 | // Supports line comments (// swift-mod-ignore) or block comments (/* swift-mod-ignore */) 37 | switch piece { 38 | case .lineComment(let text), .blockComment(let text): 39 | comment = text 40 | 41 | default: 42 | continue 43 | } 44 | 45 | let range = NSRange(comment.startIndex.. String { string } 21 | } 22 | 23 | private struct Bar { 24 | // The member item acceess level is adjusted for owner's access level. 25 | var foo: Int 26 | } 27 | """, 28 | exampleAfter: """ 29 | public struct Foo { 30 | public var foo: Int 31 | 32 | // Not triggered if access level is already present 33 | internal var bar: String 34 | 35 | public func function(string: String) -> String { string } 36 | } 37 | 38 | private struct Bar { 39 | // The member item acceess level is adjusted for owner's access level. 40 | var foo: Int 41 | } 42 | """ 43 | ) 44 | 45 | public enum AccessLebel: String, Codable { 46 | case openOrPublic 47 | case `public` 48 | case `internal` 49 | case `fileprivate` 50 | case `private` 51 | } 52 | 53 | public struct Options: Codable { 54 | public var accessLevel: AccessLebel 55 | public var implicitInternal: Bool? 56 | 57 | public init(accessLevel: AccessLebel, implicitInternal: Bool?) { 58 | self.accessLevel = accessLevel 59 | self.implicitInternal = implicitInternal 60 | } 61 | } 62 | 63 | public final class Rewriter: RuleSyntaxRewriter { 64 | private var visitStack = Stack() 65 | 66 | public override func visit(_ node: StructDeclSyntax) -> DeclSyntax { 67 | visit( 68 | node, 69 | getDeclKeyword: { $0.structKeyword }, 70 | getModifiers: { $0.modifiers }, 71 | replacingModifiers: { $0.with(\.modifiers, $1) }, 72 | visitChildren: super.visit 73 | ) 74 | } 75 | 76 | public override func visit(_ node: ClassDeclSyntax) -> DeclSyntax { 77 | visit( 78 | node, 79 | getDeclKeyword: { $0.classKeyword }, 80 | getModifiers: { $0.modifiers }, 81 | replacingModifiers: { $0.with(\.modifiers, $1) }, 82 | visitChildren: super.visit 83 | ) 84 | } 85 | 86 | public override func visit(_ node: ActorDeclSyntax) -> DeclSyntax { 87 | visit( 88 | node, 89 | getDeclKeyword: { $0.actorKeyword }, 90 | getModifiers: { $0.modifiers }, 91 | replacingModifiers: { $0.with(\.modifiers, $1) }, 92 | visitChildren: super.visit 93 | ) 94 | } 95 | 96 | public override func visit(_ node: EnumDeclSyntax) -> DeclSyntax { 97 | visit( 98 | node, 99 | getDeclKeyword: { $0.enumKeyword }, 100 | getModifiers: { $0.modifiers }, 101 | replacingModifiers: { $0.with(\.modifiers, $1) }, 102 | visitChildren: super.visit 103 | ) 104 | } 105 | 106 | public override func visit(_ node: ExtensionDeclSyntax) -> DeclSyntax { 107 | visit( 108 | node, 109 | getDeclKeyword: { $0.extensionKeyword }, 110 | getModifiers: { $0.modifiers }, 111 | replacingModifiers: { $0.with(\.modifiers, $1) }, 112 | visitChildren: super.visit 113 | ) 114 | } 115 | 116 | public override func visit(_ node: TypeAliasDeclSyntax) -> DeclSyntax { 117 | visit( 118 | node, 119 | getDeclKeyword: { $0.typealiasKeyword }, 120 | getModifiers: { $0.modifiers }, 121 | replacingModifiers: { $0.with(\.modifiers, $1) }, 122 | visitChildren: nil 123 | ) 124 | } 125 | 126 | public override func visit(_ node: AssociatedTypeDeclSyntax) -> DeclSyntax { 127 | visit( 128 | node, 129 | getDeclKeyword: { $0.associatedtypeKeyword }, 130 | getModifiers: { $0.modifiers }, 131 | replacingModifiers: { $0.with(\.modifiers, $1) }, 132 | visitChildren: nil 133 | ) 134 | } 135 | 136 | public override func visit(_ node: ProtocolDeclSyntax) -> DeclSyntax { 137 | visit( 138 | node, 139 | getDeclKeyword: { $0.protocolKeyword }, 140 | getModifiers: { $0.modifiers }, 141 | replacingModifiers: { $0.with(\.modifiers, $1) }, 142 | visitChildren: nil 143 | ) 144 | } 145 | 146 | public override func visit(_ node: VariableDeclSyntax) -> DeclSyntax { 147 | visit( 148 | node, 149 | getDeclKeyword: { $0.bindingSpecifier }, 150 | getModifiers: { $0.modifiers }, 151 | replacingModifiers: { $0.with(\.modifiers, $1) }, 152 | visitChildren: nil 153 | ) 154 | } 155 | 156 | public override func visit(_ node: FunctionDeclSyntax) -> DeclSyntax { 157 | visit( 158 | node, 159 | getDeclKeyword: { $0.funcKeyword }, 160 | getModifiers: { $0.modifiers }, 161 | replacingModifiers: { $0.with(\.modifiers, $1) }, 162 | visitChildren: nil 163 | ) 164 | } 165 | 166 | public override func visit(_ node: SubscriptDeclSyntax) -> DeclSyntax { 167 | visit( 168 | node, 169 | getDeclKeyword: { $0.subscriptKeyword }, 170 | getModifiers: { $0.modifiers }, 171 | replacingModifiers: { $0.with(\.modifiers, $1) }, 172 | visitChildren: nil 173 | ) 174 | } 175 | 176 | public override func visit(_ node: InitializerDeclSyntax) -> DeclSyntax { 177 | visit( 178 | node, 179 | getDeclKeyword: { $0.initKeyword }, 180 | getModifiers: { $0.modifiers }, 181 | replacingModifiers: { $0.with(\.modifiers, $1) }, 182 | visitChildren: nil 183 | ) 184 | } 185 | } 186 | } 187 | 188 | private extension DefaultAccessLevelRule.Rewriter { 189 | struct Visit { 190 | var accessLevel: DefaultAccessLevelRule.AccessLebel? 191 | var extensionScopeAccessLebel: DefaultAccessLevelRule.AccessLebel? 192 | var canDeclOpen: Bool 193 | var canAssignAccessLevelToChildren: Bool 194 | 195 | var canOpenChildren: Bool { 196 | accessLevel == .openOrPublic && canDeclOpen && canAssignAccessLevelToChildren 197 | } 198 | } 199 | 200 | func visit( 201 | _ node: Node, 202 | getDeclKeyword: (Node) -> TokenSyntax, 203 | getModifiers: (Node) -> DeclModifierListSyntax?, 204 | replacingModifiers: (Node, DeclModifierListSyntax) -> Node, 205 | visitChildren: ((Node) -> DeclSyntax)? 206 | ) -> DeclSyntax { 207 | let implicitInternal = options.implicitInternal ?? true 208 | 209 | let modifiers = getModifiers(node) ?? DeclModifierListSyntax([]) 210 | let visitFinally = visitChildren ?? DeclSyntax.init 211 | let parentVisit = visitStack.top 212 | 213 | let modifierTokenToAssign: TokenSyntax? 214 | let actualAccessLevel: DefaultAccessLevelRule.AccessLebel? 215 | let canAssignAccessLevelToChildren: Bool 216 | 217 | if node is ExtensionDeclSyntax { 218 | modifierTokenToAssign = nil 219 | actualAccessLevel = modifiers.accessLevel 220 | canAssignAccessLevelToChildren = actualAccessLevel == nil 221 | } 222 | else if let accessLevel = modifiers.accessLevel { 223 | modifierTokenToAssign = nil 224 | actualAccessLevel = accessLevel 225 | canAssignAccessLevelToChildren = true 226 | } 227 | else if let parentVisit = parentVisit, !parentVisit.canAssignAccessLevelToChildren { 228 | modifierTokenToAssign = nil 229 | actualAccessLevel = modifiers.accessLevel 230 | canAssignAccessLevelToChildren = true 231 | } 232 | else { 233 | canAssignAccessLevelToChildren = true 234 | 235 | // Select assignable access level. 236 | let assumedAccessLevel = assignableAccessLevel() 237 | 238 | switch assumedAccessLevel { 239 | case .openOrPublic: 240 | // Indicating whether that can open this decralation in parent scope access level. 241 | let canOpenInParent = node is ClassDeclSyntax || (node.canOpen && parentVisit?.canOpenChildren ?? false) 242 | let shouldOpen = canOpenInParent && !modifiers.hasFinal && !modifiers.hasStatic 243 | modifierTokenToAssign = 244 | shouldOpen 245 | ? .keyword(.open) 246 | : .keyword(.public) 247 | actualAccessLevel = shouldOpen ? .openOrPublic : .public 248 | 249 | case .public: 250 | modifierTokenToAssign = .keyword(.public) 251 | actualAccessLevel = .public 252 | 253 | case .internal: 254 | modifierTokenToAssign = implicitInternal ? nil : .keyword(.internal) 255 | actualAccessLevel = .internal 256 | 257 | case .fileprivate: 258 | modifierTokenToAssign = .keyword(.fileprivate) 259 | actualAccessLevel = .fileprivate 260 | 261 | case .private: 262 | modifierTokenToAssign = .keyword(.private) 263 | actualAccessLevel = .private 264 | } 265 | } 266 | 267 | // Back to the parent stack after exit current scope. 268 | defer { visitStack.pop() } 269 | visitStack.push( 270 | Visit( 271 | accessLevel: actualAccessLevel, 272 | extensionScopeAccessLebel: node is ExtensionDeclSyntax 273 | ? actualAccessLevel 274 | : parentVisit?.extensionScopeAccessLebel, 275 | canDeclOpen: node.canOpen, 276 | canAssignAccessLevelToChildren: canAssignAccessLevelToChildren 277 | ) 278 | ) 279 | 280 | let modifier = modifierTokenToAssign.map { token in 281 | DeclModifierSyntax(name: token.with(\.trailingTrivia, .space)) 282 | } 283 | 284 | // If originally has modifiers. 285 | if let modifier = modifier, let firstModifier = modifiers.first, let firstModifierToken = firstModifier.firstToken(viewMode: .sourceAccurate) { 286 | // Prepends an access level modifier that exchanged the leading trivia. 287 | let (leading, trailing) = TokenSyntax.movingLeadingTrivia( 288 | leading: modifier, 289 | for: modifier.name, 290 | trailing: firstModifier, 291 | for: firstModifierToken 292 | ) 293 | let newModifiers = DeclModifierListSyntax([leading, trailing] + Array(modifiers.dropFirst())) 294 | return visitFinally(replacingModifiers(node, newModifiers)) 295 | } 296 | else if let modifier = modifier, let nodeToken = getDeclKeyword(node).firstToken(viewMode: .sourceAccurate) { 297 | // Assigns an access level modifier that exchanged the leading trivia. 298 | let (newModifier, newNode) = TokenSyntax.movingLeadingTrivia( 299 | leading: modifier, 300 | for: modifier.name, 301 | trailing: node, 302 | for: nodeToken 303 | ) 304 | let newModifiers = DeclModifierListSyntax([newModifier]) 305 | return visitFinally(replacingModifiers(newNode, newModifiers)) 306 | } 307 | else { 308 | return visitFinally(node) 309 | } 310 | } 311 | 312 | func assignableAccessLevel() -> DefaultAccessLevelRule.AccessLebel { 313 | let parentVisit = visitStack.top 314 | let scopeAccessLevel = parentVisit?.accessLevel ?? parentVisit?.extensionScopeAccessLebel 315 | 316 | guard let priorityAccessLevel = scopeAccessLevel else { 317 | return options.accessLevel 318 | } 319 | 320 | if priorityAccessLevel.priority >= options.accessLevel.priority { 321 | return options.accessLevel 322 | } 323 | else if priorityAccessLevel.priority < DefaultAccessLevelRule.AccessLebel.internal.priority { 324 | return .internal 325 | } 326 | else { 327 | return priorityAccessLevel 328 | } 329 | } 330 | } 331 | 332 | private extension DefaultAccessLevelRule.AccessLebel { 333 | var priority: Int { 334 | switch self { 335 | case .openOrPublic, .public: 336 | return 3 337 | 338 | case .internal: 339 | return 2 340 | 341 | case .fileprivate: 342 | return 1 343 | 344 | case .private: 345 | return 0 346 | } 347 | } 348 | } 349 | 350 | private extension DeclSyntaxProtocol { 351 | var canOpen: Bool { 352 | switch self { 353 | case is ClassDeclSyntax, is FunctionDeclSyntax, is SubscriptDeclSyntax: 354 | return true 355 | 356 | case let decl as VariableDeclSyntax: 357 | return decl.hasAccessor 358 | 359 | default: 360 | return false 361 | } 362 | } 363 | } 364 | 365 | private extension DeclModifierListSyntax { 366 | var accessLevel: DefaultAccessLevelRule.AccessLebel? { 367 | accessLevelModifier.flatMap { modifier in 368 | switch modifier.name.tokenKind { 369 | case .keyword(.open): 370 | return .openOrPublic 371 | 372 | case .keyword(.public): 373 | return .public 374 | 375 | case .keyword(.internal): 376 | return .internal 377 | 378 | case .keyword(.fileprivate): 379 | return .fileprivate 380 | 381 | case .keyword(.private): 382 | return .private 383 | 384 | default: 385 | return nil 386 | } 387 | } 388 | } 389 | } 390 | -------------------------------------------------------------------------------- /Sources/SwiftModRules/DefaultMemberwiseInitializerRule.swift: -------------------------------------------------------------------------------- 1 | import SwiftModCore 2 | import SwiftSyntax 3 | 4 | public final class DefaultMemberwiseInitializerRule: RuleDefinition { 5 | public static let description = RuleDescription( 6 | name: "defaultMemberwiseInitializer", 7 | priority: .low, 8 | overview: "Defines a memberwise initializer according to the access level in the type declaration if not present", 9 | exampleOptions: Options( 10 | implicitInitializer: false, 11 | implicitInternal: true, 12 | ignoreClassesWithInheritance: false 13 | ), 14 | exampleBefore: """ 15 | struct Foo { 16 | var foo: Int 17 | var bar: String? 18 | } 19 | 20 | struct Bar { 21 | var foo: Int 22 | 23 | // Not triggered if initializer is already present 24 | init() { 25 | self.foo = 100 26 | } 27 | } 28 | """, 29 | exampleAfter: """ 30 | struct Foo { 31 | var foo: Int 32 | var bar: String? 33 | 34 | init( 35 | foo: Int, 36 | bar: String? = nil 37 | ) { 38 | self.foo = foo 39 | self.bar = bar 40 | } 41 | } 42 | 43 | struct Bar { 44 | var foo: Int 45 | 46 | // Not triggered if initializer is already present 47 | init() { 48 | self.foo = 100 49 | } 50 | } 51 | """ 52 | ) 53 | 54 | public struct Options: Codable { 55 | public var implicitInitializer: Bool? 56 | public var implicitInternal: Bool? 57 | public var ignoreClassesWithInheritance: Bool? 58 | 59 | public init(implicitInitializer: Bool?, implicitInternal: Bool?, ignoreClassesWithInheritance: Bool?) { 60 | self.implicitInitializer = implicitInitializer 61 | self.implicitInternal = implicitInternal 62 | self.ignoreClassesWithInheritance = ignoreClassesWithInheritance 63 | } 64 | } 65 | 66 | public final class Rewriter: RuleSyntaxRewriter { 67 | public override func visit(_ node: ClassDeclSyntax) -> DeclSyntax { 68 | visit( 69 | node, 70 | getModifiers: { $0.modifiers }, 71 | getMembers: { $0.memberBlock }, 72 | replacingMembers: { $0.with(\.memberBlock, $1) }, 73 | visitChildren: super.visit 74 | ) 75 | } 76 | 77 | public override func visit(_ node: StructDeclSyntax) -> DeclSyntax { 78 | visit( 79 | node, 80 | getModifiers: { $0.modifiers }, 81 | getMembers: { $0.memberBlock }, 82 | replacingMembers: { $0.with(\.memberBlock, $1) }, 83 | visitChildren: super.visit 84 | ) 85 | } 86 | } 87 | } 88 | 89 | private extension DefaultMemberwiseInitializerRule.Rewriter { 90 | struct StoredProperty { 91 | var identifierPattern: IdentifierPatternSyntax 92 | var type: TypeSyntax 93 | var value: ExprSyntax? 94 | } 95 | 96 | func visit( 97 | _ node: Node, 98 | getModifiers: (Node) -> DeclModifierListSyntax?, 99 | getMembers: (Node) -> MemberBlockSyntax, 100 | replacingMembers: (Node, MemberBlockSyntax) -> Node, 101 | visitChildren: (Node) -> DeclSyntax 102 | ) -> DeclSyntax { 103 | let implicitInternal = options.implicitInternal ?? true 104 | let implicitInitializer = options.implicitInitializer ?? false 105 | let ignoreClassesWithInheritance = options.ignoreClassesWithInheritance ?? false 106 | 107 | let modifiers = getModifiers(node) 108 | let accessLevelModifier = modifiers?.accessLevelModifier? 109 | .trimmed 110 | .assignableToInitializer 111 | let members = getMembers(node) 112 | let memberList = members.members 113 | 114 | let storedProperties: [StoredProperty] = memberList.compactMap { item in 115 | guard let variableDecl = item.decl.as(VariableDeclSyntax.self) else { 116 | return nil 117 | } 118 | 119 | let hasStatic = variableDecl.modifiers.hasStatic 120 | let hasAccessor = variableDecl.hasAccessor 121 | let value = variableDecl.value 122 | // The variable that defined as `let` and already initialized once is not need a initializer parameter.. 123 | let isAlreadyInitialized = variableDecl.bindingSpecifier.isLet && value != nil 124 | 125 | guard !hasStatic && !hasAccessor && !isAlreadyInitialized, 126 | let identifierPattern = variableDecl.identifier?.trimmed, 127 | let type = variableDecl.typeAnnotation?.trimmed.type.transformed() 128 | else { 129 | return nil 130 | } 131 | 132 | return StoredProperty( 133 | identifierPattern: identifierPattern, 134 | type: type, 135 | value: value ?? (type.isOptional ? ExprSyntax(NilLiteralExprSyntax(nilKeyword: .keyword(.nil))) : nil) 136 | ) 137 | } 138 | 139 | // Indicating whether use default implicit initializer. 140 | let shouldSkipStructImplicitInitializer = node is StructDeclSyntax && implicitInitializer && accessLevelModifier?.name.isInternal ?? true 141 | let shouldSkipClassImplicitInitializer = node is ClassDeclSyntax && implicitInitializer && accessLevelModifier?.name.isInternal ?? true && storedProperties.isEmpty 142 | let shouldSkipClassWithInheritance = ignoreClassesWithInheritance && (node as? ClassDeclSyntax).map { $0.inheritanceClause != nil } ?? false 143 | let isInitializerExists = memberList.contains { $0.decl.is(InitializerDeclSyntax.self) } 144 | 145 | if shouldSkipStructImplicitInitializer || shouldSkipClassImplicitInitializer || shouldSkipClassWithInheritance || isInitializerExists { 146 | return visitChildren(node) 147 | } 148 | 149 | let parentIndentTrivia = node.firstToken(viewMode: .sourceAccurate)?.leadingTrivia.indentation ?? Trivia() 150 | let indentTrivia = parentIndentTrivia + format.indent.trivia 151 | let parameterIndentTrivia = indentTrivia + format.indent.trivia 152 | let shouldLineBreakParameters = format.lineBreakBeforeEachArgument && storedProperties.count > 1 153 | 154 | // Make parameter clause. 155 | let parameterClause = FunctionParameterClauseSyntax( 156 | leftParen: .leftParenToken(), 157 | parameters: FunctionParameterListSyntax( 158 | storedProperties.indices.map { index in 159 | let property = storedProperties[index] 160 | let isLast = index == storedProperties.index(before: storedProperties.endIndex) 161 | return FunctionParameterSyntax( 162 | firstName: property.identifierPattern.identifier.withLeadingTrivia( 163 | .newline + parameterIndentTrivia + property.identifierPattern.identifier.leadingTrivia, 164 | condition: shouldLineBreakParameters 165 | ), 166 | colon: .colonToken(trailingTrivia: .space), 167 | // Assings the attributes to type if needed. 168 | type: property.type.attributed(), 169 | defaultValue: property.value.map { value in 170 | InitializerClauseSyntax( 171 | equal: .equalToken(leadingTrivia: .space, trailingTrivia: .space), 172 | value: value 173 | ) 174 | }, 175 | trailingComma: isLast 176 | ? nil 177 | : .commaToken().withTrailingTrivia(.space, condition: !shouldLineBreakParameters) 178 | ) 179 | } 180 | ), 181 | rightParen: .rightParenToken() 182 | .withLeadingTrivia(.newline + indentTrivia, condition: shouldLineBreakParameters) 183 | ) 184 | 185 | // Make initializer code block. 186 | let initializerCodeBlock = CodeBlockSyntax( 187 | leftBrace: .leftBraceToken( 188 | leadingTrivia: .space, 189 | trailingTrivia: storedProperties.isEmpty ? [] : .newline 190 | ), 191 | statements: CodeBlockItemListSyntax( 192 | storedProperties.map { property in 193 | CodeBlockItemSyntax( 194 | item: .expr( 195 | ExprSyntax( 196 | SequenceExprSyntax( 197 | elements: ExprListSyntax([ 198 | ExprSyntax( 199 | MemberAccessExprSyntax( 200 | base: ExprSyntax( 201 | DeclReferenceExprSyntax( 202 | baseName: .keyword(.self).with(\.leadingTrivia, parameterIndentTrivia) 203 | ) 204 | ), 205 | period: .periodToken(), 206 | declName: DeclReferenceExprSyntax( 207 | baseName: property.identifierPattern 208 | .withoutBackticks() 209 | .identifier 210 | .trimmed 211 | ) 212 | ) 213 | ), 214 | ExprSyntax( 215 | AssignmentExprSyntax( 216 | equal: .equalToken( 217 | leadingTrivia: .space, 218 | trailingTrivia: .space 219 | ) 220 | ) 221 | ), 222 | ExprSyntax( 223 | DeclReferenceExprSyntax( 224 | baseName: property.identifierPattern.identifier.appendingTrailingTrivia(.newline) 225 | ) 226 | ), 227 | ]) 228 | ) 229 | ) 230 | ) 231 | ) 232 | } 233 | ), 234 | rightBrace: .rightBraceToken() 235 | .withLeadingTrivia(indentTrivia, condition: !storedProperties.isEmpty) 236 | ) 237 | 238 | // Use default access level modifier or make new internal access level modifier if not present. 239 | let newAcessLevelModifier = (accessLevelModifier ?? DeclModifierSyntax(name: .keyword(.internal))) 240 | .with(\.leadingTrivia, indentTrivia) 241 | .with(\.trailingTrivia, .space) 242 | // Indicating whether to assign internal access level explicitly. 243 | let skipAccessLevel = newAcessLevelModifier.name.isInternal && implicitInternal 244 | 245 | // Make initializer declaration. 246 | let initializerDecl = InitializerDeclSyntax( 247 | modifiers: skipAccessLevel ? [] : DeclModifierListSyntax([newAcessLevelModifier]), 248 | initKeyword: .keyword(.`init`).withLeadingTrivia(indentTrivia, condition: skipAccessLevel), 249 | signature: FunctionSignatureSyntax(parameterClause: parameterClause), 250 | body: initializerCodeBlock 251 | ) 252 | 253 | // Make member declatation list. 254 | let member = MemberBlockItemSyntax(decl: DeclSyntax(initializerDecl)) 255 | 256 | // If originally has members. 257 | if let lastMemberToken = memberList.lastToken(viewMode: .sourceAccurate) { 258 | let newMembers = members.with(\.members, TokenSyntax.replacingTrivia(memberList, for: lastMemberToken, trailing: .newlines(2)) + [member]) 259 | let newNode = replacingMembers(node, newMembers) 260 | return visitChildren(newNode) 261 | } 262 | else { 263 | let leftBrace = members.leftBrace.withTrailingNewLinews(count: 1) 264 | let rightBrace = members.rightBrace.with(\.leadingTrivia, .newline + parentIndentTrivia) 265 | var newMembers = members 266 | newMembers.members = members.members + [member] 267 | let newNode = replacingMembers( 268 | node, 269 | newMembers 270 | .with(\.leftBrace, leftBrace) 271 | .with(\.rightBrace, rightBrace) 272 | ) 273 | return visitChildren(newNode) 274 | } 275 | } 276 | } 277 | 278 | private extension TokenSyntax { 279 | var isLet: Bool { 280 | tokenKind == .keyword(.let) 281 | } 282 | 283 | var isInternal: Bool { 284 | tokenKind == .keyword(.internal) 285 | } 286 | 287 | func withTrailingNewLinews(count: Int) -> TokenSyntax { 288 | let newlines = trailingTrivia.numberOfNewlines 289 | return newlines >= count ? self : with(\.trailingTrivia, .newlines(count - newlines)) 290 | } 291 | 292 | func withLeadingNewlines(count: Int) -> TokenSyntax { 293 | let newlines = leadingTrivia.numberOfNewlines 294 | return newlines >= count ? self : with(\.leadingTrivia, .newlines(count - newlines)) 295 | } 296 | } 297 | 298 | private extension DeclModifierSyntax { 299 | var assignableToInitializer: DeclModifierSyntax? { 300 | switch name.tokenKind { 301 | case .keyword(.open): 302 | return with(\.name, .keyword(.public)) 303 | 304 | case .keyword(.public): 305 | return self 306 | 307 | default: 308 | return nil 309 | } 310 | } 311 | } 312 | 313 | private extension TypeSyntax { 314 | func transformed() -> TypeSyntax { 315 | if let iuo = self.as(ImplicitlyUnwrappedOptionalTypeSyntax.self) { 316 | return TypeSyntax( 317 | OptionalTypeSyntax( 318 | wrappedType: iuo.wrappedType, 319 | questionMark: .postfixQuestionMarkToken() 320 | ) 321 | ) 322 | } 323 | else { 324 | return self 325 | } 326 | } 327 | 328 | func attributed() -> TypeSyntax { 329 | if self.is(FunctionTypeSyntax.self) { 330 | return TypeSyntax( 331 | AttributedTypeSyntax( 332 | attributes: AttributeListSyntax([ 333 | .attribute( 334 | AttributeSyntax( 335 | atSign: .atSignToken(), 336 | attributeName: IdentifierTypeSyntax(name: .identifier("escaping")) 337 | .with(\.trailingTrivia, .space) 338 | ) 339 | ) 340 | ]), 341 | baseType: self 342 | ) 343 | ) 344 | } 345 | else { 346 | return self 347 | } 348 | } 349 | } 350 | -------------------------------------------------------------------------------- /Sources/swift-mod/SwiftMod.swift: -------------------------------------------------------------------------------- 1 | import ArgumentParser 2 | import SwiftModCommands 3 | 4 | @main 5 | struct SwiftMod: ParsableCommand { 6 | static var configuration = CommandConfiguration( 7 | commandName: "swift-mod", 8 | abstract: "Modifies Swift source code with rules", 9 | subcommands: [ 10 | RunCommand.self, 11 | InitCommand.self, 12 | RulesCommand.self, 13 | ], 14 | defaultSubcommand: RunCommand.self 15 | ) 16 | } 17 | -------------------------------------------------------------------------------- /Tests/SwiftModCommandsTests/Configuration+CodableTests.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | import SwiftModCore 3 | import XCTest 4 | import Yams 5 | 6 | func assertConfigurationCoding(_ configuration: Configuration, file: StaticString = #file, line: UInt = #line) { 7 | do { 8 | let encoded = try YAMLEncoder().encode(configuration) 9 | let decoded = try YAMLDecoder().decode(Configuration.self, from: encoded) 10 | 11 | XCTAssertEqual(configuration.format, decoded.format, file: file, line: line) 12 | XCTAssertEqual(configuration.rules.count, decoded.rules.count, file: file, line: line) 13 | } 14 | catch { 15 | XCTFail("\(error)", file: file, line: line) 16 | } 17 | } 18 | 19 | final class ConfigurationCodableTests: XCTestCase { 20 | func testTemplateCodable() throws { 21 | assertConfigurationCoding(.template) 22 | } 23 | 24 | func testNilFormatCodable() { 25 | let configuration = Configuration(format: nil, rules: []) 26 | assertConfigurationCoding(configuration) 27 | } 28 | 29 | func testTabFormatCodable() { 30 | let configuration = Configuration( 31 | format: Format( 32 | indent: .tab, 33 | lineBreakBeforeEachArgument: nil 34 | ), 35 | rules: [] 36 | ) 37 | assertConfigurationCoding(configuration) 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Tests/SwiftModCommandsTests/InitCommandRunnerTests.swift: -------------------------------------------------------------------------------- 1 | import SwiftModCore 2 | import TSCBasic 3 | import XCTest 4 | import Yams 5 | 6 | @testable import SwiftModCommands 7 | 8 | final class InitCommandTests: XCTestCase { 9 | func testRun() throws { 10 | let fileSystem = InMemoryFileSystem() 11 | let fileManager = InMemoryFileManager(fileSystem: fileSystem) 12 | let output = try AbsolutePath(validating: "/home/cwd/output/.swift-mod.yml") 13 | let runner = InitCommandRunner( 14 | output: output, 15 | fileSystem: fileSystem, 16 | fileManager: fileManager 17 | ) 18 | 19 | try runner.run() 20 | 21 | XCTAssertEqual( 22 | try fileSystem.readFileContents(output), 23 | ByteString(encodingAsUTF8: try YAMLEncoder().encode(Configuration.template)) 24 | ) 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Tests/SwiftModCommandsTests/RulesCommandRunnerTests.swift: -------------------------------------------------------------------------------- 1 | import SwiftModCore 2 | import SwiftModRules 3 | import XCTest 4 | 5 | @testable import SwiftModCommands 6 | 7 | final class RulesCommandTests: XCTestCase { 8 | func testRun() throws { 9 | let writer = InMemoryInteractiveWriter() 10 | let runner = RulesCommandRunner( 11 | rule: nil, 12 | writer: writer 13 | ) 14 | 15 | try runner.run() 16 | 17 | XCTAssertEqual( 18 | writer.inputs, 19 | runner.overviewLines().map { 20 | InMemoryInteractiveWriter.Input(string: $0, color: .noColor, bold: false) 21 | } 22 | ) 23 | } 24 | 25 | func testRunWithDetail() throws { 26 | let writer = InMemoryInteractiveWriter() 27 | let ruleName = DefaultAccessLevelRule.description.name 28 | let runner = RulesCommandRunner(rule: ruleName, writer: writer) 29 | 30 | try runner.run() 31 | 32 | XCTAssertEqual( 33 | writer.inputs, 34 | try runner.definitionLines(ruleName: ruleName).map { 35 | InMemoryInteractiveWriter.Input(string: $0, color: .noColor, bold: false) 36 | } 37 | ) 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Tests/SwiftModCommandsTests/RunCommandRunnerTests.swift: -------------------------------------------------------------------------------- 1 | import SwiftModCore 2 | import SwiftModRules 3 | import TSCBasic 4 | import XCTest 5 | import Yams 6 | 7 | @testable import SwiftModCommands 8 | 9 | final class RunCommandRunnerTests: XCTestCase { 10 | func testRun() throws { 11 | let fileSystem = InMemoryFileSystem() 12 | let fileManager = InMemoryFileManager(fileSystem: fileSystem) 13 | let measure = Measure { Date(timeIntervalSince1970: 0) } 14 | let format = Format( 15 | indent: .spaces(4), 16 | lineBreakBeforeEachArgument: true 17 | ) 18 | let configuration = Configuration( 19 | format: format, 20 | rules: [ 21 | DefaultAccessLevelRule( 22 | options: DefaultAccessLevelRule.Options( 23 | accessLevel: .public, 24 | implicitInternal: false 25 | ), 26 | format: format 27 | ) 28 | ] 29 | ) 30 | let configurationPath = try AbsolutePath(validating: "/home/cwd/.swift-mod.yml") 31 | 32 | try fileSystem.createDirectory(AbsolutePath(validating: "/home/cwd/test"), recursive: true) 33 | try fileSystem.writeFileContents( 34 | configurationPath, 35 | bytes: ByteString(encodingAsUTF8: try YAMLEncoder().encode(configuration)) 36 | ) 37 | try fileSystem.writeFileContents( 38 | AbsolutePath(validating: "/home/cwd/test/file1.swift"), 39 | bytes: #"let cat = "meow""# 40 | ) 41 | try fileSystem.writeFileContents( 42 | AbsolutePath(validating: "/home/cwd/test/file2.swift"), 43 | bytes: #"let dog = "woof""# 44 | ) 45 | 46 | let runner = try RunCommandRunner( 47 | configuration: configurationPath, 48 | mode: .modify, 49 | paths: [ 50 | AbsolutePath(validating: "/home/cwd/test/file1.swift"), 51 | AbsolutePath(validating: "/home/cwd/test/file2.swift"), 52 | ], 53 | fileSystem: fileSystem, 54 | fileManager: fileManager, 55 | measure: measure 56 | ) 57 | try runner.run() 58 | 59 | XCTAssertEqual( 60 | try fileSystem.readFileContents(AbsolutePath(validating: "/home/cwd/test/file1.swift")), 61 | #"public let cat = "meow""# 62 | ) 63 | XCTAssertEqual( 64 | try fileSystem.readFileContents(AbsolutePath(validating: "/home/cwd/test/file2.swift")), 65 | #"public let dog = "woof""# 66 | ) 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /Tests/SwiftModCoreTests/RuleSyntaxRewriterTests.swift: -------------------------------------------------------------------------------- 1 | import SwiftModCore 2 | import SwiftSyntax 3 | import XCTest 4 | 5 | final class RuleSyntaxRewriterTests: XCTestCase { 6 | let testRule = RuleSyntaxRewriter(name: "test", options: 0, format: .default) 7 | 8 | func testIgnoreCommentForMemberDeclListItem() { 9 | let node = MemberBlockItemSyntax( 10 | decl: DeclSyntax( 11 | VariableDeclSyntax( 12 | bindingSpecifier: .keyword(.let), 13 | bindings: PatternBindingListSyntax([ 14 | PatternBindingSyntax( 15 | pattern: PatternSyntax( 16 | IdentifierPatternSyntax( 17 | identifier: .identifier("test") 18 | ) 19 | ), 20 | initializer: InitializerClauseSyntax( 21 | equal: .equalToken(), 22 | value: ExprSyntax(IntegerLiteralExprSyntax(literal: .integerLiteral("100"))) 23 | ) 24 | ) 25 | ]) 26 | ) 27 | ) 28 | ) 29 | 30 | let notIgnoreNode = testRule.visitAny(Syntax(node)) 31 | let ignoreTestNode = testRule.visitAny(Syntax(node.with(\.leadingTrivia, .lineComment("swift-mod-ignore: test")))) 32 | let ignoreOtherNode = testRule.visitAny(Syntax(node.with(\.leadingTrivia, .lineComment("swift-mod-ignore: other")))) 33 | let ignoreAllNode = testRule.visitAny(Syntax(node.with(\.leadingTrivia, .lineComment("swift-mod-ignore")))) 34 | 35 | XCTAssertNil(notIgnoreNode) 36 | XCTAssertNotNil(ignoreTestNode) 37 | XCTAssertNil(ignoreOtherNode) 38 | XCTAssertNotNil(ignoreAllNode) 39 | } 40 | 41 | func testIgnoreCommentForCodeBlockItem() { 42 | let node = CodeBlockItemSyntax( 43 | item: .expr(ExprSyntax(DeclReferenceExprSyntax(baseName: .identifier("test")))) 44 | ) 45 | 46 | let notIgnoreNode = testRule.visitAny(Syntax(node)) 47 | let ignoreTestNode = testRule.visitAny(Syntax(node.with(\.leadingTrivia, .lineComment("swift-mod-ignore: test")))) 48 | let ignoreOtherNode = testRule.visitAny(Syntax(node.with(\.leadingTrivia, .lineComment("swift-mod-ignore: other")))) 49 | let ignoreAllNode = testRule.visitAny(Syntax(node.with(\.leadingTrivia, .lineComment("swift-mod-ignore")))) 50 | 51 | XCTAssertNil(notIgnoreNode) 52 | XCTAssertNotNil(ignoreTestNode) 53 | XCTAssertNil(ignoreOtherNode) 54 | XCTAssertNotNil(ignoreAllNode) 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Tests/SwiftModRulesTests/DefaultAccessLevelRuleTests.swift: -------------------------------------------------------------------------------- 1 | import SwiftModRules 2 | import XCTest 3 | 4 | final class DefaultAccessLevelRuleTests: XCTestCase { 5 | let defaultRule = DefaultAccessLevelRule( 6 | options: DefaultAccessLevelRule.Options( 7 | accessLevel: .openOrPublic, 8 | implicitInternal: true 9 | ), 10 | format: .default 11 | ) 12 | 13 | func testDescription() throws { 14 | try assertRuleDescription(defaultRule) 15 | } 16 | 17 | func testIgnore() throws { 18 | try assertRule( 19 | defaultRule, 20 | source: """ 21 | // swift-mod-ignore: defaultAccessLevel 22 | struct Struct {} 23 | // swift-mod-ignore: defaultAccessLevel 24 | let variable = 0 25 | class Class { 26 | // swift-mod-ignore: defaultAccessLevel 27 | var property = 0 28 | } 29 | """, 30 | expected: """ 31 | // swift-mod-ignore: defaultAccessLevel 32 | struct Struct {} 33 | // swift-mod-ignore: defaultAccessLevel 34 | let variable = 0 35 | open class Class { 36 | // swift-mod-ignore: defaultAccessLevel 37 | var property = 0 38 | } 39 | """ 40 | ) 41 | } 42 | 43 | func testStruct() throws { 44 | try assertRule( 45 | defaultRule, 46 | source: """ 47 | @available(swift 5.1) 48 | struct Struct { 49 | typealias TypeAlias = Int 50 | static let staticStored = 0 51 | static func staticFunction() -> Int { 0 } 52 | var stored: Int 53 | var computed: Int { 0 } 54 | internal var internalProperty: Int 55 | func function(value: Int) -> Int { value } 56 | subscript (value: Int) -> Int { value } 57 | init(variable: Int) { self.variable = variable } 58 | } 59 | """, 60 | expected: """ 61 | @available(swift 5.1) 62 | public struct Struct { 63 | public typealias TypeAlias = Int 64 | public static let staticStored = 0 65 | public static func staticFunction() -> Int { 0 } 66 | public var stored: Int 67 | public var computed: Int { 0 } 68 | internal var internalProperty: Int 69 | public func function(value: Int) -> Int { value } 70 | public subscript (value: Int) -> Int { value } 71 | public init(variable: Int) { self.variable = variable } 72 | } 73 | """ 74 | ) 75 | } 76 | 77 | func testStructNested() throws { 78 | try assertRule( 79 | defaultRule, 80 | source: """ 81 | struct Struct { 82 | struct Nested { 83 | var stored: Int 84 | } 85 | } 86 | """, 87 | expected: """ 88 | public struct Struct { 89 | public struct Nested { 90 | public var stored: Int 91 | } 92 | } 93 | """ 94 | ) 95 | } 96 | 97 | func testStructNotTriggered() throws { 98 | try assertRule( 99 | defaultRule, 100 | source: """ 101 | internal struct Struct { 102 | struct Nested { 103 | var stored: Int 104 | } 105 | var stored: Int 106 | } 107 | """, 108 | expected: """ 109 | internal struct Struct { 110 | struct Nested { 111 | var stored: Int 112 | } 113 | var stored: Int 114 | } 115 | """ 116 | ) 117 | } 118 | 119 | func testClass() throws { 120 | try assertRule( 121 | defaultRule, 122 | source: """ 123 | @available(swift 5.1) 124 | class Class { 125 | typealias TypeAlias = Int 126 | static let staticStored = 0 127 | static func staticFunction() -> Int { 0 } 128 | var stored: Int 129 | var computed: Int { 0 } 130 | internal var internalProperty: Int 131 | func function(value: Int) -> Int { value } 132 | final func finalFunction(value: Int) -> Int { value } 133 | subscript (value: Int) -> Int { value } 134 | init(variable: Int) { self.variable = variable } 135 | } 136 | """, 137 | expected: """ 138 | @available(swift 5.1) 139 | open class Class { 140 | public typealias TypeAlias = Int 141 | public static let staticStored = 0 142 | public static func staticFunction() -> Int { 0 } 143 | public var stored: Int 144 | open var computed: Int { 0 } 145 | internal var internalProperty: Int 146 | open func function(value: Int) -> Int { value } 147 | public final func finalFunction(value: Int) -> Int { value } 148 | open subscript (value: Int) -> Int { value } 149 | public init(variable: Int) { self.variable = variable } 150 | } 151 | """ 152 | ) 153 | } 154 | 155 | func testClassFinal() throws { 156 | try assertRule( 157 | defaultRule, 158 | source: """ 159 | @available(swift 5.1) 160 | final class Class { 161 | var stored: Int 162 | var computed: Int { 0 } 163 | } 164 | """, 165 | expected: """ 166 | @available(swift 5.1) 167 | public final class Class { 168 | public var stored: Int 169 | public var computed: Int { 0 } 170 | } 171 | """ 172 | ) 173 | } 174 | 175 | func testClassNested() throws { 176 | try assertRule( 177 | defaultRule, 178 | source: """ 179 | class Class { 180 | class Nested { 181 | var stored: Int 182 | } 183 | } 184 | """, 185 | expected: """ 186 | open class Class { 187 | open class Nested { 188 | public var stored: Int 189 | } 190 | } 191 | """ 192 | ) 193 | } 194 | 195 | func testClassInternalNotTriggered() throws { 196 | try assertRule( 197 | defaultRule, 198 | source: """ 199 | internal class Class { 200 | class Nested { 201 | var stored: Int 202 | } 203 | var stored: Int 204 | } 205 | """, 206 | expected: """ 207 | internal class Class { 208 | class Nested { 209 | var stored: Int 210 | } 211 | var stored: Int 212 | } 213 | """ 214 | ) 215 | } 216 | 217 | func testClassOpenNotTriggered() throws { 218 | try assertRule( 219 | defaultRule, 220 | source: """ 221 | open class Class {} 222 | """, 223 | expected: """ 224 | open class Class {} 225 | """ 226 | ) 227 | } 228 | 229 | func testActor() throws { 230 | try assertRule( 231 | defaultRule, 232 | source: """ 233 | @available(swift 5.1) 234 | actor Actor { 235 | typealias TypeAlias = Int 236 | static let staticStored = 0 237 | static func staticFunction() -> Int { 0 } 238 | var stored: Int 239 | var computed: Int { 0 } 240 | internal var internalProperty: Int 241 | func function(value: Int) -> Int { value } 242 | subscript (value: Int) -> Int { value } 243 | init(variable: Int) { self.variable = variable } 244 | } 245 | """, 246 | expected: """ 247 | @available(swift 5.1) 248 | public actor Actor { 249 | public typealias TypeAlias = Int 250 | public static let staticStored = 0 251 | public static func staticFunction() -> Int { 0 } 252 | public var stored: Int 253 | public var computed: Int { 0 } 254 | internal var internalProperty: Int 255 | public func function(value: Int) -> Int { value } 256 | public subscript (value: Int) -> Int { value } 257 | public init(variable: Int) { self.variable = variable } 258 | } 259 | """ 260 | ) 261 | } 262 | 263 | func testActorNested() throws { 264 | try assertRule( 265 | defaultRule, 266 | source: """ 267 | actor Actor { 268 | actor Nested { 269 | var stored: Int 270 | } 271 | } 272 | """, 273 | expected: """ 274 | public actor Actor { 275 | public actor Nested { 276 | public var stored: Int 277 | } 278 | } 279 | """ 280 | ) 281 | } 282 | 283 | func testActorNotTriggered() throws { 284 | try assertRule( 285 | defaultRule, 286 | source: """ 287 | internal actor Actor { 288 | actor Nested { 289 | var stored: Int 290 | } 291 | var stored: Int 292 | } 293 | """, 294 | expected: """ 295 | internal actor Actor { 296 | actor Nested { 297 | var stored: Int 298 | } 299 | var stored: Int 300 | } 301 | """ 302 | ) 303 | } 304 | 305 | func testEnum() throws { 306 | try assertRule( 307 | defaultRule, 308 | source: """ 309 | @available(swift 5.1) 310 | enum Enum { 311 | typealias TypeAlias = Int 312 | static let staticStored = 0 313 | static func staticFunction() -> Int { 0 } 314 | var computed: Int { 0 } 315 | internal var internalComputed: Int { 0 } 316 | func function(value: Int) -> Int { value } 317 | subscript (value: Int) -> Int { value } 318 | init() {} 319 | } 320 | """, 321 | expected: """ 322 | @available(swift 5.1) 323 | public enum Enum { 324 | public typealias TypeAlias = Int 325 | public static let staticStored = 0 326 | public static func staticFunction() -> Int { 0 } 327 | public var computed: Int { 0 } 328 | internal var internalComputed: Int { 0 } 329 | public func function(value: Int) -> Int { value } 330 | public subscript (value: Int) -> Int { value } 331 | public init() {} 332 | } 333 | """ 334 | ) 335 | } 336 | 337 | func testEnumNested() throws { 338 | try assertRule( 339 | defaultRule, 340 | source: """ 341 | enum Enum { 342 | enum Nested { 343 | case case1 344 | } 345 | } 346 | """, 347 | expected: """ 348 | public enum Enum { 349 | public enum Nested { 350 | case case1 351 | } 352 | } 353 | """ 354 | ) 355 | } 356 | 357 | func testEnumNotTriggered() throws { 358 | try assertRule( 359 | defaultRule, 360 | source: """ 361 | internal enum Enum { 362 | enum Nested { 363 | case case1 364 | } 365 | } 366 | """, 367 | expected: """ 368 | internal enum Enum { 369 | enum Nested { 370 | case case1 371 | } 372 | } 373 | """ 374 | ) 375 | } 376 | 377 | func testProtocol() throws { 378 | try assertRule( 379 | defaultRule, 380 | source: """ 381 | @available(swift 5.1) 382 | protocol Protocol { 383 | associatedtype AssociatedType 384 | static var staticStored: Int { get } 385 | static func staticFunction() -> Int 386 | var property: Int { get } 387 | func function(value: Int) -> Int 388 | subscript (value: Int) -> Int 389 | init() 390 | } 391 | """, 392 | expected: """ 393 | @available(swift 5.1) 394 | public protocol Protocol { 395 | associatedtype AssociatedType 396 | static var staticStored: Int { get } 397 | static func staticFunction() -> Int 398 | var property: Int { get } 399 | func function(value: Int) -> Int 400 | subscript (value: Int) -> Int 401 | init() 402 | } 403 | """ 404 | ) 405 | } 406 | 407 | func testProtocolNotTriggered() throws { 408 | try assertRule( 409 | defaultRule, 410 | source: """ 411 | internal protocol Protocol {} 412 | """, 413 | expected: """ 414 | internal protocol Protocol {} 415 | """ 416 | ) 417 | } 418 | 419 | func testExtensionHasAccessLebel() throws { 420 | try assertRule( 421 | defaultRule, 422 | source: """ 423 | @available(swift 5.1) 424 | extension Extension { 425 | typealias TypeAlias = Int 426 | static let staticStored = 0 427 | static func staticFunction() -> Int { 0 } 428 | var computed: Int { 0 } 429 | internal var internalProperty: Int 430 | func function(value: Int) -> Int { value } 431 | subscript (value: Int) -> Int { value } 432 | init() {} 433 | } 434 | """, 435 | expected: """ 436 | @available(swift 5.1) 437 | extension Extension { 438 | public typealias TypeAlias = Int 439 | public static let staticStored = 0 440 | public static func staticFunction() -> Int { 0 } 441 | public var computed: Int { 0 } 442 | internal var internalProperty: Int 443 | public func function(value: Int) -> Int { value } 444 | public subscript (value: Int) -> Int { value } 445 | public init() {} 446 | } 447 | """ 448 | ) 449 | } 450 | 451 | func testExtensionHasNoAccessLebel() throws { 452 | try assertRule( 453 | defaultRule, 454 | source: """ 455 | @available(swift 5.1) 456 | public extension Extension { 457 | typealias TypeAlias = Int 458 | static let staticStored = 0 459 | static func staticFunction() -> Int { 0 } 460 | var computed: Int { 0 } 461 | internal var internalProperty: Int 462 | func function(value: Int) -> Int { value } 463 | subscript (value: Int) -> Int { value } 464 | init() {} 465 | } 466 | """, 467 | expected: """ 468 | @available(swift 5.1) 469 | public extension Extension { 470 | typealias TypeAlias = Int 471 | static let staticStored = 0 472 | static func staticFunction() -> Int { 0 } 473 | var computed: Int { 0 } 474 | internal var internalProperty: Int 475 | func function(value: Int) -> Int { value } 476 | subscript (value: Int) -> Int { value } 477 | init() {} 478 | } 479 | """ 480 | ) 481 | } 482 | 483 | func testExtensionNestedHasAccessLebel() throws { 484 | try assertRule( 485 | defaultRule, 486 | source: """ 487 | extension Extension { 488 | struct Struct { 489 | var stored: Int 490 | } 491 | private struct PrivateStruct { 492 | var stored: Int 493 | } 494 | class Class { 495 | var stored: Int 496 | } 497 | enum Enum { 498 | var computed: Int { 0 } 499 | } 500 | } 501 | """, 502 | expected: """ 503 | extension Extension { 504 | public struct Struct { 505 | public var stored: Int 506 | } 507 | private struct PrivateStruct { 508 | var stored: Int 509 | } 510 | open class Class { 511 | public var stored: Int 512 | } 513 | public enum Enum { 514 | public var computed: Int { 0 } 515 | } 516 | } 517 | """ 518 | ) 519 | } 520 | 521 | func testExtensionNestedHasNoAccessLebel() throws { 522 | try assertRule( 523 | defaultRule, 524 | source: """ 525 | public extension Extension { 526 | struct Struct { 527 | var stored: Int 528 | } 529 | private struct PrivateStruct { 530 | var stored: Int 531 | } 532 | class Class { 533 | var stored: Int 534 | } 535 | enum Enum { 536 | var computed: Int { 0 } 537 | } 538 | } 539 | """, 540 | expected: """ 541 | public extension Extension { 542 | struct Struct { 543 | public var stored: Int 544 | } 545 | private struct PrivateStruct { 546 | var stored: Int 547 | } 548 | class Class { 549 | public var stored: Int 550 | } 551 | enum Enum { 552 | public var computed: Int { 0 } 553 | } 554 | } 555 | """ 556 | ) 557 | } 558 | 559 | func testExtensionNotTriggered() throws { 560 | try assertRule( 561 | defaultRule, 562 | source: """ 563 | internal extension Extension { 564 | var property: Int { get } 565 | } 566 | """, 567 | expected: """ 568 | internal extension Extension { 569 | var property: Int { get } 570 | } 571 | """ 572 | ) 573 | } 574 | 575 | func testTopLevelVariable() throws { 576 | try assertRule( 577 | defaultRule, 578 | source: """ 579 | let topLevelVariable = 0 580 | internal let internalTopLevelVariable = 0 581 | """, 582 | expected: """ 583 | public let topLevelVariable = 0 584 | internal let internalTopLevelVariable = 0 585 | """ 586 | ) 587 | } 588 | 589 | func testTopLevelFuction() throws { 590 | try assertRule( 591 | defaultRule, 592 | source: """ 593 | func topLevelFunction() {} 594 | internal func internalTopLevelFunction() {} 595 | """, 596 | expected: """ 597 | public func topLevelFunction() {} 598 | internal func internalTopLevelFunction() {} 599 | """ 600 | ) 601 | } 602 | 603 | func testPrivate() throws { 604 | try assertRule( 605 | defaultRule, 606 | source: """ 607 | private struct Struct { 608 | class Nested { 609 | var stored: Int 610 | } 611 | var stored: Int 612 | } 613 | """, 614 | expected: """ 615 | private struct Struct { 616 | class Nested { 617 | var stored: Int 618 | } 619 | var stored: Int 620 | } 621 | """ 622 | ) 623 | } 624 | 625 | func testFilePrivate() throws { 626 | try assertRule( 627 | defaultRule, 628 | source: """ 629 | fileprivate struct Struct { 630 | class Nested { 631 | var stored: Int 632 | } 633 | var stored: Int 634 | } 635 | """, 636 | expected: """ 637 | fileprivate struct Struct { 638 | class Nested { 639 | var stored: Int 640 | } 641 | var stored: Int 642 | } 643 | """ 644 | ) 645 | } 646 | } 647 | -------------------------------------------------------------------------------- /Tests/SwiftModRulesTests/DefaultMemberwiseInitializerRuleTests.swift: -------------------------------------------------------------------------------- 1 | import SwiftModCore 2 | import SwiftModRules 3 | import XCTest 4 | 5 | final class DefaultMemberwiseInitializerRuleTests: XCTestCase { 6 | let defaultRule = DefaultMemberwiseInitializerRule( 7 | options: DefaultMemberwiseInitializerRule.Options( 8 | implicitInitializer: false, 9 | implicitInternal: true, 10 | ignoreClassesWithInheritance: false 11 | ), 12 | format: .default 13 | ) 14 | 15 | func testDescription() throws { 16 | try assertRuleDescription(defaultRule) 17 | } 18 | 19 | func testIgnore() throws { 20 | try assertRule( 21 | defaultRule, 22 | source: """ 23 | // swift-mod-ignore: defaultMemberwiseInitializer 24 | struct Struct {} 25 | """, 26 | expected: """ 27 | // swift-mod-ignore: defaultMemberwiseInitializer 28 | struct Struct {} 29 | """ 30 | ) 31 | } 32 | 33 | func testStruct() throws { 34 | try assertRule( 35 | defaultRule, 36 | source: """ 37 | public struct Struct { 38 | static let staticProperty: Int = 0 39 | static func staticFunction() -> Int { 0 } 40 | var property1: Int 41 | var property2: Int = 0 42 | var property3 = 0 43 | var property4: Int { 0 } 44 | internal var property5: Int 45 | var property6: Int? 46 | var property7: Int! 47 | func function(value: Int) -> Int { value } 48 | subscript (value: Int) -> Int { value } 49 | } 50 | """, 51 | expected: """ 52 | public struct Struct { 53 | static let staticProperty: Int = 0 54 | static func staticFunction() -> Int { 0 } 55 | var property1: Int 56 | var property2: Int = 0 57 | var property3 = 0 58 | var property4: Int { 0 } 59 | internal var property5: Int 60 | var property6: Int? 61 | var property7: Int! 62 | func function(value: Int) -> Int { value } 63 | subscript (value: Int) -> Int { value } 64 | 65 | public init( 66 | property1: Int, 67 | property2: Int = 0, 68 | property5: Int, 69 | property6: Int? = nil, 70 | property7: Int? = nil 71 | ) { 72 | self.property1 = property1 73 | self.property2 = property2 74 | self.property5 = property5 75 | self.property6 = property6 76 | self.property7 = property7 77 | } 78 | } 79 | """ 80 | ) 81 | } 82 | 83 | func testStructImplicitInitializer() throws { 84 | let rule = DefaultMemberwiseInitializerRule( 85 | options: DefaultMemberwiseInitializerRule.Options( 86 | implicitInitializer: true, 87 | implicitInternal: true, 88 | ignoreClassesWithInheritance: false 89 | ), 90 | format: .default 91 | ) 92 | try assertRule( 93 | rule, 94 | source: """ 95 | struct Struct {} 96 | """, 97 | expected: """ 98 | struct Struct {} 99 | """ 100 | ) 101 | } 102 | 103 | func testClass() throws { 104 | try assertRule( 105 | defaultRule, 106 | source: """ 107 | public class Class { 108 | static let staticProperty: Int = 0 109 | static func staticFunction() -> Int { 0 } 110 | var property1: Int 111 | var property2: Int = 0 112 | var property3 = 0 113 | var property4: Int { 0 } 114 | internal var property5: Int 115 | var property6: Int? 116 | var property7: Int! 117 | func function(value: Int) -> Int { value } 118 | subscript (value: Int) -> Int { value } 119 | } 120 | """, 121 | expected: """ 122 | public class Class { 123 | static let staticProperty: Int = 0 124 | static func staticFunction() -> Int { 0 } 125 | var property1: Int 126 | var property2: Int = 0 127 | var property3 = 0 128 | var property4: Int { 0 } 129 | internal var property5: Int 130 | var property6: Int? 131 | var property7: Int! 132 | func function(value: Int) -> Int { value } 133 | subscript (value: Int) -> Int { value } 134 | 135 | public init( 136 | property1: Int, 137 | property2: Int = 0, 138 | property5: Int, 139 | property6: Int? = nil, 140 | property7: Int? = nil 141 | ) { 142 | self.property1 = property1 143 | self.property2 = property2 144 | self.property5 = property5 145 | self.property6 = property6 146 | self.property7 = property7 147 | } 148 | } 149 | """ 150 | ) 151 | } 152 | 153 | func testClassImplicitInitializer() throws { 154 | let rule = DefaultMemberwiseInitializerRule( 155 | options: DefaultMemberwiseInitializerRule.Options( 156 | implicitInitializer: true, 157 | implicitInternal: true, 158 | ignoreClassesWithInheritance: false 159 | ), 160 | format: .default 161 | ) 162 | try assertRule( 163 | rule, 164 | source: """ 165 | class Class {} 166 | """, 167 | expected: """ 168 | class Class {} 169 | """ 170 | ) 171 | } 172 | 173 | func testReserved() throws { 174 | try assertRule( 175 | defaultRule, 176 | source: """ 177 | struct Struct { 178 | var `optional`: Int 179 | var `switch`: Int 180 | } 181 | """, 182 | expected: """ 183 | struct Struct { 184 | var `optional`: Int 185 | var `switch`: Int 186 | 187 | init( 188 | `optional`: Int, 189 | `switch`: Int 190 | ) { 191 | self.optional = `optional` 192 | self.switch = `switch` 193 | } 194 | } 195 | """ 196 | ) 197 | } 198 | 199 | func testNotTriggered() throws { 200 | try assertRule( 201 | defaultRule, 202 | source: """ 203 | struct Struct { 204 | var property: Int 205 | 206 | init() { 207 | property = 0 208 | } 209 | } 210 | """, 211 | expected: """ 212 | struct Struct { 213 | var property: Int 214 | 215 | init() { 216 | property = 0 217 | } 218 | } 219 | """ 220 | ) 221 | } 222 | 223 | func testPrivate() throws { 224 | try assertRule( 225 | defaultRule, 226 | source: """ 227 | private struct Struct { 228 | var property: Int 229 | } 230 | """, 231 | expected: """ 232 | private struct Struct { 233 | var property: Int 234 | 235 | init(property: Int) { 236 | self.property = property 237 | } 238 | } 239 | """ 240 | ) 241 | } 242 | 243 | func testFilePrivate() throws { 244 | try assertRule( 245 | defaultRule, 246 | source: """ 247 | fileprivate struct Struct { 248 | var property: Int 249 | } 250 | """, 251 | expected: """ 252 | fileprivate struct Struct { 253 | var property: Int 254 | 255 | init(property: Int) { 256 | self.property = property 257 | } 258 | } 259 | """ 260 | ) 261 | } 262 | 263 | func testIgnoreClassesWithInheritance() throws { 264 | let rule = DefaultMemberwiseInitializerRule( 265 | options: DefaultMemberwiseInitializerRule.Options( 266 | implicitInitializer: false, 267 | implicitInternal: true, 268 | ignoreClassesWithInheritance: true 269 | ), 270 | format: .default 271 | ) 272 | 273 | try assertRule( 274 | rule, 275 | source: """ 276 | class Class: Inheritance { 277 | var property: Int 278 | } 279 | """, 280 | expected: """ 281 | class Class: Inheritance { 282 | var property: Int 283 | } 284 | """ 285 | ) 286 | } 287 | 288 | func testCustomFormat() throws { 289 | let rule = DefaultMemberwiseInitializerRule( 290 | options: DefaultMemberwiseInitializerRule.Options( 291 | implicitInitializer: false, 292 | implicitInternal: true, 293 | ignoreClassesWithInheritance: false 294 | ), 295 | format: Format( 296 | indent: .spaces(2), 297 | lineBreakBeforeEachArgument: false 298 | ) 299 | ) 300 | 301 | try assertRule( 302 | rule, 303 | source: """ 304 | struct Struct { 305 | var property1: Int 306 | var property2: Int 307 | var property3: Int 308 | } 309 | """, 310 | expected: """ 311 | struct Struct { 312 | var property1: Int 313 | var property2: Int 314 | var property3: Int 315 | 316 | init(property1: Int, property2: Int, property3: Int) { 317 | self.property1 = property1 318 | self.property2 = property2 319 | self.property3 = property3 320 | } 321 | } 322 | """ 323 | ) 324 | } 325 | } 326 | -------------------------------------------------------------------------------- /Tests/SwiftModRulesTests/Helpers.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | import SwiftModCore 3 | import SwiftParser 4 | import XCTest 5 | 6 | func assertRuleDescription(_ rule: AnyRule, file: StaticString = #file, line: UInt = #line) throws { 7 | let description = type(of: rule).description 8 | let encodedOptions = try? JSONEncoder().encode(description.exampleOptions) 9 | let exampleSyntax = Parser.parse(source: description.exampleBefore) 10 | let exampleModified = rule.rewriter().visit(exampleSyntax).description 11 | 12 | XCTAssertFalse(description.name.isEmpty, file: file, line: line) 13 | XCTAssertFalse(description.overview.isEmpty, file: file, line: line) 14 | XCTAssertNotNil(encodedOptions, file: file, line: line) 15 | XCTAssertEqual(exampleModified, description.exampleAfter, file: file, line: line) 16 | } 17 | 18 | func assertRule(_ rule: AnyRule, source: String, expected: String, file: StaticString = #file, line: UInt = #line) throws { 19 | let syntax = Parser.parse(source: source) 20 | let modified = rule.rewriter().visit(syntax).description 21 | XCTAssertEqual(modified, expected, file: file, line: line) 22 | } 23 | -------------------------------------------------------------------------------- /Tools/Package.resolved: -------------------------------------------------------------------------------- 1 | { 2 | "originHash" : "7b87ceb41a0f3350b9201125895daf78c4f6a14bddd14dbaba4001f12762f213", 3 | "pins" : [ 4 | { 5 | "identity" : "swift-argument-parser", 6 | "kind" : "remoteSourceControl", 7 | "location" : "https://github.com/apple/swift-argument-parser.git", 8 | "state" : { 9 | "revision" : "41982a3656a71c768319979febd796c6fd111d5c", 10 | "version" : "1.5.0" 11 | } 12 | }, 13 | { 14 | "identity" : "swift-cmark", 15 | "kind" : "remoteSourceControl", 16 | "location" : "https://github.com/apple/swift-cmark.git", 17 | "state" : { 18 | "revision" : "3ccff77b2dc5b96b77db3da0d68d28068593fa53", 19 | "version" : "0.5.0" 20 | } 21 | }, 22 | { 23 | "identity" : "swift-format", 24 | "kind" : "remoteSourceControl", 25 | "location" : "https://github.com/swiftlang/swift-format.git", 26 | "state" : { 27 | "revision" : "7996ac678197d293f6c088a1e74bb778b4e10139", 28 | "version" : "510.1.0" 29 | } 30 | }, 31 | { 32 | "identity" : "swift-markdown", 33 | "kind" : "remoteSourceControl", 34 | "location" : "https://github.com/apple/swift-markdown.git", 35 | "state" : { 36 | "revision" : "8f79cb175981458a0a27e76cb42fee8e17b1a993", 37 | "version" : "0.5.0" 38 | } 39 | }, 40 | { 41 | "identity" : "swift-syntax", 42 | "kind" : "remoteSourceControl", 43 | "location" : "https://github.com/apple/swift-syntax.git", 44 | "state" : { 45 | "revision" : "2bc86522d115234d1f588efe2bcb4ce4be8f8b82", 46 | "version" : "510.0.3" 47 | } 48 | } 49 | ], 50 | "version" : 3 51 | } 52 | -------------------------------------------------------------------------------- /Tools/Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version:5.10 2 | 3 | import PackageDescription 4 | 5 | let package = Package( 6 | name: "Tools", 7 | dependencies: [ 8 | .package(url: "https://github.com/swiftlang/swift-format.git", exact: "510.1.0"), 9 | ] 10 | ) 11 | --------------------------------------------------------------------------------