|
| 1 | +import Dependencies |
| 2 | +import Foundation |
| 3 | +import Terminal |
| 4 | +import Preferences |
| 5 | + |
| 6 | +public struct CheckIfGitIgnoredDependencyKey: DependencyKey { |
| 7 | + public static var liveValue: GitIgnoredChecker = DefaultGitIgnoredChecker() |
| 8 | +} |
| 9 | + |
| 10 | +public extension DependencyValues { |
| 11 | + var gitIgnoredChecker: GitIgnoredChecker { |
| 12 | + get { self[CheckIfGitIgnoredDependencyKey.self] } |
| 13 | + set { self[CheckIfGitIgnoredDependencyKey.self] = newValue } |
| 14 | + } |
| 15 | +} |
| 16 | + |
| 17 | +public protocol GitIgnoredChecker { |
| 18 | + func checkIfGitIgnored(fileURL: URL) async -> Bool |
| 19 | +} |
| 20 | + |
| 21 | +extension GitIgnoredChecker { |
| 22 | + func checkIfGitIgnored(filePath: String) async -> Bool { |
| 23 | + await checkIfGitIgnored(fileURL: URL(fileURLWithPath: filePath)) |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +struct DefaultGitIgnoredChecker: GitIgnoredChecker { |
| 28 | + func checkIfGitIgnored(fileURL: URL) async -> Bool { |
| 29 | + if UserDefaults.shared.value(for: \.disableGitIgnoreCheck) { return false } |
| 30 | + let terminal = Terminal() |
| 31 | + guard let gitFolderURL = gitFolderURL(forFileURL: fileURL) else { |
| 32 | + return false |
| 33 | + } |
| 34 | + do { |
| 35 | + _ = try await terminal.runCommand( |
| 36 | + "/bin/bash", |
| 37 | + arguments: ["-c", "check-ignore \"filePath\""], |
| 38 | + currentDirectoryPath: gitFolderURL.path, |
| 39 | + environment: [:] |
| 40 | + ) |
| 41 | + return true |
| 42 | + } catch { |
| 43 | + return false |
| 44 | + } |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +func gitFolderURL(forFileURL fileURL: URL) -> URL? { |
| 49 | + var currentURL = fileURL |
| 50 | + let fileManager = FileManager.default |
| 51 | + while currentURL.path != "/" { |
| 52 | + let gitFolderURL = currentURL.appendingPathComponent(".git") |
| 53 | + if fileManager.fileExists(atPath: gitFolderURL.path) { |
| 54 | + return gitFolderURL |
| 55 | + } |
| 56 | + currentURL = currentURL.deletingLastPathComponent() |
| 57 | + } |
| 58 | + return nil |
| 59 | +} |
| 60 | + |
0 commit comments