use inheritance for ISavable and JsonStrorage

This commit is contained in:
Jeremy Wu 2021-06-21 21:04:19 +10:00
parent 7319133ae8
commit 6ec151a8ab
3 changed files with 5 additions and 98 deletions

View file

@ -52,10 +52,6 @@ namespace Flow.Launcher.Core.Plugin
savable?.Save();
}
// Everything plugin
var savableEverything = AllPlugins.FirstOrDefault(x => x.Metadata.ID == "D2D2C23B084D411DB66FE0C79D6C2A6E")?.Plugin as ISavable;
savableEverything?.Save();
API.SavePluginSettings();
}

View file

@ -1,11 +1,10 @@
namespace Flow.Launcher.Infrastructure.Storage
using Flow.Launcher.Plugin;
namespace Flow.Launcher.Infrastructure.Storage
{
/// <summary>
/// Save plugin settings/cache,
/// todo should be merged into a abstract class intead of seperate interface
/// </summary>
public interface ISavable
{
void Save();
}
public interface ISavable : ISettingsSavable { }
}

View file

@ -88,93 +88,5 @@ namespace Flow.Launcher.Infrastructure.Storage
}
}
public class JsonStrorage<T> where T : new()
{
private readonly JsonSerializerOptions _serializerSettings;
private T _data;
// need a new directory name
public const string DirectoryName = "Settings";
public const string FileSuffix = ".json";
public string FilePath { get; set; }
public string DirectoryPath { get; set; }
internal JsonStrorage()
{
// use property initialization instead of DefaultValueAttribute
// easier and flexible for default value of object
_serializerSettings = new JsonSerializerOptions
{
IgnoreNullValues = false
};
}
public T Load()
{
if (File.Exists(FilePath))
{
var searlized = File.ReadAllText(FilePath);
if (!string.IsNullOrWhiteSpace(searlized))
{
Deserialize(searlized);
}
else
{
LoadDefault();
}
}
else
{
LoadDefault();
}
return _data.NonNull();
}
private void Deserialize(string searlized)
{
try
{
_data = JsonSerializer.Deserialize<T>(searlized, _serializerSettings);
}
catch (JsonException e)
{
LoadDefault();
Log.Exception($"|JsonStrorage.Deserialize|Deserialize error for json <{FilePath}>", e);
}
if (_data == null)
{
LoadDefault();
}
}
private void LoadDefault()
{
if (File.Exists(FilePath))
{
BackupOriginFile();
}
_data = new T();
Save();
}
private void BackupOriginFile()
{
var timestamp = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-fffffff", CultureInfo.CurrentUICulture);
var directory = Path.GetDirectoryName(FilePath).NonNull();
var originName = Path.GetFileNameWithoutExtension(FilePath);
var backupName = $"{originName}-{timestamp}{FileSuffix}";
var backupPath = Path.Combine(directory, backupName);
File.Copy(FilePath, backupPath, true);
// todo give user notification for the backup process
}
public void Save()
{
string serialized = JsonSerializer.Serialize(_data, new JsonSerializerOptions() { WriteIndented = true });
File.WriteAllText(FilePath, serialized);
}
}
public class JsonStrorage<T> : JsonStorage<T> where T : new() { }
}