Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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_
Expand Down
28 changes: 26 additions & 2 deletions src/ReadLine/ReadLine.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using Internal.ReadLine.Abstractions;

using System.Collections.Generic;
using System.IO;

namespace System
{
Expand Down Expand Up @@ -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;
Expand All @@ -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<string>(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}");
}
}
}
}
20 changes: 20 additions & 0 deletions test/ReadLine.Tests/ReadLineTests.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.IO;
using System.Linq;
using Xunit;

Expand Down Expand Up @@ -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()
{
Expand Down