-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathModelHistoryStore.cs
More file actions
96 lines (83 loc) · 2.51 KB
/
ModelHistoryStore.cs
File metadata and controls
96 lines (83 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
using System.IO;
using System.Text.Json;
namespace WindowTranslator.Stores;
/// <summary>
/// モデル名の利用履歴を管理するストアのインターフェースです。
/// </summary>
public interface IModelHistoryStore
{
/// <summary>
/// 指定キーの履歴を取得します。
/// </summary>
IReadOnlyList<string> GetHistory(string key);
/// <summary>
/// 指定キーに値を追加します。既存の値がある場合は先頭に移動します。
/// </summary>
void AddHistory(string key, string value);
/// <summary>
/// 履歴をファイルに保存します。
/// </summary>
void Save();
}
/// <inheritdoc cref="IModelHistoryStore"/>
public class ModelHistoryStore : IModelHistoryStore
{
private static readonly string historyPath = Path.Combine(PathUtility.UserDir, "model-history.json");
private const int MaxHistoryCount = 10;
private readonly Dictionary<string, List<string>> history;
/// <summary>
/// <see cref="ModelHistoryStore"/> の新しいインスタンスを初期化します。
/// </summary>
public ModelHistoryStore()
{
if (File.Exists(historyPath))
{
try
{
using var fs = File.OpenRead(historyPath);
this.history = JsonSerializer.Deserialize<Dictionary<string, List<string>>>(fs) ?? [];
}
catch (JsonException)
{
this.history = [];
}
catch (IOException)
{
this.history = [];
}
}
else
{
this.history = [];
}
}
/// <inheritdoc/>
public IReadOnlyList<string> GetHistory(string key)
=> this.history.TryGetValue(key, out var list) ? list.AsReadOnly() : [];
/// <inheritdoc/>
public void AddHistory(string key, string value)
{
if (string.IsNullOrWhiteSpace(value))
{
return;
}
if (!this.history.TryGetValue(key, out var list))
{
list = [];
this.history[key] = list;
}
list.Remove(value);
list.Insert(0, value);
if (list.Count > MaxHistoryCount)
{
list.RemoveRange(MaxHistoryCount, list.Count - MaxHistoryCount);
}
}
/// <inheritdoc/>
public void Save()
{
Directory.CreateDirectory(PathUtility.UserDir);
using var fs = File.Create(historyPath);
JsonSerializer.Serialize(fs, this.history);
}
}