diff --git a/.github/release.yml b/.github/release.yml new file mode 100644 index 0000000..ce55182 --- /dev/null +++ b/.github/release.yml @@ -0,0 +1,17 @@ +changelog: + exclude: + labels: + - semver-noop + categories: + - title: SemVer Major + labels: + - semver-major + - title: SemVer Minor + labels: + - semver-minor + - title: SemVer Patch + labels: + - semver-patch + - title: Other Changes + labels: + - "*" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..2a6835d --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,80 @@ +name: CI +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true +on: + push: + branches: [ "main" ] + pull_request: + branches: [ "main" ] + +jobs: + soundness: + container: + image: ghcr.io/lovetodream/swift-format-ci:v5.10.0 + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + - name: Mark repo safe in non-fake global config + run: git config --global --add safe.directory "${GITHUB_WORKSPACE}" + - name: Run soundness + run: | + scripts/soundness.sh + exit $(git status --porcelain | wc -l) + + api-breakage: + if: github.event_name == 'pull_request' + runs-on: ubuntu-latest + container: swift:jammy + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + fetch-depth: 0 + # https://github.com/actions/checkout/issues/766 + - name: API breaking changes + run: | + git config --global --add safe.directory "${GITHUB_WORKSPACE}" + swift package diagnose-api-breaking-changes origin/main + + tests: + container: + image: swift:5.10-jammy + + runs-on: ubuntu-latest + + services: + loki: + image: grafana/loki:3.0.0 + + steps: + - uses: actions/checkout@v4 + - name: Cache Swift PM + uses: actions/cache@v4 + with: + path: .build + key: ${{ runner.os }}-ci-spm-${{ hashFiles('Package.swift') }} + restore-keys: ${{ runner.os }}-ci-spm- + - name: Resolve Swift dependencies + run: swift package resolve + - name: Build + run: swift build + - name: Run tests + run: swift test --enable-code-coverage + env: + XCT_LOKI_URL: http://loki:3100 + - name: Prepare Code Coverage + run: | + llvm-cov export -format "lcov" \ + .build/debug/swift-log-lokiPackageTests.xctest \ + -ignore-filename-regex="\.pb\.swift" \ + -ignore-filename-regex="\/Tests\/" \ + -instr-profile .build/debug/codecov/default.profdata \ + > info.lcov + - name: Upload coverage reports to Codecov + uses: codecov/codecov-action@v3 + with: + token: ${{ secrets.CODECOV_TOKEN }} + files: info.lcov diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 0000000..6ce137d --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,40 @@ +name: "CodeQL" + +on: + push: + branches: [ "main" ] + pull_request: + branches: [ "main" ] + +jobs: + analyze: + name: Analyze + runs-on: ubuntu-latest + permissions: { actions: write, contents: read, security-events: write } + + steps: + - uses: actions/checkout@v4 + + - name: Mark repo safe in non-fake global config + run: git config --global --add safe.directory "${GITHUB_WORKSPACE}" + + - name: Initialize CodeQL + uses: github/codeql-action/init@v3 + with: + languages: swift + + - name: Cache Swift PM + uses: actions/cache@v4 + with: + path: .build + key: ${{ runner.os }}-codeql-spm-${{ hashFiles('Package.swift') }} + restore-keys: ${{ runner.os }}-codeql-spm- + + - name: Resolve Swift dependencies + run: swift package resolve + + - name: Build + run: swift build + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v3 diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml deleted file mode 100644 index 546db39..0000000 --- a/.github/workflows/tests.yml +++ /dev/null @@ -1,34 +0,0 @@ -name: Tests - -on: - push: - branches: [ "main" ] - pull_request: - branches: [ "main" ] - -jobs: - test: - container: - image: swift:5.9-jammy - - runs-on: ubuntu-latest - - services: - loki: - image: grafana/loki:3.0.0 - - steps: - - uses: actions/checkout@v3 - - name: Build - run: swift build - - name: Run tests - run: swift test --enable-code-coverage - env: - XCT_LOKI_URL: http://loki:3100 - - name: Prepare Code Coverage - run: llvm-cov export -format="lcov" .build/debug/swift-log-lokiPackageTests.xctest -instr-profile .build/debug/codecov/default.profdata -ignore-filename-regex="\.pb\.swift" > info.lcov - - name: Upload coverage reports to Codecov - uses: codecov/codecov-action@v3 - with: - token: ${{ secrets.CODECOV_TOKEN }} - files: info.lcov diff --git a/.swift-format b/.swift-format new file mode 100644 index 0000000..ae99207 --- /dev/null +++ b/.swift-format @@ -0,0 +1,69 @@ +{ + "fileScopedDeclarationPrivacy": { + "accessLevel": "private" + }, + "indentation": { + "spaces": 4 + }, + "indentConditionalCompilationBlocks": true, + "indentSwitchCaseLabels": false, + "lineBreakAroundMultilineExpressionChainComponents": false, + "lineBreakBeforeControlFlowKeywords": false, + "lineBreakBeforeEachArgument": false, + "lineBreakBeforeEachGenericRequirement": false, + "lineLength": 100, + "maximumBlankLines": 2, + "multiElementCollectionTrailingCommas": true, + "noAssignmentInExpressions": { + "allowedFunctions": [ + "XCTAssertNoThrow" + ] + }, + "prioritizeKeepingFunctionOutputTogether": false, + "respectsExistingLineBreaks": true, + "rules": { + "AllPublicDeclarationsHaveDocumentation": false, + "AlwaysUseLiteralForEmptyCollectionInit": false, + "AlwaysUseLowerCamelCase": true, + "AmbiguousTrailingClosureOverload": true, + "BeginDocumentationCommentWithOneLineSummary": false, + "DoNotUseSemicolons": true, + "DontRepeatTypeInStaticProperties": true, + "FileScopedDeclarationPrivacy": true, + "FullyIndirectEnum": true, + "GroupNumericLiterals": true, + "IdentifiersMustBeASCII": true, + "NeverForceUnwrap": false, + "NeverUseForceTry": false, + "NeverUseImplicitlyUnwrappedOptionals": false, + "NoAccessLevelOnExtensionDeclaration": true, + "NoAssignmentInExpressions": true, + "NoBlockComments": true, + "NoCasesWithOnlyFallthrough": true, + "NoEmptyTrailingClosureParentheses": true, + "NoLabelsInCasePatterns": true, + "NoLeadingUnderscores": false, + "NoParensAroundConditions": true, + "NoPlaygroundLiterals": true, + "NoVoidReturnOnFunctionSignature": true, + "OmitExplicitReturns": false, + "OneCasePerLine": true, + "OneVariableDeclarationPerLine": true, + "OnlyOneTrailingClosureArgument": true, + "OrderedImports": true, + "ReplaceForEachWithForLoop": true, + "ReturnVoidInsteadOfEmptyTuple": true, + "TypeNamesShouldBeCapitalized": true, + "UseEarlyExits": false, + "UseLetInEveryBoundCaseVariable": true, + "UseShorthandTypeNames": true, + "UseSingleLinePropertyGetter": true, + "UseSynthesizedInitializer": true, + "UseTripleSlashForDocumentationComments": true, + "UseWhereClausesInForLoops": false, + "ValidateDocumentationComments": false + }, + "spacesAroundRangeFormationOperators": false, + "tabWidth": 8, + "version": 1 +} \ No newline at end of file diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..29fdb2b --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,3 @@ +# Code of Conduct + +SwiftLogLoki adopts Swift's code of conduct: https://www.swift.org/code-of-conduct. diff --git a/LICENSE b/LICENSE index 02f25ba..261eeb9 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,201 @@ -MIT License - -Copyright (c) 2022 Timo Zacherl - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/NOTICE.txt b/NOTICE.txt index 9aa5823..2276e74 100644 --- a/NOTICE.txt +++ b/NOTICE.txt @@ -1,20 +1,20 @@ //===----------------------------------------------------------------------===// // -// This source file is part of the swift-log-loki open source project +// This source file is part of the SwiftLogLoki open source project // -// Copyright (c) 2023 Timo Zacherl -// Licensed under MIT +// Copyright (c) 2024 Timo Zacherl and the SwiftLogLoki project authors +// Licensed under Apache License v2.0 // // See LICENSE for license information // -// SPDX-License-Identifier: MIT +// SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// -This product contains a derivation of the NIOLock implementation -from Swift NIO. +This product contains a derivation of the MockClock implementation +from Swift OTel. -* LICENSE (Apache License 2.0): -* https://www.apache.org/licenses/LICENSE-2.0 -* HOMEPAGE: -* https://github.com/apple/swift-nio + * LICENSE (Apache License 2.0): + * https://www.apache.org/licenses/LICENSE-2.0 + * HOMEPAGE: + * https://github.com/slashmo/swift-otel diff --git a/Package.swift b/Package.swift index 5a69e8f..b2360b1 100644 --- a/Package.swift +++ b/Package.swift @@ -5,7 +5,7 @@ let package = Package( name: "swift-log-loki", platforms: [.macOS(.v14), .iOS(.v17), .tvOS(.v17), .watchOS(.v10), .visionOS(.v1)], products: [ - .library(name: "LoggingLoki", targets: ["LoggingLoki"]), + .library(name: "LoggingLoki", targets: ["LoggingLoki"]) ], dependencies: [ .package(url: "https://github.com/apple/swift-log.git", from: "1.0.0"), diff --git a/README.md b/README.md index 7b27d42..35c6a57 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,8 @@ # SwiftLogLoki -[![Coverage](https://codecov.io/gh/lovetodream/swift-log-loki/graph/badge.svg?token=Q70PZWS0T2)](https://codecov.io/gh/lovetodream/swift-log-loki) +[![Coverage](https://codecov.io/gh/lovetodream/swift-log-loki/graph/badge.svg?token=Q70PZWS0T2)][Coverage] +[![Documentation](http://img.shields.io/badge/read_the-docs-2196f3.svg)][Documentation] +[![Apache 2.0 License](https://img.shields.io/badge/license-Apache%202.0-brightgreen)][Apache License] [![Tests](https://github.com/lovetodream/swift-log-loki/actions/workflows/tests.yml/badge.svg)](https://github.com/lovetodream/swift-log-loki/actions/workflows/tests.yml) [![Swift Versions](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2Flovetodream%2Fswift-log-loki%2Fbadge%3Ftype%3Dswift-versions)](https://swiftpackageindex.com/lovetodream/swift-log-loki) [![Supported Platforms](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2Flovetodream%2Fswift-log-loki%2Fbadge%3Ftype%3Dplatforms)](https://swiftpackageindex.com/lovetodream/swift-log-loki) @@ -12,7 +14,7 @@ This library can be used as an implementation of Apple's [swift-log](https://git - Supports Linux and all Apple platforms - Different logging levels such as `trace`, `debug`, `info`, `notice`, `warning`, `error` and `critical` - Option to send logs as snappy-compressed Protobuf (default) or JSON -- Batching logs via `TimeInterval`, amount of log entries or a mix of those options +- Send logs in batches via `Duration` since batch creation, amount of log entries in batch or a mix of both options ## Add dependency @@ -60,8 +62,18 @@ try await withThrowingDiscardingTaskGroup { group in ## API documentation -For more information visit the [API reference](https://swiftpackageindex.com/lovetodream/swift-log-loki/documentation/loggingloki). +For more information visit the [API reference][Documentation]. ## License -This library is licensed under the MIT license. Full license text is available in [LICENSE](https://github.com/lovetodream/swift-log-loki/blob/main/LICENSE). +[Apache 2.0][Apache License] + +Copyright (c) 2022-present, Timo Zacherl (@lovetodream) + +_This project contains code written by others not affliated with this project. All copyright claims are reserved by them. For a full list, with their claimed rights, see [NOTICE.txt](NOTICE.txt)_ + +_**Swift** is a registered trademark of **Apple, Inc**. Any use of their trademark does not imply any affiliation with or endorsement by them, and all rights are reserved by them._ + +[Coverage]: https://codecov.io/gh/lovetodream/swift-log-loki +[Documentation]: https://swiftpackageindex.com/lovetodream/swift-log-loki/documentation/loggingloki +[Apache License]: LICENSE diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..2e5bfa0 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,35 @@ +# Security Policy + +## Supported Versions + +| Version | Supported | +| ------- | ------------------ | +| 2.x | :white_check_mark: | +| 1.x | :x: | + +_Legend_: + - ✅ Currently supported, receives all security and other updates + - 🔙 Legacy support, receives backported security updates only + - ❌ Unsupported + +## Reporting a Vulnerability + +Please report known and suspected vulnerabilities privately and responsibly disclosed by [filling out a vulnerability report](https://github.com/lovetodream/swift-log-loki/security/advisories/new) on Github[^1]. Vulnerabilities may also be privately and responsibly disclosed by emailing all pertinent information to [security@timozacherl.com](mailto:security@timozacherl.com). + +[^1]: See [Github's official documentation of the vulnerability report feature](https://docs.github.com/en/code-security/security-advisories/guidance-on-reporting-and-writing-information-about-vulnerabilities/privately-reporting-a-security-vulnerability) for additional privacy and safety details. + +**⚠️ Please do _not_ file a public issue! ⚠️** + +### When to report a vulnerability + +* You think you have discovered a potential security vulnerability in SwiftLogLoki. +* You are unsure how a vulnerability affects SwiftLogLoki. + +### What happens next? + +* I will acknowledge receipt of the report within 3 working days. This may include a request for additional information about reproducing the vulnerability. +* Once I have identified a fix I may ask you to validate it. I aim to do this within 30 days. In some cases this may not be possible, for example when the vulnerability exists at the protocol level and the industry must coordinate on the disclosure process. +* If a CVE number is required, one will be requested through the [GitHub security advisory process](https://docs.github.com/en/code-security/security-advisories), providing you with full credit for the discovery. +* I will decide on a planned release date and let you know when it is. +* Prior to release, I will inform major dependents that a security-related patch is impending. +* Once the fix has been released I will publish a security advisory on GitHub. diff --git a/Snippets/BasicUsage.swift b/Snippets/BasicUsage.swift index b8268d3..1ab1dac 100644 --- a/Snippets/BasicUsage.swift +++ b/Snippets/BasicUsage.swift @@ -1,3 +1,15 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftLogLoki open source project +// +// Copyright (c) 2024 Timo Zacherl and the SwiftLogLoki project authors +// Licensed under Apache License v2.0 +// +// See LICENSE for license information +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// // snippet.setup import Logging diff --git a/Sources/LoggingLoki/Batch.swift b/Sources/LoggingLoki/Batch.swift index 76a80f8..75bd9da 100644 --- a/Sources/LoggingLoki/Batch.swift +++ b/Sources/LoggingLoki/Batch.swift @@ -1,3 +1,16 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftLogLoki open source project +// +// Copyright (c) 2024 Timo Zacherl and the SwiftLogLoki project authors +// Licensed under Apache License v2.0 +// +// See LICENSE for license information +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + import Foundation struct Batch { @@ -6,7 +19,7 @@ struct Batch { let createdAt: Clock.Instant var totalLogEntries: Int - + init(entries: [BatchEntry], createdAt: Clock.Instant) { self.entries = entries self.createdAt = createdAt diff --git a/Sources/LoggingLoki/BatchEntry.swift b/Sources/LoggingLoki/BatchEntry.swift index 44c4c6e..9e7666f 100644 --- a/Sources/LoggingLoki/BatchEntry.swift +++ b/Sources/LoggingLoki/BatchEntry.swift @@ -1,3 +1,16 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftLogLoki open source project +// +// Copyright (c) 2024 Timo Zacherl and the SwiftLogLoki project authors +// Licensed under Apache License v2.0 +// +// See LICENSE for license information +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + struct BatchEntry: Sendable { var labels: [String: String] var logEntries: [LokiLog.Transport] diff --git a/Sources/LoggingLoki/LokiLog.swift b/Sources/LoggingLoki/LokiLog.swift index 0fe6936..87f803d 100644 --- a/Sources/LoggingLoki/LokiLog.swift +++ b/Sources/LoggingLoki/LokiLog.swift @@ -1,6 +1,20 @@ -import struct Foundation.Date +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftLogLoki open source project +// +// Copyright (c) 2024 Timo Zacherl and the SwiftLogLoki project authors +// Licensed under Apache License v2.0 +// +// See LICENSE for license information +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + import Logging +import struct Foundation.Date + struct LokiLog { var timestamp: Date var level: Logger.Level diff --git a/Sources/LoggingLoki/LokiLogHandler.swift b/Sources/LoggingLoki/LokiLogHandler.swift index fb31d43..10e02e6 100644 --- a/Sources/LoggingLoki/LokiLogHandler.swift +++ b/Sources/LoggingLoki/LokiLogHandler.swift @@ -1,8 +1,23 @@ -import class Foundation.ProcessInfo +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftLogLoki open source project +// +// Copyright (c) 2024 Timo Zacherl and the SwiftLogLoki project authors +// Licensed under Apache License v2.0 +// +// See LICENSE for license information +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + import Logging +import class Foundation.ProcessInfo + /// ``LokiLogHandler`` is a logging backend for `Logging`. -public struct LokiLogHandler: LogHandler, Sendable where Clock.Duration == Duration { +public struct LokiLogHandler: LogHandler, Sendable +where Clock.Duration == Duration { private let processor: LokiLogProcessor @@ -78,15 +93,16 @@ public struct LokiLogHandler: LogHandler, Sendable wh "source": source, "file": file, "function": function, - "line": String(line) - ].merging(lokiLabels) { old, _ in old } // message specific labels win! - - processor.addEntryToBatch(.init( - timestamp: .init(), - level: level, - message: message, - metadata: effectiveMetadata - ), with: labels) + "line": String(line), + ].merging(lokiLabels) { old, _ in old } // message specific labels win! + + processor.addEntryToBatch( + .init( + timestamp: .init(), + level: level, + message: message, + metadata: effectiveMetadata + ), with: labels) } /// Add, remove, or change the logging metadata. @@ -121,7 +137,9 @@ public struct LokiLogHandler: LogHandler, Sendable wh /// `LogHandler`. public var logLevel: Logger.Level = .info - internal static func prepareMetadata(base: Logger.Metadata, provider: Logger.MetadataProvider?, explicit: Logger.Metadata?) -> Logger.Metadata { + internal static func prepareMetadata( + base: Logger.Metadata, provider: Logger.MetadataProvider?, explicit: Logger.Metadata? + ) -> Logger.Metadata { var metadata = base let provided = provider?.get() ?? [:] diff --git a/Sources/LoggingLoki/LokiLogProcessor.swift b/Sources/LoggingLoki/LokiLogProcessor.swift index 2d50256..1b8d241 100644 --- a/Sources/LoggingLoki/LokiLogProcessor.swift +++ b/Sources/LoggingLoki/LokiLogProcessor.swift @@ -1,20 +1,34 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftLogLoki open source project +// +// Copyright (c) 2024 Timo Zacherl and the SwiftLogLoki project authors +// Licensed under Apache License v2.0 +// +// See LICENSE for license information +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import AsyncAlgorithms +import AsyncHTTPClient import Logging +import NIOConcurrencyHelpers import NIOHTTP1 -import AsyncHTTPClient import ServiceLifecycle -import AsyncAlgorithms -import NIOConcurrencyHelpers /// A configuration object for ``LokiLogProcessor``. public struct LokiLogProcessorConfiguration: Sendable { /// The loki server URL, eg. `http://localhost:3100`. public var lokiURL: String { didSet { - _lokiURL = if lokiURL.hasSuffix("/") { - lokiURL + "loki/api/v1/push" - } else { - lokiURL + "/loki/api/v1/push" - } + _lokiURL = + if lokiURL.hasSuffix("/") { + lokiURL + "loki/api/v1/push" + } else { + lokiURL + "/loki/api/v1/push" + } } } internal private(set) var _lokiURL: String @@ -47,7 +61,8 @@ public struct LokiLogProcessorConfiguration: Sendable { /// Indicates the format of log messages sent to Loki. public struct LogFormat: Sendable { - public typealias CustomFormatter = @Sendable (Logger.Level, Logger.Message, Logger.Metadata) -> String + public typealias CustomFormatter = @Sendable (Logger.Level, Logger.Message, Logger.Metadata) + -> String enum Code { case logfmt @@ -97,7 +112,7 @@ public struct LokiLogProcessorConfiguration: Sendable { public static let json = Encoding(code: .json) public static let protobuf = Encoding(code: .protobuf) } - + /// Initializes a configuration. /// - Parameters: /// - lokiURL: The URL of the Loki server where to logs will be sent to. @@ -114,11 +129,12 @@ public struct LokiLogProcessorConfiguration: Sendable { logFormat: LogFormat = .structured ) { self.lokiURL = lokiURL - self._lokiURL = if lokiURL.hasSuffix("/") { - lokiURL + "loki/api/v1/push" - } else { - lokiURL + "/loki/api/v1/push" - } + self._lokiURL = + if lokiURL.hasSuffix("/") { + lokiURL + "loki/api/v1/push" + } else { + lokiURL + "/loki/api/v1/push" + } self.headers = headers self.batchSize = batchSize self.maxBatchTimeInterval = maxBatchTimeInterval @@ -132,7 +148,8 @@ public struct LokiLogProcessorConfiguration: Sendable { /// The service is sending logs as long as ``LokiLogProcessor/run()`` is not cancelled. /// /// It conforms to ``ServiceLifecycle.Service``. -public struct LokiLogProcessor: Sendable, Service where Clock.Duration == Duration { +public struct LokiLogProcessor: Sendable, Service +where Clock.Duration == Duration { final class _Storage: Sendable { fileprivate let _value: NIOLockedValueBox?> = NIOLockedValueBox(nil) } @@ -167,11 +184,13 @@ public struct LokiLogProcessor: Sendable, Service whe self.stream = stream self.continuation = continuation } - + public func run() async throws { try await withThrowingDiscardingTaskGroup { group in group.addTask { - for try await _ in AsyncTimerSequence.repeating(every: configuration.exportInterval, clock: clock).cancelOnGracefulShutdown() { + for try await _ in AsyncTimerSequence.repeating( + every: configuration.exportInterval, clock: clock + ).cancelOnGracefulShutdown() { await tick() } } @@ -200,7 +219,8 @@ public struct LokiLogProcessor: Sendable, Service whe guard let batch = safeBatch else { return nil } if let maxBatchTimeInterval = configuration.maxBatchTimeInterval, - batch.createdAt.advanced(by: maxBatchTimeInterval) <= clock.now { + batch.createdAt.advanced(by: maxBatchTimeInterval) <= clock.now + { safeBatch = nil return batch } @@ -212,14 +232,16 @@ public struct LokiLogProcessor: Sendable, Service whe return nil } - + guard let batch else { return } do { try await withTimeout(configuration.exportTimeout, clock: clock) { try await sendBatch(batch) } } catch is CancellationError { - logger.warning("Timed out exporting logs.", metadata: ["timeout": "\(configuration.exportTimeout)"]) + logger.warning( + "Timed out exporting logs.", metadata: ["timeout": "\(configuration.exportTimeout)"] + ) } catch { logger.error("Failed to export logs.", metadata: ["error": "\(error)"]) } @@ -256,7 +278,7 @@ public struct LokiLogProcessor: Sendable, Service whe try await transport .transport(buffer, url: configuration._lokiURL, headers: headers) } - + private func prettify(_ metadata: Logger.Metadata) -> String? { if metadata.isEmpty { return nil @@ -278,20 +300,21 @@ extension LokiLogProcessor where Clock == ContinuousClock { /// /// The processor can be used on multiple ``LokiLogHandler``s, /// it will manage the logs accordingly. - /// + /// /// - Parameter configuration: A configuration object used to setup the processors behaviour. public init(configuration: Configuration) { - let transformer: LokiTransformer = switch configuration.encoding.code { - case .json: - LokiJSONTransformer() - case .protobuf: - LokiProtobufTransformer() - } + let transformer: LokiTransformer = + switch configuration.encoding.code { + case .json: + LokiJSONTransformer() + case .protobuf: + LokiProtobufTransformer() + } let clock = ContinuousClock() self.init( configuration: configuration, transport: HTTPClient.shared, - transformer: transformer, + transformer: transformer, clock: clock ) } diff --git a/Sources/LoggingLoki/LokiRequest.swift b/Sources/LoggingLoki/LokiRequest.swift index 1ba5ac7..88f2fa8 100644 --- a/Sources/LoggingLoki/LokiRequest.swift +++ b/Sources/LoggingLoki/LokiRequest.swift @@ -1,10 +1,24 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftLogLoki open source project +// +// Copyright (c) 2024 Timo Zacherl and the SwiftLogLoki project authors +// Licensed under Apache License v2.0 +// +// See LICENSE for license information +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + struct LokiRequest: Encodable, Sendable { var streams: [LokiStream] static func from(entries: [BatchEntry]) -> LokiRequest { var request = LokiRequest(streams: []) for entry in entries { - request.streams.append(LokiStream(entry.logEntries, with: entry.labels)) + request.streams + .append(LokiStream(entry.logEntries, with: entry.labels)) } return request } diff --git a/Sources/LoggingLoki/LokiStream.swift b/Sources/LoggingLoki/LokiStream.swift index 7814fd5..994f40f 100644 --- a/Sources/LoggingLoki/LokiStream.swift +++ b/Sources/LoggingLoki/LokiStream.swift @@ -1,3 +1,16 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftLogLoki open source project +// +// Copyright (c) 2024 Timo Zacherl and the SwiftLogLoki project authors +// Licensed under Apache License v2.0 +// +// See LICENSE for license information +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + struct LokiStream: Encodable, Sendable { typealias Value = (String, String, [String: String]?) diff --git a/Sources/LoggingLoki/LokiTransformer.swift b/Sources/LoggingLoki/LokiTransformer.swift index 6aefb32..6f7a375 100644 --- a/Sources/LoggingLoki/LokiTransformer.swift +++ b/Sources/LoggingLoki/LokiTransformer.swift @@ -1,9 +1,23 @@ -import class Foundation.JSONEncoder +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftLogLoki open source project +// +// Copyright (c) 2024 Timo Zacherl and the SwiftLogLoki project authors +// Licensed under Apache License v2.0 +// +// See LICENSE for license information +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + import NIOCore -import NIOHTTP1 import NIOFoundationCompat +import NIOHTTP1 import Snappy +import class Foundation.JSONEncoder + protocol LokiTransformer: Sendable { func transform(_ entries: [BatchEntry], headers: inout HTTPHeaders) throws -> ByteBuffer } @@ -33,7 +47,9 @@ struct LokiProtobufTransformer: LokiTransformer { let proto = Logproto_PushRequest.with { request in request.streams = entries.map { batchEntry in Logproto_StreamAdapter.with { stream in - stream.labels = "{" + batchEntry.labels.map { "\($0)=\"\($1)\"" }.joined(separator: ",") + "}" + stream.labels = + "{" + batchEntry.labels.map { "\($0)=\"\($1)\"" }.joined(separator: ",") + + "}" stream.entries = batchEntry.logEntries.map { log in Logproto_EntryAdapter.with { entry in entry.timestamp = .init(date: log.timestamp) diff --git a/Sources/LoggingLoki/LokiTransport.swift b/Sources/LoggingLoki/LokiTransport.swift index 96e2b69..0fc0a53 100644 --- a/Sources/LoggingLoki/LokiTransport.swift +++ b/Sources/LoggingLoki/LokiTransport.swift @@ -1,6 +1,19 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftLogLoki open source project +// +// Copyright (c) 2024 Timo Zacherl and the SwiftLogLoki project authors +// Licensed under Apache License v2.0 +// +// See LICENSE for license information +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + +import AsyncHTTPClient import NIOCore import NIOHTTP1 -import AsyncHTTPClient protocol LokiTransport: Sendable { func transport(_ data: ByteBuffer, url: String, headers: HTTPHeaders) async throws diff --git a/Sources/LoggingLoki/Proto/.vscode/settings.json b/Sources/LoggingLoki/Proto/.vscode/settings.json deleted file mode 100644 index f33569f..0000000 --- a/Sources/LoggingLoki/Proto/.vscode/settings.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "protoc": { - "path": "/opt/homebrew/bin/protoc", - "compile_on_save": true, - "options": [ - "--proto_path=/Users/timozacherl/Projects/swift-log-loki/Sources/LoggingLoki/Proto", - "--swift_out=gen/swift" - ] - } -} \ No newline at end of file diff --git a/Sources/LoggingLoki/Utility/Timeout.swift b/Sources/LoggingLoki/Utility/Timeout.swift index 39d2367..6bb9f0f 100644 --- a/Sources/LoggingLoki/Utility/Timeout.swift +++ b/Sources/LoggingLoki/Utility/Timeout.swift @@ -1,3 +1,16 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftLogLoki open source project +// +// Copyright (c) 2024 Timo Zacherl and the SwiftLogLoki project authors +// Licensed under Apache License v2.0 +// +// See LICENSE for license information +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + func withTimeout( _ timeout: ClockType.Duration, priority: TaskPriority? = nil, diff --git a/Tests/LoggingLokiTests/IntegrationTests.swift b/Tests/LoggingLokiTests/IntegrationTests.swift index 182f4bc..7724e43 100644 --- a/Tests/LoggingLokiTests/IntegrationTests.swift +++ b/Tests/LoggingLokiTests/IntegrationTests.swift @@ -1,9 +1,23 @@ -import XCTest -import NIOCore -import NIOHTTP1 -import Atomics +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftLogLoki open source project +// +// Copyright (c) 2024 Timo Zacherl and the SwiftLogLoki project authors +// Licensed under Apache License v2.0 +// +// See LICENSE for license information +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + import AsyncHTTPClient +import Atomics import NIOConcurrencyHelpers +import NIOCore +import NIOHTTP1 +import XCTest + @testable import LoggingLoki final class InspectableTransport: LokiTransport { @@ -44,12 +58,52 @@ final class IntegrationTests: XCTestCase { try await runHappyPath(LokiJSONTransformer()) } + func testTimeout() async throws { + try await withThrowingDiscardingTaskGroup { group in + let clock = TestClock() + let transport = InspectableTransport() + let processor = LokiLogProcessor( + configuration: .init( + lokiURL: "http://localhost:420420", + maxBatchTimeInterval: .seconds(10)), + transport: transport, + transformer: BadRequestTransformer(), + clock: clock + ) + var sleepCalls = clock.sleepCalls.makeAsyncIterator() + group.addTask { + try await processor.run() + } + let handler = LokiLogHandler( + label: "com.timozacherl.swift-log-loki-tests", processor: processor) + logLine(handler: handler) + await sleepCalls.next() + + // move forward in time until max batch time interval is exceeded + clock.advance(by: .seconds(5)) // tick + await sleepCalls.next() + clock.advance(by: .seconds(5)) // tick + await sleepCalls.next() + + clock.advance(by: .seconds(30)) + await sleepCalls.next() // export + XCTAssertEqual(transport.transported.load(ordering: .relaxed), 0) + XCTAssertEqual(transport.errored.load(ordering: .relaxed), 1) + let errors = transport.errors.withLockedValue { $0 } + XCTAssertTrue(errors.first is CancellationError) + + group.cancelAll() + } + } + func testBadRequest() async throws { try await withThrowingDiscardingTaskGroup { group in let clock = TestClock() let transport = InspectableTransport() let processor = LokiLogProcessor( - configuration: .init(lokiURL: env("XCT_LOKI_URL") ?? "http://localhost:3100", maxBatchTimeInterval: .seconds(10)), + configuration: .init( + lokiURL: env("XCT_LOKI_URL") ?? "http://localhost:3100", + maxBatchTimeInterval: .seconds(10)), transport: transport, transformer: BadRequestTransformer(), clock: clock @@ -58,17 +112,18 @@ final class IntegrationTests: XCTestCase { group.addTask { try await processor.run() } - let handler = LokiLogHandler(label: "com.timozacherl.swift-log-loki-tests", processor: processor) + let handler = LokiLogHandler( + label: "com.timozacherl.swift-log-loki-tests", processor: processor) logLine(handler: handler) await sleepCalls.next() // move forward in time until max batch time interval is exceeded - clock.advance(by: .seconds(5)) // tick + clock.advance(by: .seconds(5)) // tick await sleepCalls.next() - clock.advance(by: .seconds(5)) // tick + clock.advance(by: .seconds(5)) // tick await sleepCalls.next() - await sleepCalls.next() // export + await sleepCalls.next() // export XCTAssertEqual(transport.transported.load(ordering: .relaxed), 0) XCTAssertEqual(transport.errored.load(ordering: .relaxed), 1) let errors = transport.errors.withLockedValue { $0 } @@ -79,12 +134,16 @@ final class IntegrationTests: XCTestCase { } } - func runHappyPath(_ transformer: LokiTransformer, file: StaticString = #filePath, line: UInt = #line) async throws { + func runHappyPath( + _ transformer: LokiTransformer, file: StaticString = #filePath, line: UInt = #line + ) async throws { try await withThrowingDiscardingTaskGroup { group in let clock = TestClock() let transport = InspectableTransport() let processor = LokiLogProcessor( - configuration: .init(lokiURL: env("XCT_LOKI_URL") ?? "http://localhost:3100", maxBatchTimeInterval: .seconds(10)), + configuration: .init( + lokiURL: env("XCT_LOKI_URL") ?? "http://localhost:3100", + maxBatchTimeInterval: .seconds(10)), transport: transport, transformer: transformer, clock: clock @@ -93,18 +152,20 @@ final class IntegrationTests: XCTestCase { group.addTask { try await processor.run() } - let handler = LokiLogHandler(label: "com.timozacherl.swift-log-loki-tests", processor: processor) + let handler = LokiLogHandler( + label: "com.timozacherl.swift-log-loki-tests", processor: processor) logLine(handler: handler) await sleepCalls.next() // move forward in time until max batch time interval is exceeded - clock.advance(by: .seconds(5)) // tick + clock.advance(by: .seconds(5)) // tick await sleepCalls.next() - clock.advance(by: .seconds(5)) // tick + clock.advance(by: .seconds(5)) // tick await sleepCalls.next() - await sleepCalls.next() // export - XCTAssertEqual(transport.transported.load(ordering: .relaxed), 1, file: file, line: line) + await sleepCalls.next() // export + XCTAssertEqual( + transport.transported.load(ordering: .relaxed), 1, file: file, line: line) group.cancelAll() } @@ -116,7 +177,7 @@ final class IntegrationTests: XCTestCase { message: "oh, something bad happened", metadata: ["log": "swift"], source: "log-loki", - file: #filePath, + file: #filePath, function: #function, line: #line ) diff --git a/Tests/LoggingLokiTests/LokiLogHandlerTests.swift b/Tests/LoggingLokiTests/LokiLogHandlerTests.swift index 74c23dd..bf345fb 100644 --- a/Tests/LoggingLokiTests/LokiLogHandlerTests.swift +++ b/Tests/LoggingLokiTests/LokiLogHandlerTests.swift @@ -1,9 +1,24 @@ -import XCTest +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftLogLoki open source project +// +// Copyright (c) 2024 Timo Zacherl and the SwiftLogLoki project authors +// Licensed under Apache License v2.0 +// +// See LICENSE for license information +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + import NIOCore import NIOHTTP1 -@testable import LoggingLoki +import XCTest + import struct Logging.Logger +@testable import LoggingLoki + final class TestTransformer: LokiTransformer, @unchecked Sendable { var logs: [LokiLog.Transport]? var labels: [String: String]? @@ -25,7 +40,7 @@ final class TestTransport: LokiTransport { _ data: ByteBuffer, url: String, headers: HTTPHeaders - ) async throws { } + ) async throws {} } final class LokiLogHandlerTests: XCTestCase { @@ -51,17 +66,21 @@ final class LokiLogHandlerTests: XCTestCase { let processing = Task { try await processor.run() } - let handler = LokiLogHandler(label: expectedLabel, service: expectedService, processor: processor) + let handler = LokiLogHandler( + label: expectedLabel, service: expectedService, processor: processor) - handler.log(level: .error, message: "\(expectedLogMessage)", metadata: ["log": "swift"], source: expectedSource, file: expectedFile, function: expectedFunction, line: expectedLine) - - clock.advance(by: .seconds(5)) // tick + handler.log( + level: .error, message: "\(expectedLogMessage)", metadata: ["log": "swift"], + source: expectedSource, file: expectedFile, function: expectedFunction, + line: expectedLine) + + clock.advance(by: .seconds(5)) // tick await sleepCalls.next() - clock.advance(by: .seconds(5)) // tick + clock.advance(by: .seconds(5)) // tick await sleepCalls.next() - await sleepCalls.next() // await export + await sleepCalls.next() // await export try checkIfLogExists(for: transformer) processing.cancel() @@ -81,26 +100,36 @@ final class LokiLogHandlerTests: XCTestCase { let processing = Task { try await processor.run() } - let handler = LokiLogHandler(label: expectedLabel, service: expectedService, processor: processor) + let handler = LokiLogHandler( + label: expectedLabel, service: expectedService, processor: processor) + + handler.log( + level: .error, message: "\(expectedLogMessage)", metadata: ["log": "swift"], + source: expectedSource, file: expectedFile, function: expectedFunction, + line: expectedLine) - handler.log(level: .error, message: "\(expectedLogMessage)", metadata: ["log": "swift"], source: expectedSource, file: expectedFile, function: expectedFunction, line: expectedLine) - - clock.advance(by: .seconds(5)) // tick + clock.advance(by: .seconds(5)) // tick await sleepCalls.next() - handler.log(level: .error, message: "\(expectedLogMessage)", metadata: ["log": "swift"], source: expectedSource, file: expectedFile, function: expectedFunction, line: expectedLine) - - clock.advance(by: .seconds(5)) // tick + handler.log( + level: .error, message: "\(expectedLogMessage)", metadata: ["log": "swift"], + source: expectedSource, file: expectedFile, function: expectedFunction, + line: expectedLine) + + clock.advance(by: .seconds(5)) // tick await sleepCalls.next() XCTAssertNil(transformer.logs?.first) - - handler.log(level: .error, message: "\(expectedLogMessage)", metadata: ["log": "swift"], source: expectedSource, file: expectedFile, function: expectedFunction, line: expectedLine) - - clock.advance(by: .seconds(5)) // tick + + handler.log( + level: .error, message: "\(expectedLogMessage)", metadata: ["log": "swift"], + source: expectedSource, file: expectedFile, function: expectedFunction, + line: expectedLine) + + clock.advance(by: .seconds(5)) // tick await sleepCalls.next() - - await sleepCalls.next() // await export + + await sleepCalls.next() // await export try checkIfLogExists(for: transformer) processing.cancel() @@ -111,7 +140,8 @@ final class LokiLogHandlerTests: XCTestCase { let transformer = TestTransformer() let clock = TestClock() let processor = LokiLogProcessor( - configuration: .init(lokiURL: "http://localhost:3100", maxBatchTimeInterval: .seconds(10)), + configuration: .init( + lokiURL: "http://localhost:3100", maxBatchTimeInterval: .seconds(10)), transport: transport, transformer: transformer, clock: clock @@ -120,70 +150,99 @@ final class LokiLogHandlerTests: XCTestCase { let processing = Task { try await processor.run() } - let handler = LokiLogHandler(label: expectedLabel, service: expectedService, processor: processor) - handler.log(level: .error, message: "\(expectedLogMessage)", metadata: ["log": "swift"], source: expectedSource, file: expectedFile, function: expectedFunction, line: expectedLine) + let handler = LokiLogHandler( + label: expectedLabel, service: expectedService, processor: processor) + handler.log( + level: .error, message: "\(expectedLogMessage)", metadata: ["log": "swift"], + source: expectedSource, file: expectedFile, function: expectedFunction, + line: expectedLine) await sleepCalls.next() XCTAssertNil(transformer.logs?.first) // move forward in time until max batch time interval is exceeded - clock.advance(by: .seconds(5)) // tick + clock.advance(by: .seconds(5)) // tick await sleepCalls.next() - clock.advance(by: .seconds(5)) // tick + clock.advance(by: .seconds(5)) // tick await sleepCalls.next() - handler.log(level: .error, message: "\(expectedLogMessage)", metadata: ["log": "swift"], source: expectedSource, file: expectedFile, function: expectedFunction, line: expectedLine) + handler.log( + level: .error, message: "\(expectedLogMessage)", metadata: ["log": "swift"], + source: expectedSource, file: expectedFile, function: expectedFunction, + line: expectedLine) await sleepCalls.next() try checkIfLogExists(for: transformer) processing.cancel() } func testMetadataPreparation() { - let metadata1 = LokiLogHandler.prepareMetadata(base: [:], provider: .init({ [:] }), explicit: [:]) + let metadata1 = LokiLogHandler.prepareMetadata( + base: [:], provider: .init({ [:] }), explicit: [:]) XCTAssertEqual(metadata1, [:]) - let metadata2 = LokiLogHandler.prepareMetadata(base: ["hello": "there"], provider: .init({ [:] }), explicit: [:]) + let metadata2 = LokiLogHandler.prepareMetadata( + base: ["hello": "there"], provider: .init({ [:] }), explicit: [:]) XCTAssertEqual(metadata2, ["hello": "there"]) - let metadata3 = LokiLogHandler.prepareMetadata(base: ["hello": "there"], provider: .init({ ["provided": "metadata"] }), explicit: [:]) + let metadata3 = LokiLogHandler.prepareMetadata( + base: ["hello": "there"], provider: .init({ ["provided": "metadata"] }), explicit: [:]) XCTAssertEqual(metadata3, ["hello": "there", "provided": "metadata"]) - let metadata4 = LokiLogHandler.prepareMetadata(base: ["hello": "there"], provider: .init({ ["provided": "metadata"] }), explicit: ["explicit": "metadata"]) - XCTAssertEqual(metadata4, ["hello": "there", "provided": "metadata", "explicit": "metadata"]) - let metadata5 = LokiLogHandler.prepareMetadata(base: ["hello": "there"], provider: nil, explicit: ["explicit": "metadata"]) + let metadata4 = LokiLogHandler.prepareMetadata( + base: ["hello": "there"], provider: .init({ ["provided": "metadata"] }), + explicit: ["explicit": "metadata"]) + XCTAssertEqual( + metadata4, ["hello": "there", "provided": "metadata", "explicit": "metadata"]) + let metadata5 = LokiLogHandler.prepareMetadata( + base: ["hello": "there"], provider: nil, explicit: ["explicit": "metadata"]) XCTAssertEqual(metadata5, ["hello": "there", "explicit": "metadata"]) - let metadata6 = LokiLogHandler.prepareMetadata(base: ["hello": "there"], provider: nil, explicit: nil) + let metadata6 = LokiLogHandler.prepareMetadata( + base: ["hello": "there"], provider: nil, explicit: nil) XCTAssertEqual(metadata6, ["hello": "there"]) - let metadata7 = LokiLogHandler.prepareMetadata(base: ["hello": "there"], provider: .init({ ["hello": "how are you"] }), explicit: nil) + let metadata7 = LokiLogHandler.prepareMetadata( + base: ["hello": "there"], provider: .init({ ["hello": "how are you"] }), explicit: nil) XCTAssertEqual(metadata7, ["hello": "how are you"]) - let metadata8 = LokiLogHandler.prepareMetadata(base: ["hello": "there"], provider: .init({ ["hello": "how are you"] }), explicit: ["hello": "I am fine"]) + let metadata8 = LokiLogHandler.prepareMetadata( + base: ["hello": "there"], provider: .init({ ["hello": "how are you"] }), + explicit: ["hello": "I am fine"]) XCTAssertEqual(metadata8, ["hello": "I am fine"]) - var handler = LokiLogHandler(label: "test", processor: .init(configuration: .init(lokiURL: ""))) + var handler = LokiLogHandler( + label: "test", processor: .init(configuration: .init(lokiURL: ""))) handler[metadataKey: "key"] = "value" XCTAssertEqual(handler.metadata, ["key": "value"]) XCTAssertEqual(handler[metadataKey: "key"], "value") } - func checkIfLogExists(for transformer: TestTransformer, file: StaticString = #filePath, line: UInt = #line) throws { + func checkIfLogExists( + for transformer: TestTransformer, file: StaticString = #filePath, line: UInt = #line + ) throws { let firstLog = try XCTUnwrap(transformer.logs?.first, file: file, line: line) XCTAssert(firstLog.line.contains(expectedLogMessage), file: file, line: line) - XCTAssert(firstLog.line.contains(Logger.Level.error.rawValue.uppercased()), file: file, line: line) + XCTAssert( + firstLog.line.contains(Logger.Level.error.rawValue.uppercased()), file: file, line: line + ) XCTAssertNotNil(firstLog.timestamp, file: file, line: line) - XCTAssert(transformer.labels?.contains(where: { key, value in - value == expectedSource && key == "source" - }) ?? false, file: file, line: line) - XCTAssert(transformer.labels?.contains(where: { key, value in - value == expectedFile && key == "file" - }) ?? false, file: file, line: line) - XCTAssert(transformer.labels?.contains(where: { key, value in - value == expectedFunction && key == "function" - }) ?? false, file: file, line: line) - XCTAssert(transformer.labels?.contains(where: { key, value in - value == String(expectedLine) && key == "line" - }) ?? false, file: file, line: line) - XCTAssert(transformer.labels?.contains(where: { key, value in - value == expectedLabel && key == "logger" - }) ?? false, file: file, line: line) - XCTAssert(transformer.labels?.contains(where: { key, value in - value == expectedService && key == "service" - }) ?? false, file: file, line: line) + XCTAssert( + transformer.labels?.contains(where: { key, value in + value == expectedSource && key == "source" + }) ?? false, file: file, line: line) + XCTAssert( + transformer.labels?.contains(where: { key, value in + value == expectedFile && key == "file" + }) ?? false, file: file, line: line) + XCTAssert( + transformer.labels?.contains(where: { key, value in + value == expectedFunction && key == "function" + }) ?? false, file: file, line: line) + XCTAssert( + transformer.labels?.contains(where: { key, value in + value == String(expectedLine) && key == "line" + }) ?? false, file: file, line: line) + XCTAssert( + transformer.labels?.contains(where: { key, value in + value == expectedLabel && key == "logger" + }) ?? false, file: file, line: line) + XCTAssert( + transformer.labels?.contains(where: { key, value in + value == expectedService && key == "service" + }) ?? false, file: file, line: line) } } diff --git a/Tests/LoggingLokiTests/LokiLogProcessorConfigurationTests.swift b/Tests/LoggingLokiTests/LokiLogProcessorConfigurationTests.swift index 55ebf3c..1d70f60 100644 --- a/Tests/LoggingLokiTests/LokiLogProcessorConfigurationTests.swift +++ b/Tests/LoggingLokiTests/LokiLogProcessorConfigurationTests.swift @@ -1,4 +1,18 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftLogLoki open source project +// +// Copyright (c) 2024 Timo Zacherl and the SwiftLogLoki project authors +// Licensed under Apache License v2.0 +// +// See LICENSE for license information +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + import XCTest + @testable import LoggingLoki final class LokiLogProcessorConfigurationTests: XCTestCase { diff --git a/Tests/LoggingLokiTests/LokiLogProcessorTests.swift b/Tests/LoggingLokiTests/LokiLogProcessorTests.swift index 50a82ee..9891df1 100644 --- a/Tests/LoggingLokiTests/LokiLogProcessorTests.swift +++ b/Tests/LoggingLokiTests/LokiLogProcessorTests.swift @@ -1,4 +1,18 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftLogLoki open source project +// +// Copyright (c) 2024 Timo Zacherl and the SwiftLogLoki project authors +// Licensed under Apache License v2.0 +// +// See LICENSE for license information +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + import XCTest + @testable import LoggingLoki final class LokiLogProcessorTests: XCTestCase { @@ -38,7 +52,10 @@ final class LokiLogProcessorTests: XCTestCase { ) let formatted = processor.makeLog(raw) XCTAssertNil(formatted.metadata) - XCTAssertEqual(formatted.line, #"INFO: My log message [additional_key: value with whitespace, basic_key: basic_value]"#) + XCTAssertEqual( + formatted.line, + #"INFO: My log message [additional_key: value with whitespace, basic_key: basic_value]"# + ) } func testLogFmtFormatEmptyMetadata() { diff --git a/Tests/LoggingLokiTests/MockClock.swift b/Tests/LoggingLokiTests/MockClock.swift index 4f08653..b284cbc 100644 --- a/Tests/LoggingLokiTests/MockClock.swift +++ b/Tests/LoggingLokiTests/MockClock.swift @@ -1,3 +1,16 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftLogLoki open source project +// +// Copyright (c) 2024 Timo Zacherl and the SwiftLogLoki project authors +// Licensed under Apache License v2.0 +// +// See LICENSE for license information +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// + //===----------------------------------------------------------------------===// // // This source file is part of the Swift OTel open source project @@ -61,7 +74,8 @@ public final class TestClock: Clock, @unchecked Sendable { struct State { // We should use a Heap here - var continuations: [(id: UInt64, deadline: Instant, continuation: CheckedContinuation)] + var continuations: + [(id: UInt64, deadline: Instant, continuation: CheckedContinuation)] var now: Instant } diff --git a/docker-compose.yml b/docker-compose.yaml similarity index 100% rename from docker-compose.yml rename to docker-compose.yaml diff --git a/scripts/check-for-broken-symlinks.sh b/scripts/check-for-broken-symlinks.sh new file mode 100755 index 0000000..0523035 --- /dev/null +++ b/scripts/check-for-broken-symlinks.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +##===----------------------------------------------------------------------===## +## +## This source file is part of the SwiftLogLoki open source project +## +## Copyright (c) 2024 Timo Zacherl and the SwiftLogLoki project authors +## Licensed under Apache License v2.0 +## +## See LICENSE for license information +## +## SPDX-License-Identifier: Apache-2.0 +## +##===----------------------------------------------------------------------===## + +set -euo pipefail + +log() { printf -- "** %s\n" "$*" >&2; } +error() { printf -- "** ERROR: %s\n" "$*" >&2; } +fatal() { error "$@"; exit 1; } + +CURRENT_SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +REPO_ROOT="$(git -C "${CURRENT_SCRIPT_DIR}" rev-parse --show-toplevel)" + +log "Checking for broken symlinks..." +NUM_BROKEN_SYMLINKS=0 +while read -r -d '' file; do + if ! test -e "${REPO_ROOT}/${file}"; then + error "Broken symlink: ${file}" + ((NUM_BROKEN_SYMLINKS++)) + fi +done < <(git -C "${REPO_ROOT}" ls-files -z) + +if [ "${NUM_BROKEN_SYMLINKS}" -gt 0 ]; then + fatal "❌ Found ${NUM_BROKEN_SYMLINKS} symlinks." +fi + +log "✅ Found 0 symlinks." diff --git a/scripts/check-for-unacceptable-language.sh b/scripts/check-for-unacceptable-language.sh new file mode 100755 index 0000000..41e7705 --- /dev/null +++ b/scripts/check-for-unacceptable-language.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +##===----------------------------------------------------------------------===## +## +## This source file is part of the SwiftLogLoki open source project +## +## Copyright (c) 2024 Timo Zacherl and the SwiftLogLoki project authors +## Licensed under Apache License v2.0 +## +## See LICENSE for license information +## +## SPDX-License-Identifier: Apache-2.0 +## +##===----------------------------------------------------------------------===## + +set -euo pipefail + +log() { printf -- "** %s\n" "$*" >&2; } +error() { printf -- "** ERROR: %s\n" "$*" >&2; } +fatal() { error "$@"; exit 1; } + +CURRENT_SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +REPO_ROOT="$(git -C "${CURRENT_SCRIPT_DIR}" rev-parse --show-toplevel)" +UNACCEPTABLE_LANGUAGE_PATTERNS_PATH="${CURRENT_SCRIPT_DIR}/unacceptable-language.txt" + +log "Checking for unacceptable language..." +PATHS_WITH_UNACCEPTABLE_LANGUAGE=$(git -C "${REPO_ROOT}" grep \ + -l -F -w \ + -f "${UNACCEPTABLE_LANGUAGE_PATTERNS_PATH}" \ + -- \ + ":(exclude)${UNACCEPTABLE_LANGUAGE_PATTERNS_PATH}" \ +) || true | /usr/bin/paste -s -d " " - + +if [ -n "${PATHS_WITH_UNACCEPTABLE_LANGUAGE}" ]; then + fatal "❌ Found unacceptable language in files: ${PATHS_WITH_UNACCEPTABLE_LANGUAGE}." +fi + +log "✅ Found no unacceptable language." diff --git a/scripts/check-license-headers.sh b/scripts/check-license-headers.sh new file mode 100755 index 0000000..a9cc462 --- /dev/null +++ b/scripts/check-license-headers.sh @@ -0,0 +1,103 @@ +#!/usr/bin/env bash +##===----------------------------------------------------------------------===## +## +## This source file is part of the SwiftLogLoki open source project +## +## Copyright (c) 2024 Timo Zacherl and the SwiftLogLoki project authors +## Licensed under Apache License v2.0 +## +## See LICENSE for license information +## +## SPDX-License-Identifier: Apache-2.0 +## +##===----------------------------------------------------------------------===## + +set -euo pipefail + +log() { printf -- "** %s\n" "$*" >&2; } +error() { printf -- "** ERROR: %s\n" "$*" >&2; } +fatal() { error "$@"; exit 1; } + +CURRENT_SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +REPO_ROOT="$(git -C "${CURRENT_SCRIPT_DIR}" rev-parse --show-toplevel)" + +EXPECTED_FILE_HEADER_TEMPLATE="@@===----------------------------------------------------------------------===@@ +@@ +@@ This source file is part of the SwiftLogLoki open source project +@@ +@@ Copyright (c) YEARS Timo Zacherl and the SwiftLogLoki project authors +@@ Licensed under Apache License v2.0 +@@ +@@ See LICENSE for license information +@@ +@@ SPDX-License-Identifier: Apache-2.0 +@@ +@@===----------------------------------------------------------------------===@@" + +PATHS_WITH_MISSING_LICENSE=( ) + +read -ra PATHS_TO_CHECK_FOR_LICENSE <<< "$( \ + git -C "${REPO_ROOT}" ls-files -z \ + ":(exclude).gitignore" \ + ":(exclude).spi.yml" \ + ":(exclude).swift-format" \ + ":(exclude).github/*" \ + ":(exclude)CODE_OF_CONDUCT.md" \ + ":(exclude)CONTRIBUTING.md" \ + ":(exclude)CONTRIBUTORS.txt" \ + ":(exclude)LICENSE.txt" \ + ":(exclude)LICENSE" \ + ":(exclude)NOTICE.txt" \ + ":(exclude)Package.swift" \ + ":(exclude)Package.resolved" \ + ":(exclude)README.md" \ + ":(exclude)SECURITY.md" \ + ":(exclude)scripts/unacceptable-language.txt" \ + ":(exclude)docker/*" \ + ":(exclude)Makefile" \ + ":(exclude)docker-compose.yaml" \ + ":(exclude)**/*.docc/*" \ + ":(exclude)**/.gitignore" \ + ":(exclude)**/Package.swift" \ + ":(exclude)**/Package.resolved" \ + ":(exclude)**/README.md" \ + ":(exclude)**/docker-compose.yaml" \ + ":(exclude)**/docker/*" \ + ":(exclude)**/.dockerignore" \ + ":(exclude)**/Makefile" \ + ":(exclude)**/*.pb.swift" \ + ":(exclude)**/*.proto" \ + | xargs -0 \ +)" + +for FILE_PATH in "${PATHS_TO_CHECK_FOR_LICENSE[@]}"; do + FILE_BASENAME=$(basename -- "${FILE_PATH}") + FILE_EXTENSION="${FILE_BASENAME##*.}" + + case "${FILE_EXTENSION}" in + swift) EXPECTED_FILE_HEADER=$(sed -e 's|@@|//|g' <<<"${EXPECTED_FILE_HEADER_TEMPLATE}") ;; + yml) EXPECTED_FILE_HEADER=$(sed -e 's|@@|##|g' <<<"${EXPECTED_FILE_HEADER_TEMPLATE}") ;; + sh) EXPECTED_FILE_HEADER=$(cat <(echo '#!/usr/bin/env bash') <(sed -e 's|@@|##|g' <<<"${EXPECTED_FILE_HEADER_TEMPLATE}")) ;; + *) fatal "Unsupported file extension for file (exclude or update this script): ${FILE_PATH}" ;; + esac + EXPECTED_FILE_HEADER_LINECOUNT=$(wc -l <<<"${EXPECTED_FILE_HEADER}") + + FILE_HEADER=$(head -n "${EXPECTED_FILE_HEADER_LINECOUNT}" "${FILE_PATH}") + NORMALIZED_FILE_HEADER=$( + echo "${FILE_HEADER}" \ + | sed -e 's/202[34]-202[34]/YEARS/' -e 's/202[34]/YEARS/' \ + ) + + if ! diff -u \ + --label "Expected header" <(echo "${EXPECTED_FILE_HEADER}") \ + --label "${FILE_PATH}" <(echo "${NORMALIZED_FILE_HEADER}") + then + PATHS_WITH_MISSING_LICENSE+=("${FILE_PATH} ") + fi +done + +if [ "${#PATHS_WITH_MISSING_LICENSE[@]}" -gt 0 ]; then + fatal "❌ Found missing license header in files: ${PATHS_WITH_MISSING_LICENSE[*]}." +fi + +log "✅ Found no files with missing license header." diff --git a/scripts/run-swift-format.sh b/scripts/run-swift-format.sh new file mode 100755 index 0000000..932cf0d --- /dev/null +++ b/scripts/run-swift-format.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +##===----------------------------------------------------------------------===## +## +## This source file is part of the SwiftLogLoki open source project +## +## Copyright (c) 2024 Timo Zacherl and the SwiftLogLoki project authors +## Licensed under Apache License v2.0 +## +## See LICENSE for license information +## +## SPDX-License-Identifier: Apache-2.0 +## +##===----------------------------------------------------------------------===## + +set -euo pipefail + +log() { printf -- "** %s\n" "$*" >&2; } +error() { printf -- "** ERROR: %s\n" "$*" >&2; } +fatal() { error "$@"; exit 1; } + +CURRENT_SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +REPO_ROOT="$(git -C "${CURRENT_SCRIPT_DIR}" rev-parse --show-toplevel)" + +FORMAT_COMMAND=(lint --strict) +for arg in "$@"; do + if [ "$arg" == "--fix" ]; then + FORMAT_COMMAND=(format --in-place) + fi +done + +SWIFTFORMAT_BIN=${SWIFTFORMAT_BIN:-$(command -v swift-format)} || fatal "❌ SWIFTFORMAT_BIN unset and no swift-format on PATH" + +git -C "${REPO_ROOT}" ls-files -z '*.swift' \ + | grep -z -v -e 'Tests/LoggingLoki/Resources' \ + -e 'Sources/LoggingLoki/Documentation.docc' \ + -e 'Proto' \ + | xargs -0 "${SWIFTFORMAT_BIN}" "${FORMAT_COMMAND[@]}" --parallel \ + && SWIFT_FORMAT_RC=$? || SWIFT_FORMAT_RC=$? + +if [ "${SWIFT_FORMAT_RC}" -ne 0 ]; then + fatal "❌ Running swift-format produced errors. + + To fix, run the following command: + + % ./scripts/run-swift-format.sh --fix + " + exit "${SWIFT_FORMAT_RC}" +fi + +log "✅ Ran swift-format with no errors." diff --git a/scripts/soundness.sh b/scripts/soundness.sh new file mode 100755 index 0000000..8ca1113 --- /dev/null +++ b/scripts/soundness.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +##===----------------------------------------------------------------------===## +## +## This source file is part of the SwiftLogLoki open source project +## +## Copyright (c) 2024 Timo Zacherl and the SwiftLogLoki project authors +## Licensed under Apache License v2.0 +## +## See LICENSE for license information +## +## SPDX-License-Identifier: Apache-2.0 +## +##===----------------------------------------------------------------------===## + +set -euo pipefail + +log() { printf -- "** %s\n" "$*" >&2; } +error() { printf -- "** ERROR: %s\n" "$*" >&2; } +fatal() { error "$@"; exit 1; } + +CURRENT_SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +NUM_CHECKS_FAILED=0 + +FIX_FORMAT="" +for arg in "$@"; do + if [ "$arg" == "--fix" ]; then + FIX_FORMAT="--fix" + fi +done + +SCRIPT_PATHS=( + "${CURRENT_SCRIPT_DIR}/check-for-broken-symlinks.sh" + "${CURRENT_SCRIPT_DIR}/check-for-unacceptable-language.sh" + "${CURRENT_SCRIPT_DIR}/check-license-headers.sh" +) + +for SCRIPT_PATH in "${SCRIPT_PATHS[@]}"; do + log "Running ${SCRIPT_PATH}..." + if ! bash "${SCRIPT_PATH}"; then + ((NUM_CHECKS_FAILED+=1)) + fi +done + +log "Running swift-format..." +bash "${CURRENT_SCRIPT_DIR}"/run-swift-format.sh $FIX_FORMAT > /dev/null +FORMAT_EXIT_CODE=$? +if [ $FORMAT_EXIT_CODE -ne 0 ]; then + ((NUM_CHECKS_FAILED+=1)) +fi + +if [ "${NUM_CHECKS_FAILED}" -gt 0 ]; then + fatal "❌ ${NUM_CHECKS_FAILED} soundness check(s) failed." +fi + +log "✅ All soundness check(s) passed." diff --git a/scripts/unacceptable-language.txt b/scripts/unacceptable-language.txt new file mode 100755 index 0000000..6ac4a98 --- /dev/null +++ b/scripts/unacceptable-language.txt @@ -0,0 +1,15 @@ +blacklist +whitelist +slave +master +sane +sanity +insane +insanity +kill +killed +killing +hang +hung +hanged +hanging