51 lines
2.2 KiB
Swift
51 lines
2.2 KiB
Swift
import Foundation
|
|
|
|
/// One commit of HEAD's recent history, as the Git view's commit list shows it.
|
|
public struct GitCommitSummary: Sendable, Equatable {
|
|
public var hash: String
|
|
public var subject: String
|
|
public var author: String
|
|
public var date: Date
|
|
|
|
public init(hash: String, subject: String, author: String, date: Date) {
|
|
self.hash = hash
|
|
self.subject = subject
|
|
self.author = author
|
|
self.date = date
|
|
}
|
|
}
|
|
|
|
public enum GitCommitLogParsing {
|
|
public static let limit = 30
|
|
/// NUL between fields and a record separator after each commit, so no subject can split a record.
|
|
public static let arguments = ["log", "-n", "\(limit)", "--no-color", "--format=%h%x00%s%x00%an%x00%ct%x1e"]
|
|
|
|
/// Reads the records `arguments` prints, newest first; a malformed record is skipped.
|
|
public static func commits(_ raw: String) -> [GitCommitSummary] {
|
|
raw.split(separator: "\u{1e}").compactMap { record in
|
|
let text = record.trimmingCharacters(in: .newlines)
|
|
let fields = text.split(separator: "\0", omittingEmptySubsequences: false)
|
|
guard fields.count == 4, !fields[0].isEmpty, let seconds = TimeInterval(fields[3]) else { return nil }
|
|
return GitCommitSummary(hash: String(fields[0]), subject: String(fields[1]), author: String(fields[2]),
|
|
date: Date(timeIntervalSince1970: seconds))
|
|
}
|
|
}
|
|
}
|
|
|
|
public enum RelativeTime {
|
|
/// "just now", "5 min ago", "3 h ago", "2 d ago", "3 w ago", "4 mo ago", "2 y ago"; a future date reads "just now".
|
|
public static func text(_ date: Date, now: Date) -> String {
|
|
let seconds = Int(now.timeIntervalSince(date))
|
|
let minute = 60, hour = 3_600, day = 86_400
|
|
switch seconds {
|
|
case ..<minute: return "just now"
|
|
case ..<hour: return "\(seconds / minute) min ago"
|
|
case ..<day: return "\(seconds / hour) h ago"
|
|
case ..<(7 * day): return "\(seconds / day) d ago"
|
|
case ..<(30 * day): return "\(seconds / (7 * day)) w ago"
|
|
case ..<(365 * day): return "\(seconds / (30 * day)) mo ago"
|
|
default: return "\(seconds / (365 * day)) y ago"
|
|
}
|
|
}
|
|
}
|