2015-08-21 13:02:36 +00:00
|
|
|
//
|
|
|
|
// Install.swift
|
|
|
|
// mas-cli
|
|
|
|
//
|
|
|
|
// Created by Andrew Naylor on 21/08/2015.
|
|
|
|
// Copyright (c) 2015 Andrew Naylor. All rights reserved.
|
|
|
|
//
|
|
|
|
|
|
|
|
struct InstallCommand: CommandType {
|
2015-12-30 21:20:25 +00:00
|
|
|
typealias Options = InstallOptions
|
2015-08-21 13:02:36 +00:00
|
|
|
let verb = "install"
|
|
|
|
let function = "Install from the Mac App Store"
|
|
|
|
|
2016-09-17 12:58:38 +00:00
|
|
|
func run(_ options: Options) -> Result<(), MASError> {
|
2016-09-06 14:28:24 +00:00
|
|
|
// Try to download applications with given identifiers and collect results
|
2016-09-14 21:28:18 +00:00
|
|
|
let downloadResults = options.appIds.flatMap { (appId) -> MASError? in
|
2016-09-17 12:58:38 +00:00
|
|
|
if let product = installedApp(appId) , !options.forceInstall {
|
2016-09-14 21:28:18 +00:00
|
|
|
warn("\(product.appName) is already installed")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return download(appId)
|
|
|
|
}
|
2016-09-14 21:07:56 +00:00
|
|
|
|
2016-09-14 21:28:18 +00:00
|
|
|
switch downloadResults.count {
|
|
|
|
case 0:
|
2016-09-17 12:58:38 +00:00
|
|
|
return .success()
|
2016-09-14 21:28:18 +00:00
|
|
|
case 1:
|
2016-09-17 12:58:38 +00:00
|
|
|
return .failure(downloadResults[0])
|
2016-09-14 21:28:18 +00:00
|
|
|
default:
|
2016-09-17 12:58:38 +00:00
|
|
|
return .failure(MASError(code: .downloadFailed))
|
2016-09-06 14:28:24 +00:00
|
|
|
}
|
2016-09-14 21:28:18 +00:00
|
|
|
}
|
|
|
|
|
2016-09-17 12:58:38 +00:00
|
|
|
fileprivate func installedApp(_ appId: UInt64) -> CKSoftwareProduct? {
|
|
|
|
let appId = NSNumber(value: appId)
|
2016-09-14 21:07:56 +00:00
|
|
|
|
2016-09-17 12:58:38 +00:00
|
|
|
let softwareMap = CKSoftwareMap.shared()
|
2016-09-14 21:28:18 +00:00
|
|
|
return softwareMap.allProducts()?.filter { $0.itemIdentifier == appId }.first
|
2015-08-21 13:02:36 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
struct InstallOptions: OptionsType {
|
2016-09-06 13:37:12 +00:00
|
|
|
let appIds: [UInt64]
|
2016-09-14 22:04:53 +00:00
|
|
|
let forceInstall: Bool
|
2015-08-21 13:02:36 +00:00
|
|
|
|
2016-09-17 12:58:38 +00:00
|
|
|
static func create(_ appIds: [Int]) -> (_ forceInstall: Bool) -> InstallOptions {
|
|
|
|
return { forceInstall in
|
|
|
|
return InstallOptions(appIds: appIds.map{UInt64($0)}, forceInstall: forceInstall)
|
|
|
|
}
|
2015-08-21 13:02:36 +00:00
|
|
|
}
|
|
|
|
|
2016-09-17 12:58:38 +00:00
|
|
|
static func evaluate(_ m: CommandMode) -> Result<InstallOptions, CommandantError<MASError>> {
|
|
|
|
return create
|
2016-09-14 21:07:56 +00:00
|
|
|
<*> m <| Argument(usage: "app ID(s) to install")
|
2016-09-14 22:04:53 +00:00
|
|
|
<*> m <| Switch(flag: nil, key: "force", usage: "force reinstall")
|
2015-08-21 13:02:36 +00:00
|
|
|
}
|
2016-09-14 21:28:18 +00:00
|
|
|
}
|