75 lines
3.0 KiB
Swift
75 lines
3.0 KiB
Swift
import Foundation
|
|
import HelderServices
|
|
|
|
/// A throwaway git repository in a temp folder, removed on deinit. For integration tests.
|
|
final class TempGitRepo {
|
|
let root: URL
|
|
private let git: URL
|
|
|
|
/// Creates the folder, runs `git init -b main`, and sets a local user so commits work anywhere.
|
|
/// A bare repository serves as a push remote.
|
|
init(bare: Bool = false) throws {
|
|
guard let git = ExecutableLocator.standard.locate("git") else {
|
|
throw ProcessRunnerError.executableNotFound("git")
|
|
}
|
|
self.git = git
|
|
root = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent("helder-test-\(UUID().uuidString)")
|
|
.resolvingSymlinksInPath()
|
|
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
|
|
if bare {
|
|
try run("init", "-q", "--bare", "-b", "main")
|
|
return
|
|
}
|
|
try run("init", "-q", "-b", "main")
|
|
try run("config", "user.name", "Helder Tests")
|
|
try run("config", "user.email", "tests@helder.invalid")
|
|
try run("config", "commit.gpgsign", "false")
|
|
}
|
|
|
|
deinit {
|
|
try? FileManager.default.removeItem(at: root)
|
|
}
|
|
|
|
/// Writes a file relative to the root, creating folders as needed.
|
|
func write(_ path: String, _ contents: String) throws {
|
|
let url = root.appendingPathComponent(path)
|
|
try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
|
|
try Data(contents.utf8).write(to: url)
|
|
}
|
|
|
|
func read(_ path: String) throws -> String {
|
|
try String(contentsOf: root.appendingPathComponent(path), encoding: .utf8)
|
|
}
|
|
|
|
/// Writes the files, stages everything and commits.
|
|
func commit(_ files: [String: String] = [:], message: String = "commit") throws {
|
|
for (path, contents) in files { try write(path, contents) }
|
|
try run("add", "-A")
|
|
try run("commit", "-q", "--allow-empty", "-m", message)
|
|
}
|
|
|
|
/// Runs git synchronously in the repo and returns stdout; throws on a non-zero exit.
|
|
@discardableResult
|
|
func run(_ arguments: String...) throws -> String {
|
|
let process = Process()
|
|
process.executableURL = git
|
|
process.arguments = arguments
|
|
process.currentDirectoryURL = root
|
|
process.standardInput = FileHandle.nullDevice
|
|
let out = Pipe()
|
|
let err = Pipe()
|
|
process.standardOutput = out
|
|
process.standardError = err
|
|
try process.run()
|
|
let data = out.fileHandleForReading.readDataToEndOfFile()
|
|
let errData = err.fileHandleForReading.readDataToEndOfFile()
|
|
process.waitUntilExit()
|
|
guard process.terminationStatus == 0 else {
|
|
throw GitError.commandFailed(arguments: arguments, exitCode: process.terminationStatus,
|
|
stderr: String(decoding: errData, as: UTF8.self))
|
|
}
|
|
return String(decoding: data, as: UTF8.self)
|
|
}
|
|
}
|