|
| 1 | +using System.Text.Json; |
| 2 | +using CodeIndex.Indexer; |
| 3 | + |
| 4 | +namespace CodeIndex.Cli; |
| 5 | + |
| 6 | +internal sealed record ActiveWorkspaceState(string Name, string Root, string DbPath); |
| 7 | + |
| 8 | +internal static class ActiveWorkspace |
| 9 | +{ |
| 10 | + internal const string EnvironmentVariable = "CDIDX_ACTIVE_WORKSPACE"; |
| 11 | + |
| 12 | + internal static string StatePath |
| 13 | + { |
| 14 | + get |
| 15 | + { |
| 16 | + var configHome = Environment.GetEnvironmentVariable("XDG_CONFIG_HOME"); |
| 17 | + var root = string.IsNullOrWhiteSpace(configHome) |
| 18 | + ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".config") |
| 19 | + : configHome; |
| 20 | + return Path.Combine(root, "cdidx", "active.json"); |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + internal static ActiveWorkspaceState? Load() |
| 25 | + { |
| 26 | + var envPath = Environment.GetEnvironmentVariable(EnvironmentVariable); |
| 27 | + if (!string.IsNullOrWhiteSpace(envPath)) |
| 28 | + return new ActiveWorkspaceState("env", Path.GetDirectoryName(Path.GetFullPath(envPath)) ?? Environment.CurrentDirectory, Path.GetFullPath(envPath)); |
| 29 | + |
| 30 | + var path = StatePath; |
| 31 | + if (!File.Exists(LongPath.EnsureWindowsPrefix(path))) |
| 32 | + return null; |
| 33 | + |
| 34 | + try |
| 35 | + { |
| 36 | + using var document = JsonDocument.Parse(File.ReadAllText(LongPath.EnsureWindowsPrefix(path))); |
| 37 | + var root = document.RootElement; |
| 38 | + var name = ReadString(root, "name") ?? "default"; |
| 39 | + var workspaceRoot = ReadString(root, "root") ?? Environment.CurrentDirectory; |
| 40 | + var dbPath = ReadString(root, "db_path"); |
| 41 | + if (string.IsNullOrWhiteSpace(dbPath)) |
| 42 | + return null; |
| 43 | + return new ActiveWorkspaceState(name, Path.GetFullPath(workspaceRoot), Path.GetFullPath(dbPath)); |
| 44 | + } |
| 45 | + catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException) |
| 46 | + { |
| 47 | + return null; |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + internal static void Save(ActiveWorkspaceState state) |
| 52 | + { |
| 53 | + Directory.CreateDirectory(Path.GetDirectoryName(StatePath)!); |
| 54 | + var payload = new ActiveWorkspaceState(state.Name, Path.GetFullPath(state.Root), Path.GetFullPath(state.DbPath)); |
| 55 | + File.WriteAllText(StatePath, JsonSerializer.Serialize(payload, ProgramRunner.CreateDefaultJsonOptions())); |
| 56 | + } |
| 57 | + |
| 58 | + private static string? ReadString(JsonElement element, string name) |
| 59 | + => element.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null; |
| 60 | +} |
0 commit comments