Skip to content

Commit

Permalink
Merge pull request #48 from mono0926/refactor
Browse files Browse the repository at this point in the history
Refactor
  • Loading branch information
mono0926 committed May 14, 2017
2 parents a6e1f25 + c1b89f2 commit fa0b8d7
Show file tree
Hide file tree
Showing 19 changed files with 444 additions and 189 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,4 @@ Pods
*LicensePlist.Output
!Cartfile*.swift
!Pods*.swift
test_result_dir
7 changes: 5 additions & 2 deletions Sources/LicensePlistCore/Entity/CocoaPods.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,15 @@ import LoggerAPI
import Himotoki

public struct CocoaPods: Library {
public var name: String
public let name: String
public let nameSpecified: String?
public let version: String?
}

extension CocoaPods {
public static func==(lhs: CocoaPods, rhs: CocoaPods) -> Bool {
return lhs.name == rhs.name && lhs.version == rhs.version
return lhs.name == rhs.name &&
lhs.nameSpecified == rhs.nameSpecified &&
lhs.version == rhs.version
}
}
15 changes: 10 additions & 5 deletions Sources/LicensePlistCore/Entity/CocoaPodsLicense.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import LoggerAPI
import Himotoki

public struct CocoaPodsLicense: License, Equatable {
public var library: CocoaPods
public let library: CocoaPods
public let body: String

public static func==(lhs: CocoaPodsLicense, rhs: CocoaPodsLicense) -> Bool {
Expand All @@ -13,11 +13,13 @@ public struct CocoaPodsLicense: License, Equatable {
}

extension CocoaPodsLicense: CustomStringConvertible {
public var description: String { return "name: \(library.name)\nbody: \(String(body.characters.prefix(20)))" }
public var description: String {
return "name: \(library.name), nameSpecified: \(nameSpecified ?? "")\nbody: \(String(body.characters.prefix(20)))"
}
}

extension CocoaPodsLicense {
public static func load(_ content: String, versionInfo: VersionInfo) -> [CocoaPodsLicense] {
public static func load(_ content: String, versionInfo: VersionInfo, config: Config) -> [CocoaPodsLicense] {
do {
let plist = try PropertyListSerialization.propertyList(from: content.data(using: String.Encoding.utf8)!,
options: [],
Expand All @@ -26,8 +28,11 @@ extension CocoaPodsLicense {
return try AcknowledgementsPlist.decodeValue(plist).preferenceSpecifiers
.filter { $0.isLicense }
.map {
CocoaPodsLicense(library: CocoaPods(name: $0.title, version: versionInfo.version(name: $0.title)),
body: $0.footerText)
let name = $0.title
return CocoaPodsLicense(library: CocoaPods(name: name,
nameSpecified: config.renames[name],
version: versionInfo.version(name: $0.title)),
body: $0.footerText)
}
} catch let e {
Log.error(String(describing: e))
Expand Down
31 changes: 12 additions & 19 deletions Sources/LicensePlistCore/Entity/Config.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,24 +13,27 @@ public struct Config {

public init(yaml: String) {
let value = try! Yaml.load(yaml)
let excludes = value["exclude"].array?.map { $0.string! } ?? []
let renames = value["rename"].dictionary?.reduce([String: String]()) { sum, e in
guard let from = e.key.string, let to = e.value.string else { return sum }
var sum = sum
sum[from] = to
return sum
} ?? [:]
let githubs = value["github"].array?.map { $0.string }.flatMap { $0 } ?? []
let gitHubList = githubs.map { GitHub.load($0, mark: "", quotes: "") }.flatMap { $0 }
let gitHubList = githubs.map { GitHub.load($0, renames: renames, mark: "", quotes: "") }.flatMap { $0 }
let githubsVersion: [GitHub] = value["github"].array?.map {
guard let dictionary = $0.dictionary else {
return nil
}
guard let owner = dictionary["owner"]?.string, let name = dictionary["name"]?.string else {
return nil
}
return GitHub(name: name, owner: owner, version: dictionary["version"]?.string)
return GitHub(name: name,
nameSpecified: renames[name],
owner: owner,
version: dictionary["version"]?.string)
}.flatMap { $0 } ?? []
let excludes = value["exclude"].array?.map { $0.string! } ?? []
let renames = value["rename"].dictionary?.reduce([String: String]()) { sum, e in
guard let from = e.key.string, let to = e.value.string else { return sum }
var sum = sum
sum[from] = to
return sum
} ?? [:]
self = Config(githubs: githubsVersion + gitHubList, excludes: excludes, renames: renames)
}

Expand Down Expand Up @@ -89,16 +92,6 @@ public struct Config {
self.githubs.forEach { Log.warning("\($0.name) was loaded from config YAML.") }
return filterExcluded((self.githubs + githubs))
}
func rename<T: HasChangeableName>(_ names: [T]) -> [T] {
return names.map { name in
if let to = renames[name.name] {
var name = name
name.name = to
return name
}
return name
}
}
}

extension Config: Equatable {
Expand Down
35 changes: 24 additions & 11 deletions Sources/LicensePlistCore/Entity/GitHub.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,33 +3,43 @@ import APIKit
import LoggerAPI

public struct GitHub: Library {
public var name: String
public let name: String
public let nameSpecified: String?
var owner: String
public let version: String?
}

extension GitHub {
public static func==(lhs: GitHub, rhs: GitHub) -> Bool {
return lhs.name == rhs.name && lhs.owner == rhs.owner && lhs.version == rhs.version
return lhs.name == rhs.name &&
lhs.nameSpecified == rhs.nameSpecified &&
lhs.owner == rhs.owner &&
lhs.version == rhs.version
}
}

extension GitHub: CustomStringConvertible {
public var description: String { return "name: \(name), owner: \(owner), version: \(version ?? "")" }
public var description: String {
return "name: \(name), nameSpecified: \(nameSpecified ?? ""), owner: \(owner), version: \(version ?? "")"
}
}

extension GitHub {
public static func load(_ content: String) -> [GitHub] {
return load(content, mark: "github ")
public static func load(_ content: String, renames: [String: String] = [:]) -> [GitHub] {
return load(content, renames: renames, mark: "github ")
}
public static func load(_ content: String, mark: String, quotes: String = "\"") -> [GitHub] {
let r = load(content, mark: mark, quotes: quotes, version: true)
public static func load(_ content: String, renames: [String: String], mark: String, quotes: String = "\"") -> [GitHub] {
let r = load(content, renames: renames, mark: mark, quotes: quotes, version: true)
if !r.isEmpty {
return r
}
return load(content, mark: mark, quotes: quotes, version: false)
return load(content, renames: renames, mark: mark, quotes: quotes, version: false)
}
public static func load(_ content: String, mark: String, quotes: String = "\"", version: Bool = false) -> [GitHub] {
public static func load(_ content: String,
renames: [String: String],
mark: String,
quotes: String = "\"",
version: Bool = false) -> [GitHub] {
let pattern = "[\\w\\.\\-]+"
let regexString = "\(mark)\(quotes)(\(pattern))/(\(pattern))\(quotes)" + (version ? " \(quotes)([\\w\\.\\-]+)\(quotes)" : "")
let regex = try! NSRegularExpression(pattern: regexString, options: [])
Expand All @@ -50,8 +60,11 @@ extension GitHub {
}
return version
}()
return GitHub(name: nsContent.substring(with: match.rangeAt(2)),
owner: nsContent.substring(with: match.rangeAt(1)), version: version)
let name = nsContent.substring(with: match.rangeAt(2))
return GitHub(name: name,
nameSpecified: renames[name],
owner: nsContent.substring(with: match.rangeAt(1)),
version: version)
}
.flatMap { $0 }
}
Expand Down
2 changes: 1 addition & 1 deletion Sources/LicensePlistCore/Entity/GitHubLicense.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import APIKit
import Result

public struct GitHubLicense: License, Equatable {
public var library: GitHub
public let library: GitHub
public let body: String
let githubResponse: LicenseResponse

Expand Down
5 changes: 1 addition & 4 deletions Sources/LicensePlistCore/Entity/HasName.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,5 @@ import LoggerAPI

public protocol HasName {
var name: String { get }
}

public protocol HasChangeableName: HasName {
var name: String { get set }
var nameSpecified: String? { get }
}
2 changes: 1 addition & 1 deletion Sources/LicensePlistCore/Entity/Library.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import Foundation
import APIKit
import LoggerAPI

public protocol Library: Hashable, Equatable, HasChangeableName {
public protocol Library: HasName, Hashable, Equatable {
var version: String? { get }
}

Expand Down
15 changes: 7 additions & 8 deletions Sources/LicensePlistCore/Entity/License.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,31 @@ import Foundation
import APIKit
import LoggerAPI

public protocol LicenseInfo: HasChangeableName {
public protocol LicenseInfo: HasName {
var body: String { get }
var version: String? { get }
var bodyEscaped: String { get }
}

public protocol License: LicenseInfo {
associatedtype LibraryType: Library
var library: LibraryType { get set }
var library: LibraryType { get }
var body: String { get }
}

extension LicenseInfo {
public func name(withVersion: Bool) -> String {
let title = nameSpecified ?? name
if let version = version, withVersion {
return "\(name) (\(version))"
return "\(title) (\(version))"
}
return name
return title
}
}

extension License {
public var name: String {
set { library.name = newValue }
get { return library.name }
}
public var name: String { return library.name }
public var nameSpecified: String? { return library.nameSpecified }
public var version: String? { return library.version }
public var bodyEscaped: String {
return body
Expand Down
124 changes: 124 additions & 0 deletions Sources/LicensePlistCore/Entity/PlistInfo.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import Foundation
import LoggerAPI

struct PlistInfo {
let options: Options
var cocoaPodsLicenses: [CocoaPodsLicense]?
var githubLibraries: [GitHub]?
var githubLicenses: [GitHubLicense]?
var summary: String?
var summaryPath: URL?
var licenses: [LicenseInfo]?

init(options: Options) {
self.options = options
}

mutating func loadCocoaPodsLicense(acknowledgements: [String]) {
guard cocoaPodsLicenses == nil else { preconditionFailure() }
Log.info("Pods License parse start")

let versionPath = options.podsPath.appendingPathComponent("Manifest.lock")
let podsVersionInfo = VersionInfo(podsManifest: versionPath.lp.read() ?? "")
let licenses = acknowledgements
.map { CocoaPodsLicense.load($0, versionInfo: podsVersionInfo, config: options.config) }
.flatMap { $0 }
let config = options.config
cocoaPodsLicenses = config.filterExcluded(licenses)
}

mutating func loadGitHubLibraries(cartfile: String?) {
Log.info("Carthage License collect start")
githubLibraries = options.config.apply(githubs: GitHub.load(cartfile ?? "", renames: options.config.renames))
}

mutating func compareWithLatestSummary() {
guard let cocoaPodsLicenses = cocoaPodsLicenses, let githubLibraries = githubLibraries else { preconditionFailure() }

let config = options.config

let contents = (cocoaPodsLicenses.map { String(describing: $0) } +
githubLibraries.map { String(describing: $0) } +
["add-version-numbers: \(options.config.addVersionNumbers)", "LicensePlist Version: \(Consts.version)"])
.joined(separator: "\n\n")
let savePath = options.outputPath.appendingPathComponent("\(Consts.prefix).latest_result.txt")
if let previous = savePath.lp.read(), previous == contents, !config.force {
Log.warning("Completed because no diff. You can execute force by `--force` flag.")
exit(0)
}
summary = contents
summaryPath = savePath
}

mutating func downloadGitHubLicenses() {
guard let githubLibraries = githubLibraries else { preconditionFailure() }

let queue = OperationQueue()
let carthageOperations = githubLibraries.map { GitHubLicense.download($0) }
queue.addOperations(carthageOperations, waitUntilFinished: true)
githubLicenses = carthageOperations.map { $0.result?.value }.flatMap { $0 }
}

mutating func collectLicenseInfos() {
guard let cocoaPodsLicenses = cocoaPodsLicenses, let githubLicenses = githubLicenses else { preconditionFailure() }

licenses = ((cocoaPodsLicenses as [LicenseInfo]) + (githubLicenses as [LicenseInfo]))
.reduce([String: LicenseInfo]()) { sum, e in
var sum = sum
sum[e.name] = e
return sum
}.values
.sorted { $0.name.lowercased() < $1.name.lowercased() }
}

func outputPlist() {
guard let licenses = licenses else { preconditionFailure() }

let tm = TemplateManager.shared

let outputPath = options.outputPath
let plistPath = outputPath.appendingPathComponent(Consts.prefix)
if plistPath.lp.deleteIfExits() {
Log.info("Deleted exiting plist within \(Consts.prefix)")
}
plistPath.lp.createDirectory()
Log.info("Directory created: \(outputPath)")

let licensListItems = licenses.map {
return tm.licenseListItem.applied(["Title": $0.name(withVersion: options.config.addVersionNumbers),
"FileName": "\(Consts.prefix)/\($0.name)"])
}
let licenseListPlist = tm.licenseList.applied(["Item": licensListItems.joined(separator: "\n")])
outputPath.appendingPathComponent("\(Consts.prefix).plist").lp.write(content: licenseListPlist)

licenses.forEach {
plistPath.appendingPathComponent("\($0.name).plist")
.lp.write(content: tm.license.applied(["Body": $0.bodyEscaped]))
}
}

func reportMissings() {
guard let githubLibraries = githubLibraries, let licenses = licenses else { preconditionFailure() }

Log.info("----------Result-----------")
Log.info("# Missing license:")
let missing = Set(githubLibraries.map { $0.name }).subtracting(Set(licenses.map { $0.name }))
if missing.isEmpty {
Log.info("None🎉")
} else {
Array(missing).sorted { $0 < $1 }.forEach { Log.warning($0) }
}
}

func finish() {
precondition(cocoaPodsLicenses != nil && githubLibraries != nil && githubLicenses != nil && licenses != nil)
guard let summary = summary, let summaryPath = summaryPath else {
fatalError("summary should be set")
}
do {
try summary.write(to: summaryPath, atomically: true, encoding: Consts.encoding)
} catch let e {
Log.error("Failed to save summary. Error: \(String(describing: e))")
}
}
}
4 changes: 2 additions & 2 deletions Sources/LicensePlistCore/Extension/URL.extension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -99,9 +99,9 @@ extension Bool: HasDefaultValue {
}

extension Array: HasDefaultValue {
static var `default`: Array<Element> { return [] }
static var `default`: [Element] { return [] }
}

extension Optional: HasDefaultValue {
static var `default`: Optional<Wrapped> { return nil }
static var `default`: Wrapped? { return nil }
}
Loading

0 comments on commit fa0b8d7

Please sign in to comment.