Add config import and export

This commit is contained in:
Ray Berezowski
2026-06-02 21:28:59 -04:00
parent 835ce2159b
commit b0fc1b4679
3 changed files with 153 additions and 8 deletions

View File

@@ -61,18 +61,35 @@ public static class ConfigService
return backupPath;
}
public static LauncherConfig Restore(string sourcePath)
public static string ExportTo(string destinationPath, LauncherConfig config)
{
if (!File.Exists(sourcePath))
if (string.IsNullOrWhiteSpace(destinationPath))
{
throw new FileNotFoundException("The selected config file was not found.", sourcePath);
throw new ArgumentException("Choose a destination path for the exported config.", nameof(destinationPath));
}
string json = File.ReadAllText(sourcePath);
LauncherConfig config = JsonSerializer.Deserialize<LauncherConfig>(json, JsonOptions)
?? throw new InvalidDataException("The selected config file could not be read.");
string? destinationFolder = Path.GetDirectoryName(destinationPath);
if (!string.IsNullOrWhiteSpace(destinationFolder))
{
Directory.CreateDirectory(destinationFolder);
}
NormalizeDisplayModes(config);
string json = JsonSerializer.Serialize(config, JsonOptions);
File.WriteAllText(destinationPath, json);
return destinationPath;
}
public static LauncherConfig ImportFrom(string sourcePath)
{
LauncherConfig config = ReadConfigFile(sourcePath);
Save(config);
return config;
}
public static LauncherConfig Restore(string sourcePath)
{
LauncherConfig config = ReadConfigFile(sourcePath);
Save(config);
return config;
}
@@ -135,6 +152,61 @@ public static class ConfigService
return config;
}
private static LauncherConfig ReadConfigFile(string sourcePath)
{
if (!File.Exists(sourcePath))
{
throw new FileNotFoundException("The selected config file was not found.", sourcePath);
}
string json = File.ReadAllText(sourcePath);
LauncherConfig config;
try
{
config = JsonSerializer.Deserialize<LauncherConfig>(json, JsonOptions)
?? throw new InvalidDataException("The selected config file could not be read.");
}
catch (JsonException ex)
{
throw new InvalidDataException("The selected file is not a valid Taskbar Launcher config.", ex);
}
ValidateConfig(config);
NormalizeDisplayModes(config);
return config;
}
private static void ValidateConfig(LauncherConfig config)
{
if (config.Items is null)
{
throw new InvalidDataException("The selected config is missing launcher items.");
}
foreach (LauncherItem item in config.Items)
{
ValidateItem(item);
}
}
private static void ValidateItem(LauncherItem item)
{
if (item.Children is null)
{
throw new InvalidDataException($"The item '{item.Title}' has an invalid children list.");
}
if (!Enum.IsDefined(item.Type))
{
throw new InvalidDataException($"The item '{item.Title}' has an invalid type.");
}
foreach (LauncherItem child in item.Children)
{
ValidateItem(child);
}
}
private static void NormalizeDisplayModes(LauncherConfig config)
{
foreach (LauncherItem item in config.Items)