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.

18.4 KB
Raw Blame
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 git (Settings › Git program) off the main thread;
/// network operations show in the Status Center.
enum GitRepo {
    struct Info: Sendable, Equatable {
        let root: URL
        let branch: String
        let ahead: Int
        let behind: Int
        let hasUpstream: Bool
    }

    /// 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: AppSettings.gitProgram)
        p.arguments = args
        p.currentDirectoryURL = dir
        // never a password prompt nobody can answer
        p.environment = ProcessInfo.processInfo.environment.merging(["GIT_TERMINAL_PROMPT": "0"]) { $1 }
        let out = Pipe(), err = Pipe()
        p.standardOutput = out
        p.standardError = err
        guard (try? p.run()) != nil else { return (-1, "", "git could not be started") }
        let o = out.fileHandleForReading.readDataToEndOfFile()
        let e = err.fileHandleForReading.readDataToEndOfFile()
        p.waitUntilExit()
        return (p.terminationStatus, String(decoding: o, as: UTF8.self), String(decoding: e, as: UTF8.self))
    }

    /// The repository `dir` is in, or nil.
    /// The folder holding the .git that `dir` is in, if any. By path, from the standardized
    /// folder up to "/" and never more than 128 steps: a URL above the root can come back as
    /// "/.." and then "/../..", and the walk went on for ever, a longer URL each time (issue
    /// 429: tens of GB while "/" was shown).
    nonisolated static func repoRoot(_ dir: URL) -> URL? {
        var path = dir.standardizedFileURL.path
        for _ in 0..<128 {
            if FileManager.default.fileExists(atPath: (path as NSString).appendingPathComponent(".git")) {
                return URL(fileURLWithPath: path, isDirectory: true)
            }
            let up = (path as NSString).deletingLastPathComponent
            if up.isEmpty || up == path || path == "/" { return nil }
            path = up
        }
        return nil
    }

    static func info(_ dir: URL) -> Info? {
        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)
        guard st == 0 else { return nil }
        var branch = "", ahead = 0, behind = 0, upstream = false
        for line in out.split(separator: "\n") {
            if line.hasPrefix("# branch.head ") { branch = String(line.dropFirst("# branch.head ".count)) }
            if line.hasPrefix("# branch.upstream ") { upstream = true }
            if line.hasPrefix("# branch.ab ") {
                for part in line.dropFirst("# branch.ab ".count).split(separator: " ") {
                    if part.hasPrefix("+") { ahead = Int(part.dropFirst()) ?? 0 }
                    if part.hasPrefix("-") { behind = Int(part.dropFirst()) ?? 0 }
                }
            }
        }
        if branch == "(detached)" { branch = String(localized: "detached") }
        return Info(root: d, branch: branch, ahead: ahead, behind: behind, hasUpstream: upstream)
    }

    static func branches(_ root: URL) -> [String] {
        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 {
    /// The branch strip's menu (git_ui.rs): sync, then the branches.
    func gitMenu(_ info: GitRepo.Info) -> NSMenu {
        let b = MenuBuilder()
        let root = info.root
        b.add(String(localized: "Fetch"), "refresh-cw") { [weak self] in self?.git(["fetch", "--prune"], title: String(localized: "Fetch"), in: root, network: true) }
        b.add(String(localized: "Pull"), "arrow-down-to-line", enabled: info.hasUpstream) { [weak self] in self?.git(["pull", "--ff-only"], title: String(localized: "Pull"), in: root, network: true) }
        b.add(String(localized: "Push"), "arrow-up-from-line") { [weak self] in
            self?.git(info.hasUpstream ? ["push"] : ["push", "-u", "origin", info.branch], title: String(localized: "Push"), in: root, network: true)
        }
        b.add(String(localized: "Sync"), "refresh-ccw", enabled: info.hasUpstream) { [weak self] in
            self?.git(["pull", "--ff-only"], title: String(localized: "Sync"), in: root, network: true) {
                self?.git(["push"], title: String(localized: "Sync"), in: root, network: true)
            }
        }
        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?.switchBranch(name, in: root)
                }
            }
        }
        b.add(String(localized: "New branch…"), "git-branch-plus") { [weak self] in
            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).
    func refreshGit() {
        guard let dir = url, dir.isFileURL, archive == nil else {
            status.git = nil
            return
        }
        Task.detached(priority: .utility) {
            let info = GitRepo.info(dir)
            await MainActor.run { [weak self] in
                guard let self, self.url == dir else { return }
                self.status.git = info
            }
        }
    }

    func git(_ args: [String], title: String, in root: URL, network: Bool, then: (() -> Void)? = nil) {
        let job = network ? StatusCenter.shared.add(title: "Git: \(title) · \(root.lastPathComponent)", folder: nil, cancel: nil) : nil
        Task.detached(priority: .userInitiated) {
            let (st, out, err) = GitRepo.run(args, in: root)
            await MainActor.run { [weak self] in
                let text = (err.isEmpty ? out : err).trimmingCharacters(in: .whitespacesAndNewlines)
                if let job { st == 0 ? job.succeed() : job.fail(text) }
                if st != 0 {
                    self?.onError?(text.isEmpty ? String(localized: "git \(args.first ?? "") failed") : text)
                } else {
                    then?()
                }
                self?.onRefresh?()
                self?.refreshGit()
            }
        }
    }
}