diff --git a/CHANGELOG.md b/CHANGELOG.md index 08d8265..c8c0eed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,21 @@ # Changelog +## 0.13.0 — 2026-11-13 + +Several projects of one organization in one connection. + +- Fixed: adding a second project of the same Azure DevOps (login, the settings window, `adolens login`) replaced the + first one, without a word - the connection is named after the organization. Another project is now added to the + connection; the default stays. +- A connection holds a default project and others (`moreProjects`): `adolens config --add-project / --remove-project`, + `--project` makes one the default (the previous default stays among the others), the settings window has a field + "Other projects of this organization", and `adolens connections`, `ado_settings` show them. +- Without `project=`, `ado_search` (work items, wiki, code), `ado_file`, `ado_pr` (lists, merged), `ado_pipeline` + (builds, deployments, artifacts, runs), `ado_label` and finding the environments look in every project of the + connection: lists under each project's name, a build, file or pipeline in the first project that has it. Creating + work items, sprints, boards and backlogs use the default project unless one is named; Claude gets the list of + projects in its instructions. + ## 0.12.2 — 2026-11-04 - Fixed: newer Claude Desktop versions keep their configuration in `%LOCALAPPDATA%\Claude-Data\\` and leave only a diff --git a/README.md b/README.md index 26c8c1a..1729d13 100644 --- a/README.md +++ b/README.md @@ -171,6 +171,13 @@ when a project has more than one active repository, and leave out work branches adolens config --connection contoso --env "ERP:dev=DEV (sbx01)" --env "ERP:staging=UAT (sbx03)" --env "ERP:master=PROD" --env "Common:master=PROD" ``` +**Several projects of one organization.** A connection holds a default project and as many others as needed (work +items and code in both, e.g. one for X++ and one for C# applications): signing in again with another project of the same +organization adds it, `adolens config --connection contoso --add-project Apps` too, and the settings window has a field +for them. Search, files, pull requests, pipelines and finding the environments look in all of them, each answer under its +project's name; creating work items and sprints, boards and backlogs use the default unless Claude passes `project=` +(it gets the list of projects). + **Code in another project.** When the work items live in one project and the code, pull requests and pipelines in another, set it once: `adolens config --connection contoso --code-project ERP` (or ask Claude: `ado_settings codeProject=ERP`). `ado_file`, `ado_search` (code), `ado_pr`, `ado_pipeline` and `ado_label` then look there. diff --git a/README.pl.md b/README.pl.md index c55e981..36cd9e8 100644 --- a/README.pl.md +++ b/README.pl.md @@ -172,6 +172,13 @@ więcej niż jedno aktywne repozytorium, i pomijają gałęzie robocze (`000000_ adolens config --connection contoso --env "ERP:dev=DEV (sbx01)" --env "ERP:staging=UAT (sbx03)" --env "ERP:master=PROD" --env "Common:master=PROD" ``` +**Kilka projektów jednej organizacji.** Połączenie ma projekt domyślny i dowolnie wiele innych (work itemy i kod w +obu, np. jeden na X++, drugi na aplikacje w C#): ponowne zalogowanie z innym projektem tej samej organizacji dopisuje go, +tak samo `adolens config --connection contoso --add-project Aplikacje`, a okno ustawień ma na nie pole. Wyszukiwanie, +pliki, pull requesty, pipeline'y i wykrywanie środowisk patrzą we wszystkie, każda odpowiedź pod nazwą swojego projektu; +tworzenie work itemów oraz sprinty, tablice i backlogi używają domyślnego, chyba że Claude poda `project=` (dostaje listę +projektów). + **Kod w innym projekcie.** Gdy work itemy są w jednym projekcie, a kod, pull requesty i pipeline'y w innym, ustaw to raz: `adolens config --connection contoso --code-project ERP` (albo poproś Claude'a: `ado_settings codeProject=ERP`). Wtedy `ado_file`, `ado_search` (kod), `ado_pr`, `ado_pipeline` i `ado_label` szukają tam. diff --git a/src/AdoLens/AdoLens.csproj b/src/AdoLens/AdoLens.csproj index 991eceb..69f8358 100644 --- a/src/AdoLens/AdoLens.csproj +++ b/src/AdoLens/AdoLens.csproj @@ -25,7 +25,7 @@ ADO Lens for Azure DevOps Azure DevOps (work items, boards, wiki, Git and TFVC, pipelines) served to AI assistants over MCP Copyright © 2026 WillowDev - 0.12.2 + 0.13.0 diff --git a/src/AdoLens/Cli.cs b/src/AdoLens/Cli.cs index 11c5e50..2fc7406 100644 --- a/src/AdoLens/Cli.cs +++ b/src/AdoLens/Cli.cs @@ -27,6 +27,7 @@ logout remove the stored PAT of a connection --connection connections list the connections config show or change settings --connection --project --team (defaults of a connection) + --add-project / --remove-project (more projects of the organization; --project sets the default) --code-project (code, pull requests and pipelines in another project; "" clears) --default-connection --mode po|dev|full --usage-log true|false --show-tokens true|false --tool-loading auto|demand|all --add-toolset --remove-toolset --confirm-above @@ -172,7 +173,10 @@ public async Task LoginAsync() project = PickProject(projects); if (project is not null && projects.Count > 0 && !projects.Contains(project, StringComparer.OrdinalIgnoreCase)) Console.WriteLine($"note: project '{project}' is not visible with this PAT"); - conn.Project = project is null ? null : projects.FirstOrDefault(p => p.Equals(project, StringComparison.OrdinalIgnoreCase)) ?? project; + project = project is null ? null : projects.FirstOrDefault(p => p.Equals(project, StringComparison.OrdinalIgnoreCase)) ?? project; + // Another project of the same organization is added to the connection, never put in place of its default. + var added = project is not null && stored?.Project is { } before && !before.Equals(project, StringComparison.OrdinalIgnoreCase); + if (project is not null) conn.AddProject(project); if (cl.Opt("team") is { } team) conn.Team = NullIfEmpty(team); CredentialStore.Write(name, org, pat); @@ -183,7 +187,10 @@ public async Task LoginAsync() Console.WriteLine($"connection '{name}' saved{(settings.DefaultConnection == name ? " (default)" : "")}: {SettingsPath}"); Console.WriteLine($"PAT saved in Windows Credential Manager: {CredentialStore.TargetFor(name)}"); - if (conn.Project is { } p) + if (added) + Console.WriteLine($"project {project} added to connection '{name}' (projects: {string.Join(", ", conn.AllProjects())}; default {conn.Project} - " + + $"change with 'adolens config --connection {name} --project {project}')"); + else if (conn.Project is { } p) Console.WriteLine($"default project: {p}"); return 0; } @@ -245,7 +252,7 @@ public int Connections() { var pat = CredentialStore.Read(name) is not null ? "PAT stored" : "no stored PAT"; Console.WriteLine($"{(name.Equals(settings.DefaultConnection, StringComparison.OrdinalIgnoreCase) ? "*" : " ")} {name,-16} " + - $"https://dev.azure.com/{c.Organization} project {c.Project ?? "-"}{(c.CodeProject is { } cp ? $" code in {cp}" : "")} team {c.Team ?? "-"} ({pat})" + + $"https://dev.azure.com/{c.Organization} project {c.Project ?? "-"}{(c.MoreProjects.Count > 0 ? $" (+ {string.Join(", ", c.MoreProjects)})" : "")}{(c.CodeProject is { } cp ? $" code in {cp}" : "")} team {c.Team ?? "-"} ({pat})" + (c.Environments.Count > 0 ? $"\n {"",-16} environments: {string.Join(", ", c.Environments.Select(e => $"{e.Key} = {e.Value}"))}" : "") + (c.LabelLanguages.Count > 0 ? $"\n {"",-16} label languages: {string.Join(", ", c.LabelLanguages)}" : "")); } @@ -262,7 +269,9 @@ public int Config() { if (!settings.Connections.TryGetValue(name, out var conn)) throw new ArgumentException($"no connection named '{name}' - add it with 'adolens login --connection {name}'"); - if (cl.Opt("project") is { } p) { conn.Project = NullIfEmpty(p); changed = true; } + if (cl.Opt("project") is { } p) { conn.SetDefaultProject(p); changed = true; } + while (cl.Opt("add-project") is { } ap) { conn.AddProject(ap); changed = true; } + while (cl.Opt("remove-project") is { } rp) { conn.MoreProjects.RemoveAll(x => x.Equals(rp.Trim(), StringComparison.OrdinalIgnoreCase)); changed = true; } if (cl.Opt("team") is { } t) { conn.Team = NullIfEmpty(t); changed = true; } if (cl.Opt("code-project") is { } cp) { conn.CodeProject = NullIfEmpty(cp); changed = true; } while (cl.Opt("env") is { } e) diff --git a/src/AdoLens/CommandLine.cs b/src/AdoLens/CommandLine.cs index 2650adb..781a23b 100644 --- a/src/AdoLens/CommandLine.cs +++ b/src/AdoLens/CommandLine.cs @@ -23,7 +23,7 @@ public sealed partial class CommandLine ["pr"] = ["connection=", "project=", "repo=", "list=", "detail=", "merged=", "since=", "top="], ["pipeline"] = ["connection=", "project=", "definition=", "branch=", "top=", "detail=", "artifacts", "artifact=", "part=", "save", "to=", "deployments", "stage="], ["changes"] = ["connection=", "repo=", "file=", "detail="], - ["config"] = ["env=", "remove-env=", "connection=", "default-connection=", "project=", "code-project=", "team=", "mode=", "usage-log=", "add-toolset=", "remove-toolset=", "confirm-above=", "show-tokens=", "tool-loading=", "language=", "label-languages=", "download-dir="], + ["config"] = ["env=", "remove-env=", "connection=", "default-connection=", "project=", "add-project=", "remove-project=", "code-project=", "team=", "mode=", "usage-log=", "add-toolset=", "remove-toolset=", "confirm-above=", "show-tokens=", "tool-loading=", "language=", "label-languages=", "download-dir="], ["item"] = ["connection=", "include=", "detail="], ["query"] = ["connection=", "project=", "wiql=", "query=", "top="], ["create"] = ["connection=", "project=", "type=", "title=", "description=", "criteria=", "assign=", "parent=", "iteration=", "area=", "tags=", "state=", "field=", "template="], diff --git a/src/AdoLens/EnvironmentFlow.cs b/src/AdoLens/EnvironmentFlow.cs index 8302531..4413519 100644 --- a/src/AdoLens/EnvironmentFlow.cs +++ b/src/AdoLens/EnvironmentFlow.cs @@ -36,7 +36,7 @@ void From(string key, string source) if (!list.Contains(source)) list.Add(source); } static string Day(DateTime? d) => d?.ToLocalTime().ToString("yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture) ?? "?"; - var projects = new[] { session.Config.CodeProject, project }.Where(p => !string.IsNullOrWhiteSpace(p)).Select(p => p!) + var projects = new[] { session.Config.CodeProject, project }.Concat(session.Config.Projects).Where(p => !string.IsNullOrWhiteSpace(p)).Select(p => p!) .Distinct(StringComparer.OrdinalIgnoreCase).ToList(); var keys = new List(); // Long-lived branches of the repositories in use (a commit in the last half year); feature and work branches are diff --git a/src/AdoLens/Knowledge.cs b/src/AdoLens/Knowledge.cs index e3a4510..94ce05d 100644 --- a/src/AdoLens/Knowledge.cs +++ b/src/AdoLens/Knowledge.cs @@ -19,6 +19,9 @@ public static partial class Knowledge /// One search over work items, wiki pages and code of a project, grouped; each part fails on its own. public static async Task SearchAsync(Lens lens, string? connection, string? project, string text, string? scope, int top, CancellationToken ct = default) { + // Several projects in the connection and none named: ask each one. + if (project is null && lens.For(connection).SearchProjects(null) is { Count: > 1 } projects) + return await ProjectFanOut.EachAsync(projects, p => SearchAsync(lens, connection, p, text, scope, top, ct)); if (string.IsNullOrWhiteSpace(text)) throw new ArgumentException("text is required"); var session = lens.For(connection); var name = session.Project(project); @@ -284,6 +287,9 @@ sealed record FileRef(bool Tfvc, string Path, string? RepoId, string? RepoName, public static async Task FileAsync(Lens lens, string? connection, string? project, string path, string? repo, string? version, string? part, bool history, int top, string? detail, CancellationToken ct = default) { + // Several projects in the connection and none named: ask each one. + if (project is null && lens.For(connection).SearchProjects(null) is { Count: > 1 } projects) + return await ProjectFanOut.FirstAsync(projects, p => FileAsync(lens, connection, p, path, repo, version, part, history, top, detail, ct)); var session = lens.For(connection); var name = session.CodeProject(project); var (file, choices) = await ResolveAsync(session, name, path, repo, ct); diff --git a/src/AdoLens/Labels.cs b/src/AdoLens/Labels.cs index 6a04c2b..a2d9055 100644 --- a/src/AdoLens/Labels.cs +++ b/src/AdoLens/Labels.cs @@ -73,6 +73,9 @@ internal static string SearchWords(string seen) => public static async Task FindAsync(Lens lens, string? connection, string? project, string text, string? branch, CancellationToken ct = default) { + // Several projects in the connection and none named: ask each one. + if (project is null && lens.For(connection).SearchProjects(null) is { Count: > 1 } projects) + return await ProjectFanOut.FirstAsync(projects, p => FindAsync(lens, connection, p, text, branch, ct)); if (string.IsNullOrWhiteSpace(text)) throw new ArgumentException("give the text of the message (as seen on screen) or a label id like @Model:Id"); var session = lens.For(connection); var name = session.CodeProject(project); diff --git a/src/AdoLens/Lens.cs b/src/AdoLens/Lens.cs index e154157..7dda50f 100644 --- a/src/AdoLens/Lens.cs +++ b/src/AdoLens/Lens.cs @@ -18,6 +18,14 @@ public sealed record Session(Config Config, AdoClient Client, MetadataService Me public string CodeProject(string? project) => !string.IsNullOrWhiteSpace(project) ? project.Trim() : Config.CodeProject ?? Project(null); + /// + /// The projects to look in when none is named: all of the connection, the code project first. One project (or one + /// named): just that one. + /// + public IReadOnlyList SearchProjects(string? project) => + !string.IsNullOrWhiteSpace(project) || Config.Projects.Count < 2 ? [CodeProject(project)] + : Config.Projects.OrderBy(p => p.Equals(Config.CodeProject, StringComparison.OrdinalIgnoreCase) ? 0 : 1).ToList(); + /// The project given, else the connection's default project. public string Project(string? project) => !string.IsNullOrWhiteSpace(project) ? project.Trim() diff --git a/src/AdoLens/McpTools.cs b/src/AdoLens/McpTools.cs index 4c1742d..33542f2 100644 --- a/src/AdoLens/McpTools.cs +++ b/src/AdoLens/McpTools.cs @@ -63,7 +63,20 @@ public static class McpTools public static string Instructions(Settings settings) { var groups = settings.ToolLoading == "demand" ? Toolsets.Loaded(settings) : Toolsets.Active(settings); - return Intro + (settings.ToolLoading == "all" ? "" : Groups) + string.Concat(Lines.Where(l => groups.Contains(l.Key)).Select(l => l.Value)); + return Intro + (settings.ToolLoading == "all" ? "" : Groups) + string.Concat(Lines.Where(l => groups.Contains(l.Key)).Select(l => l.Value)) + + Projects(settings); + } + + /// + /// Connections with several projects of one organization: search, files, pull requests and pipelines look in all; + /// creating and boards need project= for any but the default. + /// + internal static string Projects(Settings settings) + { + var many = settings.Connections.Where(c => c.Value.AllProjects().Count > 1) + .Select(c => $"{c.Key}: {string.Join(", ", c.Value.AllProjects())}").ToList(); + return many.Count == 0 ? "" : "\n- Projects (the first is the default): " + string.Join("; ", many) + + ". Search, files, pull requests and pipelines look in all of them; to create work items or read a sprint, board or backlog of another, pass project=."; } /// The writing and usage hints of a group, returned when the group is loaded during a conversation. diff --git a/src/AdoLens/Pipelines.cs b/src/AdoLens/Pipelines.cs index 56433ba..2bb5a85 100644 --- a/src/AdoLens/Pipelines.cs +++ b/src/AdoLens/Pipelines.cs @@ -24,6 +24,9 @@ static string Line(JsonElement b) => public static async Task ListAsync(Lens lens, string? connection, string? project, string? definition, string? branch, int top, CancellationToken ct = default) { + // Several projects in the connection and none named: ask each one. + if (project is null && lens.For(connection).SearchProjects(null) is { Count: > 1 } projects) + return await ProjectFanOut.EachAsync(projects, p => ListAsync(lens, connection, p, definition, branch, top, ct)); var session = lens.For(connection); var name = session.CodeProject(project); var query = new List { $"$top={Math.Clamp(top, 1, 100)}", "queryOrder=queueTimeDescending" }; @@ -81,6 +84,9 @@ internal static string Excerpt(string log, int max) public static async Task DeploymentsAsync(Lens lens, string? connection, string? project, string? definition, string? stage, int top, CancellationToken ct = default) { + // Several projects in the connection and none named: ask each one. + if (project is null && lens.For(connection).SearchProjects(null) is { Count: > 1 } projects) + return await ProjectFanOut.EachAsync(projects, p => DeploymentsAsync(lens, connection, p, definition, stage, top, ct)); var session = lens.For(connection); var name = session.CodeProject(project); var vsrm = session.Client.ServiceUrl("vsrm") + Uri.EscapeDataString(name) + "/"; @@ -120,6 +126,9 @@ public static async Task DeploymentsAsync(Lens lens, string? connection, public static async Task ArtifactsAsync(Lens lens, string? connection, string? project, int build, string? artifact, string? part, bool save, CancellationToken ct = default) { + // Several projects in the connection and none named: ask each one. + if (project is null && lens.For(connection).SearchProjects(null) is { Count: > 1 } projects) + return await ProjectFanOut.FirstAsync(projects, p => ArtifactsAsync(lens, connection, p, build, artifact, part, save, ct)); var session = lens.For(connection); var scope = AdoClient.Scope(session.CodeProject(project)); var list = await session.Client.GetListAsync($"{scope}_apis/build/builds/{build}/artifacts", ct); @@ -148,6 +157,9 @@ public static async Task ArtifactsAsync(Lens lens, string? connection, s public static async Task BuildAsync(Lens lens, string? connection, string? project, int id, string? detail, CancellationToken ct = default) { + // Several projects in the connection and none named: ask each one. + if (project is null && lens.For(connection).SearchProjects(null) is { Count: > 1 } projects) + return await ProjectFanOut.FirstAsync(projects, p => BuildAsync(lens, connection, p, id, detail, ct)); var session = lens.For(connection); var name = session.CodeProject(project); var scope = AdoClient.Scope(name); @@ -184,6 +196,9 @@ public static async Task BuildAsync(Lens lens, string? connection, strin public static async Task RunAsync(Lens lens, string? connection, string? project, string definition, string? branch, string? parameters, CancellationToken ct = default) { + // Several projects in the connection and none named: ask each one. + if (project is null && lens.For(connection).SearchProjects(null) is { Count: > 1 } projects) + return await ProjectFanOut.FirstAsync(projects, p => RunAsync(lens, connection, p, definition, branch, parameters, ct)); var session = lens.For(connection); var name = session.CodeProject(project); var def = await DefinitionAsync(session, name, definition, ct); diff --git a/src/AdoLens/ProjectFanOut.cs b/src/AdoLens/ProjectFanOut.cs new file mode 100644 index 0000000..36937e2 --- /dev/null +++ b/src/AdoLens/ProjectFanOut.cs @@ -0,0 +1,46 @@ +using System.Text; + +namespace AdoLens; + +/// +/// A question asked in every project of a connection (work items and code in two projects of one organization): the +/// answers one after another under the project's name, or the first project that has what was asked for. +/// +public static class ProjectFanOut +{ + /// Each project in turn; one project: its answer as it is. + public static async Task EachAsync(IReadOnlyList projects, Func> ask) + { + if (projects.Count == 1) return await ask(projects[0]); + var answers = await Task.WhenAll(projects.Select(async p => + { + try { return await ask(p); } + catch (Exception ex) when (ex is AdoApiException or InvalidOperationException) { return $"({ex.Message})"; } + })); + var sb = new StringBuilder(); + for (var i = 0; i < projects.Count; i++) + sb.Append(i == 0 ? "" : "\n\n").Append($"== project {projects[i]} ==\n").Append(answers[i].TrimEnd()); + return sb.ToString(); + } + + /// + /// The first project whose answer is not "nothing here" (an error, or text starting with "no "): a build, a file, a + /// pipeline found by id or name lives in one project. + /// + public static async Task FirstAsync(IReadOnlyList projects, Func> ask) + { + if (projects.Count == 1) return await ask(projects[0]); + var misses = new List(); + foreach (var p in projects) + { + try + { + var answer = await ask(p); + if (!answer.StartsWith("no ", StringComparison.OrdinalIgnoreCase)) return answer; + misses.Add($"{p}: {answer}"); + } + catch (Exception ex) when (ex is AdoApiException or InvalidOperationException) { misses.Add($"{p}: {ex.Message}"); } + } + return "not found in any project of the connection:\n" + string.Join('\n', misses.Select(m => "- " + Formatting.Collapse(m, 300))); + } +} diff --git a/src/AdoLens/PullRequests.cs b/src/AdoLens/PullRequests.cs index 04565ac..5d843c1 100644 --- a/src/AdoLens/PullRequests.cs +++ b/src/AdoLens/PullRequests.cs @@ -55,6 +55,9 @@ static string Line(JsonElement pr) public static async Task ListAsync(Lens lens, string? connection, string? project, string? list, CancellationToken ct = default) { + // Several projects in the connection and none named: ask each one. + if (project is null && lens.For(connection).SearchProjects(null) is { Count: > 1 } projects) + return await ProjectFanOut.EachAsync(projects, p => ListAsync(lens, connection, p, list, ct)); var session = lens.For(connection); var name = session.CodeProject(project); var (me, meName) = await new Boards(session).MeAsync(ct); @@ -83,6 +86,9 @@ void Section(string title, List prs, int max) public static async Task MergedAsync(Lens lens, string? connection, string? project, string branch, string? repo, string? since, int top, CancellationToken ct = default) { + // Several projects in the connection and none named: ask each one. + if (project is null && lens.For(connection).SearchProjects(null) is { Count: > 1 } projects) + return await ProjectFanOut.EachAsync(projects, p => MergedAsync(lens, connection, p, branch, repo, since, top, ct)); var session = lens.For(connection); var name = session.CodeProject(project); var target = branch.StartsWith("refs/", StringComparison.Ordinal) ? branch : "refs/heads/" + branch.Trim(); diff --git a/src/AdoLens/Queries.cs b/src/AdoLens/Queries.cs index b704166..9c8e2c0 100644 --- a/src/AdoLens/Queries.cs +++ b/src/AdoLens/Queries.cs @@ -60,6 +60,7 @@ public static string SettingsAnswer(Lens lens, string? connection, string? envir if (environments is not null || codeProject is not null) lens.SaveSettings(); var sb = new StringBuilder(environments is null && codeProject is null ? "" : "saved (new conversations use it).\n"); sb.AppendLine($"connection {cfg.Connection}: https://dev.azure.com/{conn.Organization}, project {conn.Project ?? "-"}" + + (conn.MoreProjects.Count > 0 ? $" (also: {string.Join(", ", conn.MoreProjects)})" : "") + $"{(conn.CodeProject is { } cp ? $" (code, pull requests and pipelines in {cp})" : "")}, team {conn.Team ?? "-"}, mode {lens.Settings.Mode}"); sb.Append(conn.Environments.Count == 0 ? "local environments: not set" : "environments (in flow order): " + string.Join(" -> ", conn.Environments.Select(e => Flow(e.Key, e.Value)))); diff --git a/src/AdoLens/Settings.cs b/src/AdoLens/Settings.cs index 3a52d30..6239ed2 100644 --- a/src/AdoLens/Settings.cs +++ b/src/AdoLens/Settings.cs @@ -28,6 +28,42 @@ public sealed class Connection /// items in "Sales", code in "ERP"). Null: the default project. /// public string? CodeProject { get; set; } + + /// + /// Other projects of the same organization, besides the default one (work items and code in both, e.g. one for + /// X++ and one for C# applications). Searches, files, pull requests and pipelines look in all of them; creating and + /// boards use the default unless a project is named. + /// + public List MoreProjects { get; set; } = []; + + /// + /// Adds a project to the connection: the default one when there is none yet, else one more - another project of + /// the same organization never replaces the default. Returns false when it was there already. + /// + public bool AddProject(string project) + { + project = project.Trim(); + if (string.IsNullOrEmpty(Project)) { Project = project; return true; } + if (AllProjects().Contains(project, StringComparer.OrdinalIgnoreCase)) return false; + MoreProjects.Add(project); + return true; + } + + /// Makes a project the default; the previous default stays as one of the others. + public void SetDefaultProject(string? project) + { + project = string.IsNullOrWhiteSpace(project) ? null : project.Trim(); + if (project is not null) MoreProjects.RemoveAll(p => p.Equals(project, StringComparison.OrdinalIgnoreCase)); + if (Project is { Length: > 0 } old && project is not null && !old.Equals(project, StringComparison.OrdinalIgnoreCase) + && !MoreProjects.Contains(old, StringComparer.OrdinalIgnoreCase)) + MoreProjects.Insert(0, old); + Project = project; + } + + /// The default project, the others and the code project, each once. + public List AllProjects() => + new[] { Project }.Concat(MoreProjects).Append(CodeProject).Where(p => !string.IsNullOrWhiteSpace(p)).Select(p => p!.Trim()) + .Distinct(StringComparer.OrdinalIgnoreCase).ToList(); } /// Non-secret settings (adolens.json in the data folder). PATs live in Windows Credential Manager. @@ -101,6 +137,7 @@ public static Settings Load(string path) { c.Environments = new Dictionary(c.Environments ?? [], StringComparer.OrdinalIgnoreCase); c.LabelLanguages ??= []; + c.MoreProjects ??= []; } return s; } @@ -172,6 +209,9 @@ public sealed record Config(string Connection, string Organization, string Pat, /// See . public string? CodeProject { get; init; } + /// Every project of the connection, the default first (see ). + public IReadOnlyList Projects { get; init; } = []; + /// Whether a missing label text in this language is worth reporting. public bool LabelLanguageRequired(string language) => LabelLanguages.Count == 0 || LabelLanguages.Any(l => l.Equals(language, StringComparison.OrdinalIgnoreCase)); @@ -230,9 +270,10 @@ public static Config Resolve(Settings settings, string? connection, Func kv.Key, StringComparer.OrdinalIgnoreCase)) { var item = new ListViewItem(name + (name.Equals(settings.DefaultConnection, StringComparison.OrdinalIgnoreCase) ? Ui.T(" (default)", " (domyślne)") : "")) { Tag = name }; - item.SubItems.AddRange([c.Organization, c.Project ?? "-", c.CodeProject ?? "", c.Team ?? "", CredentialStore.Read(name) is null ? Ui.T("missing", "brak") : Ui.T("stored", "zapisany")]); + item.SubItems.AddRange([c.Organization, (c.Project ?? "-") + (c.MoreProjects.Count > 0 ? $" (+{string.Join(", ", c.MoreProjects)})" : ""), c.CodeProject ?? "", c.Team ?? "", CredentialStore.Read(name) is null ? Ui.T("missing", "brak") : Ui.T("stored", "zapisany")]); connections.Items.Add(item); } if (connections.Items.Count > 0) connections.Items[0].Selected = true; @@ -238,8 +239,9 @@ void LoadConnections() void ShowConnection() { var c = Selected() is { } name && settings.Connections.TryGetValue(name, out var conn) ? conn : null; - foreach (var box in new[] { project, team, codeProject, labelLanguages }) box.Enabled = c is not null; + foreach (var box in new[] { project, moreProjects, team, codeProject, labelLanguages }) box.Enabled = c is not null; project.Text = c?.Project ?? ""; + moreProjects.Text = c is null ? "" : string.Join("; ", c.MoreProjects); team.Text = c?.Team ?? ""; codeProject.Text = c?.CodeProject ?? ""; labelLanguages.Text = c is null ? "" : string.Join(", ", c.LabelLanguages); @@ -251,6 +253,8 @@ void SaveConnection() settings = Settings.Load(path); if (!settings.Connections.TryGetValue(name, out var c)) return; c.Project = Empty(project.Text); + c.MoreProjects = moreProjects.Text.Split([';', ','], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .Where(x => !x.Equals(c.Project, StringComparison.OrdinalIgnoreCase)).Distinct(StringComparer.OrdinalIgnoreCase).ToList(); c.Team = Empty(team.Text); c.CodeProject = Empty(codeProject.Text); c.LabelLanguages = labelLanguages.Text.Split([',', ';', ' '], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToList(); @@ -668,7 +672,8 @@ async Task ConnectAsync() var settings = Settings.Load(path); var conn = settings.Connections.TryGetValue(connection, out var stored) ? stored : new Connection(); conn.Organization = org; - conn.Project = chosen is null ? conn.Project : projects.FirstOrDefault(p => p.Equals(chosen, StringComparison.OrdinalIgnoreCase)) ?? chosen; + // Another project of the same organization is added to the connection, never put in place of its default. + if (chosen is not null) conn.AddProject(projects.FirstOrDefault(p => p.Equals(chosen, StringComparison.OrdinalIgnoreCase)) ?? chosen); CredentialStore.Write(connection, org, pat.Text.Trim()); settings.Connections[connection] = conn; if (settings.DefaultConnection is null || !settings.Connections.ContainsKey(settings.DefaultConnection)) settings.DefaultConnection = connection; diff --git a/tests/AdoLens.Tests/ImprovementTests.cs b/tests/AdoLens.Tests/ImprovementTests.cs index cbdb33f..01fc512 100644 --- a/tests/AdoLens.Tests/ImprovementTests.cs +++ b/tests/AdoLens.Tests/ImprovementTests.cs @@ -31,6 +31,40 @@ public void A_repository_with_its_own_keys_uses_only_those() Assert.Equal("UAT + SCM = release stage Deploy/Stage 1", Queries.Flow("Deploy/Stage 1", "UAT + SCM")); } + [Fact] + public void A_second_project_of_the_organization_is_added_not_put_in_place_of_the_first() + { + var c = new Connection { Organization = "contoso", Project = "Erp" }; + Assert.True(c.AddProject("Apps")); + Assert.False(c.AddProject("apps")); + Assert.Equal("Erp", c.Project); + Assert.Equal(["Erp", "Apps"], c.AllProjects()); + + // A new default keeps the old one among the others. + c.SetDefaultProject("Apps"); + Assert.Equal("Apps", c.Project); + Assert.Equal(["Erp"], c.MoreProjects); + + var s = new Settings(); + s.Connections["contoso"] = c; + Assert.Contains("contoso: Apps, Erp", McpTools.Projects(s)); + Assert.Equal("", McpTools.Projects(new Settings())); + } + + [Fact] + public async Task Several_projects_are_asked_one_after_another_or_until_one_has_it() + { + var each = await ProjectFanOut.EachAsync(["Erp", "Apps"], p => Task.FromResult(p == "Erp" ? "2 builds" : "1 build")); + Assert.Equal("== project Erp ==\n2 builds\n\n== project Apps ==\n1 build", each); + Assert.Equal("only", await ProjectFanOut.EachAsync(["Erp"], _ => Task.FromResult("only"))); + + // A build or file lives in one project: the first that has it; nothing anywhere: what each said. + var first = await ProjectFanOut.FirstAsync(["Erp", "Apps"], p => p == "Erp" ? throw new AdoApiException("404") : Task.FromResult("build 7 in Apps")); + Assert.Equal("build 7 in Apps", first); + var none = await ProjectFanOut.FirstAsync(["Erp", "Apps"], p => Task.FromResult($"no file x in {p}")); + Assert.StartsWith("not found in any project of the connection:\n- Erp: no file x in Erp\n- Apps:", none); + } + [Fact] public void Code_can_live_in_another_project_than_the_work_items() { @@ -38,11 +72,14 @@ public void Code_can_live_in_another_project_than_the_work_items() try { var s = new Settings { DefaultConnection = "contoso" }; - s.Connections["contoso"] = new Connection { Organization = "contoso", Project = "Demo", CodeProject = "ERP" }; + s.Connections["contoso"] = new Connection { Organization = "contoso", Project = "Demo", CodeProject = "ERP", MoreProjects = ["Apps"] }; var session = new Lens(s, "0.0.0", dir, _ => null, _ => "pat", _ => new FakeAdo().Client()).For(null); Assert.Equal("Demo", session.Project(null)); Assert.Equal("ERP", session.CodeProject(null)); Assert.Equal("Other", session.CodeProject("Other")); + // Nothing named: every project, the code project first; one named: that one. + Assert.Equal(["ERP", "Demo", "Apps"], session.SearchProjects(null)); + Assert.Equal(["Apps"], session.SearchProjects("Apps")); } finally {