71 lines
1.9 KiB
Swift
71 lines
1.9 KiB
Swift
import Foundation
|
|
|
|
// MARK: - Command History Manager
|
|
class HistoryManager {
|
|
static let shared = HistoryManager()
|
|
private var history: [String] = []
|
|
private let maxHistory = 1000
|
|
|
|
init() {
|
|
loadHistory()
|
|
}
|
|
|
|
func addCommand(_ command: String) {
|
|
let trimmed = command.trimmingCharacters(in: .whitespacesAndNewlines)
|
|
guard !trimmed.isEmpty else { return }
|
|
|
|
// Don't add duplicate consecutive commands
|
|
if history.last != trimmed {
|
|
history.append(trimmed)
|
|
}
|
|
|
|
if history.count > maxHistory {
|
|
history.removeFirst()
|
|
}
|
|
saveHistory()
|
|
}
|
|
|
|
func searchHistory(_ query: String) -> [String] {
|
|
if query.isEmpty {
|
|
return Array(history.reversed().prefix(50))
|
|
}
|
|
|
|
// Fuzzy search - match commands containing the query
|
|
let results = history.reversed().filter { command in
|
|
command.localizedCaseInsensitiveContains(query)
|
|
}
|
|
|
|
return Array(results.prefix(50))
|
|
}
|
|
|
|
func getRecentCommands(_ count: Int = 10) -> [String] {
|
|
return Array(history.reversed().prefix(count))
|
|
}
|
|
|
|
func getSuggestion(for partial: String) -> String? {
|
|
guard !partial.isEmpty else { return nil }
|
|
|
|
// Find the most recent command that starts with the partial input
|
|
return history.reversed().first { command in
|
|
command.hasPrefix(partial) && command != partial
|
|
}
|
|
}
|
|
|
|
func getAllHistory() -> [String] {
|
|
return history
|
|
}
|
|
|
|
func clearHistory() {
|
|
history.removeAll()
|
|
saveHistory()
|
|
}
|
|
|
|
private func saveHistory() {
|
|
UserDefaults.standard.set(history, forKey: "terminal_history")
|
|
}
|
|
|
|
private func loadHistory() {
|
|
history = UserDefaults.standard.stringArray(forKey: "terminal_history") ?? []
|
|
}
|
|
}
|