1import 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).
5public 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`.
188 public init(commit: String?, subject: String?, runGit: ([String]) throws -> String) {
198 var head: (commit: String, subject: String?)?
208 var omissionNote: String?
218 if commit == nil || subject == nil {
227 do {
237 head = try Self.head(fromLog: runGit(Self.headLogArguments))
244 } catch {
253 let omitted = [commit == nil ? "commit" : nil, subject == nil ? "subject" : nil]
266 .compactMap { $0 }.joined(separator: " and ")
273 omissionNote = "left out the \(omitted), since git can't read HEAD here: \(error)"
287 }
298 }
308 self.commit = commit ?? head?.commit
318 self.subject = subject ?? head?.subject
328 self.omissionNote = omissionNote
338 }
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
404 private static func head(fromLog log: String) throws -> (commit: String, subject: String?) {
414 let lines = log.split(separator: "\n", omittingEmptySubsequences: false)
424 let subject = lines.dropFirst().first?.trimmingCharacters(in: .whitespacesAndNewlines)
434 return (
444 try PublishedLayout.runFolder(forCommit: String(lines[0])),
454 subject.flatMap { $0.isEmpty ? nil : $0 }
464 )
474 }
48}