diff --git a/README.md b/README.md index 5f01dd1..c260eb0 100644 --- a/README.md +++ b/README.md @@ -71,14 +71,20 @@ _Note: The `(prompt>)` is optional_ // Get command history ReadLine.GetHistory(); -// Add command to history -ReadLine.AddHistory("dotnet run"); +// Add commands to history +ReadLine.AddHistory("dotnet run", "git init"); -// Clear history +// Clear all in-memory history ReadLine.ClearHistory(); -// Disable history -ReadLine.HistoryEnabled = false; +// Enable or disable history recording +ReadLine.HistoryEnabled = true; + +// Load history from file +ReadLine.LoadHistory("history.txt"); + +// Save history to file +ReadLine.SaveHistory("history.txt"); ``` _Note: History information is persisted for an entire application session. Also, calls to `ReadLine.Read()` automatically adds the console input to history_ diff --git a/src/ReadLine/ReadLine.cs b/src/ReadLine/ReadLine.cs index 157cf66..5e9b2ff 100755 --- a/src/ReadLine/ReadLine.cs +++ b/src/ReadLine/ReadLine.cs @@ -2,6 +2,7 @@ using Internal.ReadLine.Abstractions; using System.Collections.Generic; +using System.IO; namespace System { @@ -32,8 +33,11 @@ public static string Read(string prompt = "", string @default = "") } else { - if (HistoryEnabled) - _history.Add(text); + if (HistoryEnabled && !string.IsNullOrWhiteSpace(text)) + { + if (_history.Count == 0 || _history[_history.Count - 1] != text) + _history.Add(text); + } } return text; @@ -58,5 +62,25 @@ private static string GetText(KeyHandler keyHandler) Console.WriteLine(); return keyHandler.Text; } + + public static void LoadHistory(string filePath) + { + if (!File.Exists(filePath)) return; + + var lines = File.ReadAllLines(filePath); + _history = new List(lines); + } + + public static void SaveHistory(string filePath) + { + try + { + File.WriteAllLines(filePath, _history); + } + catch (Exception ex) + { + Console.Error.WriteLine($"[ReadLine] Failed to save history: {ex.Message}"); + } + } } } diff --git a/test/ReadLine.Tests/ReadLineTests.cs b/test/ReadLine.Tests/ReadLineTests.cs index 7debc6a..87a8d22 100755 --- a/test/ReadLine.Tests/ReadLineTests.cs +++ b/test/ReadLine.Tests/ReadLineTests.cs @@ -1,4 +1,5 @@ using System; +using System.IO; using System.Linq; using Xunit; @@ -35,6 +36,25 @@ public void TestGetCorrectHistory() Assert.Equal("dotnet run", GetHistory()[1]); Assert.Equal("git init", GetHistory()[2]); } + + [Fact] + public void TestLoadAndSaveHistory() + { + string path = "test_history.txt"; + ClearHistory(); + AddHistory("foo", "bar"); + SaveHistory(path); + + ClearHistory(); + Assert.Empty(GetHistory()); + + LoadHistory(path); + Assert.Equal(2, GetHistory().Count); + Assert.Equal("foo", GetHistory()[0]); + Assert.Equal("bar", GetHistory()[1]); + + File.Delete(path); + } public void Dispose() {