Sources/OrgPrograms/GitHistory.swift
33 lines · 1979 bytes
3 symbols in this file
1#if os(macOS)
2import Foundation
3import OrgApp
4import OrgCore
5
6/// A file's commits, read with the system git.
7public enum GitHistory {
8 /// The commits that changed `file`, newest first, following renames (`git log --follow`);
9 /// each with the file's path in that commit. Empty outside a repository or without git.
10 public static func commits(for file: URL, git: Git? = Git.find(), limit: Int = 200) async -> [FileHistory.Commit] {
11 guard let git, let repository = await git.repository(containing: file.deletingLastPathComponent()),
12 let path = Git.relativePath(file, in: repository.top) else { return [] }
13 let arguments = ["log", "--follow", "-n", String(limit), "--name-only", "--format=%x1e%H%x1f%at%x1f%an%x1f%s", "--", path]
14 guard let output = try? await git.run(arguments, in: repository.top), output.succeeded else { return [] }
15 return output.stdout.split(separator: "\u{1e}").compactMap { record in
16 let lines = record.split(separator: "\n", omittingEmptySubsequences: true)
17 guard let header = lines.first, let name = lines.dropFirst().last else { return nil }
18 let fields = header.split(separator: "\u{1f}", omittingEmptySubsequences: false).map(String.init)
19 guard fields.count == 4, let seconds = TimeInterval(fields[1]) else { return nil }
20 return FileHistory.Commit(
21 hash: fields[0], date: Date(timeIntervalSince1970: seconds), author: fields[2], subject: fields[3],
22 path: String(name), repository: repository.top
23 )
24 }
25 }
26
27 /// The file's text in `commit`.
28 public static func text(of commit: FileHistory.Commit, git: Git? = Git.find()) async -> String? {
29 guard let git, let output = try? await git.run(["show", "\(commit.hash):\(commit.path)"], in: commit.repository), output.succeeded else { return nil }
30 return SourceText(bytes: Array(output.stdout.utf8)).text
31 }
32}
33#endif