From 40cfff50cbaf707b07a4d76600184ce1d6110729 Mon Sep 17 00:00:00 2001 From: Stephen Martinez Date: Sun, 12 Jan 2020 19:24:46 -0800 Subject: [PATCH 1/9] [CPFeature-009] Added the transform and resolve or exit extension --- .../Utilities/Result+Extensions.swift | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 Sources/CommitPrefix/Utilities/Result+Extensions.swift diff --git a/Sources/CommitPrefix/Utilities/Result+Extensions.swift b/Sources/CommitPrefix/Utilities/Result+Extensions.swift new file mode 100644 index 0000000..2bfafc4 --- /dev/null +++ b/Sources/CommitPrefix/Utilities/Result+Extensions.swift @@ -0,0 +1,55 @@ +// +// Result+Extensions.swift +// commitPrefix +// +// MIT License +// +// Copyright (c) 2020 STEPHEN L. MARTINEZ +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +import Foundation +import Consler + +extension Result { + + func transform(_ newValue: NewSuccess) -> Result { + switch self { + case .success: + return .success(newValue) + case let .failure(failure): + return .failure(failure) + } + } + +} + +extension Result where Failure == CPError { + + func resolveOrExit() -> Success { + switch self { + case let .success(value): + return value + case let .failure(cpError): + Consler.output(cpError.message, type: .error) + exit(cpError.status.value) + } + } + +} From 8264bc01674994cdd828faab6c983ddb8fd2bda5 Mon Sep 17 00:00:00 2001 From: Stephen Martinez Date: Sun, 12 Jan 2020 19:25:43 -0800 Subject: [PATCH 2/9] [CPFeature-009] Updated the Error types with the uncategorized error case --- Sources/CommitPrefix/Error+Debug/CPError.swift | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/Sources/CommitPrefix/Error+Debug/CPError.swift b/Sources/CommitPrefix/Error+Debug/CPError.swift index 73f8584..714c235 100644 --- a/Sources/CommitPrefix/Error+Debug/CPError.swift +++ b/Sources/CommitPrefix/Error+Debug/CPError.swift @@ -75,6 +75,9 @@ enum CPError: Error { case hookFileIOError case headFileIOError + // MARK: - Uncategorized Error + case unexpectedError + var message: ConslerOutput { switch self { @@ -142,6 +145,10 @@ enum CPError: Error { case .headFileIOError: return ConslerOutput("Error: ", "Unable to read the git HEAD for branch information") .describedBy(.boldRed) + + case .unexpectedError: + return ConslerOutput("Error: ", "An uncategorized error has occured") + .describedBy(.boldRed) } } @@ -176,6 +183,8 @@ enum CPError: Error { return .unavailableDependencies case .headFileIOError: return .unavailableDependencies + case .unexpectedError: + return .unexpectedError } } From 8e5e63130df9bf8def8576ba801c960489be2786 Mon Sep 17 00:00:00 2001 From: Stephen Martinez Date: Sun, 12 Jan 2020 19:27:01 -0800 Subject: [PATCH 3/9] [CPFeature-009] Converted the CommitMessageHook type to have return result types instead of throwing errors. --- .../CommitPrefix/Hook/CommitMessageHook.swift | 55 +++++++++++-------- 1 file changed, 33 insertions(+), 22 deletions(-) diff --git a/Sources/CommitPrefix/Hook/CommitMessageHook.swift b/Sources/CommitPrefix/Hook/CommitMessageHook.swift index e35c74b..934c7c2 100644 --- a/Sources/CommitPrefix/Hook/CommitMessageHook.swift +++ b/Sources/CommitPrefix/Hook/CommitMessageHook.swift @@ -48,12 +48,19 @@ struct CommitMessageHook { /// - parameters: /// - gitDirectory: A `Folder` representing the git directory /// - static func findOrCreate(with gitDirectory: Folder) throws { - let cpHook = try CommitMessageHook(gitDirectory: gitDirectory) - try cpHook.locateOrCreateHook() + static func findOrCreate(with gitDirectory: Folder) -> Result { + do { + let cpHook = try CommitMessageHook(gitDirectory: gitDirectory) + return cpHook.locateOrCreateHook() + } catch let cpError as CPError { + return .failure(cpError) + } catch { + return .failure(.unexpectedError) + } + } - private func getCommitHookFile() throws -> File? { + private func getCommitHookFile() -> Result { guard let foundCommitHookFile = try? hooksDirectory.file(named: FileName.commitMessage) else { @@ -62,19 +69,18 @@ struct CommitMessageHook { try commitHookFile.write(cmHookContents.renderScript(), encoding: .utf8) cpDebugPrint(commitHookFile.path) Shell.makeExecutable(commitHookFile.path) + return .success(commitHookFile) } catch { - throw CPError.hookFileIOError + return .failure(.hookFileIOError) } - return nil - } - return foundCommitHookFile + return .success(foundCommitHookFile) } - private func overwriteCommitHook(_ commitHookFile: File) throws { + private func overwriteCommitHook(_ commitHookFile: File) -> Result { Consler.output( ["", "There seems to be an existing commit-msg found in the hooks directory", "- Would you like to overwrite? [y/n]", ""], @@ -92,32 +98,37 @@ struct CommitMessageHook { do { // TODO: - Theres a case where the file is not executable in the first place this will not correct that try commitHookFile.write(cmHookContents.renderScript(), encoding: .utf8) + return .success(()) } catch { - throw CPError.hookFileIOError + return .failure(.hookFileIOError) } case "n": - throw CPError.overwriteCancelled + return .failure(.overwriteCancelled) default: - throw CPError.invalidYesOrNoFormat + return .failure(.invalidYesOrNoFormat) } } - private func hookIsCommitPrefix(_ hookFile: File) throws -> Bool { - - guard let hookContents = try? hookFile.readAsString(encodedAs: .utf8) else { - throw CPError.hookFileIOError + private var hookIsCommitPrefix: (File) -> Result<(File, Bool), CPError> { + return { hookFile in + guard let hookContents = try? hookFile.readAsString(encodedAs: .utf8) else { + return .failure(.hookFileIOError) + } + return .success((hookFile, hookContents.contains(self.cmHookContents.fileIdentifier))) } - - return hookContents.contains(cmHookContents.fileIdentifier) } - private func locateOrCreateHook() throws { - guard let foundCommitHookFile = try getCommitHookFile() else { return } - guard try !hookIsCommitPrefix(foundCommitHookFile) else { return } - try overwriteCommitHook(foundCommitHookFile) + private var shouldOverwriteHook: (File, Bool) -> Result { + return { $1 ? .success(()) : self.overwriteCommitHook($0) } + } + + private func locateOrCreateHook() -> Result { + return getCommitHookFile() + .flatMap(hookIsCommitPrefix) + .flatMap(shouldOverwriteHook) } } From 5dfbd00c81b2e36f7ff1c0bd82abb01422000628 Mon Sep 17 00:00:00 2001 From: Stephen Martinez Date: Sun, 12 Jan 2020 19:29:07 -0800 Subject: [PATCH 4/9] [CPFeature-009] Updated the interactor with the result type --- Sources/CommitPrefix/CPInteractor.swift | 114 ++++++++++++++---------- 1 file changed, 69 insertions(+), 45 deletions(-) diff --git a/Sources/CommitPrefix/CPInteractor.swift b/Sources/CommitPrefix/CPInteractor.swift index 0a846b5..0bd516e 100644 --- a/Sources/CommitPrefix/CPInteractor.swift +++ b/Sources/CommitPrefix/CPInteractor.swift @@ -41,6 +41,17 @@ struct CPInteractor { self.gitHEADFile = gitHEADFile } + static func create(_ gitDirectory: Folder) -> Result { + do { + let cpInteractor = try CPInteractor(gitDirectory: gitDirectory) + return .success(cpInteractor) + } catch let cpError as CPError { + return .failure(cpError) + } catch { + return .failure(.unexpectedError) + } + } + private static func build(using gitDirectory: Folder) throws -> (File, CPModel, File) { do { let initialModelData = try JSONEncoder().encode(CPModel.empty()) @@ -58,35 +69,36 @@ struct CPInteractor { } } - private func saveCommitPrefix(model: CPModel) throws { + private func saveCommitPrefix(model: CPModel) -> Result { do { let jsonEncoder = JSONEncoder() let modelData = try jsonEncoder.encode(model) try commitPrefixFile.write(modelData) + return .success(()) } catch { cpDebugPrint(error) - throw CPError.cpFileIOError + return .failure(.cpFileIOError) } } - private func branchPrefixes() throws -> [String] { + private func branchPrefixes() -> Result<[String], CPError> { guard let regexValue = commitPrefixModel.regexValue else { - throw CPError.branchValidatorNotFound + return .failure(.branchValidatorNotFound) } guard let branch = try? gitHEADFile.readAsString(encodedAs: .utf8) else { - throw CPError.headFileIOError + return .failure(.headFileIOError) } let matches = branch.occurances(ofRegex: regexValue) guard matches.count > 0 else { let validator = commitPrefixModel.branchValidator ?? "Validator Not Present" - throw CPError.invalidBranchPrefix(validator: validator) + return .failure(.invalidBranchPrefix(validator: validator)) } let uniqueMatches = Set(matches) - return Array(uniqueMatches) + return .success(Array(uniqueMatches)) } private func prefixFormatter(_ rawValue: String) -> [String] { @@ -97,79 +109,91 @@ struct CPInteractor { return parsedValues.map { "[\($0)]" } } - private func validatorFormatter(_ rawValue: String) throws -> String { + private func validatorFormatter(_ rawValue: String) -> Result { let validator = rawValue.trimmingCharacters(in: .whitespacesAndNewlines) let containsNoNumbers = validator.occurances(ofRegex: #"(\d+)"#).isEmpty let atLeastTwoCharacters = validator.count > 1 guard containsNoNumbers && atLeastTwoCharacters else { - throw CPError.invalidBranchValidatorFormat + return .failure(.invalidBranchValidatorFormat) } - return validator + return .success(validator) } - func outputPrefixes() throws -> ConslerOutput { + func outputPrefixes() -> Result { switch commitPrefixModel.prefixMode { case .normal: - return ConslerOutput(commitPrefixModel.prefixes.joined()) + return .success(ConslerOutput(commitPrefixModel.prefixes.joined())) case .branchParse: - let retrievedBranchPrefixes = try branchPrefixes() - let branchPrefixes = retrievedBranchPrefixes.map { "[\($0)]" }.joined() - let normalPrefixes = commitPrefixModel.prefixes.joined() - return ConslerOutput(branchPrefixes, normalPrefixes) + return branchPrefixes().map { + let branchPrefixes = $0.map { "[\($0)]" }.joined() + let normalPrefixes = commitPrefixModel.prefixes.joined() + return ConslerOutput(branchPrefixes, normalPrefixes) + } } } - func getCommitPrefixState() throws -> CPState { + func getCommitPrefixState() -> Result { switch commitPrefixModel.prefixMode { case .normal: - return CPState( + return .success(CPState( mode: .normal, branchPrefixes: [], normalPrefixes: commitPrefixModel.prefixes - ) + )) case .branchParse: - let retrievedBranchPrefixes = try branchPrefixes() - let branchPrefixes = retrievedBranchPrefixes.map { "[\($0)]" } - let normalPrefixes = commitPrefixModel.prefixes - return CPState( - mode: .branchParse, - branchPrefixes: branchPrefixes, - normalPrefixes: normalPrefixes - ) + return branchPrefixes().map { + let branchPrefixes = $0.map { "[\($0)]" } + let normalPrefixes = commitPrefixModel.prefixes + return CPState( + mode: .branchParse, + branchPrefixes: branchPrefixes, + normalPrefixes: normalPrefixes + ) + } } } - func deletePrefixes() throws -> ConslerOutput { + func deletePrefixes() -> Result { let newModel = commitPrefixModel.updated(with: []) - try saveCommitPrefix(model: newModel) - return ConslerOutput("CommitPrefix ", "DELETED").describedBy(.normal, .red) + return saveCommitPrefix(model: newModel) + .transform(ConslerOutput( + "CommitPrefix ", "DELETED") + .describedBy(.normal, .red)) } - func writeNew(prefixes rawValue: String) throws -> ConslerOutput { + func writeNew(prefixes rawValue: String) -> Result { let newPrefixes = prefixFormatter(rawValue) let newModel = commitPrefixModel.updated(with: newPrefixes) - try saveCommitPrefix(model: newModel) - return ConslerOutput("CommitPrefix ", "STORED ", newPrefixes.joined()) - .describedBy(.normal, .green, .green) + return saveCommitPrefix(model: newModel) + .transform(ConslerOutput( + "CommitPrefix ", "STORED ", newPrefixes.joined()) + .describedBy(.normal, .green, .green)) } - func activateBranchMode(with validator: String) throws -> ConslerOutput { - let formattedValidator = try validatorFormatter(validator) - let newModel = commitPrefixModel.updatedAsBranchMode(with: formattedValidator) - try saveCommitPrefix(model: newModel) - return ConslerOutput("CommitPrefix ","MODE BRANCH_PARSE ", formattedValidator) - .describedBy(.normal, .cyan, .green) + func activateBranchMode(with validator: String) -> Result { + switch validatorFormatter(validator) { + case let .success(formattedValidator): + let newModel = commitPrefixModel.updatedAsBranchMode(with: formattedValidator) + return saveCommitPrefix(model: newModel) + .transform(ConslerOutput( + "CommitPrefix ","MODE BRANCH_PARSE ", formattedValidator) + .describedBy(.normal, .cyan, .green)) + case let .failure(cpError): + return .failure(cpError) + } } - func activateNormalMode() throws -> ConslerOutput { + func activateNormalMode() -> Result { switch commitPrefixModel.prefixMode { case .normal: - return ConslerOutput("CommitPrefix ", "already in ", "MODE NORMAL") - .describedBy(.normal, .yellow, .cyan) + return .success(ConslerOutput("CommitPrefix ", "already in ", "MODE NORMAL") + .describedBy(.normal, .yellow, .cyan)) case .branchParse: let newModel = commitPrefixModel.updatedAsNormalMode() - try saveCommitPrefix(model: newModel) - return ConslerOutput("CommitPrefix ", "MODE NORMAL").describedBy(.normal, .cyan) + return saveCommitPrefix(model: newModel) + .transform(ConslerOutput( + "CommitPrefix ", "MODE NORMAL") + .describedBy(.normal, .cyan)) } } From 3012520c0b1fecf7ac548bf1df1051726ed337ab Mon Sep 17 00:00:00 2001 From: Stephen Martinez Date: Sun, 12 Jan 2020 19:30:08 -0800 Subject: [PATCH 5/9] [CPFeature-009] Updated the CLIArgs with Result types --- .../CLInterface/CLIArguments.swift | 54 +++++++++++-------- 1 file changed, 31 insertions(+), 23 deletions(-) diff --git a/Sources/CommitPrefix/CLInterface/CLIArguments.swift b/Sources/CommitPrefix/CLInterface/CLIArguments.swift index 597571b..aa1d8e6 100644 --- a/Sources/CommitPrefix/CLInterface/CLIArguments.swift +++ b/Sources/CommitPrefix/CLInterface/CLIArguments.swift @@ -73,46 +73,46 @@ struct CLIArguments { self.userEntry = argBuilder.buildUserEntryArgument(parser: parser) } - private func singleCommandParse(_ allCommands: [ParsedCommand]) throws -> UserCommand { + private func singleCommandParse(_ allCommands: [ParsedCommand]) -> Result { precondition(allCommands.count == 1, "Intended for single Parsed Command only!") guard let foundCommand = allCommands.first else { - throw CPError.commandNotRecognized + return .failure(.commandNotRecognized) } switch foundCommand { case .outputVersion: - return .outputVersion + return .success(.outputVersion) case .outputPrefixes: - return .outputPrefixes + return .success(.outputPrefixes) case .deletePrefixes: - return .deletePrefixes + return .success(.deletePrefixes) case .modeNormal: - return .modeNormal + return .success(.modeNormal) case .userEntry(value: let prefixes): - return .newPrefixes(value: prefixes) + return .success(.newPrefixes(value: prefixes)) default: - throw CPError.commandNotRecognized + return .failure(.commandNotRecognized) } } - private func doubleCommandParse(_ allCommands: [ParsedCommand]) throws -> UserCommand { + private func doubleCommandParse(_ allCommands: [ParsedCommand]) -> Result { precondition(allCommands.count == 2, "Intended for two Parsed Commands only!") let firstCommand = allCommands[0] let secondCommand = allCommands[1] switch (firstCommand, secondCommand) { case (.modeBranchParse, .userEntry(value: let validator)): - return .modeBranchParse(validator: validator) + return .success(.modeBranchParse(validator: validator)) case (.userEntry(value: let validator), .modeBranchParse): - return .modeBranchParse(validator: validator) + return .success(.modeBranchParse(validator: validator)) default: - throw CPError.commandNotRecognized + return .failure(.commandNotRecognized) } } - func getCommand() throws -> UserCommand { + private func getCommand() -> Result { guard let parsedArgs = try? parser.parse(rawArgs) else { - throw CPError.commandNotRecognized + return .failure(.commandNotRecognized) } var allCommands = [ParsedCommand]() @@ -123,24 +123,32 @@ struct CLIArguments { parsedArgs.get(modeNormal).map { _ in allCommands.append(.modeNormal) } parsedArgs.get(modeBranchParse).map { _ in allCommands.append(.modeBranchParse) } - try parsedArgs.get(userEntry).map { userEntry in - let noMoreThanOneEntry = userEntry.count < 2 - guard noMoreThanOneEntry else { throw CPError.invalidEntryFormat } - guard let theEntry = userEntry.first else { throw CPError.emptyEntry } - allCommands.append(.userEntry(value: theEntry)) + do { + try parsedArgs.get(userEntry).map { userEntry in + let noMoreThanOneEntry = userEntry.count < 2 + guard noMoreThanOneEntry else { throw CPError.invalidEntryFormat } + guard let theEntry = userEntry.first else { throw CPError.emptyEntry } + allCommands.append(.userEntry(value: theEntry)) + } + } catch let cpError as CPError { + return .failure(cpError) + } catch { + return .failure(.unexpectedError) } switch allCommands.count { case 0: - return .viewState + return .success(.viewState) case 1: - return try singleCommandParse(allCommands) + return singleCommandParse(allCommands) case 2: - return try doubleCommandParse(allCommands) + return doubleCommandParse(allCommands) default: - throw CPError.tooManyArguments + return .failure(.tooManyArguments) } } + var command: UserCommand { getCommand().resolveOrExit() } + } From 58ff628c0da359e51ec14630efc2e5783da7af64 Mon Sep 17 00:00:00 2001 From: Stephen Martinez Date: Sun, 12 Jan 2020 19:30:33 -0800 Subject: [PATCH 6/9] [CPFeature-009] Updated the version patch number --- Sources/CommitPrefix/Constants.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/CommitPrefix/Constants.swift b/Sources/CommitPrefix/Constants.swift index d207427..6f0a4ad 100644 --- a/Sources/CommitPrefix/Constants.swift +++ b/Sources/CommitPrefix/Constants.swift @@ -28,7 +28,7 @@ import Foundation struct CPInfo { - static let version = "1.4.2" + static let version = "1.4.3" } From 4dd0484209750b2c33e6740d7ad6193e1092f81c Mon Sep 17 00:00:00 2001 From: Stephen Martinez Date: Sun, 12 Jan 2020 19:31:05 -0800 Subject: [PATCH 7/9] [CPFeature-009] Added the CPInterface protocol for main to safely use --- Sources/CommitPrefix/CPInterface.swift | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Sources/CommitPrefix/CPInterface.swift b/Sources/CommitPrefix/CPInterface.swift index 4fac37b..c89050b 100644 --- a/Sources/CommitPrefix/CPInterface.swift +++ b/Sources/CommitPrefix/CPInterface.swift @@ -31,16 +31,16 @@ protocol CPInterface { func outputVersion() -> ConslerOutput - func outputPrefixes() throws -> ConslerOutput + func outputPrefixes() -> ConslerOutput - func viewState() throws -> ConslerOutput + func viewState() -> ConslerOutput - func deletePrefixes() throws -> ConslerOutput + func deletePrefixes() -> ConslerOutput - func writeNew(prefixes rawValue: String) throws -> ConslerOutput + func writeNew(prefixes rawValue: String) -> ConslerOutput - func activateBranchMode(with validator: String) throws -> ConslerOutput + func activateBranchMode(with validator: String) -> ConslerOutput - func activateNormalMode() throws -> ConslerOutput + func activateNormalMode() -> ConslerOutput } From 716db313ec1f7c7940d650b626ac53d76bcb6b85 Mon Sep 17 00:00:00 2001 From: Stephen Martinez Date: Sun, 12 Jan 2020 19:32:26 -0800 Subject: [PATCH 8/9] [CPFeature-009] Updated the CommitPrefix type to both conform to CPInterface and to incorporate Result types --- Sources/CommitPrefix/CPInterfaceImpl.swift | 88 ++++++++++++---------- 1 file changed, 50 insertions(+), 38 deletions(-) diff --git a/Sources/CommitPrefix/CPInterfaceImpl.swift b/Sources/CommitPrefix/CPInterfaceImpl.swift index 09567be..f05182b 100644 --- a/Sources/CommitPrefix/CPInterfaceImpl.swift +++ b/Sources/CommitPrefix/CPInterfaceImpl.swift @@ -34,14 +34,18 @@ struct CommitPrefix { static func interface() -> CPInterface { CommitPrefix() } - private func getInteractor() throws -> CPInteractor { - guard Folder.current.containsSubfolder(named: FolderName.git) else { - throw CPError.notAGitRepo(currentLocation: Folder.current.path) - } - let gitDirectory = try Folder.current.subfolder(named: FolderName.git) - try CommitMessageHook.findOrCreate(with: gitDirectory) - let cpInteractor = try CPInteractor(gitDirectory: gitDirectory) - return cpInteractor + private func getInteractor() -> Result { + + guard + Folder.current.containsSubfolder(named: FolderName.git), + let gitDirectory = try? Folder.current.subfolder(named: FolderName.git) + else { return .failure(.notAGitRepo(currentLocation: Folder.current.path)) } + + return CommitMessageHook + .findOrCreate(with: gitDirectory) + .transform(gitDirectory) + .flatMap(CPInteractor.create) + } } @@ -49,9 +53,10 @@ struct CommitPrefix { // MARK: - CPInterface Conformances extension CommitPrefix: CPInterface { - func outputPrefixes() throws -> ConslerOutput { - let cpInteractor = try getInteractor() - return try cpInteractor.outputPrefixes() + func outputPrefixes() -> ConslerOutput { + return getInteractor() + .flatMap { $0.outputPrefixes() } + .resolveOrExit() } func outputVersion() -> ConslerOutput { @@ -60,42 +65,49 @@ extension CommitPrefix: CPInterface { .describedBy(.normal, .cyan, .cyan) } - func viewState() throws -> ConslerOutput { - let cpInteractor = try getInteractor() - let cpState = try cpInteractor.getCommitPrefixState() - switch cpState.mode { - case .normal: - return ConslerOutput( - "CommitPrefix ", "MODE NORMAL", - "- prefixes: ", cpState.normalPrefixes.joined()) - .describedBy(.normal, .cyanEndsLine, .normal, .cyan) - case .branchParse: - return ConslerOutput( - "CommitPrefix ", "MODE BRANCH_PARSE", - "- branch prefixes: ", cpState.branchPrefixes.joined(), - "- stored prefixes: ", cpState.normalPrefixes.joined()) - .describedBy(.normal, .cyanEndsLine, .normal, .cyanEndsLine, .normal, .cyan) + func viewState() -> ConslerOutput { + return getInteractor() + .flatMap { $0.getCommitPrefixState() } + .map { cpState in + switch cpState.mode { + case .normal: + return ConslerOutput( + "CommitPrefix ", "MODE NORMAL", + "- prefixes: ", cpState.normalPrefixes.joined()) + .describedBy(.normal, .cyanEndsLine, .normal, .cyan) + case .branchParse: + return ConslerOutput( + "CommitPrefix ", "MODE BRANCH_PARSE", + "- branch prefixes: ", cpState.branchPrefixes.joined(), + "- stored prefixes: ", cpState.normalPrefixes.joined()) + .describedBy(.normal, .cyanEndsLine, .normal, .cyanEndsLine, .normal, .cyan) + } } + .resolveOrExit() } - func deletePrefixes() throws -> ConslerOutput { - let cpInteractor = try getInteractor() - return try cpInteractor.deletePrefixes() + func deletePrefixes() -> ConslerOutput { + return getInteractor() + .flatMap { $0.deletePrefixes() } + .resolveOrExit() } - func writeNew(prefixes rawValue: String) throws -> ConslerOutput { - let cpInteractor = try getInteractor() - return try cpInteractor.writeNew(prefixes: rawValue) + func writeNew(prefixes rawValue: String) -> ConslerOutput { + return getInteractor() + .flatMap { $0.writeNew(prefixes: rawValue) } + .resolveOrExit() } - func activateBranchMode(with validator: String) throws -> ConslerOutput { - let cpInteractor = try getInteractor() - return try cpInteractor.activateBranchMode(with: validator) + func activateBranchMode(with validator: String) -> ConslerOutput { + return getInteractor() + .flatMap { $0.activateBranchMode(with: validator) } + .resolveOrExit() } - func activateNormalMode() throws -> ConslerOutput { - let cpInteractor = try getInteractor() - return try cpInteractor.activateNormalMode() + func activateNormalMode() -> ConslerOutput { + return getInteractor() + .flatMap { $0.activateNormalMode() } + .resolveOrExit() } } From 9b5be8022c8ccd586629d6017be5931b4de8fb41 Mon Sep 17 00:00:00 2001 From: Stephen Martinez Date: Sun, 12 Jan 2020 19:33:07 -0800 Subject: [PATCH 9/9] [CPFeature-009] Updated the main file with the new result oriented api --- Sources/CommitPrefix/main.swift | 64 ++++++++++++--------------------- 1 file changed, 23 insertions(+), 41 deletions(-) diff --git a/Sources/CommitPrefix/main.swift b/Sources/CommitPrefix/main.swift index c18c15d..22bce7b 100644 --- a/Sources/CommitPrefix/main.swift +++ b/Sources/CommitPrefix/main.swift @@ -29,53 +29,35 @@ import Foundation let commandLineInterface = CLIArguments() let cpInterface = CommitPrefix.interface() - -do { - switch try commandLineInterface.getCommand() { - - case .outputVersion: - let versionOutput = cpInterface.outputVersion() - Consler.output(versionOutput) - - case .viewState: - let viewStateOutput = try cpInterface.viewState() - Consler.output(viewStateOutput) - - case .outputPrefixes: - let prefixesOutput = try cpInterface.outputPrefixes() - Consler.output(prefixesOutput) - - case .deletePrefixes: - let deletionOutput = try cpInterface.deletePrefixes() - Consler.output(deletionOutput) +switch commandLineInterface.command { + +case .outputVersion: + let versionOutput = cpInterface.outputVersion() + Consler.output(versionOutput) - case .modeNormal: - let normalModeOutput = try cpInterface.activateNormalMode() - Consler.output(normalModeOutput) - - case .modeBranchParse(validator: let rawValidatorValue): - let branchModeOutput = try cpInterface.activateBranchMode(with: rawValidatorValue) - Consler.output(branchModeOutput) - - case .newPrefixes(value: let rawPrefixValue): - let newPrefixesOutput = try cpInterface.writeNew(prefixes: rawPrefixValue) - Consler.output(newPrefixesOutput) - - } +case .viewState: + let viewStateOutput = cpInterface.viewState() + Consler.output(viewStateOutput) -} catch let prefixError as CPError { +case .outputPrefixes: + let prefixesOutput = cpInterface.outputPrefixes() + Consler.output(prefixesOutput) - Consler.output(prefixError.message ,type: .error) - exit(prefixError.status.value) +case .deletePrefixes: + let deletionOutput = cpInterface.deletePrefixes() + Consler.output(deletionOutput) -} catch { +case .modeNormal: + let normalModeOutput = cpInterface.activateNormalMode() + Consler.output(normalModeOutput) - Consler.output( - "Unexpected Error: ", error.localizedDescription, - descriptors: [.boldRed, .normal], - type: .error) +case .modeBranchParse(validator: let rawValidatorValue): + let branchModeOutput = cpInterface.activateBranchMode(with: rawValidatorValue) + Consler.output(branchModeOutput) - exit(TerminationStatus.unexpectedError.value) +case .newPrefixes(value: let rawPrefixValue): + let newPrefixesOutput = cpInterface.writeNew(prefixes: rawPrefixValue) + Consler.output(newPrefixesOutput) }