Skip to content

Commit

Permalink
Add argument parser, support copy the url in different formats
Browse files Browse the repository at this point in the history
  • Loading branch information
xiaohk committed Feb 13, 2018
1 parent f007e41 commit 6468075
Show file tree
Hide file tree
Showing 3 changed files with 83 additions and 17 deletions.
5 changes: 3 additions & 2 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ let package = Package(
// Dependencies declare other packages that this package depends on.
// .package(url: /* package url */, from: "1.0.0"),
// Rainbow to support console output in color
.package(url: "https://github.com/onevcat/Rainbow", from: "3.0.0")
.package(url: "https://github.com/onevcat/Rainbow", from: "3.0.0"),
.package(url: "https://github.com/apple/swift-package-manager.git", from: "0.1.0")
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
Expand All @@ -19,6 +20,6 @@ let package = Package(
dependencies: ["clip2imgurCore"]),
.target(
name: "clip2imgurCore",
dependencies: ["Rainbow"])
dependencies: ["Rainbow", "Utility"])
]
)
89 changes: 77 additions & 12 deletions Sources/clip2imgurCore/CommandLineInterface.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,78 @@
import Foundation
import Cocoa
import Rainbow
import Utility
import Basic

private enum copyFormat{
case markdown
case html
case plain
}

// A class managing the commmand line interface for this project
public class CommandLineInterface{
public let argc: Int32
public let argv: [String]
public let argc = CommandLine.argc
public let argv = CommandLine.arguments
private let api = ImgurAPI()

private let parser: ArgumentParser
private let useMDFormat: OptionArgument<Bool>
private let useHTMLFormat: OptionArgument<Bool>
private let doNotCopy: OptionArgument<Bool>

public init(){
self.argc = CommandLine.argc
self.argv = CommandLine.arguments
// Init the argument parser and register flags
let overview = "clip2imgur is a simple CLI that uploads your image in clipboard " +
"to Imgur."
self.parser = ArgumentParser(usage: "<flags>",
overview: overview)
self.useMDFormat = self.parser.add(
option: "--markdown",
shortName: "-m",
kind: Bool.self,
usage: "Copy the image url in Markdown format"
)

self.useHTMLFormat = self.parser.add(
option: "--html",
shortName: "-t",
kind: Bool.self,
usage: "Copy the image url in HTML format"
)

self.doNotCopy = self.parser.add(
option: "--nocopy",
shortName: "-n",
kind: Bool.self,
usage: "Do not copy the image url after submitting"
)
}

// The main logic is implemented here
// The app main logic is implemented here
public func run(){
let cliImage = ClipboardImage()
let url = self.postImage(from: cliImage.getClipboardImageBase64())
copyToClipboard(from: url)
do {
// Parse the arguments
let parsedArguments = try parser.parse(Array(self.argv.dropFirst()))

// Post the user's image
let cliImage = ClipboardImage()
let url = self.postImage(from: cliImage.getClipboardImageBase64())

// Decide how to copy the returned url
if (parsedArguments.get(self.doNotCopy) == true){
return
} else if (parsedArguments.get(self.useHTMLFormat) == true){
copyToClipboard(from: url, using: .html)
} else if (parsedArguments.get(self.useMDFormat) == true){
copyToClipboard(from: url, using: .markdown)
} else {
copyToClipboard(from: url, using: .plain)
}
} catch let error {
printError(error.localizedDescription)
self.parser.printUsage(on: stdoutStream)
}
print("The image url is coppied to your clipboard.".blue.bold)
}

Expand All @@ -38,7 +93,7 @@ public class CommandLineInterface{
var response: String?
while(true) {
print("[Enter 'yes' to start authorization, enter 'no' to post anonymously]")
print("> ".blink, terminator: "")
print("> ".bold, terminator: "")
response = readLine()
let legalResponses = ["yes", "no", "\'yes\'", "\'no\'", "y", "n"]
if (response != nil && legalResponses.contains(response!)){
Expand Down Expand Up @@ -75,9 +130,19 @@ public func printError(_ errorMessage: String){
fputs("Error: \(errorMessage)\n".red.bold, stderr)
}

// Copy the string to user's clipboard
private func copyToClipboard(from str: String){
// Copy the url to user's clipboard
private func copyToClipboard(from url: String, using format: copyFormat){
let clipboard = NSPasteboard.general
clipboard.declareTypes([.string], owner: nil)
clipboard.setString(str, forType: .string)
var formatedURL: String
// Copy the url in the specified format
switch format {
case .html:
formatedURL = "<img src=\"\(url)\">"
case .markdown:
formatedURL = "![](\(url))"
case .plain:
formatedURL = url
}
clipboard.setString(formatedURL, forType: .string)
}
6 changes: 3 additions & 3 deletions Sources/clip2imgurCore/ImgurAPI.swift
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ public class ImgurAPI: Imgurable{
print("The new URL looks like " +
"https://imgur.com/?state=copy-url#access_token=...\n".underline)
print("(4) Paste the full URL below: ".blue.bold)
print("> ".blink, terminator: "")
print("> ".bold, terminator: "")
response = readLine()

if (response != nil && response!.hasPrefix("https://imgur.com")){
Expand Down Expand Up @@ -223,7 +223,7 @@ public class ImgurAPI: Imgurable{

link = json_data["link"] as? String
if (link == nil){
printError("Failed to fetch link")
printError("Failed to fetch the link")
exit(-1)
}
} catch let error as NSError {
Expand All @@ -236,8 +236,8 @@ public class ImgurAPI: Imgurable{
)
// Start the task and wait for it to complete
dataTask.resume()
print("Uploading...")
sema.wait()

print("\n🎉 Successfully uploaded your screenshot to Imgur at \(link!.underline)\n")
return link!
}
Expand Down

0 comments on commit 6468075

Please sign in to comment.