adds nice git interface
This commit is contained in:
@@ -71,8 +71,6 @@ public struct HelderConfig: Codable, Sendable, Equatable {
|
||||
|
||||
public struct Git: Codable, Sendable, Equatable {
|
||||
public var confirmDiscard = true
|
||||
public var confirmStage = false
|
||||
public var confirmUnstage = false
|
||||
public var defaultDiffMode = DefaultDiffMode.updated
|
||||
/// Milliseconds between git status polls; 0 disables the poll.
|
||||
public var refreshInterval = 10_000
|
||||
@@ -182,15 +180,13 @@ extension HelderConfig.Editor {
|
||||
|
||||
extension HelderConfig.Git {
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case confirmDiscard, confirmStage, confirmUnstage, defaultDiffMode, refreshInterval
|
||||
case confirmDiscard, defaultDiffMode, refreshInterval
|
||||
}
|
||||
|
||||
public init(from decoder: Decoder) throws {
|
||||
let c = try decoder.container(keyedBy: CodingKeys.self)
|
||||
let d = Self()
|
||||
confirmDiscard = c.value(.confirmDiscard, d.confirmDiscard)
|
||||
confirmStage = c.value(.confirmStage, d.confirmStage)
|
||||
confirmUnstage = c.value(.confirmUnstage, d.confirmUnstage)
|
||||
defaultDiffMode = c.value(.defaultDiffMode, d.defaultDiffMode)
|
||||
refreshInterval = c.value(.refreshInterval, d.refreshInterval)
|
||||
}
|
||||
|
||||
@@ -7,8 +7,10 @@ public enum ContextTarget: Sendable, Equatable {
|
||||
case editor(reference: AgentReference, code: String?, showDiffLine: Int? = nil)
|
||||
case file(path: String)
|
||||
case directory(path: String)
|
||||
/// A git row; the row carries its own half, since one file can have two rows.
|
||||
case gitRow(path: String, staged: Bool)
|
||||
/// A file row in the Git view; a deleted file has nothing to open.
|
||||
case gitRow(path: String, isDeleted: Bool)
|
||||
/// The caret beside the Git view's Commit button.
|
||||
case commitMenu
|
||||
/// The empty space under the tree: the project folder itself.
|
||||
case projectRoot
|
||||
case terminal(TerminalKind, hasSelection: Bool)
|
||||
@@ -17,7 +19,7 @@ public enum ContextTarget: Sendable, Equatable {
|
||||
switch self {
|
||||
case let .editor(reference, _, _): reference.path
|
||||
case let .file(path), let .directory(path), let .gitRow(path, _): path
|
||||
case .projectRoot, .terminal: ""
|
||||
case .projectRoot, .terminal, .commitMenu: ""
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -30,12 +32,13 @@ public enum ContextAction: Sendable, Equatable {
|
||||
case copyFileName(String)
|
||||
case newFile(inDirectory: String)
|
||||
case newFolder(inDirectory: String)
|
||||
case stage(String)
|
||||
case unstage(String)
|
||||
case openDiff(String)
|
||||
/// Opens a file from the Git view, which closes first.
|
||||
case openFile(String)
|
||||
/// Reverts unstaged changes: modified and deleted files come back from the index, new files are removed.
|
||||
case gitDiscard([String])
|
||||
case commit(andPush: Bool)
|
||||
/// Opens the Diff of the open file at this line.
|
||||
case showDiff(String, line: Int)
|
||||
case discard(String)
|
||||
case rename(String, isDirectory: Bool)
|
||||
case revealInFinder(String)
|
||||
case delete(String, isDirectory: Bool)
|
||||
@@ -58,7 +61,15 @@ public enum ContextAction: Sendable, Equatable {
|
||||
/// Destructive items read in amber-deep.
|
||||
public var isDestructive: Bool {
|
||||
switch self {
|
||||
case .discard, .delete: true
|
||||
case .gitDiscard, .delete: true
|
||||
default: false
|
||||
}
|
||||
}
|
||||
|
||||
/// The menu's main item, set in bold.
|
||||
public var isEmphasized: Bool {
|
||||
switch self {
|
||||
case .openFile, .commit(andPush: true): true
|
||||
default: false
|
||||
}
|
||||
}
|
||||
@@ -76,7 +87,7 @@ public enum ContextActions {
|
||||
switch target {
|
||||
case let .file(path), let .gitRow(path, _): path
|
||||
case .projectRoot: projectName + "/"
|
||||
case .editor, .directory, .terminal: ""
|
||||
case .editor, .directory, .terminal, .commitMenu: ""
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,12 +138,16 @@ public enum ContextActions {
|
||||
? [.separator, .action(.waitWhat(kind), label: "Wait what?")] : []
|
||||
return (hasSelection ? [.action(.copyTerminalSelection(kind), label: "Copy")] : [])
|
||||
+ [.action(.pasteIntoTerminal(kind), label: "Paste")] + readAloud + waitWhat
|
||||
case let .gitRow(path, staged):
|
||||
return fileHead(path) + readAloudFile(path) + [
|
||||
.separator,
|
||||
staged ? .action(.unstage(path), label: "Unstage changes") : .action(.stage(path), label: "Stage changes"),
|
||||
.action(.openDiff(path), label: "Open diff"),
|
||||
.action(.discard(path), label: "Discard changes"),
|
||||
case let .gitRow(path, isDeleted):
|
||||
let open: [ContextMenuEntry] = isDeleted ? [] : [.action(.openFile(path), label: "Open in editor"), .separator]
|
||||
return open + [
|
||||
.action(.passOnReference(path, code: nil), label: "Pass on reference"),
|
||||
.action(.copyReference(path), label: "Copy reference"),
|
||||
]
|
||||
case .commitMenu:
|
||||
return [
|
||||
.action(.commit(andPush: false), label: "Commit"),
|
||||
.action(.commit(andPush: true), label: "Commit and push"),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import Foundation
|
||||
|
||||
/// The branches a checkout can pick from: local ones and the ones on "origin".
|
||||
public struct GitBranchList: Sendable, Equatable {
|
||||
/// Sorted local branch names.
|
||||
public var local: [String]
|
||||
/// Sorted "origin/x" names; "origin/HEAD" is left out.
|
||||
public var remote: [String]
|
||||
|
||||
public init(local: [String] = [], remote: [String] = []) {
|
||||
self.local = local
|
||||
self.remote = remote
|
||||
}
|
||||
|
||||
public static let empty = GitBranchList()
|
||||
|
||||
/// True when `remote` ("origin/x") already has a local branch "x".
|
||||
public func isTracked(_ remote: String) -> Bool {
|
||||
local.contains(Self.localName(ofRemote: remote))
|
||||
}
|
||||
|
||||
/// The local name a remote branch checks out as: "origin/feature/a" → "feature/a".
|
||||
public static func localName(ofRemote remote: String) -> String {
|
||||
guard let slash = remote.firstIndex(of: "/") else { return remote }
|
||||
return String(remote[remote.index(after: slash)...])
|
||||
}
|
||||
}
|
||||
|
||||
public enum GitBranchParsing {
|
||||
public static let arguments = ["for-each-ref", "--format=%(refname)", "refs/heads", "refs/remotes/origin"]
|
||||
|
||||
/// Reads one full ref name per line, as `arguments` prints them.
|
||||
public static func parse(_ raw: String) -> GitBranchList {
|
||||
var list = GitBranchList()
|
||||
for line in raw.split(whereSeparator: \.isNewline) {
|
||||
let ref = line.trimmingCharacters(in: .whitespaces)
|
||||
if ref.hasPrefix("refs/heads/") {
|
||||
list.local.append(String(ref.dropFirst("refs/heads/".count)))
|
||||
} else if ref.hasPrefix("refs/remotes/origin/") {
|
||||
let name = String(ref.dropFirst("refs/remotes/".count))
|
||||
if name != "origin/HEAD" { list.remote.append(name) }
|
||||
}
|
||||
}
|
||||
list.local.sort()
|
||||
list.remote.sort()
|
||||
return list
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
import Foundation
|
||||
|
||||
/// How a line in the git console is painted.
|
||||
public enum GitLineKind: String, Sendable, Equatable {
|
||||
case command
|
||||
case output
|
||||
case error
|
||||
case hint
|
||||
case staged
|
||||
case unstaged
|
||||
case success
|
||||
}
|
||||
|
||||
public struct GitConsoleLine: Sendable, Equatable {
|
||||
public var text: String
|
||||
public var kind: GitLineKind
|
||||
|
||||
public init(text: String, kind: GitLineKind) {
|
||||
self.text = text
|
||||
self.kind = kind
|
||||
}
|
||||
}
|
||||
|
||||
public enum GitConsoleText {
|
||||
/// The echo of a run, such as `$ git commit -m "fix the bar"`.
|
||||
public static func commandLine(_ arguments: [String]) -> String {
|
||||
(["$ git"] + arguments.map(quoted)).joined(separator: " ")
|
||||
}
|
||||
|
||||
private static func quoted(_ argument: String) -> String {
|
||||
let needsQuotes = argument.isEmpty || argument.contains { $0.isWhitespace || $0 == "\"" || $0 == "'" }
|
||||
guard needsQuotes else { return argument }
|
||||
return "\"" + argument.replacingOccurrences(of: "\"", with: "\\\"") + "\""
|
||||
}
|
||||
|
||||
/// Splits what the user typed into git arguments; a leading `git` is dropped and nil means nothing is left.
|
||||
///
|
||||
/// Quoting follows the shell: '…' is literal, "…" honours `\"` and `\\`, and an unclosed quote ends at the end.
|
||||
public static func parseInput(_ input: String) -> [String]? {
|
||||
var arguments: [String] = []
|
||||
var current = ""
|
||||
var hasToken = false
|
||||
var quote: Character?
|
||||
var escaping = false
|
||||
for char in input {
|
||||
if escaping {
|
||||
if quote == "\"" && char != "\"" && char != "\\" { current.append("\\") }
|
||||
current.append(char)
|
||||
escaping = false
|
||||
continue
|
||||
}
|
||||
switch (quote, char) {
|
||||
case ("'", "'"), ("\"", "\""):
|
||||
quote = nil
|
||||
case ("'", _):
|
||||
current.append(char)
|
||||
case (_, "\\"):
|
||||
escaping = true
|
||||
hasToken = true
|
||||
case (nil, "'"), (nil, "\""):
|
||||
quote = char
|
||||
hasToken = true
|
||||
case (nil, _) where char.isWhitespace:
|
||||
if hasToken { arguments.append(current) }
|
||||
current = ""
|
||||
hasToken = false
|
||||
default:
|
||||
current.append(char)
|
||||
hasToken = true
|
||||
}
|
||||
}
|
||||
if escaping { current.append("\\") }
|
||||
if hasToken { arguments.append(current) }
|
||||
if arguments.first == "git" { arguments.removeFirst() }
|
||||
return arguments.isEmpty ? nil : arguments
|
||||
}
|
||||
|
||||
/// The branch's place against its upstream, such as `1 ahead · 2 behind origin`.
|
||||
public static func syncLabel(ahead: Int, behind: Int, upstream: String?) -> String {
|
||||
guard let upstream else { return "no upstream" }
|
||||
let remote = upstream.split(separator: "/", maxSplits: 1).first.map(String.init) ?? upstream
|
||||
switch (ahead > 0, behind > 0) {
|
||||
case (true, true): return "\(ahead) ahead · \(behind) behind \(remote)"
|
||||
case (false, true): return "\(behind) behind \(remote)"
|
||||
case (true, false): return "\(ahead) ahead of \(remote)"
|
||||
case (false, false): return "in sync with \(remote)"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Paints the output lines of one git command. Keep one per run: `status` sections carry over between lines.
|
||||
///
|
||||
/// Git writes progress to stderr, so a stderr line alone is not an error.
|
||||
public struct GitOutputClassifier: Sendable {
|
||||
private enum StatusSection {
|
||||
case staged
|
||||
case unstaged
|
||||
case other
|
||||
}
|
||||
|
||||
private let subcommand: String?
|
||||
private var section = StatusSection.other
|
||||
|
||||
public init(arguments: [String]) {
|
||||
subcommand = Self.subcommand(of: arguments)
|
||||
}
|
||||
|
||||
public mutating func classify(_ line: String, isError: Bool) -> GitLineKind {
|
||||
let trimmed = line.drop { $0 == " " || $0 == "\t" }
|
||||
if trimmed.hasPrefix("hint:") { return .hint }
|
||||
if Self.errorPrefixes.contains(where: { trimmed.hasPrefix($0) }) { return .error }
|
||||
switch subcommand {
|
||||
case "push":
|
||||
if Self.isRefUpdate(trimmed) { return .success }
|
||||
case "status":
|
||||
if let next = Self.sections[String(trimmed)] {
|
||||
section = next
|
||||
return .output
|
||||
}
|
||||
if line.hasPrefix("\t") {
|
||||
switch section {
|
||||
case .staged: return .staged
|
||||
case .unstaged: return .unstaged
|
||||
case .other: break
|
||||
}
|
||||
}
|
||||
default:
|
||||
break
|
||||
}
|
||||
return .output
|
||||
}
|
||||
|
||||
private static let errorPrefixes = [
|
||||
"error:", "fatal:", "! [rejected]", "! [remote rejected]", "Aborting", "Please commit your changes",
|
||||
]
|
||||
|
||||
/// `a1b2c3d..e4f5a6b main -> main`, a forced `+ a...b`, or `* [new branch] x -> x`.
|
||||
private static func isRefUpdate(_ line: Substring) -> Bool {
|
||||
line.contains(" -> ")
|
||||
&& line.wholeMatch(of: /(?:\+\s*)?(?:[0-9a-f]+\.\.\.?[0-9a-f]+|\*\s+\[new [a-z ]+\])\s+.+ -> .+/) != nil
|
||||
}
|
||||
|
||||
private static let sections: [String: StatusSection] = [
|
||||
"Changes to be committed:": .staged,
|
||||
"Changes not staged for commit:": .unstaged,
|
||||
"Untracked files:": .unstaged,
|
||||
"Unmerged paths:": .other,
|
||||
]
|
||||
|
||||
/// The first argument that is not an option; `-c` and `-C` take a value.
|
||||
private static func subcommand(of arguments: [String]) -> String? {
|
||||
var skipNext = false
|
||||
for argument in arguments {
|
||||
if skipNext {
|
||||
skipNext = false
|
||||
} else if argument == "-c" || argument == "-C" {
|
||||
skipNext = true
|
||||
} else if !argument.hasPrefix("-") {
|
||||
return argument
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,8 @@ public enum GitDerivation {
|
||||
/// so a file staged as modified but deleted on disk reads as deleted.
|
||||
public static func derive(_ snapshot: GitSnapshot?) -> GitWorkingState {
|
||||
guard let snapshot else { return .empty }
|
||||
var state = GitWorkingState(branch: snapshot.branch, ahead: snapshot.ahead, canPush: snapshot.canPush, isRepository: true)
|
||||
var state = GitWorkingState(branch: snapshot.branch, ahead: snapshot.ahead, canPush: snapshot.canPush,
|
||||
behind: snapshot.behind, upstream: snapshot.upstream, isRepository: true)
|
||||
var wholeFile: [String: (head: String, disk: String, status: GitStatus, rows: Int, rowID: String)] = [:]
|
||||
var tooBig = Set<String>()
|
||||
for change in snapshot.changes {
|
||||
@@ -39,55 +40,9 @@ public enum GitDerivation {
|
||||
}
|
||||
}
|
||||
|
||||
/// Rows of one folder in the Source Control list.
|
||||
public struct ChangeGroup: Sendable, Equatable {
|
||||
/// Folder path; "" is the project root.
|
||||
public var dir: String
|
||||
public var rows: [Change]
|
||||
|
||||
public init(dir: String, rows: [Change]) {
|
||||
self.dir = dir
|
||||
self.rows = rows
|
||||
}
|
||||
}
|
||||
|
||||
public enum SourceControlText {
|
||||
/// Groups rows by folder in order of first appearance; keyboard navigation walks this same order.
|
||||
public static func groupByDir(_ list: [Change]) -> [ChangeGroup] {
|
||||
var groups: [ChangeGroup] = []
|
||||
var indexByDir: [String: Int] = [:]
|
||||
for change in list {
|
||||
let dir = PathUtils.dirname(change.path)
|
||||
if let index = indexByDir[dir] {
|
||||
groups[index].rows.append(change)
|
||||
} else {
|
||||
indexByDir[dir] = groups.count
|
||||
groups.append(ChangeGroup(dir: dir, rows: [change]))
|
||||
}
|
||||
}
|
||||
return groups
|
||||
}
|
||||
|
||||
/// The row order of the list: staged groups first, then unstaged, each folder by folder.
|
||||
public static func navigationOrder(_ changes: [Change]) -> [Change] {
|
||||
let staged = groupByDir(changes.filter(\.staged)).flatMap(\.rows)
|
||||
let unstaged = groupByDir(changes.filter { !$0.staged }).flatMap(\.rows)
|
||||
return staged + unstaged
|
||||
}
|
||||
|
||||
/// Dictation tools capitalise and add line breaks; a commit subject is one lowercase line.
|
||||
public static func normalizeCommitMessage(_ value: String) -> String {
|
||||
value.lowercased().replacingOccurrences(of: "[ \\t]*[\\r\\n]+[ \\t]*", with: " ", options: .regularExpression)
|
||||
}
|
||||
|
||||
public static func pushTooltip(canPush: Bool, ahead: Int) -> String {
|
||||
if !canPush { return "Nothing to push (⌘P)" }
|
||||
if ahead > 0 { return "Push \(ahead) commit\(ahead > 1 ? "s" : "") to remote (⌘P)" }
|
||||
return "Push the branch to remote (⌘P)"
|
||||
}
|
||||
|
||||
/// Git rows under `tests/` or `cypress/` render dimmed.
|
||||
public static func isTestFile(_ path: String) -> Bool {
|
||||
path.hasPrefix("tests/") || path.hasPrefix("cypress/")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,12 +41,18 @@ public struct GitSnapshot: Sendable, Equatable {
|
||||
public var ahead: Int
|
||||
/// True when a push would send something, including a branch without an upstream.
|
||||
public var canPush: Bool
|
||||
/// Commits the remote has that the branch does not; 0 when unknown.
|
||||
public var behind: Int
|
||||
/// The tracked branch, such as "origin/main"; nil without one.
|
||||
public var upstream: String?
|
||||
public var changes: [GitFileChange]
|
||||
|
||||
public init(branch: String, ahead: Int, canPush: Bool, changes: [GitFileChange]) {
|
||||
public init(branch: String, ahead: Int, canPush: Bool, behind: Int = 0, upstream: String? = nil, changes: [GitFileChange]) {
|
||||
self.branch = branch
|
||||
self.ahead = ahead
|
||||
self.canPush = canPush
|
||||
self.behind = behind
|
||||
self.upstream = upstream
|
||||
self.changes = changes
|
||||
}
|
||||
}
|
||||
@@ -86,6 +92,10 @@ public struct GitWorkingState: Sendable, Equatable {
|
||||
public var branch: String
|
||||
public var ahead: Int
|
||||
public var canPush: Bool
|
||||
/// Commits the remote has that the branch does not; 0 when unknown.
|
||||
public var behind: Int
|
||||
/// The tracked branch, such as "origin/main"; nil without one.
|
||||
public var upstream: String?
|
||||
public var changes: [Change]
|
||||
/// Per path: HEAD vs disk. Drives the Actual view.
|
||||
public var fileDiffs: [String: Diff]
|
||||
@@ -97,13 +107,16 @@ public struct GitWorkingState: Sendable, Equatable {
|
||||
public var isRepository: Bool
|
||||
|
||||
public init(
|
||||
branch: String = "—", ahead: Int = 0, canPush: Bool = false, changes: [Change] = [],
|
||||
branch: String = "—", ahead: Int = 0, canPush: Bool = false, behind: Int = 0, upstream: String? = nil,
|
||||
changes: [Change] = [],
|
||||
fileDiffs: [String: Diff] = [:], rowDiffs: [String: Diff] = [:],
|
||||
stagedPaths: Set<String> = [], isRepository: Bool = false
|
||||
) {
|
||||
self.branch = branch
|
||||
self.ahead = ahead
|
||||
self.canPush = canPush
|
||||
self.behind = behind
|
||||
self.upstream = upstream
|
||||
self.changes = changes
|
||||
self.fileDiffs = fileDiffs
|
||||
self.rowDiffs = rowDiffs
|
||||
@@ -127,14 +140,3 @@ public struct GitWorkingState: Sendable, Equatable {
|
||||
return changes.filter { !$0.staged && seen.insert($0.path).inserted }.map(\.path)
|
||||
}
|
||||
}
|
||||
|
||||
/// The outcome of a push, shown in a toast.
|
||||
public struct PushResult: Sendable, Equatable {
|
||||
public var ok: Bool
|
||||
public var message: String
|
||||
|
||||
public init(ok: Bool, message: String) {
|
||||
self.ok = ok
|
||||
self.message = message
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
import Foundation
|
||||
|
||||
/// A group in the Git view's change list, in the order the list shows them.
|
||||
public enum GitSectionKind: String, CaseIterable, Sendable {
|
||||
case staged
|
||||
case changed
|
||||
case untracked
|
||||
case deleted
|
||||
}
|
||||
|
||||
public struct GitSection: Sendable, Equatable, Identifiable {
|
||||
public var kind: GitSectionKind
|
||||
public var rows: [Change]
|
||||
|
||||
public init(kind: GitSectionKind, rows: [Change]) {
|
||||
self.kind = kind
|
||||
self.rows = rows
|
||||
}
|
||||
|
||||
public var id: String { kind.rawValue }
|
||||
}
|
||||
|
||||
public enum GitSections {
|
||||
/// Sorts rows into their sections; only non-empty sections come back and rows keep their order.
|
||||
///
|
||||
/// Every staged row is staged, whatever its status; an unstaged rename or conflict counts as changed.
|
||||
public static func build(_ changes: [Change]) -> [GitSection] {
|
||||
var byKind: [GitSectionKind: [Change]] = [:]
|
||||
for change in changes {
|
||||
byKind[kind(of: change), default: []].append(change)
|
||||
}
|
||||
return GitSectionKind.allCases.compactMap { kind in
|
||||
byKind[kind].map { GitSection(kind: kind, rows: $0) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Distinct paths of the rows, in order.
|
||||
public static func uniquePaths(_ rows: [Change]) -> [String] {
|
||||
var seen = Set<String>()
|
||||
return rows.compactMap { seen.insert($0.path).inserted ? $0.path : nil }
|
||||
}
|
||||
|
||||
private static func kind(of change: Change) -> GitSectionKind {
|
||||
if change.staged { return .staged }
|
||||
switch change.status {
|
||||
case .added: return .untracked
|
||||
case .deleted: return .deleted
|
||||
case .modified, .renamed, .unmerged: return .changed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One side of an inline diff line.
|
||||
public struct InlineDiffCell: Sendable, Equatable {
|
||||
public var number: Int
|
||||
public var text: String
|
||||
public var mark: LineMark?
|
||||
/// Character offsets of the part that differs from the other side; nil when the whole line counts.
|
||||
public var highlight: Range<Int>?
|
||||
|
||||
public init(number: Int, text: String, mark: LineMark? = nil, highlight: Range<Int>? = nil) {
|
||||
self.number = number
|
||||
self.text = text
|
||||
self.mark = mark
|
||||
self.highlight = highlight
|
||||
}
|
||||
}
|
||||
|
||||
public enum InlineDiffRow: Sendable, Equatable {
|
||||
case line(left: InlineDiffCell?, right: InlineDiffCell?)
|
||||
/// A run of unchanged rows folded away.
|
||||
case gap(Int)
|
||||
}
|
||||
|
||||
public enum InlineDiff {
|
||||
/// The rows of `diff.split` with `context` unchanged rows kept around each change; other unchanged runs fold into a gap.
|
||||
public static func rows(from diff: Diff, context: Int = 3) -> [InlineDiffRow] {
|
||||
let split = diff.split
|
||||
let changed = split.map { $0.left?.mark != nil || $0.right?.mark != nil }
|
||||
guard changed.contains(true) else { return [] }
|
||||
var keep = [Bool](repeating: false, count: split.count)
|
||||
for (index, isChanged) in changed.enumerated() where isChanged {
|
||||
let low = max(0, index - context), high = min(split.count - 1, index + context)
|
||||
for kept in low...high { keep[kept] = true }
|
||||
}
|
||||
var rows: [InlineDiffRow] = []
|
||||
var folded = 0
|
||||
for (index, row) in split.enumerated() {
|
||||
guard keep[index] else {
|
||||
folded += 1
|
||||
continue
|
||||
}
|
||||
if folded > 0 { rows.append(.gap(folded)) }
|
||||
folded = 0
|
||||
rows.append(line(row))
|
||||
}
|
||||
if folded > 0 { rows.append(.gap(folded)) }
|
||||
return rows
|
||||
}
|
||||
|
||||
private static func line(_ row: SplitRow) -> InlineDiffRow {
|
||||
var left = row.left.map { InlineDiffCell(number: $0.no, text: $0.text, mark: $0.mark) }
|
||||
var right = row.right.map { InlineDiffCell(number: $0.no, text: $0.text, mark: $0.mark) }
|
||||
if let old = left, let new = right, old.mark == .removed, new.mark == .added {
|
||||
let ranges = highlights(old.text, new.text)
|
||||
left?.highlight = ranges.left
|
||||
right?.highlight = ranges.right
|
||||
}
|
||||
return .line(left: left, right: right)
|
||||
}
|
||||
|
||||
/// The middle between the common prefix and the common suffix, per side; nil when nothing is shared or a middle is empty.
|
||||
static func highlights(_ old: String, _ new: String) -> (left: Range<Int>?, right: Range<Int>?) {
|
||||
let a = Array(old), b = Array(new)
|
||||
var prefix = 0
|
||||
while prefix < a.count && prefix < b.count && a[prefix] == b[prefix] { prefix += 1 }
|
||||
var suffix = 0
|
||||
while suffix < a.count - prefix && suffix < b.count - prefix && a[a.count - 1 - suffix] == b[b.count - 1 - suffix] {
|
||||
suffix += 1
|
||||
}
|
||||
guard prefix > 0 || suffix > 0 else { return (nil, nil) }
|
||||
let left = prefix..<(a.count - suffix)
|
||||
let right = prefix..<(b.count - suffix)
|
||||
return (left.isEmpty ? nil : left, right.isEmpty ? nil : right)
|
||||
}
|
||||
}
|
||||
@@ -25,12 +25,16 @@ public struct ParsedStatus: Sendable, Equatable {
|
||||
public var branch: String
|
||||
public var ahead: Int
|
||||
public var canPush: Bool
|
||||
public var behind: Int
|
||||
public var upstream: String?
|
||||
public var entries: [StatusEntry]
|
||||
|
||||
public init(branch: String, ahead: Int, canPush: Bool, entries: [StatusEntry]) {
|
||||
public init(branch: String, ahead: Int, canPush: Bool, behind: Int = 0, upstream: String? = nil, entries: [StatusEntry]) {
|
||||
self.branch = branch
|
||||
self.ahead = ahead
|
||||
self.canPush = canPush
|
||||
self.behind = behind
|
||||
self.upstream = upstream
|
||||
self.entries = entries
|
||||
}
|
||||
}
|
||||
@@ -69,6 +73,8 @@ public enum Porcelain {
|
||||
let header = String(part.dropFirst(3))
|
||||
result.branch = parseBranch(header: header)
|
||||
(result.ahead, result.canPush) = parseAhead(header: header)
|
||||
result.behind = parseBehind(header: header)
|
||||
result.upstream = parseUpstream(header: header)
|
||||
continue
|
||||
}
|
||||
let chars = Array(part.prefix(2))
|
||||
@@ -101,6 +107,20 @@ public enum Porcelain {
|
||||
return (0, !header.contains("..."))
|
||||
}
|
||||
|
||||
/// The `[behind N]` count of a header; 0 without one.
|
||||
public static func parseBehind(header: String) -> Int {
|
||||
guard let match = header.firstMatch(of: /\[[^\]]*\bbehind (\d+)/) else { return 0 }
|
||||
return Int(match.1) ?? 0
|
||||
}
|
||||
|
||||
/// The tracked branch after `...` in a header (`main...origin/main [ahead 1]` → "origin/main"); nil without one.
|
||||
public static func parseUpstream(header: String) -> String? {
|
||||
if header.hasPrefix("HEAD ") { return nil }
|
||||
guard let range = header.range(of: "...") else { return nil }
|
||||
let name = header[range.upperBound...].split(separator: " ").first.map(String.init) ?? ""
|
||||
return name.isEmpty ? nil : name
|
||||
}
|
||||
|
||||
/// Maps one porcelain column letter to the letter the row shows.
|
||||
public static func status(for code: Character) -> GitStatus {
|
||||
switch code {
|
||||
@@ -125,20 +145,6 @@ public enum Porcelain {
|
||||
return rows.isEmpty ? [GitRowSpec(status: status(for: index), staged: true)] : rows
|
||||
}
|
||||
|
||||
/// The toast line for a push: git reports on stderr, so the summary is pulled from there.
|
||||
public static func pushSummary(exitCode: Int32, stdout: String, stderr: String) -> PushResult {
|
||||
let source = stderr.isEmpty ? stdout : stderr
|
||||
var lines = source.split(whereSeparator: \.isNewline)
|
||||
.map { $0.trimmingCharacters(in: .whitespaces) }
|
||||
.filter { !$0.isEmpty }
|
||||
if exitCode != 0 { return PushResult(ok: false, message: lines.popLast() ?? "push failed") }
|
||||
let summary = lines.first { line in
|
||||
line.contains("->") || line.localizedCaseInsensitiveContains("up-to-date")
|
||||
|| line.localizedCaseInsensitiveContains("new branch")
|
||||
}
|
||||
return PushResult(ok: true, message: summary ?? lines.popLast() ?? "Pushed")
|
||||
}
|
||||
|
||||
/// True when a failed `git push` only needs `-u origin <branch>`.
|
||||
public static func needsUpstream(stderr: String) -> Bool {
|
||||
stderr.range(of: "no upstream branch|set-upstream", options: [.regularExpression, .caseInsensitive]) != nil
|
||||
|
||||
@@ -7,14 +7,12 @@ public enum FocusZone: String, Sendable, Equatable {
|
||||
case terminal
|
||||
}
|
||||
|
||||
/// Pixel widths of the three fixed columns; the editor takes the remainder.
|
||||
/// Pixel widths of the two fixed columns; the editor takes the remainder.
|
||||
public struct ColumnWidths: Sendable, Equatable {
|
||||
public var sourceControl: Double
|
||||
public var explorer: Double
|
||||
public var agent: Double
|
||||
|
||||
public init(sourceControl: Double, explorer: Double, agent: Double) {
|
||||
self.sourceControl = sourceControl
|
||||
public init(explorer: Double, agent: Double) {
|
||||
self.explorer = explorer
|
||||
self.agent = agent
|
||||
}
|
||||
@@ -25,18 +23,17 @@ public enum ColumnLayout {
|
||||
public static let roomyWidth = 1600.0
|
||||
public static let minEditorWidth = 280.0
|
||||
public static let splitterWidth = 1.0
|
||||
public static let sourceControlRange = 160.0...460.0
|
||||
public static let explorerRange = 160.0...520.0
|
||||
|
||||
/// Fluid widths for a window. Roomy: 13.4% · 16.4% · flex · 27.3% (the design's
|
||||
/// 236 · 288 · flex · 480 on a 1760 frame). Tight: 15% · 15%, and the agent column
|
||||
/// takes 30%, or 20% with the editor focused, or 50% with a terminal focused.
|
||||
/// Fluid widths for a window. Roomy: 16.4% · flex · 27.3% (the design's 288 · flex · 480
|
||||
/// on a 1760 frame). Tight: 15%, and the agent column takes 30%, or 20% with the editor
|
||||
/// focused, or 50% with a terminal focused.
|
||||
public static func fluid(windowWidth w: Double, focus: FocusZone) -> ColumnWidths {
|
||||
if w >= roomyWidth {
|
||||
return ColumnWidths(sourceControl: (w * 0.134).rounded(), explorer: (w * 0.164).rounded(), agent: (w * 0.273).rounded())
|
||||
return ColumnWidths(explorer: (w * 0.164).rounded(), agent: (w * 0.273).rounded())
|
||||
}
|
||||
let agentShare = focus == .terminal ? 0.5 : focus == .editor ? 0.2 : 0.3
|
||||
return ColumnWidths(sourceControl: (w * 0.15).rounded(), explorer: (w * 0.15).rounded(), agent: (w * agentShare).rounded())
|
||||
return ColumnWidths(explorer: (w * 0.15).rounded(), agent: (w * agentShare).rounded())
|
||||
}
|
||||
|
||||
/// Scales the fixed columns down so the flex column keeps `minEditorWidth`; unchanged when they fit.
|
||||
@@ -45,12 +42,10 @@ public enum ColumnLayout {
|
||||
let agentIsFixed = visible.agent && visible.editor
|
||||
let flexMinimum = visible.editor || visible.agent ? minEditorWidth : 0
|
||||
let budget = windowWidth - Double(visible.splitterCount) * splitterWidth - flexMinimum
|
||||
let total = (visible.sourceControl ? widths.sourceControl : 0) + (visible.explorer ? widths.explorer : 0)
|
||||
+ (agentIsFixed ? widths.agent : 0)
|
||||
let total = (visible.explorer ? widths.explorer : 0) + (agentIsFixed ? widths.agent : 0)
|
||||
guard total > budget, total > 0 else { return widths }
|
||||
let k = max(0, budget) / total
|
||||
return ColumnWidths(
|
||||
sourceControl: visible.sourceControl ? (widths.sourceControl * k).rounded(.down) : widths.sourceControl,
|
||||
explorer: visible.explorer ? (widths.explorer * k).rounded(.down) : widths.explorer,
|
||||
agent: agentIsFixed ? (widths.agent * k).rounded(.down) : widths.agent
|
||||
)
|
||||
@@ -58,20 +53,18 @@ public enum ColumnLayout {
|
||||
|
||||
/// The widest the agent column may be dragged: until the editor would drop below its minimum.
|
||||
public static func maxAgentWidth(windowWidth: Double, widths: ColumnWidths, visible: ColumnVisibility) -> Double {
|
||||
let others = (visible.sourceControl ? widths.sourceControl : 0) + (visible.explorer ? widths.explorer : 0)
|
||||
let others = visible.explorer ? widths.explorer : 0
|
||||
return max(minEditorWidth, windowWidth - Double(visible.splitterCount) * splitterWidth - others - minEditorWidth)
|
||||
}
|
||||
}
|
||||
|
||||
/// Which of the four columns are shown. A hidden column keeps its width and its contents.
|
||||
/// Which of the three columns are shown. A hidden column keeps its width and its contents.
|
||||
public struct ColumnVisibility: Sendable, Equatable {
|
||||
public var sourceControl: Bool
|
||||
public var explorer: Bool
|
||||
public var editor: Bool
|
||||
public var agent: Bool
|
||||
|
||||
public init(sourceControl: Bool = true, explorer: Bool = true, editor: Bool = true, agent: Bool = true) {
|
||||
self.sourceControl = sourceControl
|
||||
public init(explorer: Bool = true, editor: Bool = true, agent: Bool = true) {
|
||||
self.explorer = explorer
|
||||
self.editor = editor
|
||||
self.agent = agent
|
||||
@@ -81,6 +74,6 @@ public struct ColumnVisibility: Sendable, Equatable {
|
||||
|
||||
/// One splitter between each pair of neighbouring visible columns.
|
||||
public var splitterCount: Int {
|
||||
max(0, [sourceControl, explorer, editor, agent].filter { $0 }.count - 1)
|
||||
max(0, [explorer, editor, agent].filter { $0 }.count - 1)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user