Repository Public
1import SwiftUI2import GitCore3import TerminalCore4import WorkspaceCore56/// Git panel for the focused session's directory: status, branch, changed files with diff,7/// history, worktrees. Only safe operations are offered; everything comes from the git CLI.8struct GitPanelView: View {9 @Environment(WorkspaceController.self) private var controller10 let windowID: WindowID11 @State private var model = GitPanelModel()1213 var body: some View {14 let directory = controller.focusedSession(in: windowID)?.currentDirectory ?? controller.focusedSession(in: windowID)?.profile.workingDirectory15 VStack(alignment: .leading, spacing: 10) {16 HStack {17 Text("Git").font(.headline)18 Spacer()19 Button { Task { await model.refresh(directory: directory) } } label: { Image(systemName: "arrow.clockwise") }20 .buttonStyle(.borderless).accessibilityLabel("Refresh git status")21 }22 if model.loading && model.root == nil {23 ProgressView().controlSize(.small)24 } else if let root = model.root {25 content(root: root)26 } else {27 Text(directory.map { "\(TerminalSession.abbreviate($0)) is not inside a Git repository." } ?? "No focused session").font(.system(size: 11)).foregroundStyle(.secondary)28 }29 if let error = model.error { Text(error).font(.system(size: 10)).foregroundStyle(.red) }30 }31 .task(id: directory) { await model.refresh(directory: directory) }32 }3334 @ViewBuilder35 private func content(root: String) -> some View {36 VStack(alignment: .leading, spacing: 4) {37 Label(TerminalSession.abbreviate(root), systemImage: "folder").font(.system(size: 11, design: .monospaced)).lineLimit(1)38 if let status = model.status {39 HStack(spacing: 8) {40 Label(status.isDetached ? "detached \(status.headSHA?.prefix(8) ?? "")" : (status.branch ?? "no branch"), systemImage: "arrow.triangle.branch")41 if status.ahead > 0 { Text("↑\(status.ahead)").accessibilityLabel("\(status.ahead) ahead") }42 if status.behind > 0 { Text("↓\(status.behind)").accessibilityLabel("\(status.behind) behind") }43 if status.hasConflicts { Label("conflicts", systemImage: "exclamationmark.triangle.fill").foregroundStyle(.orange) }44 }45 .font(.system(size: 11))46 Text("\(status.stagedCount) staged · \(status.unstagedCount) modified · \(status.untrackedCount) untracked").font(.system(size: 10)).foregroundStyle(.secondary)47 }48 }49 Picker("Section", selection: $model.section) {50 Text("Changes").tag(GitPanelModel.Section.changes)51 Text("History").tag(GitPanelModel.Section.history)52 Text("Worktrees").tag(GitPanelModel.Section.worktrees)53 }54 .pickerStyle(.segmented).labelsHidden()55 switch model.section {56 case .changes: changes57 case .history: history58 case .worktrees: worktrees(root: root)59 }60 }6162 private var changes: some View {63 VStack(alignment: .leading, spacing: 4) {64 if let status = model.status, status.entries.isEmpty { Text("Working tree clean").font(.system(size: 11)).foregroundStyle(.secondary) }65 ForEach(model.status?.entries ?? []) { entry in66 Button {67 Task { await model.loadDiff(entry) }68 } label: {69 HStack(spacing: 6) {70 Text(entry.code).font(.system(size: 10, design: .monospaced)).frame(width: 22, alignment: .leading)71 .accessibilityLabel(entry.kind.rawValue)72 Text(entry.path).font(.system(size: 11)).lineLimit(1).truncationMode(.middle)73 Spacer()74 }75 .contentShape(Rectangle())76 }77 .buttonStyle(.plain)78 .background(model.selectedPath == entry.path ? NXTokens.accent.opacity(0.15) : Color.clear)79 }80 if !model.diff.isEmpty {81 Divider()82 DiffTextView(diff: model.diff).frame(minHeight: 160, maxHeight: 360)83 }84 }85 }8687 private var history: some View {88 VStack(alignment: .leading, spacing: 4) {89 ForEach(model.commits) { commit in90 VStack(alignment: .leading, spacing: 1) {91 Text(commit.subject).font(.system(size: 11)).lineLimit(1)92 Text("\(commit.shortSHA) · \(commit.author) · \(commit.date.formatted(date: .abbreviated, time: .shortened))").font(.system(size: 9)).foregroundStyle(.secondary)93 }94 .padding(.vertical, 1)95 }96 if model.commits.isEmpty { Text("No commits yet").font(.system(size: 11)).foregroundStyle(.secondary) }97 }98 }99100 private func worktrees(root: String) -> some View {101 VStack(alignment: .leading, spacing: 6) {102 ForEach(model.worktrees) { wt in103 HStack(spacing: 6) {104 Image(systemName: wt.path == root ? "house" : "arrow.triangle.branch").font(.system(size: 10)).accessibilityHidden(true)105 VStack(alignment: .leading, spacing: 1) {106 Text(wt.branchName ?? (wt.isDetached ? "detached" : "—")).font(.system(size: 11, weight: .medium))107 Text(TerminalSession.abbreviate(wt.path)).font(.system(size: 10)).foregroundStyle(.secondary).lineLimit(1).truncationMode(.middle)108 }109 Spacer()110 Menu {111 Button("Open in New Tab") { controller.newTab(in: windowID, profile: SessionProfile(kind: .shell(path: nil), workingDirectory: wt.path, label: wt.branchName)) }112 Button("Open Split Right") { controller.split(in: windowID, axis: .horizontal, profile: SessionProfile(kind: .shell(path: nil), workingDirectory: wt.path, label: wt.branchName)) }113 if controller.claude.cli != nil {114 Button("Start Claude Session Here") { controller.newClaudeSession(in: windowID, directory: wt.path) }115 }116 if wt.path != root {117 Divider()118 Button("Remove Worktree (only if clean)…", role: .destructive) { removeWorktree(wt) }119 }120 } label: { Image(systemName: "ellipsis.circle") }.menuStyle(.borderlessButton).frame(width: 24)121 .accessibilityLabel("Worktree actions")122 }123 }124 Divider()125 Text("New worktree for an agent").font(.system(size: 10, weight: .medium)).foregroundStyle(.secondary)126 TextField("Branch name (created from HEAD)", text: $model.newBranch).textFieldStyle(.roundedBorder).controlSize(.small)127 HStack {128 Text(model.newWorktreePath(root: root).map(TerminalSession.abbreviate) ?? "").font(.system(size: 9, design: .monospaced)).foregroundStyle(.secondary).lineLimit(1).truncationMode(.middle)129 Spacer()130 Button("Create") { Task { await model.createWorktree(root: root) } }131 .controlSize(.small)132 .disabled(!GitRepository.isValidBranchName(model.newBranch))133 }134 }135 }136137 private func removeWorktree(_ wt: GitWorktree) {138 ConfirmationPresenter.confirm(title: "Remove worktree?", message: "\(wt.path)\n\nThe worktree is removed only if it has no uncommitted changes; branches are never deleted.", action: "Remove") {139 Task { await model.removeWorktree(wt) }140 }141 }142}143144/// Monospaced, coloured unified diff (read-only).145struct DiffTextView: View {146 let diff: String147 var body: some View {148 ScrollView([.vertical, .horizontal]) {149 VStack(alignment: .leading, spacing: 0) {150 ForEach(Array(diff.split(separator: "\n", omittingEmptySubsequences: false).prefix(2000).enumerated()), id: \.offset) { _, line in151 Text(String(line))152 .font(.system(size: 10, design: .monospaced))153 .foregroundStyle(color(for: line))154 .frame(maxWidth: .infinity, alignment: .leading)155 .background(background(for: line))156 }157 }158 .textSelection(.enabled)159 }160 .background(NXTokens.panelBackground)161 .accessibilityLabel("Diff")162 }163 private func color(for line: Substring) -> Color {164 if line.hasPrefix("+++") || line.hasPrefix("---") { return .secondary }165 if line.hasPrefix("+") { return .green }166 if line.hasPrefix("-") { return .red }167 if line.hasPrefix("@@") { return .blue }168 return .primary169 }170 private func background(for line: Substring) -> Color {171 if line.hasPrefix("+"), !line.hasPrefix("+++") { return .green.opacity(0.08) }172 if line.hasPrefix("-"), !line.hasPrefix("---") { return .red.opacity(0.08) }173 return .clear174 }175}176177@MainActor178@Observable179final class GitPanelModel {180 enum Section { case changes, history, worktrees }181 var section: Section = .changes182 var root: String?183 var status: GitStatus?184 var commits: [GitCommit] = []185 var worktrees: [GitWorktree] = []186 var diff = ""187 var selectedPath: String?188 var error: String?189 var loading = false190 var newBranch = ""191 private var repo: GitRepository?192193 func refresh(directory: String?) async {194 guard let directory else { root = nil; return }195 loading = true196 defer { loading = false }197 error = nil198 guard let discovered = await GitRepository.discover(from: directory) else { root = nil; status = nil; commits = []; worktrees = []; diff = ""; return }199 if discovered != root { diff = ""; selectedPath = nil }200 root = discovered201 let repo = GitRepository(path: discovered)202 self.repo = repo203 do {204 status = try await repo.status()205 commits = try await repo.log(limit: 40)206 worktrees = try await repo.worktrees()207 } catch {208 self.error = "\(error)"209 }210 }211212 func loadDiff(_ entry: GitStatusEntry) async {213 guard let repo else { return }214 selectedPath = entry.path215 do {216 if entry.kind == .untracked {217 diff = "(untracked file: \(entry.path))"218 } else {219 let unstaged = try await repo.diff(path: entry.path, staged: false)220 let staged = (entry.kind == .staged || entry.kind == .both || entry.kind == .renamed) ? try await repo.diff(path: entry.path, staged: true) : ""221 diff = [staged.isEmpty ? nil : "# staged\n" + staged, unstaged.isEmpty ? nil : "# unstaged\n" + unstaged].compactMap { $0 }.joined(separator: "\n")222 if diff.isEmpty { diff = "(no textual diff)" }223 }224 } catch { self.error = "\(error)" }225 }226227 func newWorktreePath(root: String) -> String? {228 guard !newBranch.isEmpty else { return nil }229 let safe = newBranch.replacingOccurrences(of: "/", with: "-")230 return (root as NSString).deletingLastPathComponent + "/" + (root as NSString).lastPathComponent + "-" + safe231 }232233 func createWorktree(root: String) async {234 guard let repo, let path = newWorktreePath(root: root) else { return }235 do {236 try await repo.addWorktree(at: path, branch: newBranch, createBranch: true)237 newBranch = ""238 worktrees = try await repo.worktrees()239 } catch { self.error = "\(error)" }240 }241242 func removeWorktree(_ wt: GitWorktree) async {243 guard let repo else { return }244 do {245 try await repo.removeCleanWorktree(at: wt.path)246 worktrees = try await repo.worktrees()247 } catch { self.error = "\(error)" }248 }249}250