Skip to content

A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.

Mac: commit, remotes, branch deletion, init and clone in the Git bar

gelenmedya0d90c7f89be9
diff --git a/macos/Sources/RustyFiles/FileListController.swift b/macos/Sources/RustyFiles/FileListController.swift
index cd4dbba4..e8e84c6d 100644
--- a/macos/Sources/RustyFiles/FileListController.swift
+++ b/macos/Sources/RustyFiles/FileListController.swift
@@ -2026,6 +2026,7 @@ final class FileListController: NSObject, NSTableViewDataSource, NSTableViewDele
b.add(String(localized: "Open in Terminal"), "square-terminal") { MenuActions.openInTerminal(dir) }
// Developer tools › “Open in editor”
if Editors.offered(for: dir) { b.add(String(localized: "Open in \(Editors.name)"), "code") { Editors.open([dir]) } }
+ if archive == nil, !isGathered { gitBackgroundMenu(b, dir: dir) }
}
return Self.pruned(b.done())
}
diff --git a/macos/Sources/RustyFiles/GitBar.swift b/macos/Sources/RustyFiles/GitBar.swift
index 1659e27b..e33ca557 100644
--- a/macos/Sources/RustyFiles/GitBar.swift
+++ b/macos/Sources/RustyFiles/GitBar.swift
@@ -2,7 +2,7 @@ import AppKit
/// Built-in Git (git_ui.rs, like Files): in a Git work tree the status bar shows the branch and
/// how far it is ahead of / behind its upstream; a click offers Fetch, Pull, Push and Sync and
-/// the branches to switch to, or a new one. Everything runs `/usr/bin/git` off the main thread;
+/// the branches to switch to, or a new one. Everything runs git (Settings › Git program) off the main thread;
/// network operations show in the Status Center.
enum GitRepo {
struct Info: Sendable, Equatable {
@@ -16,7 +16,7 @@ enum GitRepo {
/// Runs git in `dir`; (exit status, output, error output).
static func run(_ args: [String], in dir: URL) -> (Int32, String, String) {
let p = Process()
- p.executableURL = URL(fileURLWithPath: "/usr/bin/git")
+ p.executableURL = URL(fileURLWithPath: AppSettings.gitProgram)
p.arguments = args
p.currentDirectoryURL = dir
// never a password prompt nobody can answer
@@ -50,7 +50,7 @@ enum GitRepo {
}
static func info(_ dir: URL) -> Info? {
- guard dir.isFileURL, FileManager.default.isExecutableFile(atPath: "/usr/bin/git") else { return nil }
+ guard dir.isFileURL, FileManager.default.isExecutableFile(atPath: AppSettings.gitProgram) else { return nil }
// a quick look for a .git above, so folders outside any repository cost nothing
guard let d = repoRoot(dir) else { return nil }
let (st, out, _) = run(["status", "--porcelain=v2", "--branch", "--untracked-files=no"], in: dir)
@@ -74,6 +74,64 @@ enum GitRepo {
let (st, out, _) = run(["for-each-ref", "--format=%(refname:short)", "refs/heads"], in: root)
return st == 0 ? out.split(separator: "\n").map(String.init) : []
}
+
+ /// The remote branches (origin/x) that have no local branch of their name.
+ static func remoteBranches(_ root: URL) -> [String] {
+ let (st, out, _) = run(["for-each-ref", "--format=%(refname:short)", "refs/remotes"], in: root)
+ guard st == 0 else { return [] }
+ let local = Set(branches(root))
+ return out.split(separator: "\n").map(String.init).filter { r in
+ guard let slash = r.firstIndex(of: "/"), !r.hasSuffix("/HEAD") else { return false }
+ return !local.contains(String(r[r.index(after: slash)...]))
+ }
+ }
+
+ /// origin's address, if the repository has one.
+ static func remoteURL(_ root: URL) -> String? {
+ let (st, out, _) = run(["remote", "get-url", "origin"], in: root)
+ let t = out.trimmingCharacters(in: .whitespacesAndNewlines)
+ return st == 0 && !t.isEmpty ? t : nil
+ }
+
+ /// git check-ref-format's rules for a branch name, without running git.
+ static func isValidBranchName(_ n: String) -> Bool {
+ if n.isEmpty || n == "@" || n.hasPrefix("-") || n.hasPrefix("/") || n.hasSuffix("/") || n.hasSuffix(".lock") || n.hasSuffix(".") { return false }
+ if n.contains("..") || n.contains("@{") || n.contains("//") { return false }
+ return !n.contains { $0.isWhitespace || "~^:?*[\\".contains($0) || ($0.asciiValue.map { $0 < 32 || $0 == 127 } ?? false) }
+ }
+}
+
+/// A question with a text box (Windows' prompt with an input): the button pressed and the text.
+@MainActor
+enum GitPrompt {
+ static func ask(_ title: String, _ info: String, value: String = "", placeholder: String = "", buttons: [String]) -> (Int, String)? {
+ let alert = NSAlert()
+ alert.messageText = title
+ alert.informativeText = info
+ let field = NSTextField(frame: NSRect(x: 0, y: 0, width: 320, height: 24))
+ field.stringValue = value
+ field.placeholderString = placeholder
+ alert.accessoryView = field
+ for b in buttons { alert.addButton(withTitle: b) }
+ alert.addButton(withTitle: String(localized: "Cancel"))
+ alert.window.initialFirstResponder = field
+ let r = alert.runModal().rawValue - NSApplication.ModalResponse.alertFirstButtonReturn.rawValue
+ guard r >= 0, r < buttons.count else { return nil }
+ return (r, field.stringValue.trimmingCharacters(in: .whitespacesAndNewlines))
+ }
+
+ static func choose(_ title: String, _ info: String, buttons: [String], destructive: Int? = nil) -> Int? {
+ let alert = NSAlert()
+ alert.messageText = title
+ alert.informativeText = info
+ for (i, b) in buttons.enumerated() {
+ let button = alert.addButton(withTitle: b)
+ if i == destructive { button.hasDestructiveAction = true }
+ }
+ alert.addButton(withTitle: String(localized: "Cancel"))
+ let r = alert.runModal().rawValue - NSApplication.ModalResponse.alertFirstButtonReturn.rawValue
+ return r >= 0 && r < buttons.count ? r : nil
+ }
}
extension FileListController {
@@ -92,31 +150,161 @@ extension FileListController {
}
}
b.separator()
+ b.add(String(localized: "Commit changes…"), "git-commit-horizontal") { [weak self] in self?.commitDialog(root) }
+ let remote = GitRepo.remoteURL(root)
+ b.add(remote == nil ? String(localized: "Connect to a remote…") : String(localized: "Change the remote address…"), "link") { [weak self] in
+ self?.connectDialog(root, current: remote, branch: info.branch)
+ }
+ b.separator()
b.sub(String(localized: "Switch branch"), "git-branch") { m in
for name in GitRepo.branches(root) {
m.add(name, checked: name == info.branch) { [weak self] in
guard name != info.branch else { return }
- self?.git(["switch", name], title: String(localized: "Switch branch"), in: root, network: false)
+ self?.switchBranch(name, in: root)
}
}
}
b.add(String(localized: "New branch…"), "git-branch-plus") { [weak self] in
- let alert = NSAlert()
- alert.messageText = String(localized: "New branch")
- alert.informativeText = String(localized: "It starts from “\(info.branch)” and becomes the current one.")
- let field = NSTextField(frame: NSRect(x: 0, y: 0, width: 260, height: 24))
- alert.accessoryView = field
- alert.addButton(withTitle: String(localized: "Create"))
- alert.addButton(withTitle: String(localized: "Cancel"))
- alert.window.initialFirstResponder = field
- guard alert.runModal() == .alertFirstButtonReturn else { return }
- let n = field.stringValue.trimmingCharacters(in: .whitespaces)
- guard !n.isEmpty else { return }
+ guard let (_, n) = GitPrompt.ask(String(localized: "New branch"), String(localized: "It starts from “\(info.branch)” and becomes the current one."),
+ placeholder: String(localized: "Branch name"), buttons: [String(localized: "Create")]), !n.isEmpty else { return }
+ guard GitRepo.isValidBranchName(n) else {
+ self?.onError?(String(localized: "Not a valid branch name (no spaces, .., ~ ^ : ? * [ or \\)."))
+ return
+ }
self?.git(["switch", "-c", n], title: String(localized: "New branch"), in: root, network: false)
}
+ let others = GitRepo.branches(root).filter { $0 != info.branch }
+ if !others.isEmpty {
+ b.sub(String(localized: "Delete branch"), "trash") { m in
+ for name in others {
+ m.add(name, "git-branch") { [weak self] in self?.deleteBranch(name, in: root, force: false) }
+ }
+ }
+ }
+ let remotes = GitRepo.remoteBranches(root)
+ if !remotes.isEmpty {
+ b.sub(String(localized: "Remote branches"), "cloud") { m in
+ for r in remotes {
+ m.add(r, "git-branch") { [weak self] in
+ // a local branch of its name that follows it
+ let local = String(r[r.index(after: r.firstIndex(of: "/")!)...])
+ self?.git(["switch", "--track", "-c", local, r], title: String(localized: "Switch branch"), in: root, network: false)
+ }
+ }
+ }
+ }
return b.done()
}
+ /// Commit: every change of the repository (new files too) as one commit (git_ui.rs commit_dialog).
+ func commitDialog(_ root: URL) {
+ guard let (_, msg) = GitPrompt.ask(String(localized: "Commit changes"),
+ String(localized: "Every change in this repository, new files too, is saved as one commit."),
+ placeholder: String(localized: "For example: Updated the cover picture"), buttons: [String(localized: "Commit")]) else { return }
+ guard !msg.isEmpty else {
+ onError?(String(localized: "Say briefly what changed."))
+ return
+ }
+ git(["add", "-A"], title: String(localized: "Commit changes"), in: root, network: false) { [weak self] in
+ self?.git(["commit", "-m", msg], title: String(localized: "Commit changes"), in: root, network: false)
+ }
+ }
+
+ /// origin's address: connect a repository to one (and push), or change it.
+ func connectDialog(_ root: URL, current: String?, branch: String) {
+ let buttons = current == nil ? [String(localized: "Connect and push"), String(localized: "Only connect")] : [String(localized: "Change")]
+ guard let (choice, address) = GitPrompt.ask(
+ current == nil ? String(localized: "Connect to a remote") : String(localized: "Remote address"),
+ String(localized: "The address of an empty repository on GitHub, GitLab or another server. Make the repository there first."),
+ value: current ?? "", placeholder: "https://github.com/you/project.git", buttons: buttons) else { return }
+ guard !address.isEmpty else {
+ onError?(String(localized: "Enter the repository's address."))
+ return
+ }
+ let set = current == nil ? ["remote", "add", "origin", address] : ["remote", "set-url", "origin", address]
+ git(set, title: String(localized: "Connect to a remote"), in: root, network: false) { [weak self] in
+ if current == nil && choice == 0 {
+ self?.git(["push", "-u", "origin", branch], title: String(localized: "Push"), in: root, network: true)
+ }
+ }
+ }
+
+ /// Switches branch; with changes not committed, asks whether to take them along or drop them.
+ func switchBranch(_ name: String, in root: URL) {
+ Task.detached(priority: .userInitiated) {
+ let (st, _, err) = GitRepo.run(["switch", name], in: root)
+ await MainActor.run { [weak self] in
+ guard let self else { return }
+ if st == 0 {
+ self.onRefresh?()
+ self.refreshGit()
+ return
+ }
+ let dirty = err.contains("would be overwritten") || err.contains("local changes")
+ guard dirty, let pick = GitPrompt.choose(
+ String(localized: "There are changes not committed"),
+ String(localized: "What should happen to your changes? The branch to switch to: “\(name)”"),
+ buttons: [String(localized: "Take them along"), String(localized: "Discard the changes")], destructive: 1)
+ else {
+ if !dirty { self.onError?(err.trimmingCharacters(in: .whitespacesAndNewlines)) }
+ return
+ }
+ if pick == 1 {
+ self.git(["switch", "--discard-changes", name], title: String(localized: "Switch branch"), in: root, network: false)
+ } else {
+ self.git(["stash", "push", "--include-untracked", "-m", "rustyfiles checkout"], title: String(localized: "Switch branch"), in: root, network: false) { [weak self] in
+ self?.git(["switch", name], title: String(localized: "Switch branch"), in: root, network: false) { [weak self] in
+ self?.git(["stash", "pop"], title: String(localized: "Switch branch"), in: root, network: false)
+ }
+ }
+ }
+ }
+ }
+ }
+
+ /// Deletes a local branch; one not merged anywhere is deleted only when asked again.
+ func deleteBranch(_ name: String, in root: URL, force: Bool) {
+ let info = force
+ ? String(localized: "“\(name)” is not merged into another branch: once deleted, its commits can no longer be reached from a branch.")
+ : String(localized: "The local branch “\(name)” will be deleted. The branch on the remote stays as it is.")
+ guard GitPrompt.choose(String(localized: "Delete the branch?"), info, buttons: [force ? String(localized: "Delete anyway") : String(localized: "Delete")], destructive: 0) != nil else { return }
+ Task.detached(priority: .userInitiated) {
+ let (st, _, err) = GitRepo.run(["branch", force ? "-D" : "-d", name], in: root)
+ await MainActor.run { [weak self] in
+ if st == 0 {
+ self?.refreshGit()
+ } else if !force, err.contains("not fully merged") {
+ self?.deleteBranch(name, in: root, force: true)
+ } else {
+ self?.onError?(err.trimmingCharacters(in: .whitespacesAndNewlines))
+ }
+ }
+ }
+ }
+
+ /// The folder background's Git: start a repository here, or clone one into a new folder here.
+ func gitBackgroundMenu(_ b: MenuBuilder, dir: URL) {
+ guard FileManager.default.isExecutableFile(atPath: AppSettings.gitProgram) else { return }
+ let inRepo = GitRepo.repoRoot(dir) != nil
+ b.sub("Git", "git-branch") { m in
+ if !inRepo {
+ m.add(String(localized: "Initialize a Git repository"), "git-branch-plus") { [weak self] in
+ self?.git(["init"], title: String(localized: "Initialize a Git repository"), in: dir, network: false)
+ }
+ }
+ m.add(String(localized: "Clone a repository…"), "git-fork") { [weak self] in
+ guard let (_, address) = GitPrompt.ask(String(localized: "Clone a repository"),
+ String(localized: "The repository is cloned into a new folder inside this one."),
+ placeholder: "https://github.com/owner/project.git", buttons: [String(localized: "Clone")]) else { return }
+ guard !address.isEmpty else {
+ self?.onError?(String(localized: "Enter the repository's address."))
+ return
+ }
+ self?.git(["clone", address], title: String(localized: "Clone a repository"), in: dir, network: true)
+ }
+ }
+ }
+
/// Runs one git command; a network one shows in the Status Center. Then the list and the
/// strip are read again.
/// Reads the branch strip again for the folder shown (off the main thread).
diff --git a/macos/Sources/RustyFiles/SelfTest.swift b/macos/Sources/RustyFiles/SelfTest.swift
index 609f4481..a38a7e44 100644
--- a/macos/Sources/RustyFiles/SelfTest.swift
+++ b/macos/Sources/RustyFiles/SelfTest.swift
@@ -58,6 +58,9 @@ enum SelfTest {
.link(name: "Apps", target: "/Applications"),
], "a browser's bookmark file is read, its toolbar folder first")
check(Bookmarks.parse(Bookmarks.toHTML(marks)) == marks, "the bookmarks bar is written as a bookmark file that reads back the same")
+ check(GitRepo.isValidBranchName("feature/new-look") && !GitRepo.isValidBranchName("bad name")
+ && !GitRepo.isValidBranchName("a..b") && !GitRepo.isValidBranchName("-x") && !GitRepo.isValidBranchName("x.lock"),
+ "a branch name is checked as git does")
// 0. the Git look-up ends at the disk's root and finds a repository from inside it (issue 429)
check(GitRepo.repoRoot(URL(fileURLWithPath: "/")) == nil, "no repository above the root")
diff --git a/macos/Sources/RustyFiles/SettingsAdvanced.swift b/macos/Sources/RustyFiles/SettingsAdvanced.swift
index d752bff0..f0b31be2 100644
--- a/macos/Sources/RustyFiles/SettingsAdvanced.swift
+++ b/macos/Sources/RustyFiles/SettingsAdvanced.swift
@@ -68,6 +68,16 @@ extension AppSettings {
set { store(newValue, "rightDrag") }
}
+ /// The git program the Git bar runs (Windows' git_path): /usr/bin/git unless another is chosen.
+ nonisolated static var gitProgram: String {
+ get {
+ let v = UserDefaults.standard.string(forKey: "gitProgram") ?? ""
+ return !v.isEmpty && FileManager.default.isExecutableFile(atPath: v) ? v : "/usr/bin/git"
+ }
+ }
+
+ static func setGitProgram(_ path: String) { store(path, "gitProgram") }
+
/// Check copies: "off", "fast" (size and date), "full" (content).
static var verifyCopies: String {
get { d.string(forKey: "verifyCopies") ?? "off" }
@@ -269,6 +279,17 @@ extension SettingsContent {
if panel.runModal() == .OK, let u = panel.url { AppSettings.terminalApp = u.path }
}),
])),
+ .card(
+ title: String(localized: "Git program"), detail: AppSettings.gitProgram, icon: "git-branch",
+ control: .buttons([
+ (String(localized: "Choose…"), {
+ let panel = NSOpenPanel()
+ panel.directoryURL = URL(fileURLWithPath: "/opt/homebrew/bin")
+ panel.message = String(localized: "Choose the git program to use (for example one from Homebrew).")
+ if panel.runModal() == .OK, let u = panel.url { AppSettings.setGitProgram(u.path) }
+ }),
+ (String(localized: "Default"), { AppSettings.setGitProgram("") }),
+ ])),
.card(
title: String(localized: "“Open in editor” in the menus"), detail: nil, icon: "square-code",
control: .choice(
diff --git a/macos/Sources/RustyFiles/SettingsLayout.swift b/macos/Sources/RustyFiles/SettingsLayout.swift
index 43ca4919..ede44574 100644
--- a/macos/Sources/RustyFiles/SettingsLayout.swift
+++ b/macos/Sources/RustyFiles/SettingsLayout.swift
@@ -199,9 +199,9 @@ enum Grouping {
enum GitStatus {
/// nil when the folder is not in a Git work tree.
static func read(_ dir: URL) -> [String: String]? {
- guard GitRepo.repoRoot(dir) != nil, FileManager.default.isExecutableFile(atPath: "/usr/bin/git") else { return nil }
+ guard GitRepo.repoRoot(dir) != nil, FileManager.default.isExecutableFile(atPath: AppSettings.gitProgram) else { return nil }
let p = Process()
- p.executableURL = URL(fileURLWithPath: "/usr/bin/git")
+ p.executableURL = URL(fileURLWithPath: AppSettings.gitProgram)
p.arguments = ["status", "--porcelain=v1", "-z", "--untracked-files=normal", "--", "."]
p.currentDirectoryURL = dir
let out = Pipe()
@@ -236,7 +236,7 @@ enum GitStatus {
private static func gitPrefix(_ dir: URL) -> String {
let p = Process()
- p.executableURL = URL(fileURLWithPath: "/usr/bin/git")
+ p.executableURL = URL(fileURLWithPath: AppSettings.gitProgram)
p.arguments = ["rev-parse", "--show-prefix"]
p.currentDirectoryURL = dir
let out = Pipe()