Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SwiftLint fixes #20

Merged
merged 8 commits into from
Mar 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
name: Build
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build:
runs-on: macos-12
timeout-minutes: 10 # If a build exceeds 10 mins, it probably isn't ever going to complete
steps:
- uses: actions/checkout@v2
- name: MacOS Version
run: sw_vers
- name: Toolchain version
run: swift -version
- name: Build
run: swift build
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name: Build & Lint
name: SwiftLint
on:
push:
branches: [ main ]
Expand Down
3 changes: 2 additions & 1 deletion .swiftlint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
disabled_rules:
- todo # New project, we have a lot of // TODO:
- missing_docs # We miss a lot of docs right now

- identifier_name # This should be fixed in a future version
- force_try # This should be fixed in a future version
# Exclude triggering type names.
type_name:
excluded:
Expand Down
17 changes: 9 additions & 8 deletions Sources/Version-Control/Base/Actions/GitHub/GitHubActions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import Foundation
import AppKit

public enum GitHubViewType: String {
case tree = "tree"
case compare = "compare"
case tree
case compare
}

public struct GitHubActions {
Expand All @@ -22,17 +22,17 @@ public struct GitHubActions {
internal func getCurrentRepositoryGitHubURL(directoryURL: URL) throws -> String {
let remoteUrls: [GitRemote] = try Remote().getRemotes(directoryURL: directoryURL)

for remote in remoteUrls {
if remote.url.contains("github.com") {
return remote.url
}
for remote in remoteUrls where remote.url.contains("github.com") {
return remote.url
}

return ""
}

/// Open a specific branch of a GitHub repository in a web browser.
///
/// This function constructs the URL for a specific branch of a GitHub repository based on the provided parameters and opens it in the default web browser.
/// This function constructs the URL for a specific branch of
/// a GitHub repository based on the provided parameters and opens it in the default web browser.
///
/// - Parameters:
/// - viewType: The type of view to open on GitHub (e.g., code, commits, pulls).
Expand Down Expand Up @@ -67,7 +67,8 @@ public struct GitHubActions {

/// Open the GitHub issue creation page for the current repository in a web browser.
///
/// This function constructs the URL for creating a new issue in the current repository on GitHub and opens it in the default web browser.
/// This function constructs the URL for creating a new issue in
/// the current repository on GitHub and opens it in the default web browser.
///
/// - Parameter directoryURL: The local directory URL of the Git repository.
///
Expand Down
25 changes: 20 additions & 5 deletions Sources/Version-Control/Base/Commands/Apply.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ public struct Apply {
///
/// - Parameters:
/// - directoryURL: The URL of the directory containing the git repository.
/// - file: A `WorkingDirectoryFileChange` object representing the file whose changes are to be applied to the index.
/// - file: A `WorkingDirectoryFileChange` object representing the file \
/// whose changes are to be applied to the index.
/// - Throws: An error if the git commands fail to execute.
///
/// # Example:
Expand All @@ -28,8 +29,10 @@ public struct Apply {
/// let fileChange = WorkingDirectoryFileChange(path: "newName.txt", status: .renamed(oldName: "oldName.txt"))
/// try await applyPatchToIndex(directoryURL: directoryURL, file: fileChange)
/// ```
func applyPatchToIndex(directoryURL: URL,
file: WorkingDirectoryFileChange) throws {
func applyPatchToIndex( // swiftlint:disable:this function_body_length
directoryURL: URL,
file: WorkingDirectoryFileChange
) throws {
// If the file was a rename we have to recreate that rename since we've
// just blown away the index.
if file.status.kind == .renamed {
Expand Down Expand Up @@ -79,9 +82,21 @@ public struct Apply {
if let diff = diff as? TextDiff {
switch diff.kind {
case .image, .binary, .submodule:
throw NSError(domain: "PatchError", code: 0, userInfo: [NSLocalizedDescriptionKey: "Can't create partial commit in binary file: \(file.path)"])
throw NSError(
domain: "com.auroraeditor.versioncontrolkit.patcherror",
code: 0,
userInfo: [
NSLocalizedDescriptionKey: "Can't create partial commit in binary file: \(file.path)"
]
)
case .unrenderable:
throw NSError(domain: "PatchError", code: 1, userInfo: [NSLocalizedDescriptionKey: "File diff is too large to generate a partial commit: \(file.path)"])
throw NSError(
domain: "com.auroraeditor.versioncontrolkit.patcherror",
code: 1,
userInfo: [
NSLocalizedDescriptionKey: "File diff is too large to generate a partial commit: \(file.path)"
]
)
default:
fatalError("Unknown diff kind: \(diff.kind)")
}
Expand Down
31 changes: 24 additions & 7 deletions Sources/Version-Control/Base/Commands/Branch.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

import Foundation

public struct Branch {
public struct Branch { // swiftlint:disable:this type_body_length

public init() {}

Expand Down Expand Up @@ -186,6 +186,7 @@ public struct Branch {
/// - Throws: An error if the shell command fails.
public func getRecentBranches(directoryURL: URL, limit: Int) throws -> [String] {
let regex = try NSRegularExpression(
// swiftlint:disable:next line_length
pattern: #"^.*? (renamed|checkout)(?:: moving from|\s*) (?:refs/heads/|\s*)(.*?) to (?:refs/heads/|\s*)(.*?)$"#,
options: []
)
Expand Down Expand Up @@ -215,7 +216,11 @@ public struct Branch {
var excludedNames = Set<String>()

for line in lines {
if let match = regex.firstMatch(in: line, options: [], range: NSRange(location: 0, length: line.utf16.count)),
if let match = regex.firstMatch(
in: line,
options: [],
range: NSRange(location: 0, length: line.utf16.count)
),
match.numberOfRanges == 4 {
let operationTypeRange = Range(match.range(at: 1), in: line)!
let excludeBranchNameRange = Range(match.range(at: 2), in: line)!
Expand Down Expand Up @@ -243,7 +248,14 @@ public struct Branch {
return Array(names)
}

let noCommitsOnBranchRe = try! NSRegularExpression(pattern: "fatal: your current branch '.*' does not have any commits yet")
func getCommitsOnBranch() {
guard let noCommitsOnBranchRe = try? NSRegularExpression(
pattern: "fatal: your current branch '.*' does not have any commits yet"
) else {
print("Failed to create regular expression")
return
}
}

/// Asynchronously fetches the names and dates of branches checked out after a specified date.
///
Expand Down Expand Up @@ -277,8 +289,12 @@ public struct Branch {

let lines = result.stdout.components(separatedBy: "\n")
for line in lines {
if let match = regex.firstMatch(in: line, options: [], range: NSRange(location: 0, length: line.utf16.count)),
match.numberOfRanges == 3 {
if let match = regex.firstMatch(
in: line,
options: [],
range: NSRange(location: 0, length: line.utf16.count)
),
match.numberOfRanges == 3 {
let timestampRange = Range(match.range(at: 1), in: line)!
let branchNameRange = Range(match.range(at: 2), in: line)!

Expand Down Expand Up @@ -334,8 +350,8 @@ public struct Branch {
/// - newName: A string representing the new name of the branch.
/// - Throws: An error if the shell command fails.
public func renameBranch(directoryURL: URL,
branch: GitBranch,
newName: String) throws {
branch: GitBranch,
newName: String) throws {
let args = [
"branch",
"-m",
Expand Down Expand Up @@ -472,3 +488,4 @@ public struct Branch {
return mergedBranches
}
}
// swiftlint:disable:this file_length
30 changes: 18 additions & 12 deletions Sources/Version-Control/Base/Commands/Checkout.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,10 @@ public struct GitCheckout {
return args
}

public func getBranchCheckoutArgs(branch: GitBranch,
enableRecurseSubmodulesFlag: Bool = false) -> [String] {
public func getBranchCheckoutArgs(
branch: GitBranch,
enableRecurseSubmodulesFlag: Bool = false
) -> [String] {
var baseArgs: [String] = []

if enableRecurseSubmodulesFlag {
Expand Down Expand Up @@ -64,12 +66,14 @@ public struct GitCheckout {
}
}

public func getCheckoutOpts(directoryURL: URL,
account: IGitAccount?,
title: String,
target: String,
progressCallback: ProgressCallback?,
initialDescription: String?) throws -> IGitExecutionOptions {
public func getCheckoutOpts( // swiftlint:disable:this function_parameter_count
directoryURL: URL,
account: IGitAccount?,
title: String,
target: String,
progressCallback: ProgressCallback?,
initialDescription: String?
) throws -> IGitExecutionOptions {
var options: IGitExecutionOptions = IGitExecutionOptions()

guard let progressCallback = progressCallback else {
Expand Down Expand Up @@ -129,10 +133,12 @@ public struct GitCheckout {
/// - Warning:
/// Ensure that the specified `directoryURL` exists and is a valid Git repository directory.
@discardableResult
public func checkoutBranch(directoryURL: URL,
account: IGitAccount?,
branch: GitBranch,
progressCallback: ProgressCallback?) throws -> Bool {
public func checkoutBranch(
directoryURL: URL,
account: IGitAccount?,
branch: GitBranch,
progressCallback: ProgressCallback?
) throws -> Bool {
let opts = try getCheckoutOpts(
directoryURL: directoryURL,
account: account,
Expand Down
22 changes: 14 additions & 8 deletions Sources/Version-Control/Base/Commands/Cherry-Pick.swift
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ public struct CherryPick {
/// - baseOptions: The base options for Git execution.
/// - commits: An array of `CommitOneLine` representing the commits to be cherry-picked.
/// - progressCallback: An escaping closure that is called with the progress of the operation.
/// - cherryPickedCount: An optional integer representing the number of commits already cherry-picked. Defaults to 0.
/// - cherryPickedCount: An optional integer representing the number of commits already cherry-picked. \
/// Defaults to 0.
/// - Returns: An `IGitExecutionOptions` instance with the process callback configured.
internal func configureOptionsWithCallBack(baseOptions: IGitExecutionOptions,
commits: [Commit],
Expand Down Expand Up @@ -129,9 +130,11 @@ public struct CherryPick {
}

guard let gitError = result.gitError else {
throw NSError(domain: "com.auroraeditor.editor",
code: 0,
userInfo: [NSLocalizedDescriptionKey: "Unhandled result found: \(result)"])
throw NSError(
domain: "com.auroraeditor.versioncontrolkit.cherrypickerror",
code: 0,
userInfo: [NSLocalizedDescriptionKey: "Unhandled result found: \(result)"]
)
}

switch gitError {
Expand All @@ -140,9 +143,11 @@ public struct CherryPick {
case .UnresolvedConflicts:
return .outstandingFilesNotStaged
default:
throw NSError(domain: "com.auroraeditor.editor",
code: 0,
userInfo: [NSLocalizedDescriptionKey: "Unhandled Git error: \(gitError)"])
throw NSError(
domain: "com.auroraeditor.versioncontrolkit.cherrypickerror",
code: 0,
userInfo: [NSLocalizedDescriptionKey: "Unhandled Git error: \(gitError)"]
)
}
}

Expand Down Expand Up @@ -208,7 +213,8 @@ public struct CherryPick {
/// - Parameters:
/// - directoryURL: The URL of the directory where the cherry-pick operation is to be continued.
/// - files: An array of `WorkingDirectoryFileChange` representing the changes to be staged.
/// - manualResolutions: A dictionary mapping file paths to `ManualConflictResolution` objects. Defaults to an empty dictionary.
/// - manualResolutions: A dictionary mapping file paths to `ManualConflictResolution` objects. \
/// Defaults to an empty dictionary.
/// - progressCallback: An optional closure called with progress information during the operation.
/// - Throws: An error if the operation cannot start or if a problem occurs during execution.
/// - Returns: A `CherryPickResult` indicating the outcome of the continued operation.
Expand Down
62 changes: 33 additions & 29 deletions Sources/Version-Control/Base/Commands/Commit.swift
Original file line number Diff line number Diff line change
Expand Up @@ -92,35 +92,39 @@ public struct GitCommit {

// Create merge commit

let result = try GitShell().git(args: ["commit",
// no-edit here ensures the app does not accidentally invoke the user's editor
"--no-edit",
// By default Git merge commits do not contain any commentary (which
// are lines prefixed with `#`). This works because the Git CLI will
// prompt the user to edit the file in `.git/COMMIT_MSG` before
// committing, and then it will run `--cleanup=strip`.
//
// This clashes with our use of `--no-edit` above as Git will now change
// it's behavior to invoke `--cleanup=whitespace` as it did not ask
// the user to edit the COMMIT_MSG as part of creating a commit.
//
// From the docs on git-commit (https://git-scm.com/docs/git-commit) I'll
// quote the relevant section:
// --cleanup=<mode>
// strip
// Strip leading and trailing empty lines, trailing whitespace,
// commentary and collapse consecutive empty lines.
// whitespace
// Same as `strip` except #commentary is not removed.
// default
// Same as `strip` if the message is to be edited. Otherwise `whitespace`.
//
// We should emulate the behavior in this situation because we don't
// let the user view or change the commit message before making the
// commit.
"--cleanup=strip"],
path: directoryURL,
name: #function)
let result = try GitShell().git(
args: [
"commit",
// no-edit here ensures the app does not accidentally invoke the user's editor
"--no-edit",
// By default Git merge commits do not contain any commentary (which
// are lines prefixed with `#`). This works because the Git CLI will
// prompt the user to edit the file in `.git/COMMIT_MSG` before
// committing, and then it will run `--cleanup=strip`.
//
// This clashes with our use of `--no-edit` above as Git will now change
// it's behavior to invoke `--cleanup=whitespace` as it did not ask
// the user to edit the COMMIT_MSG as part of creating a commit.
//
// From the docs on git-commit (https://git-scm.com/docs/git-commit) I'll
// quote the relevant section:
// --cleanup=<mode>
// strip
// Strip leading and trailing empty lines, trailing whitespace,
// commentary and collapse consecutive empty lines.
// whitespace
// Same as `strip` except #commentary is not removed.
// default
// Same as `strip` if the message is to be edited. Otherwise `whitespace`.
//
// We should emulate the behavior in this situation because we don't
// let the user view or change the commit message before making the
// commit.
"--cleanup=strip"
],
path: directoryURL,
name: #function
)

// Parse the commit SHA from the result
return parseCommitSHA(result: result)
Expand Down
3 changes: 2 additions & 1 deletion Sources/Version-Control/Base/Commands/Description.swift
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ public struct GitDescription {
/// - An error of type `Error` if any issues occur during the description retrieval process.
///
/// - Returns:
/// The project's description as a string, or an empty string if the description is not found or cannot be retrieved.
/// The project's description as a string, or an empty string if the description \
/// is not found or cannot be retrieved.
///
/// - Example:
/// ```swift
Expand Down
6 changes: 3 additions & 3 deletions Sources/Version-Control/Base/Commands/Diff-Index.swift
Original file line number Diff line number Diff line change
Expand Up @@ -122,9 +122,9 @@ public struct DiffIndex {

var map = [String: NoRenameIndexStatus]()

for i in stride(from: 0, to: pieces.count - 1, by: 2) {
let statusString = String(pieces[i])
let path = String(pieces[i + 1])
for number in stride(from: 0, to: pieces.count - 1, by: 2) {
let statusString = String(pieces[number])
let path = String(pieces[number + 1])
let status = try getIndexStatus(status: statusString)

switch status {
Expand Down
Loading
Loading