Skip to content

Commit

Permalink
initial
Browse files Browse the repository at this point in the history
  • Loading branch information
tib committed Feb 27, 2024
0 parents commit da01edd
Show file tree
Hide file tree
Showing 17 changed files with 471 additions and 0 deletions.
26 changes: 26 additions & 0 deletions .github/workflows/run-checks.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
name: Run checks

on:
pull_request:
branches:
- main

jobs:

run-checks:
# runs-on: macOS-latest
runs-on: self-hosted
steps:

- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 1

- name: Install Dependencies
run: |
brew install mint
mint install NickLockwood/[email protected] --no-link
- name: run script
run: ./scripts/run-checks.sh
8 changes: 8 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
.DS_Store
/.build
/Packages
xcuserdata/
DerivedData/
.swiftpm/configuration/registries.json
.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata
.netrc
64 changes: 64 additions & 0 deletions .swift-format
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
{
"version": 1,
"lineLength": 80,
"maximumBlankLines": 1,
"fileScopedDeclarationPrivacy": {
"accessLevel": "private"
},
"tabWidth": 4,
"indentation": {
"spaces": 4
},
"indentConditionalCompilationBlocks": false,
"indentSwitchCaseLabels": false,
"lineBreakAroundMultilineExpressionChainComponents": true,
"lineBreakBeforeControlFlowKeywords": true,
"lineBreakBeforeEachArgument": true,
"lineBreakBeforeEachGenericRequirement": true,
"prioritizeKeepingFunctionOutputTogether": false,
"respectsExistingLineBreaks": true,
"spacesAroundRangeFormationOperators": false,
"multiElementCollectionTrailingCommas": true,
"rules": {
"AllPublicDeclarationsHaveDocumentation": false,
"AlwaysUseLiteralForEmptyCollectionInit": true,
"AlwaysUseLowerCamelCase": true,
"AmbiguousTrailingClosureOverload": true,
"BeginDocumentationCommentWithOneLineSummary": true,
"DoNotUseSemicolons": true,
"DontRepeatTypeInStaticProperties": true,
"FileScopedDeclarationPrivacy": true,
"FullyIndirectEnum": true,
"GroupNumericLiterals": true,
"IdentifiersMustBeASCII": true,
"NeverForceUnwrap": false,
"NeverUseForceTry": true,
"NeverUseImplicitlyUnwrappedOptionals": true,
"NoAccessLevelOnExtensionDeclaration": true,
"NoAssignmentInExpressions": true,
"NoBlockComments": true,
"NoCasesWithOnlyFallthrough": true,
"NoEmptyTrailingClosureParentheses": true,
"NoLabelsInCasePatterns": true,
"NoLeadingUnderscores": true,
"NoParensAroundConditions": true,
"NoPlaygroundLiterals": true,
"NoVoidReturnOnFunctionSignature": true,
"OmitExplicitReturns": true,
"OneCasePerLine": true,
"OneVariableDeclarationPerLine": true,
"OnlyOneTrailingClosureArgument": true,
"OrderedImports": true,
"ReplaceForEachWithForLoop": true,
"ReturnVoidInsteadOfEmptyTuple": true,
"TypeNamesShouldBeCapitalized": true,
"UseEarlyExits": true,
"UseLetInEveryBoundCaseVariable": true,
"UseShorthandTypeNames": true,
"UseSingleLinePropertyGetter": true,
"UseSynthesizedInitializer": true,
"UseTripleSlashForDocumentationComments": true,
"UseWhereClausesInForLoops": true,
"ValidateDocumentationComments": true
}
}
24 changes: 24 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
MIT License

Copyright (c) 2024 Binary Birds Ltd.

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.
22 changes: 22 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
SHELL=/bin/bash

build:
swift build

release:
swift build -c release

test:
swift test --parallel

test-with-coverage:
swift test --parallel --enable-code-coverage

clean:
rm -rf .build

check:
./scripts/run-checks.sh

format:
./scripts/run-swift-format.sh --fix
14 changes: 14 additions & 0 deletions Package.resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"pins" : [
{
"identity" : "swift-log",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-log",
"state" : {
"revision" : "e97a6fcb1ab07462881ac165fdbb37f067e205d5",
"version" : "1.5.4"
}
}
],
"version" : 2
}
27 changes: 27 additions & 0 deletions Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// swift-tools-version:5.9
import PackageDescription

let package = Package(
name: "swift-log-env",
platforms: [
.macOS(.v14),
.iOS(.v17),
.tvOS(.v17),
.watchOS(.v10),
.visionOS(.v1),
],
products: [
.library(name: "SwiftLogEnv", targets: ["SwiftLogEnv"])
],
dependencies: [
.package(url: "https://github.com/apple/swift-log", from: "1.0.0")
],
targets: [
.target(
name: "SwiftLogEnv",
dependencies: [
.product(name: "Logging", package: "swift-log")
]
)
]
)
32 changes: 32 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# SwiftLogEnv

