Skip to content

Commit

Permalink
Improve swift style + swiftlint (#1092)
Browse files Browse the repository at this point in the history
Task/Issue URL: https://app.asana.com/0/0/1201986385932308/f

Description:
Implement style guide changes
Update swift lint
Fork style from RW repo with some added changes
  • Loading branch information
Bunn authored Apr 4, 2022
1 parent 207ea9d commit 3f6fb5e
Show file tree
Hide file tree
Showing 74 changed files with 1,241 additions and 116 deletions.
53 changes: 44 additions & 9 deletions .swiftlint.yml
Original file line number Diff line number Diff line change
@@ -1,21 +1,56 @@

disabled_rules:
- trailing_whitespace
- discarded_notification_center_observer
- notification_center_detachment
- orphaned_doc_comment
- todo
- unused_capture_list

opt_in_rules:
- closure_end_indentation
- closure_spacing
- colon
- overridden_super_call
- unused_import
- fatal_error_message

force_cast: warning
force_try: warning
legacy_hashing: error

# Rule Config
line_length:
warning: 150
ignores_comments: true
identifier_name:
min_length: 1
max_length:
warning: 40
error: 60
excluded:
- i
- id
- x
- y
- z

line_length:
warning: 150
ignores_urls: true
ignores_function_declarations: true
ignores_comments: true

vertical_whitespace:
max_empty_lines: 2

trailing_whitespace:
ignores_empty_lines: true
ignores_comments: true

private_over_fileprivate:
validate_extensions: true

type_name:
min_length: 3
max_length:
warning: 80
error: 100
min_length: 3
max_length:
warning: 80
error: 100

# General Config
excluded:
Expand Down
2 changes: 1 addition & 1 deletion AtbUITests/AtbIntegrationTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ class AtbIntegrationTests: XCTestCase {

}

fileprivate extension HttpRequest {
private extension HttpRequest {

func queryParam(_ named: String) -> String? {
return queryParams.first(where: { $0.0 == named })?.1
Expand Down
2 changes: 1 addition & 1 deletion Core/APIRequest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ public class APIRequest {

if let error = error {
completion(nil, error)
} else if let error = httpResponse?.validateStatusCode(statusCode: 200..<300) {
} else if let error = httpResponse?.validateStatusCode(statusCode: 200..<300) {
completion(nil, error)
} else {
var etag = httpResponse?.headerValue(for: APIHeaders.Name.etag)
Expand Down
2 changes: 1 addition & 1 deletion Core/BookmarkObjects.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ private struct Constants {
public protocol Bookmark: BookmarkItem {
var url: URL? { get set }

var displayTitle: String? { get }
var displayTitle: String? { get }
}

public extension Bookmark {
Expand Down
4 changes: 2 additions & 2 deletions Core/BookmarksCoreDataStorage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ public class BookmarksCoreDataStorage {
context.perform {
handler(context)
self.storeLoadedCondition.resolve()
}
}
}
}
}
Expand Down Expand Up @@ -422,7 +422,7 @@ extension BookmarksCoreDataStorage {
loadStore()
}

public func favoritesUncachedForWidget(completion: @escaping ([BookmarkManagedObject]) -> Void) {
public func favoritesUncachedForWidget(completion: @escaping ([BookmarkManagedObject]) -> Void) {
Task {
guard await hasTopLevelFolder() else {
completion([])
Expand Down
2 changes: 1 addition & 1 deletion Core/Database.swift
Original file line number Diff line number Diff line change
Expand Up @@ -122,5 +122,5 @@ private class DDGPersistentContainer: NSPersistentContainer {
override public class func defaultDirectoryURL() -> URL {

return FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: Database.Constants.databaseGroupID)!
}
}
}
6 changes: 3 additions & 3 deletions Core/PartiallyRoundedRectangleView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,9 @@ public class PartiallyRoundedRectangleView: UIView {
override public func layoutSubviews() {
super.layoutSubviews()
var corners = UIRectCorner()
if topLeftCorner { corners.insert(.topLeft) }
if topRightCorner { corners.insert(.topRight) }
if bottomLeftCorner { corners.insert(.bottomLeft) }
if topLeftCorner { corners.insert(.topLeft) }
if topRightCorner { corners.insert(.topRight) }
if bottomLeftCorner { corners.insert(.bottomLeft) }
if bottomRightCorner { corners.insert(.bottomRight) }
round(corners: corners, radius: cornerRadius)
}
Expand Down
2 changes: 1 addition & 1 deletion Core/PrivacyPractices.swift
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public class PrivacyPractices {

func findPractice(forHost host: String) -> Practice {
guard let domain = tld.domain(host) else { return Constants.unknown }
guard let term = termsOfServiceStore.terms[domain] else { return Constants.unknown}
guard let term = termsOfServiceStore.terms[domain] else { return Constants.unknown }
let entityScore = entityScores[entityMapping.findEntity(forHost: domain)?.displayName ?? ""]
return Practice(score: entityScore ?? term.derivedScore,
summary: term.summary,
Expand Down
2 changes: 1 addition & 1 deletion Core/WebCacheManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ public class WebCacheManager {
cookieStore.getAllCookies { cookies in
let group = DispatchGroup()
cookies.forEach { cookie in
if domains.contains(where: { self.isCookie(cookie, matchingDomain: $0)}) {
if domains.contains(where: { self.isCookie(cookie, matchingDomain: $0) }) {
group.enter()
cookieStore.delete(cookie) {
group.leave()
Expand Down
2 changes: 1 addition & 1 deletion DuckDuckGo/ActionSheetDaxDialogViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ class ActionSheetDaxDialogViewController: UIViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)

containerHeight.constant = daxDialogViewController?.calculateHeight() ?? 0
containerHeight.constant = daxDialogViewController?.calculateHeight() ?? 0
}

override func viewDidAppear(_ animated: Bool) {
Expand Down
2 changes: 1 addition & 1 deletion DuckDuckGo/AddOrEditBookmarkViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ class AddOrEditBookmarkViewController: UIViewController {
}
}

extension AddOrEditBookmarkViewController: BookmarkOrFavoriteDetailsDataSourceDelegate {
extension AddOrEditBookmarkViewController: BookmarkOrFavoriteDetailsDataSourceDelegate {

func bookmarkOrFavoriteDetailsDataSource(_ dataSource: BookmarkOrFavoriteDetailsDataSource,
textFieldDidChangeWithTitleText titleText: String?,
Expand Down
4 changes: 2 additions & 2 deletions DuckDuckGo/AppRatingPrompt.swift
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ class AppRatingPrompt {
func registerUsage(onDate date: Date = Date()) {
if !date.isSameDay(storage.lastAccess) {
storage.uniqueAccessDays += 1
}
}
storage.lastAccess = date
}

Expand All @@ -65,7 +65,7 @@ class AppRatingPromptCoreDataStorage: AppRatingPromptStorage {

set {
entity().lastAccess = newValue
try? context.save()
try? context.save()
}
}

Expand Down
2 changes: 1 addition & 1 deletion DuckDuckGo/AutocompleteViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ class AutocompleteViewController: UIViewController {
strongSelf.bookmarksSearch.search(query: query) { matches in
let notQueryMatches = matches.filter { $0.url?.absoluteString != query }
let filteredMatches = notQueryMatches.filter { $0.displayTitle != nil }.prefix(Constants.maxLocalItems)
let localSuggestions = filteredMatches.map { Suggestion(source: .local, suggestion: $0.displayTitle!, url: $0.url)}
let localSuggestions = filteredMatches.map { Suggestion(source: .local, suggestion: $0.displayTitle!, url: $0.url) }

guard let suggestions = suggestions, error == nil else {
os_log("%s", log: generalLog, type: .debug, error?.localizedDescription ?? "Failed to retrieve suggestions")
Expand Down
3 changes: 1 addition & 2 deletions DuckDuckGo/BookmarksDataSource.swift
Original file line number Diff line number Diff line change
Expand Up @@ -139,8 +139,7 @@ class DefaultBookmarksDataSource: BookmarksDataSource, MainBookmarksViewDataSour
bookmarksManager.convertFavoriteToBookmark(item.objectID, newIndex: destinationIndexPath.row)
} else if sourceIndexPath.section == 1 && destinationIndexPath.section == 0 {
guard let bookmark = item as? Bookmark else {
// Folders aren't allowed in favourites. We shouldn't be able to get here
fatalError()
fatalError("Folders aren't allowed in favorites. We shouldn't be able to get here")
}
bookmarksManager.convertBookmarkToFavorite(bookmark.objectID, newIndex: destinationIndexPath.row)
}
Expand Down
2 changes: 1 addition & 1 deletion DuckDuckGo/BrowserChromeManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -333,7 +333,7 @@ private class BarsAnimator {
}
}

fileprivate extension UIScrollView {
private extension UIScrollView {

/// Calculate Y-axis content offset corresponding to very bottom of the scroll area
var contentOffsetYAtBottom: CGFloat {
Expand Down
4 changes: 2 additions & 2 deletions DuckDuckGo/BrowsingMenu/BrowsingMenuViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -307,14 +307,14 @@ extension BrowsingMenuViewController: UITableViewDataSource {
switch menuEntries[indexPath.row] {
case .regular(let name, let accessibilityLabel, let image, let showNotificationDot, _):
guard let cell = tableView.dequeueReusableCell(withIdentifier: "BrowsingMenuEntryViewCell", for: indexPath) as? BrowsingMenuEntryViewCell else {
fatalError()
fatalError("Cell should be dequeued")
}

cell.configure(image: image, label: name, accessibilityLabel: accessibilityLabel, theme: theme, showNotificationDot: showNotificationDot)
return cell
case .separator:
guard let cell = tableView.dequeueReusableCell(withIdentifier: "BrowsingMenuSeparatorViewCell", for: indexPath) as? BrowsingMenuSeparatorViewCell else {
fatalError()
fatalError("Cell should be dequeued")
}

cell.separator.backgroundColor = theme.browsingMenuSeparatorColor
Expand Down
6 changes: 3 additions & 3 deletions DuckDuckGo/DirectoryMonitor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ class DirectoryMonitor {
}

func start() throws {
guard case .stopped = state else { fatalError() }
guard case .stopped = state else { fatalError("Should only start stopped state") }

directoryContents = DirectoryMonitor.contents(of: directory)

Expand Down Expand Up @@ -110,7 +110,7 @@ class DirectoryMonitor {
}

private func debounceTimerDidFire() {
guard case .debounce(let source, let timer) = state else { fatalError() }
guard case .debounce(let source, let timer) = state else { fatalError("state should be .debounce") }

timer.invalidate()
state = .started(source: source)
Expand Down Expand Up @@ -142,7 +142,7 @@ class DirectoryMonitor {
}
}

fileprivate extension DirectoryMonitor.State {
private extension DirectoryMonitor.State {
var isRunning: Bool {
switch self {
case .stopped: return false
Expand Down
4 changes: 2 additions & 2 deletions DuckDuckGo/DownloadListRepresentable.swift
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,12 @@ struct AnyDownloadListRepresentable: DownloadListRepresentable, Comparable {
self.wrappedRepresentable = representable
}

public var id: String { filename}
public var id: String { filename }
var filename: String { wrappedRepresentable.filename }
var creationDate: Date { wrappedRepresentable.creationDate }
var fileSize: Int { wrappedRepresentable.fileSize }
var type: DownloadListRepresentableType { wrappedRepresentable.type }
var filePath: String { wrappedRepresentable.filePath}
var filePath: String { wrappedRepresentable.filePath }

static func < (lhs: AnyDownloadListRepresentable, rhs: AnyDownloadListRepresentable) -> Bool {
lhs.creationDate < rhs.creationDate
Expand Down
4 changes: 2 additions & 2 deletions DuckDuckGo/DownloadsListSectioningHelper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -95,10 +95,10 @@ class DownloadsListSectioningHelper {

switch downloadRepresentable.type {
case .ongoing:
guard let download = downloadRepresentable.wrappedRepresentable as? Download else { fatalError() }
guard let download = downloadRepresentable.wrappedRepresentable as? Download else { fatalError("Ongoing download should be Download") }
row = OngoingDownloadRowViewModel(download: download)
case .complete:
guard let url = downloadRepresentable.wrappedRepresentable as? URL else { fatalError() }
guard let url = downloadRepresentable.wrappedRepresentable as? URL else { fatalError("Complete download should be URL") }
row = CompleteDownloadRowViewModel(fileURL: url)
}

Expand Down
2 changes: 1 addition & 1 deletion DuckDuckGo/FavoritesOverlay.swift
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ class FavoritesOverlay: UIViewController {
}

@objc private func keyboardDidShow(notification: NSNotification) {
guard !AppWidthObserver.shared.isLargeWidth else { return }
guard !AppWidthObserver.shared.isLargeWidth else { return }
guard let keyboardFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else { return }
let keyboardSize = keyboardFrame.size
let contentInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize.height + Constants.margin * 2, right: 0.0)
Expand Down
4 changes: 2 additions & 2 deletions DuckDuckGo/FileSizeDebugViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ struct FileItem {
let isDirectory: Bool
let size: Int?

var isEmpty: Bool { (size ?? 0) == 0}
var isEmpty: Bool { (size ?? 0) == 0 }
}

class FileSizeDebugViewController: UITableViewController {
Expand Down Expand Up @@ -160,7 +160,7 @@ class FileSizeDebugViewController: UITableViewController {
}
}

fileprivate extension URL {
private extension URL {

var isDirectory: Bool {
let urlForDirectory = (try? resourceValues(forKeys: [.isDirectoryKey]).isDirectory) ?? false
Expand Down
2 changes: 1 addition & 1 deletion DuckDuckGo/FindInPageUserScript.swift
Original file line number Diff line number Diff line change
Expand Up @@ -40,5 +40,5 @@ public class FindInPageUserScript: NSObject, UserScript {
let currentResult = dict["currentResult"] as? Int
let totalResults = dict["totalResults"] as? Int
findInPage?.update(currentResult: currentResult, totalResults: totalResults)
}
}
}
2 changes: 2 additions & 0 deletions DuckDuckGo/FindInPageView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,8 @@ class FindInPageView: UIView {
weak var findInPage: FindInPage?

override func awakeFromNib() {
super.awakeFromNib()

layer.shadowRadius = 1
layer.shadowOffset = CGSize(width: 0, height: -1.0 / UIScreen.main.scale)
layer.shadowColor = UIColor.black.cgColor
Expand Down
2 changes: 1 addition & 1 deletion DuckDuckGo/FullscreenDaxDialogViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ extension TabViewController: FullscreenDaxDialogDelegate {
}
}

fileprivate extension DefaultDaxDialogsSettings {
private extension DefaultDaxDialogsSettings {

var browsingDialogsSeenCount: String {
let count = [ browsingMajorTrackingSiteShown,
Expand Down
2 changes: 1 addition & 1 deletion DuckDuckGo/LaunchTabNotification.swift
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ class LaunchTabNotification {

}

fileprivate extension NSNotification.Name {
private extension NSNotification.Name {

static let launchTab: NSNotification.Name = Notification.Name(rawValue: "com.duckduckgo.notification.launchTab")

Expand Down
4 changes: 2 additions & 2 deletions DuckDuckGo/NativeDisplayableCertificateBuilderDriver.swift
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ class NativeDisplayableCertificateBuilderDriver: DisplayableCertificateBuilderDr

}

fileprivate extension SecCertificate {
private extension SecCertificate {

func toDisplayable() -> DisplayableCertificate {
let displayable = DisplayableCertificate()
Expand Down Expand Up @@ -85,7 +85,7 @@ fileprivate extension SecCertificate {

}

fileprivate extension SecKey {
private extension SecKey {

func toDisplayable() -> DisplayableKey {
var key = DisplayableKey()
Expand Down
2 changes: 1 addition & 1 deletion DuckDuckGo/OnboardingViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ class OnboardingViewController: UIViewController, Onboarding {
}

override var shouldAutorotate: Bool {
return true
return true
}

}
Expand Down
2 changes: 1 addition & 1 deletion DuckDuckGo/OngoingDownloadRow.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
import SwiftUI
import Combine

struct OngoingDownloadRow: View {
struct OngoingDownloadRow: View {
@ObservedObject var rowModel: OngoingDownloadRowViewModel

var cancelButtonAction: () -> Void
Expand Down
Loading

0 comments on commit 3f6fb5e

Please sign in to comment.