| 1 | using CascadeIDE.Features.Workspace; |
| 2 | using CascadeIDE.Models; |
| 3 | |
| 4 | namespace CascadeIDE.Services; |
| 5 | |
| 6 | internal static class WorkspaceFeatureResolver |
| 7 | { |
| 8 | public static RepositoryFeatureToml? ResolveFeatureFromWorkspaceToml( |
| 9 | RepositoryWorkspaceToml? workspaceToml, |
| 10 | string repositoryRootDirectory, |
| 11 | string absoluteFilePath) |
| 12 | { |
| 13 | var features = workspaceToml?.Workspace?.Features?.Feature; |
| 14 | if (features is not { Count: > 0 }) |
| 15 | return null; |
| 16 | |
| 17 | var rel = TryComputeRepoRelativePath(repositoryRootDirectory, absoluteFilePath); |
| 18 | if (rel is null) |
| 19 | return null; |
| 20 | |
| 21 | var normalizedRel = NormalizePath(rel); |
| 22 | |
| 23 | RepositoryFeatureToml? best = null; |
| 24 | var bestLen = -1; |
| 25 | |
| 26 | foreach (var f in features) |
| 27 | { |
| 28 | if (f.Paths is not { Count: > 0 }) |
| 29 | continue; |
| 30 | |
| 31 | foreach (var raw in f.Paths) |
| 32 | { |
| 33 | var p = NormalizePath(raw); |
| 34 | if (p.Length == 0) |
| 35 | continue; |
| 36 | |
| 37 | if (!normalizedRel.StartsWith(p, StringComparison.OrdinalIgnoreCase)) |
| 38 | continue; |
| 39 | |
| 40 | if (p.Length > bestLen) |
| 41 | { |
| 42 | best = f; |
| 43 | bestLen = p.Length; |
| 44 | } |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | return best; |
| 49 | } |
| 50 | |
| 51 | public static string BuildFeatureLine(RepositoryFeatureToml? feature) |
| 52 | { |
| 53 | if (feature is null) |
| 54 | return ""; |
| 55 | |
| 56 | var title = (feature.Title ?? "").Trim(); |
| 57 | var id = (feature.Id ?? "").Trim(); |
| 58 | if (title.Length > 0 && id.Length > 0) |
| 59 | return $"Feature: {title} ({id})"; |
| 60 | if (title.Length > 0) |
| 61 | return $"Feature: {title}"; |
| 62 | if (id.Length > 0) |
| 63 | return $"Feature: {id}"; |
| 64 | return ""; |
| 65 | } |
| 66 | |
| 67 | private static string NormalizePath(string raw) => |
| 68 | (raw ?? "") |
| 69 | .Trim() |
| 70 | .Replace('\\', '/'); |
| 71 | |
| 72 | private static string? TryComputeRepoRelativePath(string repositoryRootDirectory, string absoluteFilePath) |
| 73 | { |
| 74 | try |
| 75 | { |
| 76 | var root = CanonicalFilePath.Normalize(repositoryRootDirectory.Trim()); |
| 77 | var abs = CanonicalFilePath.Normalize(absoluteFilePath.Trim()); |
| 78 | if (!abs.StartsWith(root, StringComparison.OrdinalIgnoreCase)) |
| 79 | return null; |
| 80 | |
| 81 | var rel = abs[root.Length..].TrimStart('\\', '/'); |
| 82 | return rel; |
| 83 | } |
| 84 | catch |
| 85 | { |
| 86 | return null; |
| 87 | } |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | |