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

Argument Parser migration #14

Merged
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
9 changes: 9 additions & 0 deletions Package.resolved
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,15 @@
"version": "0.9.0"
}
},
{
"package": "swift-argument-parser",
"repositoryURL": "https://github.com/apple/swift-argument-parser",
"state": {
"branch": null,
"revision": "3d79b2b5a2e5af52c14e462044702ea7728f5770",
"version": "0.1.0"
}
},
{
"package": "SwiftCLI",
"repositoryURL": "https://github.com/jakeheis/SwiftCLI",
Expand Down
10 changes: 9 additions & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,22 @@ let package = Package(
.package(
url: "https://github.com/kylef/PathKit",
from: "1.0.0"
),
.package(
elfenlaid marked this conversation as resolved.
Show resolved Hide resolved
url: "https://github.com/apple/swift-argument-parser",
from: "0.1.0"
)
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
// Targets can depend on other targets in this package, and on products in packages which this package depends on.
.target(
name: "Badgy",
dependencies: ["SwiftCLI", "PathKit"]),
dependencies: [
"SwiftCLI",
"PathKit",
.product(name: "ArgumentParser", package: "swift-argument-parser")
]),
.testTarget(
name: "BadgyTests",
dependencies: ["Badgy"]),
Expand Down
151 changes: 151 additions & 0 deletions Sources/Badgy/Commands/Badgy.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
//
// Badgy
elfenlaid marked this conversation as resolved.
Show resolved Hide resolved
//

import Foundation
import ArgumentParser
import PathKit

struct Badgy: ParsableCommand {
static var configuration = CommandConfiguration(
abstract: "A command-line tool to add labels to your app icon",
version: "0.1.4",
subcommands: [Long.self, Small.self],
defaultSubcommand: Long.self
)
}

extension Badgy {
struct Options: ParsableArguments {
@Argument(help :"Specify badge text")
var label: String

@Argument(help :"Specify path to icon with format .png | .jpg | .jpeg | .appiconset", transform: Icon.init(path:))
var icon: Icon

@Option(help: """
Specify a valid hex color code in a case insensitive format: '#rrggbb' | '#rrggbbaa'
or
Provide a named color: 'snow' | 'snow1' | ...
Complete list of named colors: https://imagemagick.org/script/color.php#color_names
""")
var color: ColorCode?

@Option(help: """
Specify a valid hex color code in a case insensitive format: '#rrggbb' | '#rrggbbaa'
or
Provide a named color: 'snow' | 'snow1' | ...
Complete list of named colors: https://imagemagick.org/script/color.php#color_names
""")
var tintColor: ColorCode?

@Flag(help: "Indicates Badgy should replace the input icon")
var replace: Bool

@Flag(help: "Log tech details for nerds")
var verbose: Bool

func validate() throws {
guard DependencyManager().areDependenciesInstalled() else {
throw ValidationError("Missing dependencies. Run: 'brew install imagemagick'")
}

Logger.shared.verbose = verbose
}
}
}

extension Badgy {
struct Long: ParsableCommand {
static var configuration = CommandConfiguration(
abstract: "Add rectangular label to app icon"
)

@OptionGroup()
var options: Badgy.Options

@Option(default: .bottom, help: "Position on which to place the badge. Supported positions: \(Position.longLabelPositions.formatted())")
var position: Position

@Option(default: 0, help: "The rotation angle of the badge in degrees range of -180 ... 180")
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does it behave any different with negative values than SwiftCLI?
I've recently seen an issue with it for not really testing before.
Only acceptable when escaped and within single or double quotes

--angle '\-15'

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Out of scope for this PR

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

oh, good catch, haven't thought about it before

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like a common problem for CLIs :)
Yet, as a workaround: ArgumentParser handles negative values if = is used. Example: --angle=-15

Related:
apple/swift-argument-parser#31
apple/swift-argument-parser#153

var angle: Int

func validate() throws {
guard options.label.count <= 4 else {
throw ValidationError("Label should contain maximum 4 characters")
}

guard position.isValidForLongLabels else {
throw ValidationError("Invalid provided position, supported positions are: \(Position.longLabelPositions.formatted())")
}

let validAngleRange = -180...180
guard validAngleRange.contains(angle) else {
throw ValidationError("Angle should be within range: \(validAngleRange)")
}
}

func run() throws {
Logger.shared.logSection("$ ", item: "badgy long \"\(options.label)\" \"\(options.icon.path)\"", color: .ios)

var pipeline = IconSignPipeline.make(withOptions: options)
pipeline.position = position
pipeline.angle = angle

try pipeline.execute()
}
}
}