Create custom loggers using a subsystem identifier and a log level.

## Install

Add the repository as a dependency:

```swift
.package(url: "https://github.com/binarybirds/swift-log-env", from: "1.0.0"),
```

Add `SwiftLogEnv` to the target dependencies:

```swift
.product(name: "SwiftLogEnv", package: "swift-log-env"),
```

Update the packages and you are ready.

## Usage example

Basic example

```swift
import SwiftLogEnv

let libLogger = Logger.subsystem("my-lib", .notice)
let appLogger = Logger.subsystem("my-app", .notice)

// LOG_LEVEL=info MY_LIB_LOG_LEVEL=trace swift run MyApp
```
59 changes: 59 additions & 0 deletions Sources/SwiftLogEnv/Logger+Subsystem.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import Foundation
import Logging

extension Logger {

///
/// Creates a custom logger using a subsystem identifier and a log level.
///
/// This method allows users to specify the log level for each subsystem, baded on environment variables:
/// - Set the `LOG_LEVEL` environment variable to override all subsystem log levels.
/// - Set a custom `{id}_LOG_LEVEL` variable to override the log level for a given subsystem.
///
/// - Note: When looking for environmental variables, the provided logger id is automatically lowercased, dashes (`-`) are always replaced with underscores (`_`) and a `_LOG_LEVEL` suffix is added to the id.
///
/// **Example**
///
/// ```swift
/// let libLogger = Logger.subsystem("my-lib", .notice)
/// let appLogger = Logger.subsystem("my-app", .notice)
/// ```
/// **Environmental variables**
/// ```sh
/// LOG_LEVEL=info MY_LIB_LOG_LEVEL=trace swift run MyApp
/// ```
/// **Expected log levels**
/// - libLogger = `.trace`
/// - appLogger = `.info`
///
/// - Parameters:
/// - id: The identifier of the logger subsystem, used as the label for the logger.
/// - level: Custom log level for the logger (default value: `.info`).
/// - Returns: A `Logger` instance
public static func subsystem(
_ id: String,
_ level: Logger.Level = .info
) -> Logger {
var logger = Logger(label: id)
logger.logLevel = level

let env = ProcessInfo.processInfo.environment
if let rawLevel = env["LOG_LEVEL"]?.lowercased(),
let level = Logger.Level(rawValue: rawLevel)
{
logger.logLevel = level
}

let envKey =
id
.appending("-log-level")
.replacingOccurrences(of: "-", with: "_")
.uppercased()
if let rawLevel = env[envKey]?.lowercased(),
let level = Logger.Level(rawValue: rawLevel)
{
logger.logLevel = level
}
return logger
}
}
24 changes: 24 additions & 0 deletions scripts/check-broken-symlinks.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#!/usr/bin/env bash
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."
24 changes: 24 additions & 0 deletions scripts/check-local-swift-dependencies.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#!/usr/bin/env bash
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)"

read -ra PATHS_TO_CHECK <<< "$( \
git -C "${REPO_ROOT}" ls-files -z \
"Package.swift" \
| xargs -0 \
)"

for FILE_PATH in "${PATHS_TO_CHECK[@]}"; do
echo $FILE_PATH
if [[ $(grep ".package(path:" "${FILE_PATH}"|wc -l) -ne 0 ]] ; then
fatal "❌ The '${FILE_PATH}' file contains local Swift package reference(s)."
fi
done

log "✅ Found 0 local Swift package dependency references."
24 changes: 24 additions & 0 deletions scripts/check-unacceptable-language.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#!/usr/bin/env bash
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."
19 changes: 19 additions & 0 deletions scripts/install-swift-format.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#!/usr/bin/env bash
set -euo pipefail

log() { printf -- "** %s\n" "$*" >&2; }
error() { printf -- "** ERROR: %s\n" "$*" >&2; }
fatal() { error "$@"; exit 1; }

# https://github.com/apple/swift-format

VERSION="509.0.0"

curl -L -o "${VERSION}.tar.gz" "https://github.com/apple/swift-format/archive/refs/tags/${VERSION}.tar.gz"
tar -xf "${VERSION}.tar.gz"
cd "swift-format-${VERSION}"
swift build -c release
install .build/release/swift-format /usr/local/bin/swift-format
cd ..
rm -f "${VERSION}.tar.gz"
rm -rf "swift-format-${VERSION}"
Loading

0 comments on commit da01edd

Please sign in to comment.