using System.Collections; using System.Text.Json; namespace Repository; public class Repository : IRepository { private const string _appName = "Keychain"; private readonly string _filePath; private List? _cache; private bool _cacheDirty = true; public Repository(string fileName) { var xdgDataHome = Environment.GetEnvironmentVariable("XDG_DATA_HOME"); string dataHome; if (!string.IsNullOrEmpty(xdgDataHome)) { dataHome = Path.Combine(xdgDataHome, _appName); } else { dataHome = Path.Combine( Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".local", "share"), _appName ); } _filePath = Path.Combine(dataHome, fileName); } public IEnumerable ReadAll() { if (!_cacheDirty && _cache != null) return _cache; if (!File.Exists(_filePath)) { _cache = new List(); } else { var json = File.ReadAllText(_filePath); _cache = JsonSerializer.Deserialize>(json) ?? new List(); } _cacheDirty = false; return _cache; } public object Get(uint id) { } public void WriteAll(IEnumerable items) { var json = JsonSerializer.Serialize(items); var directory = Path.GetDirectoryName(_filePath); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory!); } File.WriteAllText(_filePath, json); _cache = (List)items; _cacheDirty = false; } }