Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
jameshurst committed Nov 9, 2020
0 parents commit bf536e2
Show file tree
Hide file tree
Showing 19 changed files with 13,946 additions and 0 deletions.
26 changes: 26 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
name: CI

on:
push:
branches: [ master ]
pull_request:
branches: [ master ]

jobs:
build:
runs-on: macos-latest

steps:
- uses: actions/checkout@v2

- name: Cache tools
id: cache-tools
uses: actions/cache@v2
with:
path: |
tools/.bin
tools/.mint
key: ${{ runner.os }}-${{ hashFiles('tools/mint') }}-${{ hashFiles('Mintfile') }}

- name: Run CI script
run: ./scripts/run_ci.sh
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
.build/
.swiftpm/
xcuserdata/
tools/.bin/
tools/.mint/
*.xcodeproj
19 changes: 19 additions & 0 deletions .swiftformat
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# fileHeader
--header strip

# numberFormatting
--decimalgrouping 3,5
--fractiongrouping enabled

# unusedArguments
--stripunusedargs closure-only

# wrapArguments
--wraparguments before-first
--wrapcollections before-first

# disabled
--disable specifiers

# version
--swiftversion 5.3
100 changes: 100 additions & 0 deletions .swiftlint.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
included:
- Sources
- Tests

excluded:
- Tests/LinuxMain.swift
- Tests/PublicSuffixTests/XCTestManifests.swift

# -- MASTER -- #

analyzer_rules:
- unused_declaration
- unused_import

disabled_rules:
- file_length
- function_body_length
- type_body_length

opt_in_rules:
- anyobject_protocol
- array_init
- attributes
- closure_end_indentation
- closure_spacing
- collection_alignment
- contains_over_filter_count
- contains_over_filter_is_empty
- contains_over_first_not_nil
- contains_over_range_nil_comparison
- discouraged_object_literal
- empty_collection_literal
- empty_count
- empty_string
- empty_xctest_method
- enum_case_associated_values_count
- explicit_init
- extension_access_modifier
- fallthrough
- fatal_error_message
- file_header
- file_name
- first_where
- flatmap_over_map_reduce
- identical_operands
- implicit_return
- joined_default_parameter
- last_where
- legacy_multiple
- legacy_random
- literal_expression_end_indentation
- lower_acl_than_parent
- missing_docs
- modifier_order
- multiline_arguments
- multiline_literal_brackets
- multiline_parameters
- multiline_parameters_brackets
- nimble_operator
- nslocalizedstring_key
- number_separator
- operator_usage_whitespace
- overridden_super_call
- override_in_extension
- pattern_matching_keywords
- private_action
- private_outlet
- prohibited_interface_builder
- prohibited_super_call
- quick_discouraged_call
- quick_discouraged_focused_test
- quick_discouraged_pending_test
- reduce_into
- redundant_nil_coalescing
- redundant_type_annotation
- single_test_class
- sorted_first_last
- sorted_imports
- static_operator
- strong_iboutlet
- switch_case_on_newline
- toggle_bool
- unavailable_function
- unneeded_parentheses_in_closure_argument
- unowned_variable_capture
- untyped_error_in_catch
- vertical_parameter_alignment_on_call
- vertical_whitespace_closing_braces
- vertical_whitespace_opening_braces
- xct_specific_matcher
- yoda_condition

line_length:
warning: 120

number_separator:
minimum_length: 5

trailing_comma:
mandatory_comma: true
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2020 James Hurst

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.
3 changes: 3 additions & 0 deletions Mintfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
nicklockwood/SwiftFormat@0.47.2
realm/SwiftLint@0.40.3
thii/xcbeautify@0.8.1
24 changes: 24 additions & 0 deletions Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// swift-tools-version:5.3

import PackageDescription

let package = Package(
name: "PublicSuffix",
platforms: [
.iOS(.v9),
.tvOS(.v9),
.macOS(.v10_10),
],
products: [
.library(name: "PublicSuffix", targets: ["PublicSuffix"]),
],
targets: [
.target(
name: "PublicSuffix",
resources: [
.copy("public_suffix_list.dat")
]
),
.testTarget(name: "PublicSuffixTests", dependencies: ["PublicSuffix"]),
]
)
31 changes: 31 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# PublicSuffix

