| 1 | | import Foundation |
| 2 | | |
| 3 | | /// The commit and subject a report records: what the options name, and for the rest the |
| 4 | | /// repository's HEAD (DESIGN.md D7). |
| 5 | | public struct ReportedCommit: Sendable, Equatable { |
| 6 | | public let commit: String? |
| 7 | | public let subject: String? |
| 8 | | /// Says what was left out and why, when HEAD was needed and couldn't be read. |
| 9 | | public let omissionNote: String? |
| 10 | | |
| 11 | | /// - Parameters: |
| 12 | | /// - commit: the commit named, recorded as given; nil takes HEAD's, shortened as |
| 13 | | /// published runs record it. |
| 14 | | /// - subject: the subject named; nil takes HEAD's first message line, if it has one. |
| 15 | | /// - runGit: runs `git` with the arguments and returns its standard output. Not |
| 16 | | /// called when both are named. What it throws leaves out what HEAD would have |
| 17 | | /// given and is reported in `omissionNote`. |
| 18 | 8 | public init(commit: String?, subject: String?, runGit: ([String]) throws -> String) { |
| 19 | 8 | var head: (commit: String, subject: String?)? |
| 20 | 8 | var omissionNote: String? |
| 21 | 8 | if commit == nil || subject == nil { |
| 22 | 7 | do { |
| 23 | 7 | head = try Self.head(fromLog: runGit(Self.headLogArguments)) |
| 24 | 4 | } catch { |
| 25 | 3 | let omitted = [commit == nil ? "commit" : nil, subject == nil ? "subject" : nil] |
| 26 | 6 | .compactMap { $0 }.joined(separator: " and ") |
| 27 | 3 | omissionNote = "left out the \(omitted), since git can't read HEAD here: \(error)" |
| 28 | 7 | } |
| 29 | 8 | } |
| 30 | 8 | self.commit = commit ?? head?.commit |
| 31 | 8 | self.subject = subject ?? head?.subject |
| 32 | 8 | self.omissionNote = omissionNote |
| 33 | 8 | } |
| 34 | | |
| 35 | | /// One `log` call, so both come from the same commit and a repository without one |
| 36 | | /// says so in words. Without `--no-show-signature` a user's `log.showSignature` |
| 37 | | /// would put signature checks ahead of the hash. |
| 38 | | private static let headLogArguments = ["log", "-1", "--no-show-signature", "--format=%H%n%s"] |
| 39 | | |
| 40 | 4 | private static func head(fromLog log: String) throws -> (commit: String, subject: String?) { |
| 41 | 4 | let lines = log.split(separator: "\n", omittingEmptySubsequences: false) |
| 42 | 4 | let subject = lines.dropFirst().first?.trimmingCharacters(in: .whitespacesAndNewlines) |
| 43 | 4 | return ( |
| 44 | 4 | try PublishedLayout.runFolder(forCommit: String(lines[0])), |
| 45 | 4 | subject.flatMap { $0.isEmpty ? nil : $0 } |
| 46 | 4 | ) |
| 47 | 4 | } |
| 48 | | } |