adds nice git interface
This commit is contained in:
@@ -82,7 +82,7 @@ public final class EditorStore {
|
||||
/// Closes the overlay only while it is the Diff.
|
||||
@ObservationIgnored public var dismissDiffOverlay: (() -> Void)?
|
||||
@ObservationIgnored public var showToast: ((String, String?) -> Void)?
|
||||
/// After a write: the git column should re-read.
|
||||
/// After a write: git should re-read.
|
||||
@ObservationIgnored public var fileSaved: ((String) -> Void)?
|
||||
/// Asked before a dirty file closes; without it a dirty file stays open.
|
||||
@ObservationIgnored public var confirmUnsavedClose: ((String) -> UnsavedCloseChoice)?
|
||||
@@ -110,7 +110,7 @@ public final class EditorStore {
|
||||
self.init(root: root, files: files, gitState: { sourceControl.state }, session: session, recentFiles: recentFiles)
|
||||
}
|
||||
|
||||
/// `gitState` is read, never written: the editor only follows the git column.
|
||||
/// `gitState` is read, never written: the editor only follows git.
|
||||
public init(root: String, files: FileServicing, gitState: @escaping @MainActor () -> GitWorkingState,
|
||||
session: SessionStoring, recentFiles: RecentFilesStoring) {
|
||||
self.root = root
|
||||
|
||||
@@ -5,7 +5,6 @@ import Observation
|
||||
|
||||
/// Which column has keyboard focus: drives the active-panel tint and arrow-key navigation.
|
||||
public enum Panel: String, Sendable, CaseIterable {
|
||||
case sourceControl
|
||||
case explorer
|
||||
case editor
|
||||
case terminal
|
||||
@@ -13,42 +12,36 @@ public enum Panel: String, Sendable, CaseIterable {
|
||||
|
||||
/// The column layout one project remembers between launches.
|
||||
public struct ColumnLayoutSnapshot: Codable, Sendable, Equatable {
|
||||
public var sourceControlWidth: Double
|
||||
public var explorerWidth: Double
|
||||
public var agentWidth: Double
|
||||
public var fluid: Bool
|
||||
public var gitVisible: Bool
|
||||
public var explorerVisible: Bool
|
||||
public var fileVisible: Bool
|
||||
public var claudeVisible: Bool
|
||||
|
||||
public init(sourceControlWidth: Double, explorerWidth: Double, agentWidth: Double, fluid: Bool,
|
||||
visibility: ColumnVisibility = .all) {
|
||||
self.sourceControlWidth = sourceControlWidth
|
||||
public init(explorerWidth: Double, agentWidth: Double, fluid: Bool, visibility: ColumnVisibility = .all) {
|
||||
self.explorerWidth = explorerWidth
|
||||
self.agentWidth = agentWidth
|
||||
self.fluid = fluid
|
||||
gitVisible = visibility.sourceControl
|
||||
explorerVisible = visibility.explorer
|
||||
fileVisible = visibility.editor
|
||||
claudeVisible = visibility.agent
|
||||
}
|
||||
|
||||
/// Older snapshots only know `gitVisible`; a missing flag means shown.
|
||||
/// A missing visibility flag means shown. Snapshots from before the Git view also hold
|
||||
/// `sourceControlWidth` and `gitVisible`; they are ignored.
|
||||
public init(from decoder: Decoder) throws {
|
||||
let c = try decoder.container(keyedBy: CodingKeys.self)
|
||||
sourceControlWidth = try c.decode(Double.self, forKey: .sourceControlWidth)
|
||||
explorerWidth = try c.decode(Double.self, forKey: .explorerWidth)
|
||||
agentWidth = try c.decode(Double.self, forKey: .agentWidth)
|
||||
fluid = try c.decode(Bool.self, forKey: .fluid)
|
||||
gitVisible = try c.decodeIfPresent(Bool.self, forKey: .gitVisible) ?? true
|
||||
explorerVisible = try c.decodeIfPresent(Bool.self, forKey: .explorerVisible) ?? true
|
||||
fileVisible = try c.decodeIfPresent(Bool.self, forKey: .fileVisible) ?? true
|
||||
claudeVisible = try c.decodeIfPresent(Bool.self, forKey: .claudeVisible) ?? true
|
||||
}
|
||||
|
||||
public var visibility: ColumnVisibility {
|
||||
ColumnVisibility(sourceControl: gitVisible, explorer: explorerVisible, editor: fileVisible, agent: claudeVisible)
|
||||
ColumnVisibility(explorer: explorerVisible, editor: fileVisible, agent: claudeVisible)
|
||||
}
|
||||
|
||||
public static func key(root: String) -> String { "helder.layout:" + root }
|
||||
@@ -91,12 +84,14 @@ public struct UserDefaultsLayoutStore: LayoutPersisting, @unchecked Sendable {
|
||||
@Observable
|
||||
@MainActor
|
||||
public final class LayoutStore {
|
||||
public private(set) var widths = ColumnWidths(sourceControl: 236, explorer: 288, agent: 480)
|
||||
public private(set) var widths = ColumnWidths(explorer: 288, agent: 480)
|
||||
/// The agent pane's share of the right column; persisted across launches.
|
||||
public private(set) var agentFraction: Double
|
||||
public private(set) var windowWidth: Double = 1680
|
||||
/// The title bar's pane toggles; ⌘G flips Source Control.
|
||||
/// The title bar's pane toggles; ⌘1–⌘3 flip them.
|
||||
public private(set) var visibility = ColumnVisibility.all
|
||||
/// ⌘G: the full-screen Git view over the whole window. Not persisted; the columns stay mounted under it.
|
||||
public private(set) var isGitViewOpen = false
|
||||
/// ⌘L: columns re-fit on resize and focus. A manual splitter drag turns this off.
|
||||
public private(set) var fluid = true
|
||||
/// ⌘.: dotfiles show in the tree and the search.
|
||||
@@ -145,25 +140,23 @@ public final class LayoutStore {
|
||||
self.root = root
|
||||
activePanel = nil
|
||||
focusZone = .neutral
|
||||
isGitViewOpen = false
|
||||
let saved = persistence?.load(root: root)
|
||||
visibility = saved?.visibility ?? .all
|
||||
fluid = saved?.fluid ?? true
|
||||
if let saved, !saved.fluid {
|
||||
widths = ColumnWidths(sourceControl: clamp(saved.sourceControlWidth, ColumnLayout.sourceControlRange),
|
||||
explorer: clamp(saved.explorerWidth, ColumnLayout.explorerRange),
|
||||
widths = ColumnWidths(explorer: clamp(saved.explorerWidth, ColumnLayout.explorerRange),
|
||||
agent: max(saved.agentWidth, ColumnLayout.minEditorWidth))
|
||||
}
|
||||
refit()
|
||||
}
|
||||
|
||||
public var snapshot: ColumnLayoutSnapshot {
|
||||
ColumnLayoutSnapshot(sourceControlWidth: widths.sourceControl, explorerWidth: widths.explorer,
|
||||
agentWidth: widths.agent, fluid: fluid, visibility: visibility)
|
||||
ColumnLayoutSnapshot(explorerWidth: widths.explorer, agentWidth: widths.agent, fluid: fluid, visibility: visibility)
|
||||
}
|
||||
|
||||
public func isVisible(_ panel: Panel) -> Bool {
|
||||
switch panel {
|
||||
case .sourceControl: visibility.sourceControl
|
||||
case .explorer: visibility.explorer
|
||||
case .editor: visibility.editor
|
||||
case .terminal: visibility.agent
|
||||
@@ -178,7 +171,6 @@ public final class LayoutStore {
|
||||
public func setVisible(_ panel: Panel, _ visible: Bool) {
|
||||
guard isVisible(panel) != visible else { return }
|
||||
switch panel {
|
||||
case .sourceControl: visibility.sourceControl = visible
|
||||
case .explorer: visibility.explorer = visible
|
||||
case .editor: visibility.editor = visible
|
||||
case .terminal: visibility.agent = visible
|
||||
@@ -188,6 +180,18 @@ public final class LayoutStore {
|
||||
save()
|
||||
}
|
||||
|
||||
public func openGitView() {
|
||||
isGitViewOpen = true
|
||||
}
|
||||
|
||||
public func closeGitView() {
|
||||
isGitViewOpen = false
|
||||
}
|
||||
|
||||
public func toggleGitView() {
|
||||
isGitViewOpen.toggle()
|
||||
}
|
||||
|
||||
public func toggleFluid() {
|
||||
fluid.toggle()
|
||||
refit()
|
||||
@@ -221,11 +225,6 @@ public final class LayoutStore {
|
||||
refit()
|
||||
}
|
||||
|
||||
public func dragSourceControl(by delta: Double) {
|
||||
fluid = false
|
||||
widths.sourceControl = clamp(widths.sourceControl + delta, ColumnLayout.sourceControlRange)
|
||||
}
|
||||
|
||||
public func dragExplorer(by delta: Double) {
|
||||
fluid = false
|
||||
widths.explorer = clamp(widths.explorer + delta, ColumnLayout.explorerRange)
|
||||
@@ -267,12 +266,10 @@ public final class LayoutStore {
|
||||
guard isVisible(panel) else { return nil }
|
||||
let splitter = ColumnLayout.splitterWidth
|
||||
let v = visibility
|
||||
let explorerStart = v.sourceControl ? widths.sourceControl + splitter : 0
|
||||
let flexStart = explorerStart + (v.explorer ? widths.explorer + splitter : 0)
|
||||
let flexStart = v.explorer ? widths.explorer + splitter : 0
|
||||
let agentStart = v.editor ? max(flexStart, windowWidth - widths.agent) : flexStart
|
||||
switch panel {
|
||||
case .sourceControl: return 0...widths.sourceControl
|
||||
case .explorer: return explorerStart...(explorerStart + widths.explorer)
|
||||
case .explorer: return 0...widths.explorer
|
||||
case .editor: return flexStart...max(flexStart, v.agent ? agentStart - splitter : windowWidth)
|
||||
case .terminal: return agentStart...max(agentStart, windowWidth)
|
||||
}
|
||||
|
||||
@@ -3,31 +3,76 @@ import HelderCore
|
||||
import HelderServices
|
||||
import Observation
|
||||
|
||||
/// The long git run the Git view's Pull or Push button is waiting on.
|
||||
public enum GitBusy: Sendable, Equatable {
|
||||
case push
|
||||
case pull
|
||||
}
|
||||
|
||||
/// One console line with an id that stays put while older lines drop off the top.
|
||||
public struct GitConsoleEntry: Identifiable, Sendable, Equatable {
|
||||
public let id: Int
|
||||
public var line: GitConsoleLine
|
||||
}
|
||||
|
||||
/// What an expanded file row shows under it.
|
||||
public enum GitRowDetail: Equatable {
|
||||
case rows([InlineDiffRow])
|
||||
/// The file is over the diff cap, so no text was read.
|
||||
case tooBig
|
||||
}
|
||||
|
||||
@Observable
|
||||
@MainActor
|
||||
public final class SourceControlStore {
|
||||
public private(set) var state = GitWorkingState.empty
|
||||
/// False until the first read landed, so the column can tell "loading" from "clean".
|
||||
public private(set) var state = GitWorkingState.empty {
|
||||
didSet {
|
||||
sections = GitSections.build(state.changes)
|
||||
inlineCache = [:]
|
||||
}
|
||||
}
|
||||
/// False until the first read landed, so the view can tell "loading" from "clean".
|
||||
public private(set) var hasLoaded = false
|
||||
/// The commit box draft; always one lowercase line (see `setCommitMessage`).
|
||||
public private(set) var sections: [GitSection] = []
|
||||
public private(set) var collapsedSections: Set<GitSectionKind> = []
|
||||
/// Keys from `rowKey(_:_:)`.
|
||||
public private(set) var expandedRows: Set<String> = []
|
||||
/// The commit message draft; always one lowercase line (see `setCommitMessage`).
|
||||
public private(set) var commitMessage = ""
|
||||
/// The keyboard cursor, kept as a row id because the list reorders under it.
|
||||
public var selectedRowID: String?
|
||||
public private(set) var isPushing = false
|
||||
/// The `git` config section: confirmations and the poll interval.
|
||||
/// `user.name <user.email>`, read when the view opens.
|
||||
public private(set) var author: String?
|
||||
public private(set) var branches = GitBranchList.empty
|
||||
public private(set) var busy: GitBusy?
|
||||
public private(set) var lines: [GitConsoleEntry] = []
|
||||
public var consoleInput = ""
|
||||
public private(set) var history: [String] = []
|
||||
/// The `git` config section: the discard confirmation and the poll interval.
|
||||
public var config = HelderConfig.Git() {
|
||||
didSet {
|
||||
if pollTask != nil && config.refreshInterval != oldValue.refreshInterval { startPolling() }
|
||||
}
|
||||
}
|
||||
|
||||
public static let maxConsoleLines = 400
|
||||
public static let remoteTimeout: TimeInterval = 120
|
||||
|
||||
/// Receives a toast title and its mono detail line; `WorkspaceModel` wires it to `ToastStore`.
|
||||
@ObservationIgnored public var notify: (_ title: String, _ detail: String?) -> Void = { _, _ in }
|
||||
/// Asks for the keyboard in the message field, after git refused an empty message.
|
||||
@ObservationIgnored public var focusMessage: () -> Void = {}
|
||||
|
||||
@ObservationIgnored private let git: GitServicing
|
||||
@ObservationIgnored private let derive: @Sendable (GitSnapshot?) -> GitWorkingState
|
||||
@ObservationIgnored private var refreshGeneration = 0
|
||||
@ObservationIgnored private var pollTask: Task<Void, Never>?
|
||||
@ObservationIgnored private var nextLineID = 0
|
||||
@ObservationIgnored private var historyCursor: Int?
|
||||
@ObservationIgnored private var isFetching = false
|
||||
@ObservationIgnored private var inlineCache: [String: GitRowDetail] = [:]
|
||||
/// The last git command queued; the next one waits for it, so two never race for `.git/index.lock`.
|
||||
@ObservationIgnored private var commandTail: Task<Void, Never>?
|
||||
/// The status error already in the console, so a poll that keeps failing logs it once.
|
||||
@ObservationIgnored private var loggedStatusError: String?
|
||||
|
||||
/// `derive` runs off the main actor, since it diffs every changed file.
|
||||
public init(git: GitServicing, derive: @escaping @Sendable (GitSnapshot?) -> GitWorkingState = { GitDerivation.derive($0) }) {
|
||||
@@ -35,21 +80,7 @@ public final class SourceControlStore {
|
||||
self.derive = derive
|
||||
}
|
||||
|
||||
// MARK: Rows
|
||||
|
||||
/// Rows in list order: staged folder groups, then unstaged ones.
|
||||
public var rows: [Change] { SourceControlText.navigationOrder(state.changes) }
|
||||
|
||||
public var stagedGroups: [ChangeGroup] { SourceControlText.groupByDir(state.changes.filter(\.staged)) }
|
||||
public var unstagedGroups: [ChangeGroup] { SourceControlText.groupByDir(state.changes.filter { !$0.staged }) }
|
||||
|
||||
public var selectedRow: Change? { state.changes.first { $0.id == selectedRowID } }
|
||||
|
||||
/// Paths with a staged row, in row order: what "unstage all" sends to git.
|
||||
public var stagedPaths: [String] {
|
||||
var seen = Set<String>()
|
||||
return state.changes.filter { $0.staged && seen.insert($0.path).inserted }.map(\.path)
|
||||
}
|
||||
// MARK: Derived
|
||||
|
||||
/// The status letter the Explorer shows per file; the unstaged row wins, as in the file-level diff.
|
||||
public var fileStatuses: [String: GitStatus] {
|
||||
@@ -60,30 +91,63 @@ public final class SourceControlStore {
|
||||
return out
|
||||
}
|
||||
|
||||
/// Moves the cursor; a cursor whose row vanished starts over at the top.
|
||||
public func moveSelection(by step: Int) {
|
||||
let list = rows
|
||||
guard !list.isEmpty else { return }
|
||||
guard let index = list.firstIndex(where: { $0.id == selectedRowID }) else {
|
||||
selectedRowID = list[0].id
|
||||
return
|
||||
}
|
||||
selectedRowID = list[min(max(index + step, 0), list.count - 1)].id
|
||||
/// Any change, staged or not; it locks branch switching.
|
||||
public var isDirty: Bool { !state.changes.isEmpty }
|
||||
|
||||
/// Distinct changed paths, a file with two rows once.
|
||||
public var changedPathCount: Int { Set(state.changes.map(\.path)).count }
|
||||
|
||||
public var stagedPathCount: Int { GitSections.uniquePaths(state.changes.filter(\.staged)).count }
|
||||
|
||||
/// The ready look of the Commit button; the button itself always runs git.
|
||||
public var canCommitNow: Bool {
|
||||
stagedPathCount > 0 && !commitMessage.trimmingCharacters(in: .whitespaces).isEmpty
|
||||
}
|
||||
|
||||
// MARK: Commit box
|
||||
|
||||
public var canCommit: Bool {
|
||||
state.stagedCount > 0 && !commitMessage.trimmingCharacters(in: .whitespaces).isEmpty
|
||||
public var syncLabel: String {
|
||||
GitConsoleText.syncLabel(ahead: state.ahead, behind: state.behind, upstream: state.upstream)
|
||||
}
|
||||
|
||||
// MARK: Sections and rows
|
||||
|
||||
public static func rowKey(_ kind: GitSectionKind, _ row: Change) -> String {
|
||||
"\(kind.rawValue):\(row.id)"
|
||||
}
|
||||
|
||||
public func isCollapsed(_ kind: GitSectionKind) -> Bool { collapsedSections.contains(kind) }
|
||||
|
||||
public func toggleSection(_ kind: GitSectionKind) {
|
||||
if !collapsedSections.insert(kind).inserted { collapsedSections.remove(kind) }
|
||||
}
|
||||
|
||||
public func isExpanded(_ kind: GitSectionKind, _ row: Change) -> Bool {
|
||||
expandedRows.contains(Self.rowKey(kind, row))
|
||||
}
|
||||
|
||||
public func toggleRow(_ kind: GitSectionKind, _ row: Change) {
|
||||
let key = Self.rowKey(kind, row)
|
||||
if !expandedRows.insert(key).inserted { expandedRows.remove(key) }
|
||||
}
|
||||
|
||||
/// The inline side-by-side rows of a row's own half; cached until the next status read.
|
||||
public func detail(for row: Change) -> GitRowDetail {
|
||||
if let cached = inlineCache[row.id] { return cached }
|
||||
let diff = state.rowDiffs[row.id]
|
||||
let detail: GitRowDetail = diff?.isTooBig == true ? .tooBig : .rows(diff.map { InlineDiff.rows(from: $0) } ?? [])
|
||||
inlineCache[row.id] = detail
|
||||
return detail
|
||||
}
|
||||
|
||||
// MARK: Commit message
|
||||
|
||||
public func setCommitMessage(_ value: String) {
|
||||
commitMessage = SourceControlText.normalizeCommitMessage(value)
|
||||
}
|
||||
|
||||
// MARK: Git
|
||||
// MARK: Reading git
|
||||
|
||||
/// Re-reads git and derives rows and diffs; a result that a newer refresh overtook is dropped.
|
||||
/// A failed read still counts as loaded, so the view never waits forever; its error lands in the console once.
|
||||
public func refresh() async {
|
||||
refreshGeneration += 1
|
||||
let generation = refreshGeneration
|
||||
@@ -91,10 +155,18 @@ public final class SourceControlStore {
|
||||
do {
|
||||
snapshot = try await git.load()
|
||||
} catch {
|
||||
Log.warn("git", "status failed: \(error)")
|
||||
guard generation == refreshGeneration else { return }
|
||||
let message = "status failed: \(error)"
|
||||
Log.warn("git", message)
|
||||
if message != loggedStatusError {
|
||||
loggedStatusError = message
|
||||
log(message, .error)
|
||||
}
|
||||
hasLoaded = true
|
||||
return
|
||||
}
|
||||
guard generation == refreshGeneration else { return }
|
||||
loggedStatusError = nil
|
||||
let derive = self.derive
|
||||
let derived = await Task.detached(priority: .userInitiated) { derive(snapshot) }.value
|
||||
guard generation == refreshGeneration else { return }
|
||||
@@ -102,104 +174,253 @@ public final class SourceControlStore {
|
||||
hasLoaded = true
|
||||
}
|
||||
|
||||
/// Loads once for a column that appears before `WorkspaceModel` refreshed.
|
||||
/// Loads once for a view that appears before `WorkspaceModel` refreshed.
|
||||
public func loadIfNeeded() async {
|
||||
if !hasLoaded { await refresh() }
|
||||
}
|
||||
|
||||
public func stage(_ path: String) async {
|
||||
await run("Stage failed", detail: path) { try await self.git.stage([path]) }
|
||||
public func reloadBranches() async {
|
||||
branches = await git.branches()
|
||||
}
|
||||
|
||||
public func unstage(_ path: String) async {
|
||||
await run("Unstage failed", detail: path) { try await self.git.unstage([path]) }
|
||||
/// The Git view opened: reads the author and the branches, then fetches origin so ahead/behind are honest.
|
||||
/// Without an origin there is nothing to fetch, so the console stays quiet.
|
||||
public func viewOpened() async {
|
||||
author = await git.author()
|
||||
await reloadBranches()
|
||||
await loadIfNeeded()
|
||||
guard !isFetching, state.isRepository, !branches.remote.isEmpty || state.upstream?.hasPrefix("origin/") == true else { return }
|
||||
isFetching = true
|
||||
defer { isFetching = false }
|
||||
await run(["fetch", "origin"], timeout: Self.remoteTimeout)
|
||||
await afterCommand()
|
||||
}
|
||||
|
||||
/// Stages every path with an unstaged row, including ones that also have a staged row.
|
||||
public func stageAll() async {
|
||||
let paths = state.unstagedPaths
|
||||
// MARK: Staging
|
||||
|
||||
/// Always the listed paths, never `add -A`, which would also take files the view has not shown yet.
|
||||
public func stage(_ paths: [String]) async {
|
||||
guard !paths.isEmpty else { return }
|
||||
await run("Stage failed", detail: nil) { try await self.git.stage(paths) }
|
||||
await run(["add", "--"] + paths)
|
||||
await afterCommand()
|
||||
}
|
||||
|
||||
public func unstageAll() async {
|
||||
let paths = stagedPaths
|
||||
/// A staged rename takes its source along, or the old path stays staged as deleted.
|
||||
/// A repository without commits has no HEAD to restore from, so `rm --cached` takes over there.
|
||||
public func unstage(_ paths: [String]) async {
|
||||
guard !paths.isEmpty else { return }
|
||||
await run("Unstage failed", detail: nil) { try await self.git.unstage(paths) }
|
||||
}
|
||||
|
||||
/// Commits the staged files with the draft, clears it, and returns how many files went in (0 when nothing did).
|
||||
public func commit() async -> Int {
|
||||
let message = commitMessage.trimmingCharacters(in: .whitespaces)
|
||||
guard !message.isEmpty, state.stagedCount > 0 else { return 0 }
|
||||
let count = Set(state.changes.filter(\.staged).map(\.path)).count
|
||||
commitMessage = ""
|
||||
do {
|
||||
try await git.commit(message: message)
|
||||
} catch {
|
||||
Log.error("git", "commit failed: \(error)")
|
||||
if commitMessage.isEmpty { commitMessage = message }
|
||||
notify("Commit failed", Self.failureDetail(error))
|
||||
return 0
|
||||
let staged = state.changes.filter(\.staged)
|
||||
let all = Set(paths) == Set(GitSections.uniquePaths(staged))
|
||||
let sources = staged.filter { $0.status == .renamed && paths.contains($0.path) }.compactMap(\.originalPath)
|
||||
let withSources = paths + sources.filter { !paths.contains($0) }
|
||||
let pathspec = all ? ["."] : ["--"] + withSources
|
||||
let result = await run(["restore", "--staged"] + pathspec)
|
||||
if !result.succeeded && result.stderr.contains("HEAD") {
|
||||
await run(["rm", "--cached", "-r"] + pathspec)
|
||||
}
|
||||
await refresh()
|
||||
await afterCommand()
|
||||
}
|
||||
|
||||
/// Modified and deleted files come back with `restore`, new files go with `clean -f`; conflicts are left alone.
|
||||
public func discard(_ paths: [String]) async {
|
||||
let paths = paths.filter { unstagedStatus($0) != .unmerged }
|
||||
guard !paths.isEmpty else { return }
|
||||
let fresh = paths.filter { unstagedStatus($0) == .added }
|
||||
let tracked = paths.filter { unstagedStatus($0) != .added }
|
||||
if !tracked.isEmpty { await run(["restore", "--"] + tracked) }
|
||||
if !fresh.isEmpty { await run(["clean", "-f", "--"] + fresh) }
|
||||
await afterCommand()
|
||||
}
|
||||
|
||||
private func unstagedStatus(_ path: String) -> GitStatus? {
|
||||
state.changes.first { !$0.staged && $0.path == path }?.status
|
||||
}
|
||||
|
||||
/// The confirm dialog a discard needs, or nil to run it straight away; restoring deleted files never asks.
|
||||
public func confirmation(for action: ContextAction) -> ConfirmRequest? {
|
||||
guard case let .gitDiscard(paths) = action, config.confirmDiscard, !paths.isEmpty else { return nil }
|
||||
let statuses = paths.map(unstagedStatus)
|
||||
let hasNew = statuses.contains(.added)
|
||||
if statuses.allSatisfy({ $0 == .deleted }) { return nil }
|
||||
let allNew = statuses.allSatisfy { $0 == .added }
|
||||
let what = paths.count == 1 ? paths[0] : "\(paths.count) files"
|
||||
return ConfirmRequest(
|
||||
title: allNew ? "Delete \(what)?" : "Discard changes to \(what)?",
|
||||
body: hasNew ? "New files are removed from disk. This cannot be undone." : "This reverts to the last commit and cannot be undone.",
|
||||
confirmLabel: allNew ? "Delete" : "Discard",
|
||||
action: action
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: Commit, push, pull
|
||||
|
||||
/// Always runs `git commit`, so git's own refusal (nothing staged, empty message) lands in the console.
|
||||
public func commit(andPush: Bool = false) async {
|
||||
let message = commitMessage.trimmingCharacters(in: .whitespaces)
|
||||
let count = stagedPathCount
|
||||
let arguments = ["commit", "-m", message]
|
||||
let result = await run(arguments)
|
||||
await afterCommand()
|
||||
guard result.succeeded else {
|
||||
notify("Commit failed", Self.failureDetail(of: result, arguments: arguments))
|
||||
if message.isEmpty { focusMessage() }
|
||||
return
|
||||
}
|
||||
if commitMessage.trimmingCharacters(in: .whitespaces) == message { commitMessage = "" }
|
||||
let subject = message.count > 34 ? String(message.prefix(34)) + "…" : message
|
||||
notify("Committed \(count) file\(count == 1 ? "" : "s")", subject)
|
||||
return count
|
||||
if andPush { await push() }
|
||||
}
|
||||
|
||||
public func push() async -> PushResult {
|
||||
guard !isPushing else { return PushResult(ok: false, message: "A push is already running") }
|
||||
isPushing = true
|
||||
notify("Pushing…", nil)
|
||||
let result = await git.push()
|
||||
isPushing = false
|
||||
await refresh()
|
||||
notify(result.ok ? "Pushed" : "Push failed", result.message)
|
||||
/// A branch without an upstream is pushed again with `-u origin <branch>`. Ignored while a push or pull runs.
|
||||
public func push() async {
|
||||
guard busy == nil else { return }
|
||||
busy = .push
|
||||
let branch = state.branch
|
||||
let ahead = state.ahead
|
||||
var arguments = ["push"]
|
||||
var result = await run(arguments, timeout: Self.remoteTimeout)
|
||||
if !result.succeeded && Porcelain.needsUpstream(stderr: result.stderr) && branch != "HEAD" && branch != "—" {
|
||||
arguments = ["push", "-u", "origin", branch]
|
||||
result = await run(arguments, timeout: Self.remoteTimeout)
|
||||
}
|
||||
busy = nil
|
||||
await afterCommand()
|
||||
guard result.succeeded else {
|
||||
notify("Push failed", Self.failureDetail(of: result, arguments: arguments))
|
||||
return
|
||||
}
|
||||
let commits = ahead > 0 ? "\(ahead) commit\(ahead == 1 ? "" : "s") " : ""
|
||||
notify("Pushed \(commits)to origin/\(branch)", nil)
|
||||
}
|
||||
|
||||
/// Merges when the branches diverged; a bare `pull` without `pull.rebase` config refuses to choose.
|
||||
/// Ignored while a push or pull runs.
|
||||
public func pull() async {
|
||||
guard busy == nil else { return }
|
||||
busy = .pull
|
||||
let branch = state.branch
|
||||
let behind = state.behind
|
||||
let arguments = ["pull", "--no-rebase"]
|
||||
let result = await run(arguments, timeout: Self.remoteTimeout)
|
||||
busy = nil
|
||||
await afterCommand()
|
||||
guard result.succeeded else {
|
||||
notify("Pull failed", Self.failureDetail(of: result, arguments: arguments))
|
||||
return
|
||||
}
|
||||
if behind > 0 {
|
||||
notify("Pulled \(behind) commit\(behind == 1 ? "" : "s") from origin/\(branch)", nil)
|
||||
} else if !result.stdout.contains("Already up to date") {
|
||||
notify("Pulled from origin/\(branch)", nil)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Branches
|
||||
|
||||
/// Refuses with a toast while the tree is dirty, without asking git. A remote branch switches by its local
|
||||
/// name, which git creates as a tracking branch when it does not exist yet.
|
||||
@discardableResult
|
||||
public func switchBranch(_ name: String, remote: Bool) async -> Bool {
|
||||
if isDirty {
|
||||
let count = changedPathCount
|
||||
notify("— Commit or discard \(count) file\(count == 1 ? "" : "s") before you switch.", nil)
|
||||
return false
|
||||
}
|
||||
let local = remote ? GitBranchList.localName(ofRemote: name) : name
|
||||
guard local != state.branch else { return false }
|
||||
let result = await run(["switch", local])
|
||||
await afterCommand()
|
||||
guard result.succeeded else { return false }
|
||||
expandedRows = []
|
||||
notify("Switched to \(local)", nil)
|
||||
return true
|
||||
}
|
||||
|
||||
// MARK: Console
|
||||
|
||||
/// Runs what was typed; `clear` empties the log and a bare `log` reads as a short one-line log.
|
||||
public func submitConsoleInput() async {
|
||||
let typed = consoleInput.trimmingCharacters(in: .whitespaces)
|
||||
consoleInput = ""
|
||||
historyCursor = nil
|
||||
guard let arguments = GitConsoleText.parseInput(typed) else { return }
|
||||
history.append(typed)
|
||||
if arguments == ["clear"] {
|
||||
clearConsole()
|
||||
return
|
||||
}
|
||||
let run = arguments == ["log"] ? ["log", "--oneline", "--decorate", "-n", "30"] : arguments
|
||||
await self.run(run, literalPathspecs: false, timeout: Self.remoteTimeout)
|
||||
await afterCommand()
|
||||
}
|
||||
|
||||
/// ↑ in the input: steps back through what was typed, stopping at the oldest.
|
||||
public func recallPreviousInput() {
|
||||
guard !history.isEmpty else { return }
|
||||
let cursor = max(0, (historyCursor ?? history.count) - 1)
|
||||
historyCursor = cursor
|
||||
consoleInput = history[cursor]
|
||||
}
|
||||
|
||||
public func clearConsole() {
|
||||
lines = []
|
||||
}
|
||||
|
||||
// MARK: Running git
|
||||
|
||||
/// Queues the command behind the one before it, then runs it; see `runNow`.
|
||||
@discardableResult
|
||||
private func run(_ arguments: [String], literalPathspecs: Bool = true, timeout: TimeInterval? = nil) async -> GitCommandResult {
|
||||
let previous = commandTail
|
||||
let command = Task { [weak self] () -> GitCommandResult in
|
||||
await previous?.value
|
||||
guard let self else { return GitCommandResult(exitCode: -1, stdout: "", stderr: "cancelled") }
|
||||
return await self.runNow(arguments, literalPathspecs: literalPathspecs, timeout: timeout)
|
||||
}
|
||||
commandTail = Task { _ = await command.value }
|
||||
return await command.value
|
||||
}
|
||||
|
||||
/// Logs the exact command, streams its output classified line by line, and returns how it ended.
|
||||
/// Lines arrive off the main actor; one consumer keeps them in order and is drained before this returns.
|
||||
private func runNow(_ arguments: [String], literalPathspecs: Bool, timeout: TimeInterval?) async -> GitCommandResult {
|
||||
log(GitConsoleText.commandLine(arguments), .command)
|
||||
let (stream, continuation) = AsyncStream<(String, Bool)>.makeStream()
|
||||
let consumer = Task { [weak self] in
|
||||
var classifier = GitOutputClassifier(arguments: arguments)
|
||||
for await (line, isError) in stream {
|
||||
self?.log(line, classifier.classify(line, isError: isError))
|
||||
}
|
||||
}
|
||||
let result = await git.execute(arguments, literalPathspecs: literalPathspecs, timeout: timeout) { line, isError in
|
||||
continuation.yield((line, isError))
|
||||
}
|
||||
continuation.finish()
|
||||
await consumer.value
|
||||
return result
|
||||
}
|
||||
|
||||
public func discard(_ path: String) async {
|
||||
do {
|
||||
try await git.discard([path])
|
||||
} catch {
|
||||
Log.error("git", "discard failed: \(error)")
|
||||
notify("Discard failed", path)
|
||||
await refresh()
|
||||
return
|
||||
}
|
||||
private func afterCommand() async {
|
||||
await refresh()
|
||||
notify("Discarded changes", path)
|
||||
await reloadBranches()
|
||||
}
|
||||
|
||||
// MARK: Actions
|
||||
|
||||
/// The confirm dialog an action needs first under the config, or nil to run it straight away.
|
||||
public func confirmation(for action: ContextAction) -> ConfirmRequest? {
|
||||
switch action {
|
||||
case let .discard(path) where config.confirmDiscard:
|
||||
ConfirmRequest(title: "Discard changes to \(path)?",
|
||||
body: "This reverts the file to the last commit and cannot be undone.",
|
||||
confirmLabel: "Discard", action: action)
|
||||
case let .stage(path) where config.confirmStage:
|
||||
ConfirmRequest(title: "Stage \(path)?", confirmLabel: "Stage", action: action)
|
||||
case let .unstage(path) where config.confirmUnstage:
|
||||
ConfirmRequest(title: "Unstage \(path)?", confirmLabel: "Unstage", action: action)
|
||||
default:
|
||||
nil
|
||||
}
|
||||
private func log(_ text: String, _ kind: GitLineKind) {
|
||||
lines.append(GitConsoleEntry(id: nextLineID, line: GitConsoleLine(text: text, kind: kind)))
|
||||
nextLineID += 1
|
||||
if lines.count > Self.maxConsoleLines { lines.removeFirst(lines.count - Self.maxConsoleLines) }
|
||||
}
|
||||
|
||||
/// Runs a git action that is already confirmed; false for actions this store does not own.
|
||||
@discardableResult
|
||||
public func perform(_ action: ContextAction) async -> Bool {
|
||||
switch action {
|
||||
case let .stage(path): await stage(path)
|
||||
case let .unstage(path): await unstage(path)
|
||||
case let .discard(path): await discard(path)
|
||||
default: return false
|
||||
/// The toast detail of a failed run: its first error line, else its last line that is not a hint.
|
||||
private static func failureDetail(of result: GitCommandResult, arguments: [String]) -> String? {
|
||||
var classifier = GitOutputClassifier(arguments: arguments)
|
||||
let lines = [(result.stderr, true), (result.stdout, false)].flatMap { text, isError in
|
||||
text.split(whereSeparator: \.isNewline).map { (String($0), isError) }
|
||||
}
|
||||
return true
|
||||
let classified = lines.map { ($0.0.trimmingCharacters(in: .whitespaces), classifier.classify($0.0, isError: $0.1)) }
|
||||
.filter { !$0.0.isEmpty }
|
||||
return classified.first { $0.1 == .error }?.0 ?? classified.last { $0.1 != .hint }?.0
|
||||
}
|
||||
|
||||
// MARK: Polling
|
||||
@@ -225,19 +446,4 @@ public final class SourceControlStore {
|
||||
}
|
||||
|
||||
public var isPolling: Bool { pollTask != nil }
|
||||
|
||||
private func run(_ failure: String, detail: String?, _ operation: () async throws -> Void) async {
|
||||
do {
|
||||
try await operation()
|
||||
} catch {
|
||||
Log.error("git", "\(failure): \(error)")
|
||||
notify(failure, detail ?? Self.failureDetail(error))
|
||||
}
|
||||
await refresh()
|
||||
}
|
||||
|
||||
private static func failureDetail(_ error: Error) -> String {
|
||||
if case let GitError.commandFailed(_, _, stderr) = error, !stderr.isEmpty { return stderr }
|
||||
return String(describing: error)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,36 +69,47 @@ extension WorkspaceModel {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Git view
|
||||
|
||||
/// Opens the Git view on its message field, re-reads git and fetches origin; an open view only takes the field again.
|
||||
func openGitView() {
|
||||
if !layout.isGitViewOpen {
|
||||
layout.openGitView()
|
||||
scheduleRefresh(.git)
|
||||
if let sourceControl { track { await sourceControl.viewOpened() } }
|
||||
}
|
||||
focusRequest = FocusRequest(.commitMessage)
|
||||
}
|
||||
|
||||
/// Hands the keyboard back to the column that had it before the view opened.
|
||||
func closeGitView() {
|
||||
guard layout.isGitViewOpen else { return }
|
||||
layout.closeGitView()
|
||||
guard let panel = layout.activePanel else {
|
||||
focusRequest = nil
|
||||
return
|
||||
}
|
||||
focusRequest = FocusRequest(.panel(panel))
|
||||
if panel == .editor { editor?.requestTextFocus() }
|
||||
}
|
||||
|
||||
// MARK: Focus and the row cursor
|
||||
|
||||
func focus(_ panel: Panel) {
|
||||
let previous = layout.activePanel
|
||||
layout.focus(panel)
|
||||
guard layout.activePanel == panel else { return }
|
||||
focusRequest = FocusRequest(.panel(panel))
|
||||
if panel == .editor { editor?.requestTextFocus() }
|
||||
if panel == .sourceControl && previous != .sourceControl { scheduleRefresh(.git) }
|
||||
}
|
||||
|
||||
func moveRowCursor(by step: Int) {
|
||||
switch layout.activePanel {
|
||||
case .sourceControl: sourceControl?.moveSelection(by: step)
|
||||
case .explorer: explorer?.moveSelection(by: step, showHidden: layout.showHidden)
|
||||
default: break
|
||||
}
|
||||
guard layout.activePanel == .explorer else { return }
|
||||
explorer?.moveSelection(by: step, showHidden: layout.showHidden)
|
||||
}
|
||||
|
||||
func openSelectedRow() {
|
||||
switch layout.activePanel {
|
||||
case .sourceControl:
|
||||
guard let row = selectedGitRow() else { return }
|
||||
open(row.change.path, OpenOptions(side: row.change.staged ? .staged : .unstaged))
|
||||
case .explorer:
|
||||
guard let explorer, let row = selectedTreeRow() else { return }
|
||||
if row.row.kind == .directory { explorer.toggle(row.row.path) } else { open(row.row.path) }
|
||||
default:
|
||||
break
|
||||
}
|
||||
guard layout.activePanel == .explorer, let explorer, let row = selectedTreeRow() else { return }
|
||||
if row.row.kind == .directory { explorer.toggle(row.row.path) } else { open(row.row.path) }
|
||||
}
|
||||
|
||||
// MARK: Editor
|
||||
|
||||
@@ -42,29 +42,12 @@ extension WorkspaceModel {
|
||||
|
||||
// MARK: Row menus
|
||||
|
||||
/// ⌘→ in Source Control or Explorer: the selected row's menu, beside the column at the row's height.
|
||||
/// ⌘→ in the Explorer: the selected row's menu, beside the column at the row's height.
|
||||
func openRowMenu() {
|
||||
switch layout.activePanel {
|
||||
case .sourceControl:
|
||||
guard let row = selectedGitRow() else { return }
|
||||
showContextMenu(.gitRow(path: row.change.path, staged: row.change.staged),
|
||||
anchor: rowMenuAnchor(.sourceControl, frame: rowFrames[.git(row.change.id)],
|
||||
estimate: row.index, rowHeight: Metrics.sourceControlRow))
|
||||
case .explorer:
|
||||
guard let row = selectedTreeRow() else { return }
|
||||
showContextMenu(ExplorerStore.target(for: row.row),
|
||||
anchor: rowMenuAnchor(.explorer, frame: rowFrames[.tree(row.row.path)],
|
||||
estimate: row.index, rowHeight: Metrics.explorerRow))
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
func selectedGitRow() -> (change: Change, index: Int)? {
|
||||
guard let sourceControl else { return nil }
|
||||
let rows = sourceControl.rows
|
||||
guard let index = rows.firstIndex(where: { $0.id == sourceControl.selectedRowID }) else { return nil }
|
||||
return (rows[index], index)
|
||||
guard layout.activePanel == .explorer, let row = selectedTreeRow() else { return }
|
||||
showContextMenu(ExplorerStore.target(for: row.row),
|
||||
anchor: rowMenuAnchor(.explorer, frame: rowFrames[.tree(row.row.path)],
|
||||
estimate: row.index, rowHeight: Metrics.explorerRow))
|
||||
}
|
||||
|
||||
func selectedTreeRow() -> (row: TreeRow, index: Int)? {
|
||||
@@ -90,7 +73,13 @@ extension WorkspaceModel {
|
||||
let sourceControl = sourceControl, explorer = explorer, editor = editor
|
||||
switch action {
|
||||
case let .passOnReference(reference, code):
|
||||
closeGitView()
|
||||
overlay.present(.passOn(PassOnRequest(reference: reference, code: code, anchor: anchor)))
|
||||
case let .openFile(path):
|
||||
closeGitView()
|
||||
open(path)
|
||||
case let .commit(andPush):
|
||||
track { await sourceControl?.commit(andPush: andPush) }
|
||||
case let .passOnFileName(name):
|
||||
overlay.present(.passOn(PassOnRequest(reference: name, anchor: anchor)))
|
||||
case let .bouwen(name):
|
||||
@@ -118,18 +107,16 @@ extension WorkspaceModel {
|
||||
case let .rename(path, isDirectory):
|
||||
overlay.present(.namePrompt(NamePromptRequest(purpose: .rename(path: path, isDirectory: isDirectory),
|
||||
initialName: PathUtils.basename(path), anchor: anchor)))
|
||||
case let .openDiff(path):
|
||||
open(path, OpenOptions(showDiff: true))
|
||||
case let .showDiff(path, line):
|
||||
if editor?.activePath == path { editor?.openDiff(atLine: line) }
|
||||
case let .copyTerminalSelection(kind):
|
||||
if let text = terminal.selection(kind) { app.system.copy(text) }
|
||||
case let .pasteIntoTerminal(kind):
|
||||
if let text = app.system.pasteboardText() { terminal.paste(text, into: kind) }
|
||||
case let .discard(path):
|
||||
case let .gitDiscard(paths):
|
||||
track {
|
||||
await sourceControl?.discard(path)
|
||||
await editor?.reloadFromDisk(path)
|
||||
await sourceControl?.discard(paths)
|
||||
for path in paths where editor?.isLoaded(path) == true { await editor?.reloadFromDisk(path) }
|
||||
}
|
||||
case let .delete(path, isDirectory):
|
||||
track {
|
||||
@@ -138,10 +125,7 @@ extension WorkspaceModel {
|
||||
await sourceControl?.refresh()
|
||||
}
|
||||
default:
|
||||
track {
|
||||
if await sourceControl?.perform(action) == true { return }
|
||||
await explorer?.perform(action)
|
||||
}
|
||||
track { _ = await explorer?.perform(action) }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -54,6 +54,7 @@ extension WorkspaceModel {
|
||||
|
||||
let sourceControl = SourceControlStore(git: services.git)
|
||||
sourceControl.notify = notify
|
||||
sourceControl.focusMessage = { [weak self] in self?.focusRequest = FocusRequest(.commitMessage) }
|
||||
self.sourceControl = sourceControl
|
||||
|
||||
let explorer = ExplorerStore(files: services.files, system: app.system)
|
||||
|
||||
@@ -45,8 +45,6 @@ public struct RefreshScope: OptionSet, Sendable {
|
||||
|
||||
/// A list row whose on-screen frame the ⌘→ menu anchors to.
|
||||
public enum RowKey: Hashable, Sendable {
|
||||
/// A Source Control row, by `Change.id`.
|
||||
case git(String)
|
||||
/// An Explorer row, by path.
|
||||
case tree(String)
|
||||
}
|
||||
@@ -100,7 +98,7 @@ public final class WorkspaceModel {
|
||||
@ObservationIgnored var lifecycleTask: Task<Void, Never>?
|
||||
/// Moves on every project switch, so work that awaited across one can tell its project is gone.
|
||||
@ObservationIgnored var generation = 0
|
||||
/// Where the Source Control and Explorer rows sit on screen, in top-left window coordinates.
|
||||
/// Where the Explorer rows sit on screen, in top-left window coordinates.
|
||||
@ObservationIgnored var rowFrames: [RowKey: CGRect] = [:]
|
||||
@ObservationIgnored var hasStarted = false
|
||||
@ObservationIgnored var resignedKey = false
|
||||
@@ -148,7 +146,8 @@ public final class WorkspaceModel {
|
||||
case let .launcherSelect(index): launcher.select(index)
|
||||
case .launcherActivate: activateLauncher()
|
||||
|
||||
case .toggleGit: layout.togglePane(.sourceControl)
|
||||
case .toggleGit: layout.isGitViewOpen ? closeGitView() : openGitView()
|
||||
case .closeGitView: closeGitView()
|
||||
case let .togglePane(panel): layout.togglePane(panel)
|
||||
case .toggleAutoFit: layout.toggleFluid()
|
||||
case .toggleHidden: layout.toggleHidden()
|
||||
@@ -174,15 +173,36 @@ public final class WorkspaceModel {
|
||||
case .selectAllInFile: editor?.selectAll()
|
||||
|
||||
case .commit:
|
||||
guard let sourceControl, sourceControl.canCommit else { return }
|
||||
track { _ = await sourceControl.commit() }
|
||||
guard let sourceControl else { return }
|
||||
track { await sourceControl.commit() }
|
||||
case .push:
|
||||
guard let sourceControl else { return }
|
||||
track { _ = await sourceControl.push() }
|
||||
case .focusCommitMessage:
|
||||
layout.setVisible(.sourceControl, true)
|
||||
layout.focus(.sourceControl)
|
||||
focusRequest = FocusRequest(.commitMessage)
|
||||
track { await sourceControl.push() }
|
||||
case .pull:
|
||||
guard let sourceControl else { return }
|
||||
track {
|
||||
await sourceControl.pull()
|
||||
self.scheduleRefresh([.tree, .openFiles])
|
||||
}
|
||||
case let .stage(paths):
|
||||
guard let sourceControl else { return }
|
||||
track { await sourceControl.stage(paths) }
|
||||
case let .unstage(paths):
|
||||
guard let sourceControl else { return }
|
||||
track { await sourceControl.unstage(paths) }
|
||||
case let .switchBranch(name, remote):
|
||||
guard let sourceControl else { return }
|
||||
track {
|
||||
guard await sourceControl.switchBranch(name, remote: remote) else { return }
|
||||
self.scheduleRefresh([.tree, .openFiles])
|
||||
}
|
||||
case .submitConsoleInput:
|
||||
guard let sourceControl else { return }
|
||||
track {
|
||||
await sourceControl.submitConsoleInput()
|
||||
self.scheduleRefresh([.tree, .openFiles])
|
||||
}
|
||||
case .focusCommitMessage: openGitView()
|
||||
|
||||
case .copyCleanCopy: copyCleanCopy()
|
||||
|
||||
@@ -230,9 +250,7 @@ public final class WorkspaceModel {
|
||||
|
||||
/// A click inside a column: it becomes the active panel without taking first responder.
|
||||
public func pointerFocused(_ panel: Panel) {
|
||||
let previous = layout.activePanel
|
||||
layout.focus(panel)
|
||||
if panel == .sourceControl && previous != .sourceControl { scheduleRefresh(.git) }
|
||||
}
|
||||
|
||||
func wireTerminal() {
|
||||
@@ -241,7 +259,7 @@ public final class WorkspaceModel {
|
||||
}
|
||||
}
|
||||
|
||||
/// A Source Control or Explorer row reports where it sits (nil when it leaves the screen).
|
||||
/// An Explorer row reports where it sits (nil when it leaves the screen).
|
||||
public func rowFrameChanged(_ key: RowKey, _ frame: CGRect?) {
|
||||
rowFrames[key] = frame
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user