A Swift package that uses the [Public Suffix List](https://publicsuffix.org) to parse domain names.

## Usage

```swift
let components = SuffixList.default.parse("www.example.com")
print(components?.tld) // com
print(components?.sld) // example
print(domainName?.domain) // example.com
print(domainName?.subdomain) // www
```

## SuffixList

A `SuffixList` is used to parse domain names.

A bundled version of the public suffix list is included as `SuffixList.default`. You may also use your own custom suffix list.

## Installation

### Xcode 11+

* Select **File** > **Swift Packages** > **Add Package Dependency...**
* Enter the package repository URL: `https://github.com/jameshurst/PublicSuffix-Swift.git`
* Confirm the version and let Xcode resolve the package

## License

This library is released under the MIT license. See [LICENSE](LICENSE) for details.
16 changes: 16 additions & 0 deletions Sources/PublicSuffix/DomainComponents.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import Foundation

/// The components of a domain.
public struct DomainComponents {
/// The top-level domain (public suffix).
public let tld: String
/// The second-level domain (first part to the left of the TLD).
public let sld: String
/// The domain (SLD and TLD).
public let domain: String
/// The subdomain (parts to the left of the SLD).
public let subdomain: String?
/// Whether the domain has a known TLD. An unknown TLD may indicate that the TLD is invalid or hasn't been added to
/// the list yet.
public let hasKnownTLD: Bool
}
110 changes: 110 additions & 0 deletions Sources/PublicSuffix/Punycode.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import Foundation

// swiftlint:disable identifier_name
class Punycode {
private static let base: UInt32 = 36
private static let tMin: UInt32 = 1
private static let tMax: UInt32 = 26
private static let skew: UInt32 = 38
private static let damp: UInt32 = 700
private static let initialBias: UInt32 = 72
private static let initialN: UInt32 = 0x80
private static let delimiter = UnicodeScalar(0x2D)! // -

private static func adapt(delta: UInt32, numberOfPoints: UInt32, isFirstTime: Bool) -> UInt32 {
var delta = isFirstTime ? delta / damp : delta / 2
delta += delta / numberOfPoints

var k: UInt32 = 0
while delta > ((base - tMin) * tMax) / 2 {
delta /= base - tMin
k += base
}

return k + (((base - tMin + 1) * delta) / (delta + skew))
}

// swiftlint:disable:next cyclomatic_complexity
static func decode(_ input: String) -> String? {
let inputScalars = input.unicodeScalars
var scalars: [UnicodeScalar]
var output: String

if let index = inputScalars.lastIndex(of: delimiter) {
if index > inputScalars.startIndex {
scalars = Array(inputScalars[inputScalars.index(after: index)...])
} else {
scalars = Array(inputScalars)
}

output = String(inputScalars[..<index])
} else {
scalars = Array(inputScalars)
output = String()
}

var codePoint = initialN
var bias = initialBias
var i: UInt32 = 0

while !scalars.isEmpty {
let previousI = i
var weight: UInt32 = 1
var k = base

while true {
guard !scalars.isEmpty else {
return nil // End of input before the end of this delta
}

let byte = scalars.removeFirst().value
let digit: UInt32
switch byte {
case 0x30 ... 0x39:
digit = byte - 0x30 + 26
case 0x41 ... 0x5A:
digit = byte - 0x41
case 0x61 ... 0x7A:
digit = byte - 0x61
default:
return nil
}

if digit > (UInt32.max - i) / weight {
return nil // Overflow
}

i += digit * weight
let t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias)
if digit < t {
break
}

if weight > UInt32.max / (base - t) {
return nil // Overflow
}

weight *= base - t
k += base
}

let length = UInt32(output.count)
bias = adapt(delta: i - previousI, numberOfPoints: length + 1, isFirstTime: previousI == 0)
if i / (length + 1) > UInt32.max - codePoint {
return nil // Overflow
}

codePoint += i / (length + 1)
i %= length + 1

guard let scalar = UnicodeScalar(codePoint) else {
return nil
}

output.insert(Character(scalar), at: output.index(output.startIndex, offsetBy: Int(i)))
i += 1
}

return output
}
}
32 changes: 32 additions & 0 deletions Sources/PublicSuffix/Rule.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import Foundation

struct Rule: Equatable {
let labels: [String]
let isException: Bool

init(_ string: String) {
if string.hasPrefix("!") {
isException = true
labels = string.dropFirst().split(separator: ".").map(String.init)
} else {
isException = false
labels = string.split(separator: ".").map(String.init)
}
}

func matches(_ input: String) -> Bool {
// Split the input in to its labels
let inputLabels = input.components(separatedBy: ".")

// The input needs at least as many labels as the rule has
guard inputLabels.count >= labels.count else {
return false
}

// The input matches the rule if the input labels has the rule labels as a suffix
return inputLabels.reversed().starts(with: labels.reversed(), by: { inputLabel, label in
// A rule label always matches if its a wildcard
label == "*" ? true : inputLabel == label
})
}
}
Loading

0 comments on commit bf536e2

Please sign in to comment.