├── Tests └── SourceParsingFrameworkTests │ ├── Fixtures │ ├── empty_lines_sources_list.txt │ ├── Components.swift │ ├── SingleLineInheritedTypes.swift │ ├── MultiLineInheritedTypes.swift │ ├── Attributes.swift │ ├── Types.swift │ ├── sources_list_minescaped.txt │ └── sources_list.txt │ ├── AbstractSourceParsingTests.swift │ ├── FilteFilters │ ├── KeywordRegexFilterTests.swift │ └── UrlFilterTests.swift │ ├── Utilities │ ├── ExtensionsTests.swift │ └── FileEnumeratorTests.swift │ └── Tasks │ └── BaseFileFilterTaskTests.swift ├── .travis.yml ├── .gitignore ├── NOTICE.txt ├── Sources ├── SourceParsingFramework │ ├── GenericError.swift │ ├── FileFilters │ │ ├── FileFilter.swift │ │ ├── KeywordRegexFilter.swift │ │ └── UrlFilter.swift │ ├── Utilities │ │ ├── CachedFileReader.swift │ │ ├── Regex.swift │ │ ├── Extensions.swift │ │ ├── ProcessUtilities.swift │ │ ├── Logger.swift │ │ └── FileEnumerator.swift │ └── Tasks │ │ └── BaseFileFilterTask.swift └── CommandFramework │ ├── Extensions.swift │ ├── Command.swift │ └── AbstractCommand.swift ├── Package.swift ├── CONTRIBUTING.md ├── README.md ├── CODE_OF_CONDUCT.md └── LICENSE.txt /Tests/SourceParsingFrameworkTests/Fixtures/empty_lines_sources_list.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /Tests/SourceParsingFrameworkTests/Fixtures/Components.swift: -------------------------------------------------------------------------------- 1 | class MyComponent: Component { 2 | 3 | } 4 | -------------------------------------------------------------------------------- /Tests/SourceParsingFrameworkTests/Fixtures/SingleLineInheritedTypes.swift: -------------------------------------------------------------------------------- 1 | class MyClass2: SuperClass { 2 | 3 | } 4 | -------------------------------------------------------------------------------- /Tests/SourceParsingFrameworkTests/Fixtures/MultiLineInheritedTypes.swift: -------------------------------------------------------------------------------- 1 | class MyClass: SuperClass< 2 | Blah, 3 | Foo, 4 | Bar 5 | > { 6 | 7 | } 8 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: objective-c 2 | osx_image: xcode11.4 3 | 4 | env: 5 | - ACTION=test PLATFORM=Mac DESTINATION='platform=OS X' 6 | - ACTION=test PLATFORM=iOS DESTINATION='platform=iOS Simulator,name=iPhone XS' 7 | - ACTION=test PLATFORM=tvOS DESTINATION='platform=tvOS Simulator,name=Apple TV 4K' 8 | 9 | script: 10 | - swift test 11 | -------------------------------------------------------------------------------- /Tests/SourceParsingFrameworkTests/Fixtures/Attributes.swift: -------------------------------------------------------------------------------- 1 | class SomeChildClass: SomeParent { 2 | let a = "haha" 3 | 4 | override var myOtherProperty: Int { 5 | return someMethod() 6 | } 7 | 8 | override func myMethod(_ arg1: Int, arg2: String, _: Object) -> String { 9 | return "" 10 | } 11 | 12 | func voidReturnType() { 13 | 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Tests/SourceParsingFrameworkTests/Fixtures/Types.swift: -------------------------------------------------------------------------------- 1 | class MyClass { 2 | let a = "haha" 3 | 4 | var myOtherProperty: Int { 5 | return someMethod() 6 | } 7 | 8 | func myMethod(_ arg1: Int, arg2: String, _: Object) -> String { 9 | return "" 10 | } 11 | 12 | func voidReturnType() { 13 | 14 | } 15 | } 16 | 17 | protocol MyProtocol { 18 | 19 | } 20 | 21 | struct MyStruct { 22 | 23 | } 24 | 25 | let globalLet = "a" 26 | 27 | var globalVar = "b" 28 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## OSX 2 | *.DS_Store 3 | 4 | # Xcode Include to support Carthage for the Foundation project. 5 | *.xcodeproj 6 | *.xcworkspace 7 | 8 | ## Build generated 9 | build/ 10 | DerivedData/ 11 | 12 | ## Various settings 13 | *.pbxuser 14 | !default.pbxuser 15 | *.mode1v3 16 | !default.mode1v3 17 | *.mode2v3 18 | !default.mode2v3 19 | *.perspectivev3 20 | !default.perspectivev3 21 | xcuserdata/ 22 | 23 | ## Other 24 | *.moved-aside 25 | *.xccheckout 26 | *.xcscmblueprint 27 | 28 | ## Obj-C/Swift specific 29 | *.hmap 30 | *.ipa 31 | *.dSYM.zip 32 | *.dSYM 33 | 34 | # Swift Package Manager 35 | # 36 | # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. 37 | Packages/ 38 | Package.pins 39 | Package.resolved 40 | .build/ 41 | -------------------------------------------------------------------------------- /NOTICE.txt: -------------------------------------------------------------------------------- 1 | Swift Common depends on the following libraries: 2 | 3 | SourceKitten (https://github.com/jpsim/SourceKitten) 4 | Swift Package Manager (https://github.com/apple/swift-package-manager) 5 | Swift Concurrency (https://github.com/uber/swift-concurrency) 6 | 7 | Copyright (C) 2017 The Guava Authors 8 | 9 | Licensed under the Apache License, Version 2.0 (the "License"); 10 | you may not use this file except in compliance with the License. 11 | You may obtain a copy of the License at 12 | 13 | http://www.apache.org/licenses/LICENSE-2.0 14 | 15 | Unless required by applicable law or agreed to in writing, software 16 | distributed under the License is distributed on an "AS IS" BASIS, 17 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | See the License for the specific language governing permissions and 19 | limitations under the License. 20 | -------------------------------------------------------------------------------- /Sources/SourceParsingFramework/GenericError.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2018. Uber Technologies 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | // 16 | 17 | import Foundation 18 | 19 | /// A generic error that contains a message. 20 | public enum GenericError: Error { 21 | /// The error with a message. 22 | case withMessage(String) 23 | } 24 | -------------------------------------------------------------------------------- /Sources/CommandFramework/Extensions.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2018. Uber Technologies 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | // 16 | 17 | import Foundation 18 | import TSCUtility 19 | 20 | extension ArgumentParser.Result { 21 | 22 | public func get(_ arg: OptionArgument, withDefault defaultValue: Double) -> Double { 23 | if let value = get(arg) { 24 | return Double(value) 25 | } else { 26 | return defaultValue 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Sources/CommandFramework/Command.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2018. Uber Technologies 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | // 16 | 17 | import Foundation 18 | import TSCUtility 19 | 20 | /// A specific Needle instruction to be executed based on a set of input 21 | /// arguments. 22 | public protocol Command { 23 | /// Name used to check if this command should be executed. 24 | var name: String { get } 25 | 26 | /// Execute the command. 27 | /// 28 | /// - parameter arguments: The command line arguments to execute the 29 | /// command with. 30 | func execute(with arguments: ArgumentParser.Result) 31 | } 32 | -------------------------------------------------------------------------------- /Tests/SourceParsingFrameworkTests/AbstractSourceParsingTests.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2018. Uber Technologies 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | // 16 | 17 | import XCTest 18 | 19 | /// Base class for all parser related tests. 20 | class AbstractSourceParsingTests: XCTestCase { 21 | 22 | /// Retrieve the URL for a fixture file. 23 | /// 24 | /// - parameter file: The name of the file including extension. 25 | /// - returns: The fixture file URL. 26 | func fixtureUrl(for file: String) -> URL { 27 | return URL(fileURLWithPath: #file).deletingLastPathComponent().appendingPathComponent("Fixtures/\(file)") 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version:5.1 2 | import PackageDescription 3 | 4 | let package = Package( 5 | name: "Swift-Common", 6 | products: [ 7 | .library(name: "SourceParsingFramework", targets: ["SourceParsingFramework"]), 8 | .library(name: "CommandFramework", targets: ["CommandFramework"]), 9 | ], 10 | dependencies: [ 11 | .package(url: "https://github.com/apple/swift-tools-support-core.git", .upToNextMajor(from: "0.0.1")), 12 | .package(url: "https://github.com/uber/swift-concurrency.git", .upToNextMajor(from: "0.6.5")), 13 | ], 14 | targets: [ 15 | .target( 16 | name: "SourceParsingFramework", 17 | dependencies: [ 18 | "SwiftToolsSupport-auto", 19 | "Concurrency", 20 | ]), 21 | .testTarget( 22 | name: "SourceParsingFrameworkTests", 23 | dependencies: ["SourceParsingFramework"], 24 | exclude: [ 25 | "Fixtures", 26 | ]), 27 | .target( 28 | name: "CommandFramework", 29 | dependencies: [ 30 | "SwiftToolsSupport-auto", 31 | "SourceParsingFramework", 32 | ]), 33 | ], 34 | swiftLanguageVersions: [.v5] 35 | ) 36 | -------------------------------------------------------------------------------- /Sources/SourceParsingFramework/FileFilters/FileFilter.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2018. Uber Technologies 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | // 16 | 17 | import Foundation 18 | 19 | /// The base protocol of a file filter. It determines if the parsing 20 | /// sequence should continue based on the file. 21 | public protocol FileFilter: AnyObject { 22 | 23 | /// Execute the filter. 24 | /// 25 | /// - returns: `true` if the filter passed and the task should either 26 | /// execute the next filter or move onto the next task in the sequence 27 | /// if there are no more filters. `false` if the filter failed, and 28 | /// the task sequence should abort. 29 | func filter() -> Bool 30 | } 31 | -------------------------------------------------------------------------------- /Sources/SourceParsingFramework/Utilities/CachedFileReader.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2018. Uber Technologies 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | // 16 | 17 | import Foundation 18 | 19 | /// A singleton utility providing file content reading functionality 20 | /// with caching built-in. 21 | public class CachedFileReader { 22 | 23 | /// The singleton instance. 24 | public static let instance = CachedFileReader() 25 | 26 | /// Retrieve the content at the given URL. 27 | /// 28 | /// - note: If the URL file content has been read into memory already, 29 | /// the cached data is returned. Otherwise the file is read from disk. 30 | /// - parameter url: The URL to read the file from. 31 | /// - returns: The file content at the given URL. 32 | /// - throws: If reading file failed. 33 | public func content(forUrl url: URL) throws -> String { 34 | let nsUrl = url as NSURL 35 | if let cachedContent = cache.object(forKey: nsUrl) { 36 | return cachedContent as String 37 | } 38 | 39 | let content = try String(contentsOf: url) 40 | cache.setObject(content as NSString, forKey: nsUrl) 41 | return content 42 | } 43 | 44 | // MARK: - Private 45 | 46 | private let cache = NSCache() 47 | 48 | private init() {} 49 | } 50 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Swift Common 2 | 3 | Uber welcomes contributions of all kinds and sizes. This includes everything from from simple bug reports to large features. 4 | 5 | Before we can accept your contributions, we kindly ask you to sign our [Contributor License Agreement](https://cla-assistant.io/uber/swift-common). 6 | 7 | Workflow 8 | -------- 9 | 10 | We love GitHub issues! 11 | 12 | For small feature requests, an issue first proposing it for discussion or demo implementation in a PR suffice. 13 | 14 | For big features, please open an issue so that we can agree on the direction, and hopefully avoid investing a lot of time on a feature that might need reworking. 15 | 16 | Small pull requests for things like typos, bug fixes, etc are always welcome. 17 | 18 | DOs and DON'Ts 19 | -------------- 20 | 21 | * DO follow our [coding style](https://github.com/raywenderlich/swift-style-guide) 22 | * DO include tests when adding new features. When fixing bugs, start with adding a test that highlights how the current behavior is broken. 23 | * DO keep the discussions focused. When a new or related topic comes up it's often better to create new issue than to side track the discussion. 24 | 25 | * DON'T submit PRs that alter licensing related files or headers. If you believe there's a problem with them, file an issue and we'll be happy to discuss it. 26 | 27 | Guiding Principles 28 | ------------------ 29 | 30 | * We allow anyone to participate in our projects. Tasks can be carried out by anyone that demonstrates the capability to complete them 31 | * Always be respectful of one another. Assume the best in others and act with empathy at all times 32 | * Collaborate closely with individuals maintaining the project or experienced users. Getting ideas out in the open and seeing a proposal before it's a pull request helps reduce redundancy and ensures we're all connected to the decision making process 33 | -------------------------------------------------------------------------------- /Tests/SourceParsingFrameworkTests/FilteFilters/KeywordRegexFilterTests.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2018. Uber Technologies 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | // 16 | 17 | import XCTest 18 | @testable import SourceParsingFramework 19 | 20 | class KeywordRegexFilterTests: AbstractSourceParsingTests { 21 | 22 | private var content: String! 23 | 24 | override func setUp() { 25 | super.setUp() 26 | 27 | let contentUrl = fixtureUrl(for: "Components.swift") 28 | content = try! String(contentsOf: contentUrl) 29 | } 30 | 31 | func test_filter_noKeyword_verifyResult() { 32 | let filter = KeywordRegexFilter(content: content, keyword: "blah", regex: Regex(".")) 33 | 34 | let result = filter.filter() 35 | 36 | XCTAssertFalse(result) 37 | } 38 | 39 | func test_filter_hasKeywordNoMatchingRegex_verifyResult() { 40 | let filter = KeywordRegexFilter(content: content, keyword: "Component", regex: Regex("blah")) 41 | 42 | let result = filter.filter() 43 | 44 | XCTAssertFalse(result) 45 | } 46 | 47 | func test_filter_hasKeywordMatchingRegex_verifyResult() { 48 | let filter = KeywordRegexFilter(content: content, keyword: "Component", regex: Regex(": *Component *<")) 49 | 50 | let result = filter.filter() 51 | 52 | XCTAssertTrue(result) 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /Tests/SourceParsingFrameworkTests/Utilities/ExtensionsTests.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2018. Uber Technologies 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | // 16 | 17 | import XCTest 18 | 19 | class ExtensionsTests: AbstractSourceParsingTests { 20 | 21 | private var filePath: String! 22 | private var dirPath: String! 23 | 24 | override func setUp() { 25 | super.setUp() 26 | 27 | filePath = "\(#file)" 28 | let index = filePath.range(of: "/", options: .backwards)!.lowerBound 29 | dirPath = String(filePath.prefix(upTo: index)) 30 | } 31 | 32 | func test_sha256_verifyResults() { 33 | let input = "Some random string" 34 | let sha256 = input.shortSHA256Value 35 | XCTAssertEqual(sha256, "7e2ab276842ae9fb52ae") 36 | } 37 | 38 | func test_isDirectory_verifyResults() { 39 | XCTAssertFalse(filePath.isDirectory) 40 | XCTAssertTrue(dirPath.isDirectory) 41 | } 42 | 43 | func test_urlInit_verifyIsFileURL() { 44 | let fileUrl = URL(path: filePath) 45 | XCTAssertTrue(fileUrl.isFileURL) 46 | 47 | let dirUrl = URL(path: dirPath) 48 | XCTAssertFalse(dirUrl.isFileURL) 49 | } 50 | 51 | func test_sequence_isAnyElementInSet() { 52 | let array = [1, 42, 491, 10] 53 | let set1 = Set([42]) 54 | 55 | XCTAssertTrue(array.isAnyElement(in: set1)) 56 | 57 | let set2 = Set([41]) 58 | 59 | XCTAssertFalse(array.isAnyElement(in: set2)) 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /Tests/SourceParsingFrameworkTests/FilteFilters/UrlFilterTests.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2018. Uber Technologies 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | // 16 | 17 | import XCTest 18 | @testable import SourceParsingFramework 19 | 20 | class UrlFilterTests: AbstractSourceParsingTests { 21 | 22 | func test_filter_notSwift_verifyResult() { 23 | let url = fixtureUrl(for: "empty_lines_sources_list.txt") 24 | let filter = UrlFilter(url: url, exclusionSuffixes: [], exclusionPaths: []) 25 | 26 | let result = filter.filter() 27 | 28 | XCTAssertFalse(result) 29 | } 30 | 31 | func test_filter_swiftSuffixExcluded_verifyResult() { 32 | let url = fixtureUrl(for: "MultiLineInheritedTypes.swift") 33 | let filter = UrlFilter(url: url, exclusionSuffixes: ["Types"], exclusionPaths: []) 34 | 35 | let result = filter.filter() 36 | 37 | XCTAssertFalse(result) 38 | } 39 | 40 | func test_filter_swiftPathExcluded_verifyResult() { 41 | let url = fixtureUrl(for: "MultiLineInheritedTypes.swift") 42 | let filter = UrlFilter(url: url, exclusionSuffixes: [], exclusionPaths: ["/Fixtures"]) 43 | 44 | let result = filter.filter() 45 | 46 | XCTAssertFalse(result) 47 | } 48 | 49 | func test_filter_swiftNonExcluded_verifyResult() { 50 | let url = fixtureUrl(for: "MultiLineInheritedTypes.swift") 51 | let filter = UrlFilter(url: url, exclusionSuffixes: ["Tests"], exclusionPaths: ["/Data"]) 52 | 53 | let result = filter.filter() 54 | 55 | XCTAssertTrue(result) 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /Sources/SourceParsingFramework/Utilities/Regex.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2018. Uber Technologies 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | // 16 | 17 | import Foundation 18 | 19 | /// A simple wrapper around `NSRegularExpression` to make the API easier to use. 20 | public class Regex { 21 | 22 | /// The backing `NSRegularExpression`. 23 | public let expression: NSRegularExpression 24 | 25 | /// Initializer. 26 | /// 27 | /// - parameter expression: The expression in `String` format. 28 | public init(_ expression: String) { 29 | do { 30 | self.expression = try NSRegularExpression(pattern: expression, options: []) 31 | } catch { 32 | fatalError("Could not create NSRegularExpression for expression \(expression).") 33 | } 34 | } 35 | 36 | /// Retrieve the first match in the given content. 37 | /// 38 | /// - parameter content: The content to check from. 39 | /// - returns: The first matching result if there is a match. `nil` otherwise. 40 | public func firstMatch(in content: String) -> NSTextCheckingResult? { 41 | return expression.firstMatch(in: content, options: [], range: NSRange(location:0, length:content.count)) 42 | } 43 | 44 | /// Retrieve all the matches in the given content. 45 | /// 46 | /// - parameter content: The content to check from. 47 | /// - returns: All the matching results. 48 | public func matches(in content: String) -> [NSTextCheckingResult] { 49 | return expression.matches(in: content, options: [], range: NSRange(location:0, length:content.count)) 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /Sources/SourceParsingFramework/FileFilters/KeywordRegexFilter.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2018. Uber Technologies 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | // 16 | 17 | import Foundation 18 | 19 | /// A filter that checks if the given content contains the keyword and 20 | /// at least has one match of the given regular expression. 21 | /// 22 | /// - note: The keyword is always used first since string matching is 23 | /// more performant. If the content contains the keyword, then regular 24 | /// expression check is performed. 25 | open class KeywordRegexFilter: FileFilter { 26 | 27 | /// Initializer. 28 | /// 29 | /// - parameter content: The content to be filtered. 30 | /// - parameter keyword: The keyword the content must contain. 31 | /// - parameter regex: The regular expression the content must have 32 | /// at least one match. 33 | public init(content: String, keyword: String, regex: Regex) { 34 | self.content = content 35 | self.keyword = keyword 36 | self.regex = regex 37 | } 38 | 39 | /// Execute the filter. 40 | /// 41 | /// - returns: `true` if the file content contains the keyword and 42 | /// at least has one match of the regular expression. `false` 43 | /// otherwise. 44 | public final func filter() -> Bool { 45 | // Use simple string matching first since it's more performant. 46 | if !content.contains(keyword) { 47 | return false 48 | } 49 | 50 | // Match actual syntax using Regex. 51 | if regex.firstMatch(in: content) != nil { 52 | return true 53 | } 54 | 55 | return false 56 | } 57 | 58 | // MARK: - Private 59 | 60 | private let content: String 61 | private let keyword: String 62 | private let regex: Regex 63 | } 64 | -------------------------------------------------------------------------------- /Sources/CommandFramework/AbstractCommand.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2018. Uber Technologies 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | // 16 | 17 | import Foundation 18 | import SourceParsingFramework 19 | import TSCUtility 20 | 21 | /// The base class of all commands that perform a set of logic common 22 | /// to all commands. 23 | open class AbstractCommand: Command { 24 | /// The name used to check if this command should be executed. 25 | public let name: String 26 | 27 | /// The default value for waiting timeout in seconds. 28 | public let defaultTimeout: TimeInterval = 30.0 29 | 30 | /// Initializer. 31 | /// 32 | /// - parameter name: The name used to check if this command should 33 | /// be executed. 34 | /// - parameter overview: The overview description of this command. 35 | /// - parameter parser: The argument parser to use. 36 | public init(name: String, overview: String, parser: ArgumentParser) { 37 | self.name = name 38 | let subparser = parser.add(subparser: name, overview: overview) 39 | setupArguments(with: subparser) 40 | } 41 | 42 | /// Setup the arguments using the given parser. 43 | /// 44 | /// - parameter parser: The argument parser to use. 45 | open func setupArguments(with parser: ArgumentParser) { 46 | loggingLevel = parser.add(option: "--logging-level", shortName: "-lv", kind: String.self, usage: "The logging level to use.") 47 | } 48 | 49 | /// Execute the command. 50 | /// 51 | /// - parameter arguments: The command line arguments to execute the 52 | /// command with. 53 | open func execute(with arguments: ArgumentParser.Result) { 54 | if let loggingLevelArg = arguments.get(loggingLevel), let loggingLevel = LoggingLevel.level(from: loggingLevelArg) { 55 | set(minLoggingOutputLevel: loggingLevel) 56 | } 57 | } 58 | 59 | // MARK: - Private 60 | 61 | private var loggingLevel: OptionArgument! 62 | } 63 | -------------------------------------------------------------------------------- /Sources/SourceParsingFramework/FileFilters/UrlFilter.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2018. Uber Technologies 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | // 16 | 17 | import Foundation 18 | 19 | /// A filter that performs checks based on URL content. 20 | public class UrlFilter: FileFilter { 21 | 22 | /// Initializer. 23 | /// 24 | /// - parameter url: The file URL to read from. 25 | /// - parameter exclusionSuffixes: The list of file name suffixes to 26 | /// check from. If the given URL filename's suffix matches any in the 27 | /// this list, the URL will be excluded. 28 | /// - parameter exclusionPaths: The list of path components to check. 29 | /// If the given URL's path contains any elements in this list, the 30 | /// URL will be excluded. 31 | public init(url: URL, exclusionSuffixes: [String], exclusionPaths: [String]) { 32 | self.url = url 33 | self.exclusionSuffixes = exclusionSuffixes 34 | self.exclusionPaths = exclusionPaths 35 | } 36 | 37 | /// Execute the filter. 38 | /// 39 | /// - returns: `true` if the URL should be parsed. `false` otherwise. 40 | public func filter() -> Bool { 41 | if !url.isSwiftSource || urlHasExcludedSuffix || urlHasExcludedPath { 42 | return false 43 | } 44 | return true 45 | } 46 | 47 | // MARK: - Private 48 | 49 | private let url: URL 50 | private let exclusionSuffixes: [String] 51 | private let exclusionPaths: [String] 52 | 53 | private var urlHasExcludedSuffix: Bool { 54 | let name = url.deletingPathExtension().lastPathComponent 55 | for suffix in exclusionSuffixes { 56 | if name.hasSuffix(suffix) { 57 | return true 58 | } 59 | } 60 | return false 61 | } 62 | 63 | private var urlHasExcludedPath: Bool { 64 | let path = url.absoluteString 65 | for component in exclusionPaths { 66 | if path.contains(component) { 67 | return true 68 | } 69 | } 70 | return false 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Swift Common 2 | 3 | [![Build Status](https://travis-ci.com/uber/swift-common.svg?branch=master)](https://travis-ci.com/uber/swift-common?branch=master) 4 | [![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage) 5 | [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) 6 | 7 | ## Requirements 8 | 9 | - Xcode 9.3+ 10 | - Swift 4.0+ 11 | 12 | ## Overview 13 | 14 | Swift-Common contains reusable modules shared among a number of Uber's Swift open source projects, such as [Needle](https://github.com/uber/needle), [Swift Abstract Class](https://github.com/uber/swift-abstract-class) and etc. This code is not specifically designed for external consumption beyond Uber's open source projects. However, it is certainly possible for other projects to depend on these libraries. 15 | 16 | ### SourceParsingFramework 17 | 18 | This framework contains common code used for filtering and parsing Swift source code. 19 | 20 | ### CommandFramework 21 | 22 | This framework contains common code for parsing command line arguments. 23 | 24 | ## Installation 25 | 26 | Since Uber's Swift open source projects use [Swift Package Manager](https://github.com/apple/swift-package-manager) this project only supports installation via SPM. Please refer to the standard SPM package setup for details. 27 | 28 | ## Building 29 | 30 | First fetch the dependencies: 31 | 32 | ```bash 33 | $ swift package resolve 34 | ``` 35 | 36 | You can then build from the command-line: 37 | 38 | ```bash 39 | $ swift build 40 | ``` 41 | 42 | Or create an Xcode project and build using the IDE: 43 | 44 | ```bash 45 | $ swift package generate-xcodeproj 46 | ``` 47 | 48 | ## Testing 49 | 50 | From command-line. 51 | 52 | ```bash 53 | $ swift test 54 | ``` 55 | 56 | Or you can follow the steps above to generate a Xcode project and run tests within Xcode. 57 | 58 | ## Related projects 59 | 60 | If you like Swift Common, check out other related open source projects from our team: 61 | - [Needle](https://github.com/uber/needle): a compile-time safe Swift dependency injection framework. 62 | - [Swift Abstract Class](https://github.com/uber/swift-abstract-class): a light-weight library along with an executable that enables compile-time safe abstract class development for Swift projects. 63 | - [Swift Concurrency](https://github.com/uber/swift-concurrency): a set of concurrency utility classes used by Uber, inspired by the equivalent [java.util.concurrent](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/package-summary.html) package classes. 64 | 65 | ## License 66 | [![FOSSA Status](https://app.fossa.io/api/projects/git%2Bgithub.com%2Fuber%2Fswift-concurrency.svg?type=large)](https://app.fossa.io/projects/git%2Bgithub.com%2Fuber%2Fswift-concurrency?ref=badge_large) 67 | -------------------------------------------------------------------------------- /Tests/SourceParsingFrameworkTests/Fixtures/sources_list_minescaped.txt: -------------------------------------------------------------------------------- 1 | /Users/yiw/Uber/ios/apps/carbon/Driver/DriverCore/DriverCore/AppStartup/LaunchSteps/NetworkingStep.swift /Users/yiw/Uber/ios/apps/carbon/Driver/DriverCore/DriverCore/AppStartup/LaunchSteps/RootRIBStep.swift /Users/yiw/Uber/ios/apps/carbon/Driver/DriverCore/DriverCore/AppStartup/LaunchSteps/StacktraceGenerationStep.swift /Users/yiw/Uber/ios/apps/carbon/Driver/DriverCore/DriverCore/AppStartup/LaunchSteps/StartupReasonReporterStep.swift /Users/yiw/Uber/ios/apps/carbon/Driver/DriverCore/DriverCore/AppStartup/LaunchSteps/StorageStep.swift '/Users/yiw/Uber/ios/apps/carbon/PluginFeatures/ProfileRatings/ProfileRatings/Rides & Deliveries/Deliveries/DeliveryRatingsBuilder.swift' '/Users/yiw/Uber/ios/apps/carbon/PluginFeatures/ProfileRatings/ProfileRatings/Rides & Deliveries/Deliveries/DeliveryRatingsHistogramContainerView.swift' '/Users/yiw/Uber/ios/apps/carbon/PluginFeatures/ProfileRatings/ProfileRatings/Rides & Deliveries/Deliveries/DeliveryRatingsInteractor.swift' '/Users/yiw/Uber/ios/apps/carbon/PluginFeatures/ProfileRatings/ProfileRatings/Rides & Deliveries/Deliveries/DeliveryRatingsRouter.swift' '/Users/yiw/Uber/ios/apps/carbon/PluginFeatures/ProfileRatings/ProfileRatings/Rides & Deliveries/Deliveries/DeliveryRatingsSummaryViewController.swift' '/Users/yiw/Uber/ios/apps/carbon/PluginFeatures/ProfileRatings/ProfileRatings/Rides & Deliveries/Deliveries/DeliveryRatingsViewController.swift' '/Users/yiw/Uber/ios/apps/carbon/PluginFeatures/ProfileRatings/ProfileRatings/Rides & Deliveries/Deliveries/Late Delivery/DeliveriesRatingLateTripBuilder.swift' '/Users/yiw/Uber/ios/apps/carbon/PluginFeatures/ProfileRatings/ProfileRatings/Rides & Deliveries/Deliveries/Late Delivery/DeliveriesRatingLateTripInteractor.swift' '/Users/yiw/Uber/ios/apps/carbon/PluginFeatures/ProfileRatings/ProfileRatings/Rides & Deliveries/Deliveries/Late Delivery/DeliveriesRatingLateTripRouter.swift' '/Users/yiw/Uber/ios/apps/carbon/PluginFeatures/ProfileRatings/ProfileRatings/Rides & Deliveries/Deliveries/Late Delivery/DeliveriesRatingLateTripViewController.swift' '/Users/yiw/Uber/ios/apps/carbon/PluginFeatures/ProfileRatings/ProfileRatings/Rides & Deliveries/Deliveries/Late Delivery/Views/DeliveriesRatingLateTripDescriptionCell.swift' '/Users/yiw/Uber/ios/apps/carbon/PluginFeatures/ProfileRatings/ProfileRatings/Rides & Deliveries/Deliveries/Late Delivery/Views/DeliveriesRatingLateTripItemCell.swift' '/Users/yiw/Uber/ios/libraries/common/ContactPicker/ContactPicker/View Models/ContactViewModel.swift' /Users/yiw/Uber/ios/apps/carbon/Driver/DriverCore/DriverCore/Account/AccountBuilder.swift /Users/yiw/Uber/ios/apps/carbon/Driver/DriverCore/DriverCore/Account/AccountInteractor.swift /Users/yiw/Uber/ios/apps/carbon/Driver/DriverCore/DriverCore/Account/AccountRouter.swift /Users/yiw/Uber/ios/apps/carbon/Driver/DriverCore/DriverCore/Account/AccountViewController.swift /Users/yiw/Uber/ios/apps/carbon/Driver/DriverCore/DriverCore/Account/Component/AccountComponent+AccountNonCore.swift /Users/yiw/Uber/ios/apps/carbon/Driver/DriverCore/DriverCore/Account/Component/AccountComponent+VehicleSelection.swift /Users/yiw/Uber/ios/apps/carbon/Driver/DriverCore/DriverCore/Account/Views/AccountItemCell.swift /Users/yiw/Uber/ios/apps/carbon/Driver/DriverCore/DriverCore/Account/Views/AccountSignOutCell.swift 2 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at mobile-open-source@uber.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /Sources/SourceParsingFramework/Tasks/BaseFileFilterTask.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2018. Uber Technologies 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | // 16 | 17 | import Concurrency 18 | import Foundation 19 | 20 | /// The result of filtering the source file. 21 | public enum FilterResult { 22 | /// The source URL and content that should be processed further. 23 | case shouldProcess(URL, String) 24 | /// The file should be skipped. 25 | case skip 26 | } 27 | 28 | /// A base task implementation that checks the common aspects of a file 29 | /// to determine if the file needs to be parsed for AST. 30 | open class BaseFileFilterTask: AbstractTask { 31 | 32 | /// Initializer. 33 | /// 34 | /// - parameter url: The file URL to read from. 35 | /// - parameter exclusionSuffixes: The list of file name suffixes to 36 | /// check from. If the given URL filename's suffix matches any in the 37 | /// this list, the URL will be excluded. 38 | /// - parameter exclusionPaths: The list of path components to check. 39 | /// If the given URL's path contains any elements in this list, the 40 | /// URL will be excluded. 41 | /// - parameter taskId: The tracking task ID to use. 42 | public init(url: URL, exclusionSuffixes: [String], exclusionPaths: [String], taskId: Int = nonTrackingDefaultTaskId) { 43 | self.url = url 44 | self.exclusionSuffixes = exclusionSuffixes 45 | self.exclusionPaths = exclusionPaths 46 | super.init(id: taskId) 47 | } 48 | 49 | /// Execute the task and returns the filter result indicating if the file 50 | /// should be parsed. 51 | /// 52 | /// - returns: The `FilterResult`. 53 | /// - throws: Any error occurred during execution. 54 | public final override func execute() throws -> FilterResult { 55 | let urlFilter = UrlFilter(url: url, exclusionSuffixes: exclusionSuffixes, exclusionPaths: exclusionPaths) 56 | if !urlFilter.filter() { 57 | return FilterResult.skip 58 | } 59 | 60 | let content = try CachedFileReader.instance.content(forUrl: url) 61 | let filters = self.filters(for: content) 62 | for filter in filters { 63 | // If any filter passed, the file needs to be parsed. 64 | if filter.filter() { 65 | return FilterResult.shouldProcess(url, content) 66 | } 67 | } 68 | 69 | return FilterResult.skip 70 | } 71 | 72 | /// Create a set of filters for the given file content. 73 | /// 74 | /// - parameter content: The file content the returned filters should 75 | /// be applied on. 76 | /// - returns: A set of filters to use on the given content. 77 | open func filters(for content: String) -> [FileFilter] { 78 | return [] 79 | } 80 | 81 | // MARK: - Private 82 | 83 | private let url: URL 84 | private let exclusionSuffixes: [String] 85 | private let exclusionPaths: [String] 86 | } 87 | -------------------------------------------------------------------------------- /Tests/SourceParsingFrameworkTests/Fixtures/sources_list.txt: -------------------------------------------------------------------------------- 1 | /Users/yiw/Uber/ios/vendor/box/Box/Box.swift 2 | /Users/yiw/Uber/ios/vendor/box/Box/BoxType.swift 3 | /Users/yiw/Uber/ios/vendor/box/Box/MutableBox.swift 4 | /Users/yiw/Uber/ios/vendor/freddy/Sources/IntExtensions.swift 5 | /Users/yiw/Uber/ios/vendor/freddy/Sources/JSON.swift 6 | /Users/yiw/Uber/ios/vendor/freddy/Sources/JSONDecodable.swift 7 | /Users/yiw/Uber/ios/vendor/freddy/Sources/JSONEncodable.swift 8 | /Users/yiw/Uber/ios/vendor/freddy/Sources/JSONEncodingDetector.swift 9 | /Users/yiw/Uber/ios/vendor/freddy/Sources/JSONLiteralConvertible.swift 10 | /Users/yiw/Uber/ios/vendor/freddy/Sources/JSONOptional.swift 11 | /Users/yiw/Uber/ios/vendor/freddy/Sources/JSONParser.swift 12 | /Users/yiw/Uber/ios/vendor/freddy/Sources/JSONParsing.swift 13 | /Users/yiw/Uber/ios/vendor/freddy/Sources/JSONSerializing.swift 14 | /Users/yiw/Uber/ios/vendor/freddy/Sources/JSONSubscripting.swift 15 | /Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Concurrency/ConcurrentReadVariable.swift 16 | /Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Concurrency/DispatchOperators.swift 17 | /Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Concurrency/DispatchQueue.swift 18 | /Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Concurrency/ReadWriteLock.swift 19 | /Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Concurrency/RecursiveSyncLock.swift 20 | /Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Concurrency/Sychronized.swift 21 | /Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Concurrency/SynchronizedDictionary.swift 22 | /Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Date/Date.swift 23 | /Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Errors/Asserts.swift 24 | /Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Extensions/DeviceExtensions.swift 25 | /Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Extensions/Enumerations.swift 26 | /Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Extensions/FoundationExtensions.swift 27 | /Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Extensions/Math.swift 28 | /Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Extensions/ObfuscationExtensions.swift 29 | /Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Extensions/SequenceExtensions.swift 30 | /Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/FileSystem/FileManaging.swift 31 | /Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/LogModelMetadata/LogModelMetadata.swift 32 | /Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Obfuscation/Obfuscation.swift 33 | /Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Resources/BuildType.swift 34 | /Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Resources/BuildVersion.swift 35 | /Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Resources/BundleType.swift 36 | /Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Runtime/RunType.swift 37 | /Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/TestMocks/Manual/ManualProtocolMocks.swift 38 | /Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/TestMocks/PresidioFoundationProtocolMocks.swift 39 | -------------------------------------------------------------------------------- /Tests/SourceParsingFrameworkTests/Tasks/BaseFileFilterTaskTests.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2018. Uber Technologies 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | // 16 | 17 | import XCTest 18 | @testable import SourceParsingFramework 19 | 20 | class BaseFileFilterTaskTests: AbstractSourceParsingTests { 21 | 22 | func test_filter_notSwift_verifyResult() { 23 | let url = fixtureUrl(for: "empty_lines_sources_list.txt") 24 | let task = MockComponentFileFilterTask(url: url, exclusionSuffixes: [], exclusionPaths: []) 25 | 26 | let result = try! task.execute() 27 | 28 | switch result { 29 | case .shouldProcess(_, _): 30 | XCTFail() 31 | case .skip: 32 | break 33 | } 34 | } 35 | 36 | func test_filter_swiftSuffixExcluded_verifyResult() { 37 | let url = fixtureUrl(for: "MultiLineInheritedTypes.swift") 38 | let task = MockComponentFileFilterTask(url: url, exclusionSuffixes: ["Types"], exclusionPaths: []) 39 | 40 | let result = try! task.execute() 41 | 42 | switch result { 43 | case .shouldProcess(_, _): 44 | XCTFail() 45 | case .skip: 46 | break 47 | } 48 | } 49 | 50 | func test_filter_swiftPathExcluded_verifyResult() { 51 | let url = fixtureUrl(for: "MultiLineInheritedTypes.swift") 52 | let task = MockComponentFileFilterTask(url: url, exclusionSuffixes: [], exclusionPaths: ["/Fixtures"]) 53 | 54 | let result = try! task.execute() 55 | 56 | switch result { 57 | case .shouldProcess(_, _): 58 | XCTFail() 59 | case .skip: 60 | break 61 | } 62 | } 63 | 64 | func test_filter_swiftNonExcludedNoKeywordOrRegex_verifyResult() { 65 | let url = fixtureUrl(for: "MultiLineInheritedTypes.swift") 66 | let task = MockComponentFileFilterTask(url: url, exclusionSuffixes: ["Tests"], exclusionPaths: ["/Data"]) 67 | 68 | let result = try! task.execute() 69 | 70 | switch result { 71 | case .shouldProcess(_, _): 72 | XCTFail() 73 | case .skip: 74 | break 75 | } 76 | } 77 | 78 | func test_filter_swiftNonExcludedHasMatch_verifyResult() { 79 | let url = fixtureUrl(for: "Components.swift") 80 | let task = MockComponentFileFilterTask(url: url, exclusionSuffixes: ["Tests"], exclusionPaths: ["/Data"]) 81 | 82 | let result = try! task.execute() 83 | 84 | switch result { 85 | case .shouldProcess(let processUrl, let content): 86 | XCTAssertEqual(url, processUrl) 87 | XCTAssertEqual(content, try! String(contentsOf: url)) 88 | case .skip: 89 | XCTFail() 90 | } 91 | } 92 | } 93 | 94 | private class MockComponentFileFilterTask: BaseFileFilterTask { 95 | 96 | override func filters(for content: String) -> [FileFilter] { 97 | return [KeywordRegexFilter(content: content, keyword: "Component", regex: Regex(": *Component *<"))] 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /Sources/SourceParsingFramework/Utilities/Extensions.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2018. Uber Technologies 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | // 16 | 17 | import TSCBasic 18 | import Foundation 19 | 20 | /// Utility String extensions. 21 | extension String { 22 | 23 | /// The SHA256 value of this String. 24 | public var shortSHA256Value: String { 25 | return SHA256().hash(self).hexadecimalRepresentation.substring(with: NSRange(location: 0, length: 20))! 26 | } 27 | 28 | /// Return the same String with the first character lowercased. 29 | /// 30 | /// - returns: The same String with the first character lowercased. 31 | public func lowercasedFirstChar() -> String { 32 | let ommitFirstCharIndex = index(after: startIndex) 33 | return String(self[startIndex]).lowercased() + String(self[ommitFirstCharIndex...]) 34 | } 35 | 36 | /// Returns the substring of the given range. 37 | /// 38 | /// - parameter range: The `NSRange` to retrieve substring with. 39 | /// - returns: The substring if the range is valid. `nil` otherwise. 40 | public func substring(with range: NSRange) -> String? { 41 | guard let range = Range(range, in: self) else { 42 | return nil 43 | } 44 | return String(self[range]) 45 | } 46 | 47 | /// Check if this path represents a directory. 48 | /// 49 | /// - note: Use this property instead of `URL.isFileURL` property, since 50 | /// that property only checks for URL scheme, which can be inaccurate. 51 | public var isDirectory: Bool { 52 | var isDirectory = ObjCBool(false) 53 | FileManager.default.fileExists(atPath: self, isDirectory: &isDirectory) 54 | return isDirectory.boolValue 55 | } 56 | 57 | /// Check if this string contains any one of the elements in the 58 | /// given array. 59 | /// 60 | /// - parameter array: The list of elements to check. 61 | /// - returns: `true` if this string contains at least one element 62 | /// in the given array. `false` otherwise. 63 | public func containsAny(in array: [String]) -> Bool { 64 | for element in array { 65 | if contains(element) { 66 | return true 67 | } 68 | } 69 | return false 70 | } 71 | } 72 | 73 | /// Utility URL extensions. 74 | extension URL { 75 | 76 | /// Initializer. 77 | /// 78 | /// - note: This initializer first checks if the given path is a directory. 79 | /// If so, it initializes a directory URL. Otherwise a URL with the `file` 80 | /// scheme is initialized. This allows the returned URL to correctly return 81 | /// the `isFileURL` property. 82 | /// - parameter path: The `String` path to use. 83 | public init(path: String) { 84 | if path.isDirectory { 85 | self.init(string: path)! 86 | } else { 87 | self.init(fileURLWithPath: path) 88 | } 89 | } 90 | 91 | /// Check if this URL represents a Swift source file by examining its 92 | /// file extenson. 93 | /// 94 | /// - returns: `true` if the URL is a Swift source file. `false` 95 | /// otherwise. 96 | public var isSwiftSource: Bool { 97 | return pathExtension == "swift" 98 | } 99 | } 100 | 101 | /// Sequence extensions. 102 | extension Sequence where Element: Hashable { 103 | 104 | /// Checks if any elements of this sequence is in the given set. 105 | /// 106 | /// - parameter set: The set to check against. 107 | /// - returns: `true` if at least one of the elements in this sequence 108 | /// is in the given set. `false` otherwise. 109 | public func isAnyElement(in set: Set) -> Bool { 110 | for e in self { 111 | if set.contains(e) { 112 | return true 113 | } 114 | } 115 | return false 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /Sources/SourceParsingFramework/Utilities/ProcessUtilities.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2018. Uber Technologies 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | // 16 | 17 | import Foundation 18 | 19 | /// A set of utility functions for running processes. 20 | public protocol ProcessUtilities { 21 | 22 | /// The current list of processes without controlling ttys in jobs 23 | /// format. 24 | var currentNonControllingTTYSProcesses: String { get } 25 | 26 | /// A convinient method for killing all the processes with given name. 27 | /// This executes `/usr/bin/killall -9` with the given process name. 28 | /// 29 | /// - parameter processName: The name of the process to kill. 30 | /// - returns: `true` if succeeded. `false` otherwise. 31 | func killAll(_ processName: String) -> Bool 32 | 33 | /// Execute the given process with given arguments and return the 34 | /// standard output as a `String`. 35 | /// 36 | /// - parameter path: The path to the process to execute. 37 | /// - parameter process: The name of the process to execute. 38 | /// - parameter arguments: The list of arguments to supply to the 39 | /// process. 40 | /// - returns: The standard output content as a single `String` and 41 | /// the standard error content as a single `String`. 42 | func execute(path: String, processName: String, withArguments arguments: [String]) -> (output: String, error: String) 43 | } 44 | 45 | /// A set of utility functions for running processes. 46 | public class ProcessUtilitiesImpl: ProcessUtilities { 47 | 48 | /// Initializer. 49 | public init() {} 50 | 51 | /// The current list of processes without controlling ttys in jobs 52 | /// format. 53 | public var currentNonControllingTTYSProcesses: String { 54 | // Select processes without controlling ttys in jobs format. 55 | return execute(processName: "ps", withArguments: ["-xj"]).output.lowercased() 56 | } 57 | 58 | /// A convinient method for killing all the processes with given name. 59 | /// This executes `/usr/bin/killall -9` with the given process name. 60 | /// 61 | /// - parameter processName: The name of the process to kill. 62 | /// - returns: `true` if succeeded. `false` otherwise. 63 | public func killAll(_ processName: String) -> Bool { 64 | let result = execute(path: "/usr/bin/", processName: "killall", withArguments: ["-9", processName]) 65 | return result.error.isEmpty 66 | } 67 | 68 | /// Execute the given process with given arguments and return the 69 | /// standard output as a `String`. 70 | /// 71 | /// - parameter path: The path to the process to execute. 72 | /// - parameter process: The name of the process to execute. 73 | /// - parameter arguments: The list of arguments to supply to the 74 | /// process. 75 | /// - returns: The standard output content as a single `String` and 76 | /// the standard error content as a single `String`. 77 | public func execute(path: String = "/bin", processName: String, withArguments arguments: [String] = []) -> (output: String, error: String) { 78 | let justName = processName.starts(with: "/") ? String(processName.suffix(from: processName.index(processName.startIndex, offsetBy: 1))) : processName 79 | let justPath = path.hasSuffix("/") ? path : path + "/" 80 | 81 | let task = Process() 82 | task.launchPath = justPath + justName 83 | task.arguments = arguments 84 | let outputPipe = Pipe() 85 | task.standardOutput = outputPipe 86 | let errorPipe = Pipe() 87 | task.standardError = errorPipe 88 | task.launch() 89 | 90 | let output = read(pipe: outputPipe) ?? "" 91 | let error = read(pipe: errorPipe) ?? "" 92 | return (output, error) 93 | } 94 | 95 | // MARK: - Private 96 | 97 | private func read(pipe: Pipe) -> String? { 98 | let handle = pipe.fileHandleForReading 99 | let data = handle.readDataToEndOfFile() 100 | return String(data: data, encoding: .utf8) 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /Sources/SourceParsingFramework/Utilities/Logger.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2018. Uber Technologies 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | // 16 | 17 | import Concurrency 18 | import Foundation 19 | 20 | /// The various levels of logging. 21 | public enum LoggingLevel: Int { 22 | /// The most verbose level including all logs. 23 | case debug 24 | /// The level that includes everything except debug logs. 25 | case info 26 | /// The level that only includes warning logs. 27 | case warning 28 | /// The level that indicates a fatal error has occurred. 29 | case error 30 | 31 | /// An cute emoticon describing the log level. 32 | public var emoticon: String { 33 | switch self { 34 | case .debug: return "🐞" 35 | case .info: return "📋" 36 | case .warning: return "❗️" 37 | case .error: return "💩" 38 | } 39 | } 40 | 41 | /// A text description the log level. 42 | public var text: String { 43 | switch self { 44 | case .debug: return "debug" 45 | case .info: return "info" 46 | case .warning: return "warning" 47 | case .error: return "error" 48 | } 49 | } 50 | 51 | /// Retrieve the logging level based on the given String value. 52 | /// 53 | /// - parameter value: The `String` value to parse from. 54 | /// - returns: The corresponding `LoggingLevel` if there is one. 55 | /// `nil` otherwise. 56 | public static func level(from value: String) -> LoggingLevel? { 57 | switch value { 58 | case "debug": return .debug 59 | case "info": return .info 60 | case "warning": return .warning 61 | case "error": return .error 62 | default: return nil 63 | } 64 | } 65 | } 66 | 67 | // Use `AtomicInt` since logging may be invoked from multiple threads. 68 | private let minLoggingOutputLevel = AtomicInt(initialValue: LoggingLevel.warning.rawValue) 69 | 70 | /// Set the minimum logging level required to output a message. 71 | /// 72 | /// - parameter minLoggingOutputLevel: The minimum logging level. 73 | public func set(minLoggingOutputLevel level: LoggingLevel) { 74 | minLoggingOutputLevel.value = level.rawValue 75 | } 76 | 77 | /// Log the given message at the `debug` level. 78 | /// 79 | /// - parameter message: The message to log. 80 | /// - parameter path: The file path this error applies to 81 | /// (if specified, the log output changes to one that matches compiler error and can be parsed easily by build systems) 82 | /// - note: The mesasge is only logged if the current `minLoggingOutputLevel` 83 | /// is set at or below the `debug` level. 84 | public func debug(_ message: String, path: String? = nil) { 85 | log(message, atLevel: .debug, path: path) 86 | } 87 | 88 | /// Log the given message at the `info` level. 89 | /// 90 | /// - parameter message: The message to log. 91 | /// - parameter path: The file path this error applies to 92 | /// (if specified, the log output changes to one that matches compiler error and can be parsed easily by build systems) 93 | /// - note: The mesasge is only logged if the current `minLoggingOutputLevel` 94 | /// is set at or below the `info` level. 95 | public func info(_ message: String, path: String? = nil) { 96 | log(message, atLevel: .info, path: path) 97 | } 98 | 99 | /// Log the given message at the `warning` level. 100 | /// 101 | /// - parameter message: The message to log. 102 | /// - parameter path: The file path this error applies to 103 | /// (if specified, the log output changes to one that matches compiler error and can be parsed easily by build systems) 104 | /// - note: The mesasge is only logged if the current `minLoggingOutputLevel` 105 | /// is set at or below the `warning` level. 106 | public func warning(_ message: String, path: String? = nil) { 107 | log(message, atLevel: .warning, path: path) 108 | } 109 | 110 | /// Log the given message at the `error` level and terminate. 111 | /// 112 | /// - parameter message: The message to log. 113 | /// - parameter path: The file path this error applies to 114 | /// (if specified, the log output changes to one that matches compiler error and can be parsed easily by build systems) 115 | /// - returns: `Never`. 116 | /// - note: The mesasge is only logged if the current `minLoggingOutputLevel` 117 | /// is set at or below the `error` level. 118 | /// - note: This method terminates the program. It returns `Never`. 119 | public func error(_ message: String, path: String? = nil) -> Never { 120 | log(message, atLevel: .error, path: path) 121 | exit(1) 122 | } 123 | 124 | private func log(_ message: String, atLevel level: LoggingLevel, path: String?) { 125 | #if DEBUG 126 | UnitTestLogger.instance.log(message, at: level) 127 | #endif 128 | 129 | if level.rawValue >= minLoggingOutputLevel.value { 130 | if let path = path { 131 | print("\(path):1:1: \(level.text): \(message)") 132 | } else { 133 | print("\(level.text): \(level.emoticon) \(message)") 134 | } 135 | } 136 | } 137 | 138 | // MARK: - Unit Test 139 | 140 | /// A logger that accumulates log messages to support unit testing. 141 | public class UnitTestLogger { 142 | 143 | /// The singleton instance. 144 | public static let instance = UnitTestLogger() 145 | 146 | /// The current set of logged messages. 147 | public var messages: [String] { 148 | return lockedMessages.values 149 | } 150 | 151 | // NARK: - Private 152 | 153 | private let lockedMessages = LockedArray() 154 | 155 | private init() {} 156 | 157 | fileprivate func log(_ message: String, at level: LoggingLevel) { 158 | lockedMessages.append(message) 159 | } 160 | } 161 | 162 | private class LockedArray { 163 | 164 | private let lock = NSLock() 165 | private var unsafeValues = [ValueType]() 166 | 167 | fileprivate var values: [ValueType] { 168 | lock.lock() 169 | defer { 170 | lock.unlock() 171 | } 172 | return Array(unsafeValues) 173 | } 174 | 175 | fileprivate func append(_ value: ValueType) { 176 | lock.lock() 177 | defer { 178 | lock.unlock() 179 | } 180 | unsafeValues.append(value) 181 | } 182 | } 183 | -------------------------------------------------------------------------------- /Sources/SourceParsingFramework/Utilities/FileEnumerator.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2018. Uber Technologies 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | // 16 | 17 | import Foundation 18 | 19 | /// The supported formats for the sources list file. 20 | public enum SourcesListFileFormat { 21 | /// Newline format, where paths are separated by the newline character. 22 | case newline 23 | /// Minimum escaping format, where paths that contain spaces are 24 | /// escaped with single quotes while paths that don't contain any 25 | /// spaces are not wrapped with any quotes. Paths are separated by 26 | /// a single space character. 27 | case minEscaping 28 | 29 | /// Parse the given `String` value into the format enumeration. 30 | /// 31 | /// - parameter value: The `String` value to parse. 32 | /// - returns: The `SourcesListFileFormat` case. `nil` if the given 33 | /// string does not match any supported formats. 34 | public static func format(with value: String) -> SourcesListFileFormat? { 35 | switch value.lowercased() { 36 | case "newline": return .newline 37 | case "minescaping": return .minEscaping 38 | default: return nil 39 | } 40 | } 41 | } 42 | 43 | /// A utility class that provides file enumeration from a root directory. 44 | public class FileEnumerator { 45 | 46 | /// Initializer. 47 | public init() {} 48 | 49 | /// Enumerate all the files in the root URL. If the given URL is a 50 | /// directory, it is traversed recursively to surface all file URLs. 51 | /// If the given URL is a file, it is treated as a text file where 52 | /// each line is assumed to be a path to a file. 53 | /// 54 | /// - parameter rootUrl: The root URL to enumerate from. 55 | /// - parameter sourcesListFormatValue: The optional `String` value of 56 | /// the format used by the sources list file. If `nil` and the the given 57 | /// `rootUrl` is a file containing a list of Swift source paths, the 58 | /// `SourcesListFileFormat.newline` format is used. If the given `rootUrl` 59 | /// is not a file containing a list of Swift source paths, this value is 60 | /// ignored. 61 | /// - parameter handler: The closure to invoke when a file URL is found. 62 | /// - throws: `FileEnumerationError` if any errors occurred. 63 | public func enumerate(from rootUrl: URL, withSourcesListFormat sourcesListFormatValue: String?, handler: (URL) -> Void) throws { 64 | if rootUrl.isFileURL { 65 | if rootUrl.isSwiftSource { 66 | handler(rootUrl) 67 | } else { 68 | let format = try sourcesListFileFormat(from: sourcesListFormatValue, withDefault: .newline) 69 | let fileUrls = try self.fileUrls(fromSourcesList: rootUrl, with: format) 70 | for fileUrl in fileUrls { 71 | handler(fileUrl) 72 | } 73 | } 74 | } else { 75 | let enumerator = try newFileEnumerator(for: rootUrl) 76 | while let nextObjc = enumerator.nextObject() { 77 | if let fileUrl = nextObjc as? URL { 78 | handler(fileUrl) 79 | } 80 | } 81 | } 82 | } 83 | 84 | // MARK: - Private 85 | 86 | private func sourcesListFileFormat(from stringValue: String?, withDefault defaultFormat: SourcesListFileFormat) throws -> SourcesListFileFormat { 87 | if let stringValue = stringValue { 88 | if let parsedFormat = SourcesListFileFormat.format(with: stringValue) { 89 | return parsedFormat 90 | } else { 91 | throw GenericError.withMessage("Failed to parse sources list format \(stringValue)") 92 | } 93 | } else { 94 | return defaultFormat 95 | } 96 | } 97 | 98 | private func fileUrls(fromSourcesList listUrl: URL, with format: SourcesListFileFormat) throws -> [URL] { 99 | do { 100 | let content = try CachedFileReader.instance.content(forUrl: listUrl) 101 | 102 | let paths: [String] 103 | switch format { 104 | case .newline: 105 | paths = perLineFilePaths(from: content) 106 | case .minEscaping: 107 | paths = minEscapingFilePaths(from: content) 108 | } 109 | 110 | return paths 111 | .map { (path: String) -> URL in 112 | URL(fileURLWithPath: path) 113 | } 114 | } catch { 115 | throw GenericError.withMessage("Failed to read source paths from list file at \(listUrl) \(error)") 116 | } 117 | } 118 | 119 | private func perLineFilePaths(from content: String) -> [String] { 120 | return content 121 | .components(separatedBy: "\n") 122 | .compactMap { (string: String) -> String? in 123 | let trimmedString = string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) 124 | return trimmedString.isEmpty ? nil : trimmedString 125 | } 126 | } 127 | 128 | private func minEscapingFilePaths(from content: String) -> [String] { 129 | // Mixed lines where each line is either a single-quoted minimally escaped paths or a 130 | // non-escaped path. 131 | let mixedLines = content 132 | .replacingOccurrences(of: " '", with: "\n'") 133 | .replacingOccurrences(of: "' ", with: "'\n") 134 | .components(separatedBy: "\n") 135 | 136 | var paths = [String]() 137 | for line in mixedLines { 138 | // If a line starts with a single quote, then it at least contains a minimally escaped path. 139 | if line.starts(with: "'") { 140 | let path = line.replacingOccurrences(of: "'", with: "").trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) 141 | if !path.isEmpty { 142 | paths.append(path) 143 | } 144 | } 145 | // Otherwise the line is a set of paths separated by spaces. 146 | else { 147 | let nonEscapedPaths = line 148 | .components(separatedBy: " ") 149 | .compactMap { (string: String) -> String? in 150 | let path = string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) 151 | return path.isEmpty ? nil : path 152 | } 153 | paths.append(contentsOf: nonEscapedPaths) 154 | } 155 | } 156 | return paths 157 | } 158 | 159 | private func newFileEnumerator(for rootUrl: URL) throws -> FileManager.DirectoryEnumerator { 160 | let errorHandler = { (url: URL, error: Error) -> Bool in 161 | fatalError("Failed to traverse \(url) with error \(error).") 162 | } 163 | if let enumerator = FileManager.default.enumerator(at: rootUrl, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles], errorHandler: errorHandler) { 164 | return enumerator 165 | } else { 166 | throw GenericError.withMessage("Failed traverse \(rootUrl)") 167 | } 168 | } 169 | } 170 | -------------------------------------------------------------------------------- /Tests/SourceParsingFrameworkTests/Utilities/FileEnumeratorTests.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Copyright (c) 2018. Uber Technologies 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | // 16 | 17 | import XCTest 18 | @testable import SourceParsingFramework 19 | 20 | class FileEnumeratorTests: AbstractSourceParsingTests { 21 | 22 | func test_enumerate_withSourcesFile_verifyUrls() { 23 | let sourcesListUrl = fixtureUrl(for: "sources_list.txt") 24 | let enumerator = FileEnumerator() 25 | var urls = [String]() 26 | try! enumerator.enumerate(from: sourcesListUrl, withSourcesListFormat: nil) { (url: URL) in 27 | urls.append(url.absoluteString) 28 | } 29 | 30 | let expectedUrls = [ 31 | "file:///Users/yiw/Uber/ios/vendor/box/Box/Box.swift", 32 | "file:///Users/yiw/Uber/ios/vendor/box/Box/BoxType.swift", 33 | "file:///Users/yiw/Uber/ios/vendor/box/Box/MutableBox.swift", 34 | "file:///Users/yiw/Uber/ios/vendor/freddy/Sources/IntExtensions.swift", 35 | "file:///Users/yiw/Uber/ios/vendor/freddy/Sources/JSON.swift", 36 | "file:///Users/yiw/Uber/ios/vendor/freddy/Sources/JSONDecodable.swift", 37 | "file:///Users/yiw/Uber/ios/vendor/freddy/Sources/JSONEncodable.swift", 38 | "file:///Users/yiw/Uber/ios/vendor/freddy/Sources/JSONEncodingDetector.swift", 39 | "file:///Users/yiw/Uber/ios/vendor/freddy/Sources/JSONLiteralConvertible.swift", 40 | "file:///Users/yiw/Uber/ios/vendor/freddy/Sources/JSONOptional.swift", 41 | "file:///Users/yiw/Uber/ios/vendor/freddy/Sources/JSONParser.swift", 42 | "file:///Users/yiw/Uber/ios/vendor/freddy/Sources/JSONParsing.swift", 43 | "file:///Users/yiw/Uber/ios/vendor/freddy/Sources/JSONSerializing.swift", 44 | "file:///Users/yiw/Uber/ios/vendor/freddy/Sources/JSONSubscripting.swift", 45 | "file:///Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Concurrency/ConcurrentReadVariable.swift", 46 | "file:///Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Concurrency/DispatchOperators.swift", 47 | "file:///Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Concurrency/DispatchQueue.swift", 48 | "file:///Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Concurrency/ReadWriteLock.swift", 49 | "file:///Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Concurrency/RecursiveSyncLock.swift", 50 | "file:///Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Concurrency/Sychronized.swift", 51 | "file:///Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Concurrency/SynchronizedDictionary.swift", 52 | "file:///Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Date/Date.swift", 53 | "file:///Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Errors/Asserts.swift", 54 | "file:///Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Extensions/DeviceExtensions.swift", 55 | "file:///Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Extensions/Enumerations.swift", 56 | "file:///Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Extensions/FoundationExtensions.swift", 57 | "file:///Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Extensions/Math.swift", 58 | "file:///Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Extensions/ObfuscationExtensions.swift", 59 | "file:///Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Extensions/SequenceExtensions.swift", 60 | "file:///Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/FileSystem/FileManaging.swift", 61 | "file:///Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/LogModelMetadata/LogModelMetadata.swift", 62 | "file:///Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Obfuscation/Obfuscation.swift", 63 | "file:///Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Resources/BuildType.swift", 64 | "file:///Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Resources/BuildVersion.swift", 65 | "file:///Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Resources/BundleType.swift", 66 | "file:///Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/Runtime/RunType.swift", 67 | "file:///Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/TestMocks/Manual/ManualProtocolMocks.swift", 68 | "file:///Users/yiw/Uber/ios/libraries/foundation/PresidioFoundation/PresidioFoundation/TestMocks/PresidioFoundationProtocolMocks.swift", 69 | ] 70 | 71 | XCTAssertEqual(urls, expectedUrls) 72 | } 73 | 74 | func test_enumerate_withEmptySourcesFile_verifyUrls() { 75 | let sourcesListUrl = fixtureUrl(for: "empty_lines_sources_list.txt") 76 | let enumerator = FileEnumerator() 77 | var urls = [String]() 78 | try! enumerator.enumerate(from: sourcesListUrl, withSourcesListFormat: nil) { (url: URL) in 79 | urls.append(url.absoluteString) 80 | } 81 | 82 | XCTAssertTrue(urls.isEmpty) 83 | } 84 | 85 | func test_enumerate_withNonexistentSourcesFile_verifyUrls() { 86 | let sourcesListUrl = fixtureUrl(for: "doesNotExist.txt") 87 | let enumerator = FileEnumerator() 88 | do { 89 | try enumerator.enumerate(from: sourcesListUrl, withSourcesListFormat: nil) { _ in } 90 | XCTFail() 91 | } catch { 92 | switch error { 93 | case GenericError.withMessage(let message): 94 | XCTAssertTrue(message.contains(sourcesListUrl.absoluteString)) 95 | default: 96 | XCTFail() 97 | } 98 | } 99 | } 100 | 101 | func test_enumerate_withMinimallyEscapedFormat_verifyUrls() { 102 | let sourcesListUrl = fixtureUrl(for: "sources_list_minescaped.txt") 103 | let enumerator = FileEnumerator() 104 | var urls = [String]() 105 | try! enumerator.enumerate(from: sourcesListUrl, withSourcesListFormat: "minescaping") { (url: URL) in 106 | urls.append(url.absoluteString) 107 | } 108 | 109 | let expectedUrls = [ 110 | "file:///Users/yiw/Uber/ios/apps/carbon/Driver/DriverCore/DriverCore/AppStartup/LaunchSteps/NetworkingStep.swift", 111 | "file:///Users/yiw/Uber/ios/apps/carbon/Driver/DriverCore/DriverCore/AppStartup/LaunchSteps/RootRIBStep.swift", 112 | "file:///Users/yiw/Uber/ios/apps/carbon/Driver/DriverCore/DriverCore/AppStartup/LaunchSteps/StacktraceGenerationStep.swift", 113 | "file:///Users/yiw/Uber/ios/apps/carbon/Driver/DriverCore/DriverCore/AppStartup/LaunchSteps/StartupReasonReporterStep.swift", 114 | "file:///Users/yiw/Uber/ios/apps/carbon/Driver/DriverCore/DriverCore/AppStartup/LaunchSteps/StorageStep.swift", 115 | "file:///Users/yiw/Uber/ios/apps/carbon/PluginFeatures/ProfileRatings/ProfileRatings/Rides%20&%20Deliveries/Deliveries/DeliveryRatingsBuilder.swift", 116 | "file:///Users/yiw/Uber/ios/apps/carbon/PluginFeatures/ProfileRatings/ProfileRatings/Rides%20&%20Deliveries/Deliveries/DeliveryRatingsHistogramContainerView.swift", 117 | "file:///Users/yiw/Uber/ios/apps/carbon/PluginFeatures/ProfileRatings/ProfileRatings/Rides%20&%20Deliveries/Deliveries/DeliveryRatingsInteractor.swift", 118 | "file:///Users/yiw/Uber/ios/apps/carbon/PluginFeatures/ProfileRatings/ProfileRatings/Rides%20&%20Deliveries/Deliveries/DeliveryRatingsRouter.swift", 119 | "file:///Users/yiw/Uber/ios/apps/carbon/PluginFeatures/ProfileRatings/ProfileRatings/Rides%20&%20Deliveries/Deliveries/DeliveryRatingsSummaryViewController.swift", 120 | "file:///Users/yiw/Uber/ios/apps/carbon/PluginFeatures/ProfileRatings/ProfileRatings/Rides%20&%20Deliveries/Deliveries/DeliveryRatingsViewController.swift", 121 | "file:///Users/yiw/Uber/ios/apps/carbon/PluginFeatures/ProfileRatings/ProfileRatings/Rides%20&%20Deliveries/Deliveries/Late%20Delivery/DeliveriesRatingLateTripBuilder.swift", 122 | "file:///Users/yiw/Uber/ios/apps/carbon/PluginFeatures/ProfileRatings/ProfileRatings/Rides%20&%20Deliveries/Deliveries/Late%20Delivery/DeliveriesRatingLateTripInteractor.swift", 123 | "file:///Users/yiw/Uber/ios/apps/carbon/PluginFeatures/ProfileRatings/ProfileRatings/Rides%20&%20Deliveries/Deliveries/Late%20Delivery/DeliveriesRatingLateTripRouter.swift", 124 | "file:///Users/yiw/Uber/ios/apps/carbon/PluginFeatures/ProfileRatings/ProfileRatings/Rides%20&%20Deliveries/Deliveries/Late%20Delivery/DeliveriesRatingLateTripViewController.swift", 125 | "file:///Users/yiw/Uber/ios/apps/carbon/PluginFeatures/ProfileRatings/ProfileRatings/Rides%20&%20Deliveries/Deliveries/Late%20Delivery/Views/DeliveriesRatingLateTripDescriptionCell.swift", 126 | "file:///Users/yiw/Uber/ios/apps/carbon/PluginFeatures/ProfileRatings/ProfileRatings/Rides%20&%20Deliveries/Deliveries/Late%20Delivery/Views/DeliveriesRatingLateTripItemCell.swift", 127 | "file:///Users/yiw/Uber/ios/libraries/common/ContactPicker/ContactPicker/View%20Models/ContactViewModel.swift", 128 | "file:///Users/yiw/Uber/ios/apps/carbon/Driver/DriverCore/DriverCore/Account/AccountBuilder.swift", 129 | "file:///Users/yiw/Uber/ios/apps/carbon/Driver/DriverCore/DriverCore/Account/AccountInteractor.swift", 130 | "file:///Users/yiw/Uber/ios/apps/carbon/Driver/DriverCore/DriverCore/Account/AccountRouter.swift", 131 | "file:///Users/yiw/Uber/ios/apps/carbon/Driver/DriverCore/DriverCore/Account/AccountViewController.swift", 132 | "file:///Users/yiw/Uber/ios/apps/carbon/Driver/DriverCore/DriverCore/Account/Component/AccountComponent+AccountNonCore.swift", 133 | "file:///Users/yiw/Uber/ios/apps/carbon/Driver/DriverCore/DriverCore/Account/Component/AccountComponent+VehicleSelection.swift", 134 | "file:///Users/yiw/Uber/ios/apps/carbon/Driver/DriverCore/DriverCore/Account/Views/AccountItemCell.swift", 135 | "file:///Users/yiw/Uber/ios/apps/carbon/Driver/DriverCore/DriverCore/Account/Views/AccountSignOutCell.swift", 136 | ] 137 | 138 | XCTAssertEqual(urls, expectedUrls) 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | --------------------------------------------------------------------------------