Objects.swift (7854B)
1 // SPDX-License-Identifier: GPL-2.0-only 2 import CryptoKit 3 import Foundation 4 5 public enum GitError: Error, Equatable, CustomStringConvertible { 6 case malformed(String) 7 case missingObject(String) 8 case unauthorized 9 case notFound 10 case http(Int) 11 case network(String) 12 case remote(String) 13 case pushRejected(String) 14 15 public var description: String { 16 switch self { 17 case .malformed(let what): return "invalid git data: \(what)" 18 case .missingObject(let id): return "missing git object: \(id)" 19 case .unauthorized: return "credentials rejected" 20 case .notFound: return "repository not found" 21 case .http(let code): return "HTTP error \(code)" 22 case .network(let what): return "network: \(what)" 23 case .remote(let what): return "server: \(what)" 24 case .pushRejected(let why): return "push rejected: \(why)" 25 } 26 } 27 } 28 29 /// Git object identifier (SHA-1, 20 bytes). 30 public struct ObjectID: Hashable, Sendable, CustomStringConvertible, Codable { 31 public let bytes: [UInt8] 32 33 public init?(bytes: [UInt8]) { 34 guard bytes.count == 20 else { return nil } 35 self.bytes = bytes 36 } 37 38 public init?<S: StringProtocol>(hex: S) { 39 let chars = Array(hex.utf8) 40 guard chars.count == 40 else { return nil } 41 var out = [UInt8]() 42 out.reserveCapacity(20) 43 for i in stride(from: 0, to: 40, by: 2) { 44 guard let hi = Self.nibble(chars[i]), let lo = Self.nibble(chars[i + 1]) else { return nil } 45 out.append(hi << 4 | lo) 46 } 47 self.bytes = out 48 } 49 50 private static func nibble(_ c: UInt8) -> UInt8? { 51 switch c { 52 case 48...57: return c - 48 53 case 97...102: return c - 87 54 case 65...70: return c - 55 55 default: return nil 56 } 57 } 58 59 public var hex: String { 60 let digits = Array("0123456789abcdef".utf8) 61 var out = [UInt8]() 62 out.reserveCapacity(40) 63 for b in bytes { 64 out.append(digits[Int(b >> 4)]) 65 out.append(digits[Int(b & 15)]) 66 } 67 return String(decoding: out, as: UTF8.self) 68 } 69 70 public var description: String { hex } 71 72 public var isZero: Bool { bytes.allSatisfy { $0 == 0 } } 73 public static let zero = ObjectID(bytes: [UInt8](repeating: 0, count: 20))! 74 75 public init(from decoder: Decoder) throws { 76 let text = try decoder.singleValueContainer().decode(String.self) 77 guard let id = ObjectID(hex: text) else { 78 throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "invalid git identifier")) 79 } 80 self = id 81 } 82 83 public func encode(to encoder: Encoder) throws { 84 var container = encoder.singleValueContainer() 85 try container.encode(hex) 86 } 87 } 88 89 public enum ObjectType: UInt8, Sendable { 90 case commit = 1, tree = 2, blob = 3, tag = 4 91 92 public var name: String { 93 switch self { 94 case .commit: return "commit" 95 case .tree: return "tree" 96 case .blob: return "blob" 97 case .tag: return "tag" 98 } 99 } 100 } 101 102 public struct GitObject: Sendable, Equatable { 103 public let type: ObjectType 104 public let data: [UInt8] 105 106 public init(type: ObjectType, data: [UInt8]) { 107 self.type = type 108 self.data = data 109 } 110 111 public var id: ObjectID { 112 var hasher = Insecure.SHA1() 113 hasher.update(data: Array("\(type.name) \(data.count)\u{0}".utf8)) 114 hasher.update(data: data) 115 return ObjectID(bytes: Array(hasher.finalize()))! 116 } 117 } 118 119 func sha1(_ bytes: [UInt8]) -> [UInt8] { 120 Array(Insecure.SHA1.hash(data: bytes)) 121 } 122 123 // MARK: - Trees 124 125 public struct TreeEntry: Sendable, Equatable { 126 public var mode: String 127 public var name: String 128 public var id: ObjectID 129 130 public init(mode: String, name: String, id: ObjectID) { 131 self.mode = mode 132 self.name = name 133 self.id = id 134 } 135 136 public var isTree: Bool { mode == "40000" || mode == "040000" } 137 138 public static func tree(_ name: String, _ id: ObjectID) -> TreeEntry { .init(mode: "40000", name: name, id: id) } 139 public static func blob(_ name: String, _ id: ObjectID) -> TreeEntry { .init(mode: "100644", name: name, id: id) } 140 } 141 142 public enum Tree { 143 public static func parse(_ data: [UInt8]) throws -> [TreeEntry] { 144 var entries = [TreeEntry]() 145 var i = 0 146 while i < data.count { 147 guard let space = data[i...].firstIndex(of: 0x20) else { throw GitError.malformed("tree: mode") } 148 guard let nul = data[space...].firstIndex(of: 0) else { throw GitError.malformed("tree: name") } 149 guard nul + 21 <= data.count else { throw GitError.malformed("tree: identifier") } 150 let mode = String(decoding: data[i..<space], as: UTF8.self) 151 let name = String(decoding: data[(space + 1)..<nul], as: UTF8.self) 152 let id = ObjectID(bytes: Array(data[(nul + 1)..<(nul + 21)]))! 153 entries.append(TreeEntry(mode: mode, name: name, id: id)) 154 i = nul + 21 155 } 156 return entries 157 } 158 159 /// Serializes a tree in the order git requires (directories compare as "name/"). 160 public static func serialize(_ entries: [TreeEntry]) -> [UInt8] { 161 func key(_ e: TreeEntry) -> [UInt8] { Array(e.name.utf8) + (e.isTree ? [0x2f] : []) } 162 let sorted = entries.sorted { key($0).lexicographicallyPrecedes(key($1)) } 163 var out = [UInt8]() 164 for e in sorted { 165 out.append(contentsOf: Array((e.mode == "040000" ? "40000" : e.mode).utf8)) 166 out.append(0x20) 167 out.append(contentsOf: Array(e.name.utf8)) 168 out.append(0) 169 out.append(contentsOf: e.id.bytes) 170 } 171 return out 172 } 173 } 174 175 // MARK: - Commits 176 177 public struct Commit: Sendable, Equatable { 178 public var tree: ObjectID 179 public var parents: [ObjectID] 180 public var author: String 181 public var committer: String 182 public var message: String 183 184 public init(tree: ObjectID, parents: [ObjectID], author: String, committer: String, message: String) { 185 self.tree = tree 186 self.parents = parents 187 self.author = author 188 self.committer = committer 189 self.message = message 190 } 191 192 public static func parse(_ data: [UInt8]) throws -> Commit { 193 let text = String(decoding: data, as: UTF8.self) 194 let parts = text.components(separatedBy: "\n\n") 195 let header = parts.first ?? "" 196 let message = parts.dropFirst().joined(separator: "\n\n") 197 var tree: ObjectID? 198 var parents = [ObjectID]() 199 var author = "", committer = "" 200 for line in header.split(separator: "\n") { 201 if line.hasPrefix("tree ") { 202 tree = ObjectID(hex: line.dropFirst(5)) 203 } else if line.hasPrefix("parent ") { 204 if let p = ObjectID(hex: line.dropFirst(7)) { parents.append(p) } 205 } else if line.hasPrefix("author ") { 206 author = String(line.dropFirst(7)) 207 } else if line.hasPrefix("committer ") { 208 committer = String(line.dropFirst(10)) 209 } 210 } 211 guard let tree else { throw GitError.malformed("commit without a tree") } 212 return Commit(tree: tree, parents: parents, author: author, committer: committer, message: message) 213 } 214 215 public func serialize() -> [UInt8] { 216 var text = "tree \(tree.hex)\n" 217 for p in parents { text += "parent \(p.hex)\n" } 218 text += "author \(author)\ncommitter \(committer)\n\n\(message)" 219 return Array(text.utf8) 220 } 221 222 /// "Name <email> seconds +0000" 223 public static func signature(name: String, email: String, date: Date = Date()) -> String { 224 "\(name) <\(email)> \(Int(date.timeIntervalSince1970)) +0000" 225 } 226 }