extension Badgy {
struct Small: ParsableCommand {
static var configuration = CommandConfiguration(
abstract: "Add small square label to app icon"
)

@OptionGroup()
var options: Badgy.Options

@Option(default: .bottomLeft, help: "Position on which to place the badge. Supported positions: \(Position.allCases.formatted())")
var position: Position

func validate() throws {
guard options.label.count <= 1 else {
throw ValidationError("Label should contain maximum 1 character")
}
}

func run() throws {
Logger.shared.logSection("$ ", item: "badgy small \"\(options.label)\" \"\(options.icon.path)\"", color: .ios)

var pipeline = IconSignPipeline.make(withOptions: options)
pipeline.position = position

try pipeline.execute()
}
}
}

extension Position: ExpressibleByArgument { }

private extension IconSignPipeline {
static func make(withOptions options: Badgy.Options) -> IconSignPipeline {
var pipeline = IconSignPipeline(icon: options.icon, label: options.label)

pipeline.color = options.color?.value
pipeline.tintColor = options.tintColor?.value
pipeline.replace = options.replace

return pipeline
}
}

private extension Position {
static let longLabelPositions: Set<Position> = Set([
.top, .left, .bottom, .right, .center
])

var isValidForLongLabels: Bool {
Position.longLabelPositions.contains(self)
}
}
77 changes: 14 additions & 63 deletions Sources/Badgy/Commands/Long.swift
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@ final class Long: DependencyManager, Command, IconSetDelegate {
var iconSetImages: IconSetImages?

public func execute() throws {
Logger.shared.verbose = VerboseFlag.value

guard areDependenciesInstalled()
else {
throw CLI.Error(message: "Missing dependencies. Run: 'brew install imagemagick'")
Expand All @@ -86,72 +88,21 @@ final class Long: DependencyManager, Command, IconSetDelegate {
throw CLI.Error(message: "Angle should be within range -180 ... 180")
}
}

var baseIcon = icon
if isIconSet(Path(icon)) {
logger.logDebug("", item: "Finding the largest image in the .appiconset", color: .purple)

iconSetImages = iconSetImages(for: Path(icon))

guard
let largest = iconSetImages?.largest,
largest.size.width > 0
else {
logger.logError("❌ ", item: "Couldn't find the largest image in the set")
exit(1)
}
baseIcon = largest.image.absolute().description
logger.logDebug("Found: ", item: baseIcon, color: .purple)
}

try process(baseIcon: baseIcon)
}

private func process(baseIcon: String) throws {
let folder = Path("Badgy")
private func process() throws {
var pipeline = IconSignPipeline(
icon: try Icon(path: icon),
label: labelText
)

try factory.makeBadge(with: labelText, colorHexCode: color, tintColorHexCode: tintColor, angle: angleInt, inFolder: folder, completion: { (result) in
switch result {
case .success(_):
try self.factory.appendBadge(to: baseIcon,
folder: folder,
label: self.labelText,
position: Position(rawValue: self.position ?? "bottom")) {
(result) in
switch result {
case .success(let filename):
let filePath = Path(filename)
guard filePath.exists
else {
self.logger.logError("❌ ", item: "Failed to create badge")
return
}
self.logger.logInfo(item: "Icon with badge '\(self.labelText)' created at '\(filePath.absolute().description)'")
try self.factory.cleanUp(folder: folder)

if ReplaceFlag.value, let iconSet = self.iconSetImages {
self.replace(iconSet: iconSet, with: filePath)
} else {
self.resize(filePath: filePath)
}
case .failure(let error):
try self.factory.cleanUp(folder: folder)
throw CLI.Error(message: error.localizedDescription)
}
}
case .failure(let error):
try self.factory.cleanUp(folder: folder)
throw CLI.Error(message: error.localizedDescription)
}
})
}

private func resize(filePath: Path) {
factory.resize(filename: filePath)
}

private func replace(iconSet: IconSetImages, with newBadgeFile: Path) {
factory.replace(iconSet, with: newBadgeFile)
pipeline.position = Position(rawValue: position ?? "bottom")
pipeline.color = color
pipeline.tintColor = color
pipeline.angle = angleInt
pipeline.replace = ReplaceFlag.value

try pipeline.execute()
}
}

83 changes: 18 additions & 65 deletions Sources/Badgy/Commands/Small.swift
Original file line number Diff line number Diff line change
Expand Up @@ -67,75 +67,28 @@ final class Small: DependencyManager, Command, IconSetDelegate {
var iconSetImages: IconSetImages?

public func execute() throws {
Logger.shared.verbose = VerboseFlag.value

guard areDependenciesInstalled()
else {
throw CLI.Error(message: "Missing dependencies. Run: 'brew install imagemagick'")
}
logger.logSection("$ ", item: "badgy small \"\(char)\" \"\(icon)\"", color: .ios)

var baseIcon = icon
if isIconSet(Path(icon)) {
logger.logDebug("", item: "Finding the largest image in the .appiconset", color: .purple)

iconSetImages = iconSetImages(for: Path(icon))

guard
let largest = iconSetImages?.largest,
largest.size.width > 0
else {
logger.logError("❌ ", item: "Couldn't find the largest image in the set")
exit(1)
}
baseIcon = largest.image.absolute().description
logger.logDebug("Found: ", item: baseIcon, color: .purple)
throw CLI.Error(message: "Missing dependencies. Run: 'brew install imagemagick'")
}
logger.logSection("$ ", item: "badgy small \"\(char)\" \"\(icon)\"", color: .ios)

try process(baseIcon: baseIcon)
try process()
}

private func process(baseIcon: String) throws {
let folder = Path("Badgy")
factory.makeSmall(with: char, colorHexCode: color, tintColorHexCode: tintColor, inFolder: folder, completion: { (result) in
switch result {
case .success(_):
try self.factory.appendBadge(to: baseIcon,
folder: folder,
label: self.char,
position: Position(rawValue: self.position ?? "bottomLeft")) {
(result) in
switch result {
case .success(let filename):
let filePath = Path(filename)
guard filePath.exists
else {
self.logger.logError("❌ ", item: "Failed to create badge")
return
}
self.logger.logInfo(item: "Icon with badge '\(self.char)' created at '\(filePath.absolute().description)'")
try self.factory.cleanUp(folder: folder)

if ReplaceFlag.value, let iconSet = self.iconSetImages {
self.replace(iconSet: iconSet, with: filePath)
} else {
self.resize(filePath: filePath)
}
case .failure(let error):
try self.factory.cleanUp(folder: folder)
throw CLI.Error(message: error.localizedDescription)
}
}
case .failure(let error):
try self.factory.cleanUp(folder: folder)
throw CLI.Error(message: error.localizedDescription)
}
})
}

private func resize(filePath: Path) {
factory.resize(filename: filePath)
}

private func replace(iconSet: IconSetImages, with newBadgeFile: Path) {
factory.replace(iconSet, with: newBadgeFile)

private func process() throws {
var pipeline = IconSignPipeline(
icon: try Icon(path: icon),
label: char
)

pipeline.position = Position(rawValue: self.position ?? "bottomLeft")
elfenlaid marked this conversation as resolved.
Show resolved Hide resolved
pipeline.color = color
pipeline.tintColor = color
pipeline.replace = ReplaceFlag.value

try pipeline.execute()
}
}
Loading