Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use the XDG layout on Linux (including migration) #83

Merged
merged 1 commit into from
Feb 20, 2024
Merged
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
75 changes: 71 additions & 4 deletions Source/Services/State/StateService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,17 +82,58 @@ public async Task Write()

static string GeneratePath()
{
var path = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
string path;

// We use ".MQTTnetApp" instead of ".mqttMultimeter" because the app name was changed
// and the state should be still working when starting the app with the new name!
path = Path.Combine(path, ".MQTTnetApp", "State");
// This will work for Linux and macOS.
if (Environment.OSVersion.Platform == PlatformID.Unix)
{
path = GeneratePathForLinux();
}
else
{
path = GeneratePathForWindows();
}

path = Path.Combine(path, "State");

Directory.CreateDirectory(path);

return path;
}

static string GeneratePathForLinux()
{
// We follow the XDG Base Directory Specification https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
var path = Environment.GetEnvironmentVariable("XDG_CONFIG_HOME");
if (string.IsNullOrEmpty(path))
{
// From spec: If $XDG_CONFIG_HOME is either not set or empty, a default equal to $HOME/.config should be used.
path = Environment.GetEnvironmentVariable("HOME");
if (string.IsNullOrEmpty(path))
{
path = "~";
}

path = Path.Combine(path, ".config");
}

if (string.IsNullOrEmpty(path))
{
path = "~";
}

path = Path.Combine(path, "mqtt-multimeter");

Migrate(path);

return path;
}

static string GeneratePathForWindows()
{
return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "mqtt-multimeter");
}

void Load()
{
try
Expand All @@ -115,4 +156,30 @@ void Load()

_isLoaded = true;
}

static void Migrate(string destinationPath)
{
try
{
if (Directory.Exists(destinationPath))
{
// If the new directory exist we stop the migration to prevent data loss.
// This requires that the user will delete/move the old variant of the directory
// on it's own.
return;
}

// The first version of the app was named "MQTTnetApp". That is the reason for the different name.
var legacyPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".MQTTnetApp");

if (Directory.Exists(legacyPath))
{
Directory.Move(legacyPath, destinationPath);
}
}
catch (Exception exception)
{
Debug.WriteLine(exception);
}
}
}
Loading