From 2825a4f9825f6bc4628aa17faba6d63b751c2698 Mon Sep 17 00:00:00 2001 From: Pieter van Ginkel Date: Sat, 21 Nov 2026 15:29:02 +0100 Subject: [PATCH 1/9] Added the YouTrack plugin's WPF-free REST client and its Linux test project. The client, its DTOs, and URL and query building, in the four files the design names, without WPF or TQL dependencies. Tql.Plugins.YouTrack.Test compiles them into plain net8.0, so the tests run on Linux, against answers captured from YouTrack 2026.2 and anonymised, and against a live YouTrack when YOUTRACK_TEST_URL and YOUTRACK_TEST_TOKEN are set. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RGjkV3AFfnNjd6n2D9pwGX --- Tql.sln | 7 + .../Services/YouTrackClient.cs | 492 +++++++++++++++ .../Services/YouTrackDtos.cs | 77 +++ .../Support/YouTrackQueries.cs | 61 ++ .../Support/YouTrackUrls.cs | 110 ++++ .../Fixtures/Agiles.json | 17 + .../Fixtures/Config.json | 4 + .../Fixtures/Dashboards.json | 12 + .../Fixtures/Issue-NotFound.json | 4 + .../Fixtures/Issue.json | 5 + .../Fixtures/Issues-InvalidQuery.json | 12 + .../Fixtures/Issues.json | 27 + .../Fixtures/Me.json | 9 + .../Fixtures/NotFound.json | 4 + .../Fixtures/Projects.json | 50 ++ .../Fixtures/SavedQueries.json | 44 ++ .../Fixtures/Unauthorized-InvalidToken.json | 4 + .../Fixtures/Unauthorized-NotLoggedIn.json | 4 + .../Fixtures/Users.json | 47 ++ .../Fixtures/WebApp.html | 108 ++++ .../LiveYouTrackFixture.cs | 157 +++++ .../Support/FakeHttpMessageHandler.cs | 91 +++ .../Support/Fixtures.cs | 21 + .../Tql.Plugins.YouTrack.Test.csproj | 34 ++ .../YouTrackClientFixture.cs | 568 ++++++++++++++++++ .../YouTrackQueriesFixture.cs | 58 ++ .../YouTrackUrlsFixture.cs | 142 +++++ .../packages.lock.json | 83 +++ 28 files changed, 2252 insertions(+) create mode 100644 src/Tql.Plugins.YouTrack/Services/YouTrackClient.cs create mode 100644 src/Tql.Plugins.YouTrack/Services/YouTrackDtos.cs create mode 100644 src/Tql.Plugins.YouTrack/Support/YouTrackQueries.cs create mode 100644 src/Tql.Plugins.YouTrack/Support/YouTrackUrls.cs create mode 100644 tests/Tql.Plugins.YouTrack.Test/Fixtures/Agiles.json create mode 100644 tests/Tql.Plugins.YouTrack.Test/Fixtures/Config.json create mode 100644 tests/Tql.Plugins.YouTrack.Test/Fixtures/Dashboards.json create mode 100644 tests/Tql.Plugins.YouTrack.Test/Fixtures/Issue-NotFound.json create mode 100644 tests/Tql.Plugins.YouTrack.Test/Fixtures/Issue.json create mode 100644 tests/Tql.Plugins.YouTrack.Test/Fixtures/Issues-InvalidQuery.json create mode 100644 tests/Tql.Plugins.YouTrack.Test/Fixtures/Issues.json create mode 100644 tests/Tql.Plugins.YouTrack.Test/Fixtures/Me.json create mode 100644 tests/Tql.Plugins.YouTrack.Test/Fixtures/NotFound.json create mode 100644 tests/Tql.Plugins.YouTrack.Test/Fixtures/Projects.json create mode 100644 tests/Tql.Plugins.YouTrack.Test/Fixtures/SavedQueries.json create mode 100644 tests/Tql.Plugins.YouTrack.Test/Fixtures/Unauthorized-InvalidToken.json create mode 100644 tests/Tql.Plugins.YouTrack.Test/Fixtures/Unauthorized-NotLoggedIn.json create mode 100644 tests/Tql.Plugins.YouTrack.Test/Fixtures/Users.json create mode 100644 tests/Tql.Plugins.YouTrack.Test/Fixtures/WebApp.html create mode 100644 tests/Tql.Plugins.YouTrack.Test/LiveYouTrackFixture.cs create mode 100644 tests/Tql.Plugins.YouTrack.Test/Support/FakeHttpMessageHandler.cs create mode 100644 tests/Tql.Plugins.YouTrack.Test/Support/Fixtures.cs create mode 100644 tests/Tql.Plugins.YouTrack.Test/Tql.Plugins.YouTrack.Test.csproj create mode 100644 tests/Tql.Plugins.YouTrack.Test/YouTrackClientFixture.cs create mode 100644 tests/Tql.Plugins.YouTrack.Test/YouTrackQueriesFixture.cs create mode 100644 tests/Tql.Plugins.YouTrack.Test/YouTrackUrlsFixture.cs create mode 100644 tests/Tql.Plugins.YouTrack.Test/packages.lock.json diff --git a/Tql.sln b/Tql.sln index 5395e9f0..2577550b 100644 --- a/Tql.sln +++ b/Tql.sln @@ -45,6 +45,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Tql.Benchmarks", "src\Tql.B EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Tql.Localization", "src\Tql.Localization\Tql.Localization.csproj", "{3BCD5CFB-31AD-42E5-BC08-40C38F63523E}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Tql.Plugins.YouTrack.Test", "tests\Tql.Plugins.YouTrack.Test\Tql.Plugins.YouTrack.Test.csproj", "{581A2C7D-0C4D-4B2D-8621-4834EC4378F6}" +EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{C6ED2573-EB45-49CB-BFD3-9D09A60BA23F}" ProjectSection(SolutionItems) = preProject Directory.Build.props = Directory.Build.props @@ -137,6 +139,10 @@ Global {3BCD5CFB-31AD-42E5-BC08-40C38F63523E}.Debug|Any CPU.Build.0 = Debug|Any CPU {3BCD5CFB-31AD-42E5-BC08-40C38F63523E}.Release|Any CPU.ActiveCfg = Release|Any CPU {3BCD5CFB-31AD-42E5-BC08-40C38F63523E}.Release|Any CPU.Build.0 = Release|Any CPU + {581A2C7D-0C4D-4B2D-8621-4834EC4378F6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {581A2C7D-0C4D-4B2D-8621-4834EC4378F6}.Debug|Any CPU.Build.0 = Debug|Any CPU + {581A2C7D-0C4D-4B2D-8621-4834EC4378F6}.Release|Any CPU.ActiveCfg = Release|Any CPU + {581A2C7D-0C4D-4B2D-8621-4834EC4378F6}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -161,6 +167,7 @@ Global {493C14D2-0DAF-4167-BC04-2023DF55AB45} = {E67CF545-0D68-469F-BD58-DAC8EDCE4562} {E5226BB4-2336-40E5-8A8F-9B3F241AA459} = {094A034F-EBB5-42F1-A87B-633A3117042F} {3BCD5CFB-31AD-42E5-BC08-40C38F63523E} = {094A034F-EBB5-42F1-A87B-633A3117042F} + {581A2C7D-0C4D-4B2D-8621-4834EC4378F6} = {E67CF545-0D68-469F-BD58-DAC8EDCE4562} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {473D3E4B-C738-47D6-8D01-1D80FA3D6F49} diff --git a/src/Tql.Plugins.YouTrack/Services/YouTrackClient.cs b/src/Tql.Plugins.YouTrack/Services/YouTrackClient.cs new file mode 100644 index 00000000..e0a048d7 --- /dev/null +++ b/src/Tql.Plugins.YouTrack/Services/YouTrackClient.cs @@ -0,0 +1,492 @@ +using System; +using System.Collections.Immutable; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using Tql.Plugins.YouTrack.Support; + +namespace Tql.Plugins.YouTrack.Services; + +// The REST client for one YouTrack connection, authenticated with a permanent +// token. Every list call passes $top, because YouTrack picks a page size of its +// own when it's left out; the cached lists page with $skip and $top until a +// page comes back short. +// +// This file has no WPF or TQL dependencies, so the plain net8.0 test project +// can compile it. The plugin shows the "unable to connect" notification bar +// through the response observer, and maps the exceptions below to its labels. +internal class YouTrackClient +{ + public const int DefaultPageSize = 500; + public const int DefaultSearchTop = 100; + + // Only what the plugin displays or links to. + public const string ConfigFields = "version"; + public const string UserFields = "id,login,fullName,email,banned,guest"; + public const string IssueFields = "idReadable,summary"; + public const string ProjectFields = "id,shortName,name,archived,iconUrl"; + public const string AgileBoardFields = "id,name"; + public const string SavedQueryFields = "id,name,query"; + public const string DashboardFields = "id,name"; + + private readonly HttpClient _httpClient; + private readonly AuthenticationHeaderValue _authorization; + private readonly Action? _responseObserver; + + /// The service URL, with one trailing slash. + public string ServiceUrl { get; } + + /// The $top of every page of the cached lists. + public int PageSize { get; init; } = DefaultPageSize; + + /// The HTTP client to send every request with. + /// The address YouTrack is opened on. + /// The permanent token, decrypted. + /// + /// Called with the status code of every response to a request that + /// carried the token, e.g. to show a notification bar on a 401 and remove + /// it on anything else. + /// + public YouTrackClient( + HttpClient httpClient, + string serviceUrl, + string token, + Action? responseObserver = null + ) + { + _httpClient = httpClient; + _authorization = new AuthenticationHeaderValue("Bearer", token); + _responseObserver = responseObserver; + + ServiceUrl = YouTrackUrls.NormalizeServiceUrl(serviceUrl); + } + + /// + /// The first step of the connection check, without a token: finds the URL + /// whose "api/config" answers YouTrack's FrontendConfig, trying the + /// entered URL and then its parent paths down to the bare host. A + /// self-hosted YouTrack answers an unknown path with its web app, so a URL + /// copied from the address bar answers HTML rather than a 404. + /// + /// The URL is not an http or https URL. + /// + /// Neither the URL nor any of its parent paths answers as YouTrack. + /// + /// The host can't be reached. + public static async Task CheckServiceUrl( + HttpClient httpClient, + string url, + CancellationToken cancellationToken = default + ) + { + var enteredUrl = YouTrackUrls.NormalizeServiceUrl(url); + var enteredApiUrl = default(string); + var enteredAnswer = default(string); + var enteredStatusCode = default(HttpStatusCode?); + + foreach (var candidate in YouTrackUrls.GetServiceUrlCandidates(enteredUrl)) + { + var apiUrl = $"{candidate}api/config?fields={ConfigFields}"; + + using var request = CreateRequest(apiUrl); + using var response = await httpClient.SendAsync(request, cancellationToken); + + var json = await ReadJson(response, cancellationToken); + var config = json != null ? TryDeserialize(json) : null; + + if (response.IsSuccessStatusCode && config?.Type == "FrontendConfig") + return new YouTrackServiceCheck(enteredUrl, candidate, config.Version); + + if (enteredApiUrl == null) + { + enteredApiUrl = apiUrl; + enteredAnswer = DescribeAnswer(response); + enteredStatusCode = response.StatusCode; + } + } + + throw new YouTrackNotAnApiException( + $"No YouTrack REST API answers at {enteredUrl}: {enteredApiUrl} answered " + + $"{enteredAnswer}, and none of its parent paths answered as YouTrack either.", + enteredApiUrl!, + enteredStatusCode + ); + } + + /// + /// The second step of the connection check: the user the token belongs to. + /// + /// The token is wrong or missing. + public async Task GetCurrentUser(CancellationToken cancellationToken = default) + { + return ( + await Get($"api/users/me?fields={UserFields}", cancellationToken) + )!; + } + + /// + /// The first issues a YouTrack query finds, in YouTrack's order. + /// + /// + /// YouTrack can't parse the query, as happens while a query is half typed, + /// e.g. "#Unres" or "state: Op". + /// + public async Task> SearchIssues( + string query, + int top = DefaultSearchTop, + CancellationToken cancellationToken = default + ) + { + return await GetArray( + $"api/issues?fields={IssueFields}&query={Uri.EscapeDataString(query)}&$top={top}", + cancellationToken + ); + } + + /// + /// The issue with an ID such as "KC-230", in any case, or null when there is + /// no such issue. + /// + public async Task GetIssue( + string id, + CancellationToken cancellationToken = default + ) + { + return await Get( + $"api/issues/{Uri.EscapeDataString(id.Trim())}?fields={IssueFields}", + cancellationToken, + notFoundAsNull: true + ); + } + + /// The projects, archived ones left out. + /// + /// The token may not list projects. + /// + public async Task> GetProjects( + CancellationToken cancellationToken = default + ) + { + var projects = await GetAll( + "api/admin/projects", + ProjectFields, + cancellationToken + ); + + return projects + .Where(p => !p.Archived) + .Select(p => p with { IconUrl = ResolveUrl(p.IconUrl) }) + .ToImmutableArray(); + } + + /// + /// The token may not list agile boards. + /// + public Task> GetAgileBoards( + CancellationToken cancellationToken = default + ) => GetAll("api/agiles", AgileBoardFields, cancellationToken); + + /// + /// The token may not list saved searches. + /// + public Task> GetSavedQueries( + CancellationToken cancellationToken = default + ) => GetAll("api/savedQueries", SavedQueryFields, cancellationToken); + + /// + /// The dashboards. The endpoint isn't in the REST API reference. + /// + /// + /// The installation has no such endpoint, or the token may not use it. + /// + public Task> GetDashboards( + CancellationToken cancellationToken = default + ) => GetAll("api/dashboards", DashboardFields, cancellationToken); + + /// + /// Users for the people directory: those the query finds, leaving out + /// users without an email address, banned users and guests. The query + /// parameter isn't in the REST API reference. + /// + /// + /// The token may not list users (403). + /// + public async Task> SearchUsers( + string query, + int top = DefaultSearchTop, + CancellationToken cancellationToken = default + ) + { + var users = await GetArray( + $"api/users?fields={UserFields}&query={Uri.EscapeDataString(query)}&$top={top}", + cancellationToken + ); + + return users + .Where(p => !string.IsNullOrEmpty(p.Email) && !p.Banned && !p.Guest) + .ToImmutableArray(); + } + + /// + /// Downloads an icon or avatar. A host-relative URL is resolved against + /// the service URL. The token goes only to the service URL's own scheme, + /// host and port; a URL elsewhere, such as Gravatar or an external Hub, is + /// fetched without it. Redirects don't carry it either: HttpClient drops + /// the Authorization header when it follows one, and the built-in Hub + /// answers a user without an uploaded avatar with a redirect to Gravatar. + /// + /// + /// The service URL refused the token. + /// + /// The download failed. + public async Task DownloadFile( + string url, + Func> action, + CancellationToken cancellationToken = default + ) + { + var absoluteUrl = YouTrackUrls.Resolve(ServiceUrl, url); + var withToken = YouTrackUrls.IsSameOrigin(ServiceUrl, absoluteUrl); + + using var request = new HttpRequestMessage(HttpMethod.Get, absoluteUrl); + + if (withToken) + request.Headers.Authorization = _authorization; + + using var response = await _httpClient.SendAsync(request, cancellationToken); + + if (withToken) + { + _responseObserver?.Invoke(response.StatusCode); + + if (response.StatusCode == HttpStatusCode.Unauthorized) + { + throw new YouTrackUnauthorizedException( + $"{ServiceUrl} refused the token for {absoluteUrl}.", + absoluteUrl + ); + } + } + + if (!response.IsSuccessStatusCode) + { + throw new YouTrackException( + $"{absoluteUrl} answered {DescribeAnswer(response)}.", + absoluteUrl, + response.StatusCode + ); + } + + return await action(response.Content); + } + + private string? ResolveUrl(string? url) => + string.IsNullOrEmpty(url) ? url : YouTrackUrls.Resolve(ServiceUrl, url); + + private async Task> GetAll( + string path, + string fields, + CancellationToken cancellationToken + ) + { + var results = ImmutableArray.CreateBuilder(); + + for (var skip = 0; ; skip += PageSize) + { + var page = await GetArray( + $"{path}?fields={fields}&$skip={skip}&$top={PageSize}", + cancellationToken + ); + + results.AddRange(page); + + if (page.Length < PageSize) + return results.ToImmutable(); + } + } + + private async Task> GetArray( + string pathAndQuery, + CancellationToken cancellationToken + ) + { + var result = await Get?>(pathAndQuery, cancellationToken); + + return result is { IsDefault: false } array ? array : ImmutableArray.Empty; + } + + private async Task Get( + string pathAndQuery, + CancellationToken cancellationToken, + bool notFoundAsNull = false + ) + { + var url = ServiceUrl + pathAndQuery; + + using var request = CreateRequest(url); + + request.Headers.Authorization = _authorization; + + using var response = await _httpClient.SendAsync(request, cancellationToken); + + _responseObserver?.Invoke(response.StatusCode); + + var json = await ReadJson(response, cancellationToken); + var error = + json != null && !response.IsSuccessStatusCode + ? TryDeserialize(json) + : null; + + if (response.StatusCode == HttpStatusCode.Unauthorized) + { + throw new YouTrackUnauthorizedException( + $"{ServiceUrl} refused the token: {error?.ErrorDescription ?? "401 Unauthorized"}.", + url + ); + } + + if (json == null) + { + throw new YouTrackNotAnApiException( + $"{url} answered {DescribeAnswer(response)} instead of JSON, so {ServiceUrl} " + + "isn't the address of a YouTrack REST API. Use the address YouTrack is " + + "opened on, e.g. https://youtrack.example.com/.", + url, + response.StatusCode + ); + } + + if (response.StatusCode == HttpStatusCode.NotFound && notFoundAsNull) + return default; + + if (!response.IsSuccessStatusCode) + { + var message = + $"{url} answered {DescribeAnswer(response)}: " + + (error?.ErrorDescription ?? error?.Error ?? "no details"); + + throw response.StatusCode switch + { + HttpStatusCode.Forbidden + or HttpStatusCode.NotFound + => new YouTrackUnavailableException(message, url, response.StatusCode), + HttpStatusCode.BadRequest when error?.Error == "invalid_query" + => new YouTrackInvalidQueryException(message, url), + _ => new YouTrackException(message, url, response.StatusCode) + }; + } + + try + { + return JsonSerializer.Deserialize(json); + } + catch (JsonException ex) + { + throw new YouTrackException( + $"{url} answered JSON YouTrackClient can't read: {ex.Message}", + url, + response.StatusCode, + ex + ); + } + } + + private static HttpRequestMessage CreateRequest(string url) + { + var request = new HttpRequestMessage(HttpMethod.Get, url); + + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + return request; + } + + private static async Task ReadJson( + HttpResponseMessage response, + CancellationToken cancellationToken + ) + { + var mediaType = response.Content.Headers.ContentType?.MediaType; + + var isJson = + mediaType != null + && ( + mediaType.Equals("application/json", StringComparison.OrdinalIgnoreCase) + || mediaType.EndsWith("+json", StringComparison.OrdinalIgnoreCase) + ); + + return isJson ? await response.Content.ReadAsStringAsync(cancellationToken) : null; + } + + private static T? TryDeserialize(string json) + where T : class + { + try + { + return JsonSerializer.Deserialize(json); + } + catch (JsonException) + { + return null; + } + } + + private static string DescribeAnswer(HttpResponseMessage response) + { + var mediaType = response.Content.Headers.ContentType?.MediaType ?? "no content type"; + + return $"HTTP {(int)response.StatusCode} with {mediaType}"; + } +} + +/// +/// A YouTrack request failed. The base of the exceptions below, and itself +/// thrown for any other failure, such as a 500. +/// +internal class YouTrackException( + string message, + string requestUrl, + HttpStatusCode? statusCode, + Exception? innerException = null +) : HttpRequestException(message, innerException, statusCode) +{ + public string RequestUrl { get; } = requestUrl; +} + +/// +/// 401: the token is wrong or missing. Measured: an invalid token and no token +/// both get 401. +/// +internal class YouTrackUnauthorizedException(string message, string requestUrl) + : YouTrackException(message, requestUrl, HttpStatusCode.Unauthorized); + +/// +/// 403 or 404 on a list endpoint: the installation lacks it or the token may +/// not use it. The plugin leaves the category out for the connection and logs +/// the error. +/// +internal class YouTrackUnavailableException( + string message, + string requestUrl, + HttpStatusCode statusCode +) : YouTrackException(message, requestUrl, statusCode); + +/// +/// 400 "invalid_query": YouTrack can't parse the search query. +/// +internal class YouTrackInvalidQueryException(string message, string requestUrl) + : YouTrackException(message, requestUrl, HttpStatusCode.BadRequest); + +/// +/// The answer isn't JSON, typically the web app's HTML page: the URL isn't the +/// address of a YouTrack REST API. +/// is the status of that answer, often 200. +/// +internal class YouTrackNotAnApiException( + string message, + string requestUrl, + HttpStatusCode? statusCode +) : YouTrackException(message, requestUrl, statusCode); diff --git a/src/Tql.Plugins.YouTrack/Services/YouTrackDtos.cs b/src/Tql.Plugins.YouTrack/Services/YouTrackDtos.cs new file mode 100644 index 00000000..5789dd10 --- /dev/null +++ b/src/Tql.Plugins.YouTrack/Services/YouTrackDtos.cs @@ -0,0 +1,77 @@ +using System.Text.Json.Serialization; + +namespace Tql.Plugins.YouTrack.Services; + +// The JSON shapes of the YouTrack REST API, limited to the fields YouTrackClient +// requests. YouTrack adds a "$type" to every object; only the configuration +// check reads it. URL fields hold absolute URLs: YouTrackClient resolves the +// host-relative ones the API returns. +// +// This file has no WPF or TQL dependencies, so the plain net8.0 test project +// can compile it. + +internal record YouTrackConfigDto( + [property: JsonPropertyName("$type")] string? Type, + [property: JsonPropertyName("version")] string? Version +); + +internal record YouTrackErrorDto( + [property: JsonPropertyName("error")] string? Error, + [property: JsonPropertyName("error_description")] string? ErrorDescription +); + +internal record YouTrackUserDto( + [property: JsonPropertyName("id")] string Id, + [property: JsonPropertyName("login")] string Login, + [property: JsonPropertyName("fullName")] string? FullName, + [property: JsonPropertyName("email")] string? Email, + [property: JsonPropertyName("banned")] bool Banned, + [property: JsonPropertyName("guest")] bool Guest +); + +internal record YouTrackIssueDto( + [property: JsonPropertyName("idReadable")] string IdReadable, + [property: JsonPropertyName("summary")] string Summary +); + +internal record YouTrackProjectDto( + [property: JsonPropertyName("id")] string Id, + [property: JsonPropertyName("shortName")] string ShortName, + [property: JsonPropertyName("name")] string Name, + [property: JsonPropertyName("archived")] bool Archived, + [property: JsonPropertyName("iconUrl")] string? IconUrl +); + +internal record YouTrackAgileBoardDto( + [property: JsonPropertyName("id")] string Id, + [property: JsonPropertyName("name")] string Name +); + +internal record YouTrackSavedQueryDto( + [property: JsonPropertyName("id")] string Id, + [property: JsonPropertyName("name")] string Name, + [property: JsonPropertyName("query")] string Query +); + +internal record YouTrackDashboardDto( + [property: JsonPropertyName("id")] string Id, + [property: JsonPropertyName("name")] string Name +); + +/// +/// The outcome of . +/// +/// The URL as entered, normalized. +/// +/// The URL the REST API answered on: or one of +/// its parent paths. +/// +/// The YouTrack version, e.g. "2026.2". +internal record YouTrackServiceCheck(string EnteredUrl, string ServiceUrl, string? Version) +{ + /// + /// Whether the REST API answered on a parent path rather than on the + /// entered URL, so the dialog should offer . + /// + public bool IsSuggestion => EnteredUrl != ServiceUrl; +} diff --git a/src/Tql.Plugins.YouTrack/Support/YouTrackQueries.cs b/src/Tql.Plugins.YouTrack/Support/YouTrackQueries.cs new file mode 100644 index 00000000..d21f1ef1 --- /dev/null +++ b/src/Tql.Plugins.YouTrack/Support/YouTrackQueries.cs @@ -0,0 +1,61 @@ +using System.Text.RegularExpressions; + +namespace Tql.Plugins.YouTrack.Support; + +// YouTrack search queries the plugin builds from what the user types. The text +// goes to YouTrack as a query, so "#Unresolved for: me" works. YouTrack +// matches word prefixes on its own ("kubecod" finds "KubeCoder"), so nothing +// appends a "*", which could also break a query the user typed. +// +// This file has no WPF or TQL dependencies, so the plain net8.0 test project +// can compile it. +internal static class YouTrackQueries +{ + // A project short name starts with a letter. Matching ignores case: + // YouTrack finds "kc-230" as well as "KC-230". + private static readonly Regex IssueIdRe = + new(@"^[A-Z][A-Z0-9_]*-\d+$", RegexOptions.Compiled | RegexOptions.IgnoreCase); + + private static readonly Regex PlainValueRe = new(@"^\w+$", RegexOptions.Compiled); + + /// + /// Whether the text is an issue ID, such as "KC-230", which the plugin + /// fetches directly before it searches. + /// + public static bool IsIssueId(string text) => IssueIdRe.IsMatch(text.Trim()); + + /// + /// The issues of a project: "project: KC text", or the most recently + /// updated ones without text. + /// + public static string Project(string shortName, string? text) + { + var query = $"project: {Value(shortName)}"; + + if (string.IsNullOrWhiteSpace(text)) + return query + " sort by: updated desc"; + + return $"{query} {text.Trim()}"; + } + + /// + /// A saved search narrowed with the text: "(saved query) and (text)". + /// YouTrack accepts a "sort by:" inside the parentheses. + /// + public static string SavedSearch(string savedQuery, string? text) + { + if (string.IsNullOrWhiteSpace(text)) + return savedQuery; + if (string.IsNullOrWhiteSpace(savedQuery)) + return text.Trim(); + + return $"({savedQuery.Trim()}) and ({text.Trim()})"; + } + + /// + /// A value as the right-hand side of an attribute, in braces when it is + /// more than letters, digits and underscores. + /// + public static string Value(string value) => + PlainValueRe.IsMatch(value) ? value : $"{{{value}}}"; +} diff --git a/src/Tql.Plugins.YouTrack/Support/YouTrackUrls.cs b/src/Tql.Plugins.YouTrack/Support/YouTrackUrls.cs new file mode 100644 index 00000000..b9831586 --- /dev/null +++ b/src/Tql.Plugins.YouTrack/Support/YouTrackUrls.cs @@ -0,0 +1,110 @@ +using System; +using System.Collections.Immutable; + +namespace Tql.Plugins.YouTrack.Support; + +// Service URLs and the links the plugin opens. A service URL is the address +// the user opens YouTrack on, kept with one trailing slash; the REST API is +// "api/" and every link is built from it, so an installation +// under a path prefix needs no special handling. +// +// This file has no WPF or TQL dependencies, so the plain net8.0 test project +// can compile it. +internal static class YouTrackUrls +{ + /// + /// Turns what the user entered into a service URL: an absolute http or + /// https URL without query or fragment, with one trailing slash. A bare + /// host gets https. + /// + /// The URL is not an http or https URL. + public static string NormalizeServiceUrl(string url) + { + var text = url.Trim(); + if (!text.Contains("://")) + text = "https://" + text; + + if ( + !Uri.TryCreate(text, UriKind.Absolute, out var uri) + || (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps) + || uri.Host.Length == 0 + ) + { + throw new ArgumentException($"'{url}' is not an http or https URL.", nameof(url)); + } + + return $"{uri.Scheme}://{uri.Authority}{uri.AbsolutePath.TrimEnd('/')}/"; + } + + /// + /// The service URL followed by the URLs with its path segments removed one + /// at a time, down to the bare host. The connection check tries them in + /// this order. + /// + public static ImmutableArray GetServiceUrlCandidates(string serviceUrl) + { + var url = NormalizeServiceUrl(serviceUrl); + var uri = new Uri(url); + var root = $"{uri.Scheme}://{uri.Authority}/"; + + var result = ImmutableArray.CreateBuilder(); + + result.Add(url); + + while (url != root) + { + var path = url.Substring(root.Length).TrimEnd('/'); + var index = path.LastIndexOf('/'); + + url = index < 0 ? root : root + path.Substring(0, index + 1); + + result.Add(url); + } + + return result.ToImmutable(); + } + + /// + /// Resolves a URL the API returned, such as the host-relative + /// "/hub/api/rest/avatar/...", against the service URL by the normal URI + /// rules. An absolute URL is returned as is. + /// + public static string Resolve(string serviceUrl, string url) + { + return new Uri(new Uri(WithTrailingSlash(serviceUrl)), url).AbsoluteUri; + } + + /// + /// Whether the URL has the service URL's scheme, host and port: the only + /// place the token may be sent. + /// + public static bool IsSameOrigin(string serviceUrl, string url) + { + var service = new Uri(WithTrailingSlash(serviceUrl)); + + return Uri.TryCreate(url, UriKind.Absolute, out var other) + && string.Equals(service.Scheme, other.Scheme, StringComparison.OrdinalIgnoreCase) + && string.Equals(service.Host, other.Host, StringComparison.OrdinalIgnoreCase) + && service.Port == other.Port; + } + + public static string GetIssueUrl(string serviceUrl, string idReadable) => + $"{WithTrailingSlash(serviceUrl)}issue/{Uri.EscapeDataString(idReadable)}"; + + public static string GetProjectUrl(string serviceUrl, string shortName) => + $"{WithTrailingSlash(serviceUrl)}projects/{Uri.EscapeDataString(shortName)}"; + + public static string GetAgileBoardUrl(string serviceUrl, string id) => + $"{WithTrailingSlash(serviceUrl)}agiles/{Uri.EscapeDataString(id)}/current"; + + public static string GetSavedSearchUrl(string serviceUrl, string query) => + $"{WithTrailingSlash(serviceUrl)}issues?q={Uri.EscapeDataString(query)}"; + + public static string GetDashboardUrl(string serviceUrl, string id) => + $"{WithTrailingSlash(serviceUrl)}dashboard?id={Uri.EscapeDataString(id)}"; + + public static string GetNewIssueUrl(string serviceUrl, string shortName) => + $"{WithTrailingSlash(serviceUrl)}newIssue?project={Uri.EscapeDataString(shortName)}"; + + private static string WithTrailingSlash(string serviceUrl) => serviceUrl.TrimEnd('/') + "/"; +} diff --git a/tests/Tql.Plugins.YouTrack.Test/Fixtures/Agiles.json b/tests/Tql.Plugins.YouTrack.Test/Fixtures/Agiles.json new file mode 100644 index 00000000..6989dbaf --- /dev/null +++ b/tests/Tql.Plugins.YouTrack.Test/Fixtures/Agiles.json @@ -0,0 +1,17 @@ +[ + { + "name": "Sprint Board", + "id": "201-11", + "$type": "Agile" + }, + { + "name": "Kanban", + "id": "201-12", + "$type": "Agile" + }, + { + "name": "Support", + "id": "201-13", + "$type": "Agile" + } +] diff --git a/tests/Tql.Plugins.YouTrack.Test/Fixtures/Config.json b/tests/Tql.Plugins.YouTrack.Test/Fixtures/Config.json new file mode 100644 index 00000000..f8969d17 --- /dev/null +++ b/tests/Tql.Plugins.YouTrack.Test/Fixtures/Config.json @@ -0,0 +1,4 @@ +{ + "version": "2026.2", + "$type": "FrontendConfig" +} diff --git a/tests/Tql.Plugins.YouTrack.Test/Fixtures/Dashboards.json b/tests/Tql.Plugins.YouTrack.Test/Fixtures/Dashboards.json new file mode 100644 index 00000000..fb56c3e8 --- /dev/null +++ b/tests/Tql.Plugins.YouTrack.Test/Fixtures/Dashboards.json @@ -0,0 +1,12 @@ +[ + { + "name": "YouTrack Default Dashboard", + "id": "173-10", + "$type": "Dashboard" + }, + { + "name": "Team overview", + "id": "173-11", + "$type": "Dashboard" + } +] diff --git a/tests/Tql.Plugins.YouTrack.Test/Fixtures/Issue-NotFound.json b/tests/Tql.Plugins.YouTrack.Test/Fixtures/Issue-NotFound.json new file mode 100644 index 00000000..8e4760d5 --- /dev/null +++ b/tests/Tql.Plugins.YouTrack.Test/Fixtures/Issue-NotFound.json @@ -0,0 +1,4 @@ +{ + "error": "Not Found", + "error_description": "Entity with id DEMO-999999 not found" +} diff --git a/tests/Tql.Plugins.YouTrack.Test/Fixtures/Issue.json b/tests/Tql.Plugins.YouTrack.Test/Fixtures/Issue.json new file mode 100644 index 00000000..5d997667 --- /dev/null +++ b/tests/Tql.Plugins.YouTrack.Test/Fixtures/Issue.json @@ -0,0 +1,5 @@ +{ + "summary": "Search matches word prefixes", + "idReadable": "DEMO-12", + "$type": "Issue" +} diff --git a/tests/Tql.Plugins.YouTrack.Test/Fixtures/Issues-InvalidQuery.json b/tests/Tql.Plugins.YouTrack.Test/Fixtures/Issues-InvalidQuery.json new file mode 100644 index 00000000..d9060905 --- /dev/null +++ b/tests/Tql.Plugins.YouTrack.Test/Fixtures/Issues-InvalidQuery.json @@ -0,0 +1,12 @@ +{ + "error": "invalid_query", + "error_description": "Can't parse search query, please check and update query syntax", + "error_developer_message": "Can't parse search query", + "error_field": "query", + "error_children": [ + { + "error": "The value \"Op\" isn't used for the State field.", + "error_description": "" + } + ] +} diff --git a/tests/Tql.Plugins.YouTrack.Test/Fixtures/Issues.json b/tests/Tql.Plugins.YouTrack.Test/Fixtures/Issues.json new file mode 100644 index 00000000..558e370c --- /dev/null +++ b/tests/Tql.Plugins.YouTrack.Test/Fixtures/Issues.json @@ -0,0 +1,27 @@ +[ + { + "summary": "Search matches word prefixes", + "idReadable": "DEMO-12", + "$type": "Issue" + }, + { + "summary": "Landing page loads slowly on mobile", + "idReadable": "WEB-7", + "$type": "Issue" + }, + { + "summary": "Rotate the staging certificates", + "idReadable": "OPS-31", + "$type": "Issue" + }, + { + "summary": "Document the backup procedure", + "idReadable": "DOCS-4", + "$type": "Issue" + }, + { + "summary": "Crash when the configuration file is empty", + "idReadable": "DEMO-3", + "$type": "Issue" + } +] diff --git a/tests/Tql.Plugins.YouTrack.Test/Fixtures/Me.json b/tests/Tql.Plugins.YouTrack.Test/Fixtures/Me.json new file mode 100644 index 00000000..85afafdb --- /dev/null +++ b/tests/Tql.Plugins.YouTrack.Test/Fixtures/Me.json @@ -0,0 +1,9 @@ +{ + "login": "jdoe", + "guest": false, + "email": "jane.doe@example.com", + "banned": false, + "fullName": "Jane Doe", + "id": "2-11", + "$type": "Me" +} diff --git a/tests/Tql.Plugins.YouTrack.Test/Fixtures/NotFound.json b/tests/Tql.Plugins.YouTrack.Test/Fixtures/NotFound.json new file mode 100644 index 00000000..59d71188 --- /dev/null +++ b/tests/Tql.Plugins.YouTrack.Test/Fixtures/NotFound.json @@ -0,0 +1,4 @@ +{ + "error": "Not Found", + "error_description": "HTTP 404 Not Found" +} diff --git a/tests/Tql.Plugins.YouTrack.Test/Fixtures/Projects.json b/tests/Tql.Plugins.YouTrack.Test/Fixtures/Projects.json new file mode 100644 index 00000000..086e4c07 --- /dev/null +++ b/tests/Tql.Plugins.YouTrack.Test/Fixtures/Projects.json @@ -0,0 +1,50 @@ +[ + { + "shortName": "DEMO", + "iconUrl": null, + "archived": false, + "name": "Demo", + "id": "0-101", + "$type": "Project" + }, + { + "shortName": "WEB", + "iconUrl": null, + "archived": false, + "name": "Website", + "id": "0-102", + "$type": "Project" + }, + { + "shortName": "OPS", + "iconUrl": null, + "archived": false, + "name": "Operations", + "id": "0-103", + "$type": "Project" + }, + { + "shortName": "OLD", + "iconUrl": null, + "archived": true, + "name": "Legacy Portal", + "id": "0-104", + "$type": "Project" + }, + { + "shortName": "DOCS", + "iconUrl": null, + "archived": false, + "name": "Documentation", + "id": "0-105", + "$type": "Project" + }, + { + "shortName": "MOB", + "iconUrl": null, + "archived": false, + "name": "Mobile App", + "id": "0-106", + "$type": "Project" + } +] diff --git a/tests/Tql.Plugins.YouTrack.Test/Fixtures/SavedQueries.json b/tests/Tql.Plugins.YouTrack.Test/Fixtures/SavedQueries.json new file mode 100644 index 00000000..0c3f4111 --- /dev/null +++ b/tests/Tql.Plugins.YouTrack.Test/Fixtures/SavedQueries.json @@ -0,0 +1,44 @@ +[ + { + "query": "for: me", + "name": "Assigned to me", + "id": "11-20", + "$type": "SavedQuery" + }, + { + "query": "commenter: me", + "name": "Commented by me", + "id": "11-21", + "$type": "SavedQuery" + }, + { + "query": "by: me", + "name": "Reported by me", + "id": "11-22", + "$type": "SavedQuery" + }, + { + "query": "document type: Issue", + "name": "All issues", + "id": "11-23", + "$type": "SavedQuery" + }, + { + "query": "document type: Ticket", + "name": "All tickets", + "id": "11-24", + "$type": "SavedQuery" + }, + { + "query": "State: -Done Type: Bug ", + "name": "Open bugs", + "id": "11-25", + "$type": "SavedQuery" + }, + { + "query": "tag: {Needs review} sort by: {resolved date} desc", + "name": "Recently resolved", + "id": "11-26", + "$type": "SavedQuery" + } +] diff --git a/tests/Tql.Plugins.YouTrack.Test/Fixtures/Unauthorized-InvalidToken.json b/tests/Tql.Plugins.YouTrack.Test/Fixtures/Unauthorized-InvalidToken.json new file mode 100644 index 00000000..66f602f6 --- /dev/null +++ b/tests/Tql.Plugins.YouTrack.Test/Fixtures/Unauthorized-InvalidToken.json @@ -0,0 +1,4 @@ +{ + "error": "Unauthorized", + "error_description": "Invalid token" +} diff --git a/tests/Tql.Plugins.YouTrack.Test/Fixtures/Unauthorized-NotLoggedIn.json b/tests/Tql.Plugins.YouTrack.Test/Fixtures/Unauthorized-NotLoggedIn.json new file mode 100644 index 00000000..548b8b04 --- /dev/null +++ b/tests/Tql.Plugins.YouTrack.Test/Fixtures/Unauthorized-NotLoggedIn.json @@ -0,0 +1,4 @@ +{ + "error": "Unauthorized", + "error_description": "You are not logged in." +} diff --git a/tests/Tql.Plugins.YouTrack.Test/Fixtures/Users.json b/tests/Tql.Plugins.YouTrack.Test/Fixtures/Users.json new file mode 100644 index 00000000..a2cb37b3 --- /dev/null +++ b/tests/Tql.Plugins.YouTrack.Test/Fixtures/Users.json @@ -0,0 +1,47 @@ +[ + { + "login": "build-bot", + "guest": false, + "email": null, + "banned": false, + "fullName": "Build Bot", + "id": "2-12", + "$type": "User" + }, + { + "login": "guest", + "guest": true, + "email": null, + "banned": true, + "fullName": "Guest", + "id": "2-10", + "$type": "User" + }, + { + "login": "bsmith", + "guest": false, + "email": "bob.smith@example.com", + "banned": false, + "fullName": "Bob Smith", + "id": "2-13", + "$type": "User" + }, + { + "login": "jdoe", + "guest": false, + "email": "jane.doe@example.com", + "banned": false, + "fullName": "Jane Doe", + "id": "2-11", + "$type": "User" + }, + { + "login": "cjones", + "guest": false, + "email": "carol.jones@example.com", + "banned": true, + "fullName": "Carol Jones", + "id": "2-14", + "$type": "User" + } +] diff --git a/tests/Tql.Plugins.YouTrack.Test/Fixtures/WebApp.html b/tests/Tql.Plugins.YouTrack.Test/Fixtures/WebApp.html new file mode 100644 index 00000000..b7bd9787 --- /dev/null +++ b/tests/Tql.Plugins.YouTrack.Test/Fixtures/WebApp.html @@ -0,0 +1,108 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + +
+
+ +
+
+
+
+ + +
+
+ +
+ + + + + + + + + + diff --git a/tests/Tql.Plugins.YouTrack.Test/LiveYouTrackFixture.cs b/tests/Tql.Plugins.YouTrack.Test/LiveYouTrackFixture.cs new file mode 100644 index 00000000..491e510b --- /dev/null +++ b/tests/Tql.Plugins.YouTrack.Test/LiveYouTrackFixture.cs @@ -0,0 +1,157 @@ +using System; +using System.Linq; +using System.Net.Http; +using System.Threading.Tasks; +using NUnit.Framework; +using Tql.Plugins.YouTrack.Services; +using Tql.Plugins.YouTrack.Support; + +namespace Tql.Plugins.YouTrack.Test; + +/// +/// Runs the client against a live YouTrack, read-only (GET requests only), +/// when YOUTRACK_TEST_URL and YOUTRACK_TEST_TOKEN are set. Ignored otherwise. +/// +[TestFixture] +internal class LiveYouTrackFixture +{ + private HttpClient _httpClient = null!; + private string _serviceUrl = null!; + private string _token = null!; + + [OneTimeSetUp] + public void OneTimeSetUp() + { + var url = Environment.GetEnvironmentVariable("YOUTRACK_TEST_URL"); + var token = Environment.GetEnvironmentVariable("YOUTRACK_TEST_TOKEN"); + + if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(token)) + { + Assert.Ignore( + "Set YOUTRACK_TEST_URL and YOUTRACK_TEST_TOKEN to run against a live YouTrack." + ); + return; + } + + _serviceUrl = YouTrackUrls.NormalizeServiceUrl(url); + _token = token; + _httpClient = new HttpClient(); + } + + [OneTimeTearDown] + public void OneTimeTearDown() + { + _httpClient?.Dispose(); + } + + private YouTrackClient CreateClient(string? token = null) => + new(_httpClient, _serviceUrl, token ?? _token); + + [Test] + public async Task CheckServiceUrlAcceptsTheServiceUrl() + { + var result = await YouTrackClient.CheckServiceUrl(_httpClient, _serviceUrl); + + Assert.That(result.ServiceUrl, Is.EqualTo(_serviceUrl)); + Assert.That(result.IsSuggestion, Is.False); + Assert.That(result.Version, Is.Not.Empty); + } + + [Test] + public async Task CheckServiceUrlOffersTheServiceUrlForACopiedPage() + { + var result = await YouTrackClient.CheckServiceUrl(_httpClient, $"{_serviceUrl}issues"); + + Assert.That(result.ServiceUrl, Is.EqualTo(_serviceUrl)); + Assert.That(result.IsSuggestion, Is.True); + } + + [Test] + public void ACopiedPageIsNotAYouTrackApi() + { + Assert.ThrowsAsync( + () => new YouTrackClient(_httpClient, $"{_serviceUrl}issues", _token).GetCurrentUser() + ); + } + + [Test] + public async Task GetCurrentUser() + { + var user = await CreateClient().GetCurrentUser(); + + Assert.That(user.Login, Is.Not.Empty); + Assert.That(user.Guest, Is.False); + } + + [Test] + public void AnInvalidTokenIsUnauthorized() + { + Assert.ThrowsAsync( + () => CreateClient("perm:invented.token.value").GetCurrentUser() + ); + } + + [Test] + public async Task SearchIssuesAndGetIssue() + { + var client = CreateClient(); + + var issues = await client.SearchIssues("sort by: updated desc", 5); + + Assert.That(issues, Has.Length.InRange(1, 5)); + Assert.That( + issues.Select(p => p.IdReadable), + Has.All.Matches(YouTrackQueries.IsIssueId) + ); + + var issue = await client.GetIssue(issues[0].IdReadable.ToLowerInvariant()); + + Assert.That(issue, Is.EqualTo(issues[0])); + } + + [Test] + public async Task GetIssueOfAnUnknownIdIsNull() + { + Assert.That(await CreateClient().GetIssue("NOSUCHPROJECT-999999999"), Is.Null); + } + + [Test] + public void AHalfTypedQueryIsAnInvalidQuery() + { + Assert.ThrowsAsync( + () => CreateClient().SearchIssues("#NoSuchStateOrTagAtAll") + ); + } + + [Test] + public async Task CachedListsPage() + { + var client = new YouTrackClient(_httpClient, _serviceUrl, _token) { PageSize = 2 }; + + var projects = await client.GetProjects(); + + Assert.That(projects, Is.Not.Empty); + Assert.That(projects, Has.None.Matches(p => p.Archived)); + Assert.That(projects.Select(p => p.Id), Is.Unique); + + await client.GetAgileBoards(); + await client.GetSavedQueries(); + await client.GetDashboards(); + } + + [Test] + public async Task SearchUsers() + { + var client = CreateClient(); + var me = await client.GetCurrentUser(); + + var users = await client.SearchUsers(me.Login); + + Assert.That( + users, + Has.All.Matches(p => + !string.IsNullOrEmpty(p.Email) && !p.Banned && !p.Guest + ) + ); + } +} diff --git a/tests/Tql.Plugins.YouTrack.Test/Support/FakeHttpMessageHandler.cs b/tests/Tql.Plugins.YouTrack.Test/Support/FakeHttpMessageHandler.cs new file mode 100644 index 00000000..53c4643a --- /dev/null +++ b/tests/Tql.Plugins.YouTrack.Test/Support/FakeHttpMessageHandler.cs @@ -0,0 +1,91 @@ +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace Tql.Plugins.YouTrack.Test.Support; + +/// +/// Replays canned answers by exact request URL and records every request. A +/// URL without an answer gets a 599, so a test sees which URL it missed. +/// +internal class FakeHttpMessageHandler : HttpMessageHandler +{ + private readonly Dictionary> _answers = new(); + + public List Requests { get; } = new(); + + public FakeHttpMessageHandler Answer( + string url, + string content, + string mediaType, + HttpStatusCode statusCode = HttpStatusCode.OK + ) + { + _answers[new Uri(url).AbsoluteUri] = () => + new HttpResponseMessage(statusCode) + { + Content = new StringContent(content, Encoding.UTF8, mediaType) + }; + + return this; + } + + public FakeHttpMessageHandler AnswerJson( + string url, + string json, + HttpStatusCode statusCode = HttpStatusCode.OK + ) => Answer(url, json, "application/json", statusCode); + + public FakeHttpMessageHandler AnswerFixture( + string url, + string fixture, + HttpStatusCode statusCode = HttpStatusCode.OK + ) => AnswerJson(url, Fixtures.Read(fixture), statusCode); + + public FakeHttpMessageHandler AnswerHtml(string url) => + Answer(url, Fixtures.Read("WebApp.html"), "text/html"); + + public FakeHttpMessageHandler AnswerBytes(string url, byte[] content, string mediaType) + { + _answers[new Uri(url).AbsoluteUri] = () => + { + var result = new ByteArrayContent(content); + result.Headers.ContentType = new MediaTypeHeaderValue(mediaType); + return new HttpResponseMessage(HttpStatusCode.OK) { Content = result }; + }; + + return this; + } + + protected override Task SendAsync( + HttpRequestMessage request, + CancellationToken cancellationToken + ) + { + var url = request.RequestUri!.AbsoluteUri; + + Requests.Add(new RecordedRequest(request.Method, url, request.Headers.Authorization)); + + var response = _answers.TryGetValue(url, out var answer) + ? answer() + : new HttpResponseMessage((HttpStatusCode)599) + { + Content = new StringContent($"No answer for {url}") + }; + + response.RequestMessage = request; + + return Task.FromResult(response); + } +} + +internal record RecordedRequest( + HttpMethod Method, + string Url, + AuthenticationHeaderValue? Authorization +); diff --git a/tests/Tql.Plugins.YouTrack.Test/Support/Fixtures.cs b/tests/Tql.Plugins.YouTrack.Test/Support/Fixtures.cs new file mode 100644 index 00000000..db22af1b --- /dev/null +++ b/tests/Tql.Plugins.YouTrack.Test/Support/Fixtures.cs @@ -0,0 +1,21 @@ +using System.IO; + +namespace Tql.Plugins.YouTrack.Test.Support; + +/// +/// The captured answers in Fixtures/, embedded in the test assembly. +/// +internal static class Fixtures +{ + public static string Read(string name) + { + var assembly = typeof(Fixtures).Assembly; + + using var stream = + assembly.GetManifestResourceStream($"Fixtures.{name}") + ?? throw new FileNotFoundException($"No fixture named '{name}'"); + using var reader = new StreamReader(stream); + + return reader.ReadToEnd(); + } +} diff --git a/tests/Tql.Plugins.YouTrack.Test/Tql.Plugins.YouTrack.Test.csproj b/tests/Tql.Plugins.YouTrack.Test/Tql.Plugins.YouTrack.Test.csproj new file mode 100644 index 00000000..8fad9aeb --- /dev/null +++ b/tests/Tql.Plugins.YouTrack.Test/Tql.Plugins.YouTrack.Test.csproj @@ -0,0 +1,34 @@ + + + + + net8.0 + disable + enable + 12.0 + true + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/Tql.Plugins.YouTrack.Test/YouTrackClientFixture.cs b/tests/Tql.Plugins.YouTrack.Test/YouTrackClientFixture.cs new file mode 100644 index 00000000..f1efe9b5 --- /dev/null +++ b/tests/Tql.Plugins.YouTrack.Test/YouTrackClientFixture.cs @@ -0,0 +1,568 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Text.Json.Nodes; +using System.Threading.Tasks; +using NUnit.Framework; +using Tql.Plugins.YouTrack.Services; +using Tql.Plugins.YouTrack.Test.Support; + +namespace Tql.Plugins.YouTrack.Test; + +[TestFixture] +internal class YouTrackClientFixture +{ + private const string ServiceUrl = "https://issues.example.com/"; + private const string Token = "perm:invented.token.value"; + + private FakeHttpMessageHandler _handler = null!; + private HttpClient _httpClient = null!; + private List _observed = null!; + + [SetUp] + public void SetUp() + { + _handler = new FakeHttpMessageHandler(); + _httpClient = new HttpClient(_handler); + _observed = new List(); + } + + [TearDown] + public void TearDown() + { + _httpClient.Dispose(); + } + + private YouTrackClient CreateClient( + string serviceUrl = ServiceUrl, + int pageSize = YouTrackClient.DefaultPageSize + ) => new(_httpClient, serviceUrl, Token, _observed.Add) { PageSize = pageSize }; + + private IEnumerable RequestedUrls => _handler.Requests.Select(p => p.Url); + + private void AssertEveryRequestCarriesTheToken() + { + Assert.That(_handler.Requests, Is.Not.Empty); + + foreach (var request in _handler.Requests) + { + Assert.That(request.Method, Is.EqualTo(HttpMethod.Get), request.Url); + Assert.That(request.Authorization?.Scheme, Is.EqualTo("Bearer"), request.Url); + Assert.That(request.Authorization?.Parameter, Is.EqualTo(Token), request.Url); + } + } + + // The service URL check. + + [Test] + public async Task CheckServiceUrlAcceptsTheServiceUrl() + { + _handler.AnswerFixture($"{ServiceUrl}api/config?fields=version", "Config.json"); + + var result = await YouTrackClient.CheckServiceUrl( + _httpClient, + "https://issues.example.com" + ); + + Assert.That(result.EnteredUrl, Is.EqualTo(ServiceUrl)); + Assert.That(result.ServiceUrl, Is.EqualTo(ServiceUrl)); + Assert.That(result.IsSuggestion, Is.False); + Assert.That(result.Version, Is.EqualTo("2026.2")); + Assert.That(_handler.Requests.Single().Authorization, Is.Null); + } + + [Test] + public async Task CheckServiceUrlOffersTheUrlWithoutTheCopiedPath() + { + _handler + .AnswerHtml($"{ServiceUrl}issues/api/config?fields=version") + .AnswerFixture($"{ServiceUrl}api/config?fields=version", "Config.json"); + + var result = await YouTrackClient.CheckServiceUrl( + _httpClient, + "https://issues.example.com/issues?q=for:%20me" + ); + + Assert.That(result.EnteredUrl, Is.EqualTo($"{ServiceUrl}issues/")); + Assert.That(result.ServiceUrl, Is.EqualTo(ServiceUrl)); + Assert.That(result.IsSuggestion, Is.True); + Assert.That( + RequestedUrls, + Is.EqualTo( + new[] + { + $"{ServiceUrl}issues/api/config?fields=version", + $"{ServiceUrl}api/config?fields=version" + } + ) + ); + } + + [Test] + public async Task CheckServiceUrlKeepsAPathPrefix() + { + _handler + .AnswerHtml("https://www.example.com/youtrack/issue/DEMO-12/api/config?fields=version") + .AnswerHtml("https://www.example.com/youtrack/issue/api/config?fields=version") + .AnswerFixture( + "https://www.example.com/youtrack/api/config?fields=version", + "Config.json" + ); + + var result = await YouTrackClient.CheckServiceUrl( + _httpClient, + "https://www.example.com/youtrack/issue/DEMO-12" + ); + + Assert.That(result.ServiceUrl, Is.EqualTo("https://www.example.com/youtrack/")); + Assert.That(result.IsSuggestion, Is.True); + Assert.That(_handler.Requests, Has.Count.EqualTo(3)); + } + + [Test] + public void CheckServiceUrlFailsClearlyWithoutYouTrack() + { + _handler + .AnswerHtml("https://www.example.com/wiki/api/config?fields=version") + .AnswerFixture( + "https://www.example.com/api/config?fields=version", + "NotFound.json", + HttpStatusCode.NotFound + ); + + var ex = Assert.ThrowsAsync( + () => YouTrackClient.CheckServiceUrl(_httpClient, "https://www.example.com/wiki") + )!; + + Assert.That( + ex.Message, + Does.Contain("No YouTrack REST API answers at https://www.example.com/wiki/") + ); + Assert.That(ex.Message, Does.Contain("text/html")); + Assert.That(ex.StatusCode, Is.EqualTo(HttpStatusCode.OK)); + Assert.That(_handler.Requests, Has.Count.EqualTo(2)); + } + + [Test] + public void CheckServiceUrlRejectsWhatIsNotAUrl() + { + Assert.ThrowsAsync( + () => YouTrackClient.CheckServiceUrl(_httpClient, "ftp://issues.example.com/") + ); + Assert.That(_handler.Requests, Is.Empty); + } + + // The current user and the token. + + [Test] + public async Task GetCurrentUserSendsTheToken() + { + _handler.AnswerFixture( + $"{ServiceUrl}api/users/me?fields=id,login,fullName,email,banned,guest", + "Me.json" + ); + + var user = await CreateClient().GetCurrentUser(); + + Assert.That( + user, + Is.EqualTo( + new YouTrackUserDto( + "2-11", + "jdoe", + "Jane Doe", + "jane.doe@example.com", + false, + false + ) + ) + ); + AssertEveryRequestCarriesTheToken(); + Assert.That(_observed, Is.EqualTo(new[] { HttpStatusCode.OK })); + } + + [TestCase("Unauthorized-InvalidToken.json", "Invalid token")] + [TestCase("Unauthorized-NotLoggedIn.json", "You are not logged in.")] + public void UnauthorizedMeansAWrongToken(string fixture, string description) + { + _handler.AnswerFixture( + $"{ServiceUrl}api/users/me?fields=id,login,fullName,email,banned,guest", + fixture, + HttpStatusCode.Unauthorized + ); + + var ex = Assert.ThrowsAsync( + () => CreateClient().GetCurrentUser() + )!; + + Assert.That(ex.StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized)); + Assert.That(ex.Message, Does.Contain(description)); + Assert.That(_observed, Is.EqualTo(new[] { HttpStatusCode.Unauthorized })); + } + + [Test] + public void AnHtmlAnswerIsNotAYouTrackApi() + { + var serviceUrl = $"{ServiceUrl}issues/"; + + _handler.AnswerHtml( + $"{serviceUrl}api/users/me?fields=id,login,fullName,email,banned,guest" + ); + + var ex = Assert.ThrowsAsync( + () => CreateClient(serviceUrl).GetCurrentUser() + )!; + + Assert.That(ex.StatusCode, Is.EqualTo(HttpStatusCode.OK)); + Assert.That(ex.Message, Does.Contain("text/html instead of JSON")); + Assert.That( + ex.Message, + Does.Contain($"{serviceUrl} isn't the address of a YouTrack REST API") + ); + Assert.That(ex, Is.InstanceOf()); + } + + [Test] + public void ConstructorNormalizesTheServiceUrl() + { + Assert.That(CreateClient("https://issues.example.com").ServiceUrl, Is.EqualTo(ServiceUrl)); + Assert.That( + CreateClient("https://www.example.com/youtrack").ServiceUrl, + Is.EqualTo("https://www.example.com/youtrack/") + ); + } + + // Issues. + + [Test] + public async Task SearchIssuesSendsTheQueryAsTyped() + { + _handler.AnswerFixture( + $"{ServiceUrl}api/issues?fields=idReadable,summary&query=%23Unresolved%20for%3A%20me&$top=100", + "Issues.json" + ); + + var issues = await CreateClient().SearchIssues("#Unresolved for: me"); + + Assert.That(issues, Has.Length.EqualTo(5)); + Assert.That( + issues[0], + Is.EqualTo(new YouTrackIssueDto("DEMO-12", "Search matches word prefixes")) + ); + AssertEveryRequestCarriesTheToken(); + } + + [Test] + public async Task SearchIssuesPassesTop() + { + _handler.AnswerFixture( + $"{ServiceUrl}api/issues?fields=idReadable,summary&query=kubecod&$top=10", + "Issues.json" + ); + + await CreateClient().SearchIssues("kubecod", 10); + + Assert.That(_handler.Requests, Has.Count.EqualTo(1)); + } + + [Test] + public void AQueryYouTrackCannotParseIsAnInvalidQuery() + { + _handler.AnswerFixture( + $"{ServiceUrl}api/issues?fields=idReadable,summary&query=state%3A%20Op&$top=100", + "Issues-InvalidQuery.json", + HttpStatusCode.BadRequest + ); + + var ex = Assert.ThrowsAsync( + () => CreateClient().SearchIssues("state: Op") + )!; + + Assert.That(ex.StatusCode, Is.EqualTo(HttpStatusCode.BadRequest)); + Assert.That(ex.Message, Does.Contain("Can't parse search query")); + } + + [Test] + public async Task GetIssueFetchesTheIssue() + { + _handler.AnswerFixture( + $"{ServiceUrl}api/issues/demo-12?fields=idReadable,summary", + "Issue.json" + ); + + var issue = await CreateClient().GetIssue("demo-12"); + + Assert.That( + issue, + Is.EqualTo(new YouTrackIssueDto("DEMO-12", "Search matches word prefixes")) + ); + AssertEveryRequestCarriesTheToken(); + } + + [Test] + public async Task GetIssueOfAnUnknownIdIsNull() + { + _handler.AnswerFixture( + $"{ServiceUrl}api/issues/DEMO-999999?fields=idReadable,summary", + "Issue-NotFound.json", + HttpStatusCode.NotFound + ); + + var issue = await CreateClient().GetIssue("DEMO-999999"); + + Assert.That(issue, Is.Null); + Assert.That(_observed, Is.EqualTo(new[] { HttpStatusCode.NotFound })); + } + + // The cached lists. + + [Test] + public async Task GetProjectsLeavesOutArchivedProjects() + { + _handler.AnswerFixture( + $"{ServiceUrl}api/admin/projects?fields=id,shortName,name,archived,iconUrl&$skip=0&$top=500", + "Projects.json" + ); + + var projects = await CreateClient().GetProjects(); + + Assert.That( + projects.Select(p => p.ShortName), + Is.EqualTo(new[] { "DEMO", "WEB", "OPS", "DOCS", "MOB" }) + ); + Assert.That( + projects[0], + Is.EqualTo(new YouTrackProjectDto("0-101", "DEMO", "Demo", false, null)) + ); + AssertEveryRequestCarriesTheToken(); + } + + [TestCase(2, new[] { 0, 2, 4, 6 })] + [TestCase(4, new[] { 0, 4 })] + [TestCase(6, new[] { 0, 6 })] + [TestCase(7, new[] { 0 })] + public async Task CachedListsPageUntilExhausted(int pageSize, int[] skips) + { + var all = JsonNode.Parse(Fixtures.Read("Projects.json"))!.AsArray(); + + foreach (var skip in skips) + { + var page = new JsonArray( + all.Skip(skip).Take(pageSize).Select(p => p!.DeepClone()).ToArray() + ); + + _handler.AnswerJson( + $"{ServiceUrl}api/admin/projects?fields=id,shortName,name,archived,iconUrl&$skip={skip}&$top={pageSize}", + page.ToJsonString() + ); + } + + var projects = await CreateClient(pageSize: pageSize).GetProjects(); + + Assert.That(projects, Has.Length.EqualTo(5)); + Assert.That( + RequestedUrls, + Is.EqualTo( + skips.Select(p => + $"{ServiceUrl}api/admin/projects?fields=id,shortName,name,archived,iconUrl&$skip={p}&$top={pageSize}" + ) + ) + ); + } + + [Test] + public async Task GetProjectsResolvesHostRelativeIcons() + { + var serviceUrl = "https://www.example.com/youtrack/"; + var json = JsonNode.Parse(Fixtures.Read("Projects.json"))!.AsArray(); + + json[0]!["iconUrl"] = "/hub/api/rest/avatar/0b6f1f62-1f5e-4c43-9b0e-6d5c1b1e2a33?s=48"; + json[1]!["iconUrl"] = "api/files/74-1?sign=invented"; + + _handler.AnswerJson( + $"{serviceUrl}api/admin/projects?fields=id,shortName,name,archived,iconUrl&$skip=0&$top=500", + json.ToJsonString() + ); + + var projects = await CreateClient(serviceUrl).GetProjects(); + + Assert.That( + projects[0].IconUrl, + Is.EqualTo( + "https://www.example.com/hub/api/rest/avatar/0b6f1f62-1f5e-4c43-9b0e-6d5c1b1e2a33?s=48" + ) + ); + Assert.That( + projects[1].IconUrl, + Is.EqualTo("https://www.example.com/youtrack/api/files/74-1?sign=invented") + ); + Assert.That(projects[2].IconUrl, Is.Null); + } + + [Test] + public async Task GetAgileBoards() + { + _handler.AnswerFixture( + $"{ServiceUrl}api/agiles?fields=id,name&$skip=0&$top=500", + "Agiles.json" + ); + + var boards = await CreateClient().GetAgileBoards(); + + Assert.That( + boards, + Is.EqualTo( + new[] + { + new YouTrackAgileBoardDto("201-11", "Sprint Board"), + new YouTrackAgileBoardDto("201-12", "Kanban"), + new YouTrackAgileBoardDto("201-13", "Support") + } + ) + ); + AssertEveryRequestCarriesTheToken(); + } + + [Test] + public async Task GetSavedQueries() + { + _handler.AnswerFixture( + $"{ServiceUrl}api/savedQueries?fields=id,name,query&$skip=0&$top=500", + "SavedQueries.json" + ); + + var queries = await CreateClient().GetSavedQueries(); + + Assert.That(queries, Has.Length.EqualTo(7)); + Assert.That( + queries[0], + Is.EqualTo(new YouTrackSavedQueryDto("11-20", "Assigned to me", "for: me")) + ); + Assert.That( + queries[6].Query, + Is.EqualTo("tag: {Needs review} sort by: {resolved date} desc") + ); + AssertEveryRequestCarriesTheToken(); + } + + [Test] + public async Task GetDashboards() + { + _handler.AnswerFixture( + $"{ServiceUrl}api/dashboards?fields=id,name&$skip=0&$top=500", + "Dashboards.json" + ); + + var dashboards = await CreateClient().GetDashboards(); + + Assert.That( + dashboards, + Is.EqualTo( + new[] + { + new YouTrackDashboardDto("173-10", "YouTrack Default Dashboard"), + new YouTrackDashboardDto("173-11", "Team overview") + } + ) + ); + AssertEveryRequestCarriesTheToken(); + } + + [TestCase(HttpStatusCode.NotFound, "NotFound.json")] + [TestCase(HttpStatusCode.Forbidden, "NotFound.json")] + public void AMissingOrForbiddenEndpointIsUnavailable(HttpStatusCode statusCode, string fixture) + { + _handler.AnswerFixture( + $"{ServiceUrl}api/dashboards?fields=id,name&$skip=0&$top=500", + fixture, + statusCode + ); + + var ex = Assert.ThrowsAsync( + () => CreateClient().GetDashboards() + )!; + + Assert.That(ex.StatusCode, Is.EqualTo(statusCode)); + } + + // The people directory. + + [Test] + public async Task SearchUsersLeavesOutUsersWithoutEmailBannedUsersAndGuests() + { + _handler.AnswerFixture( + $"{ServiceUrl}api/users?fields=id,login,fullName,email,banned,guest&query=jane%20doe&$top=100", + "Users.json" + ); + + var users = await CreateClient().SearchUsers("jane doe"); + + Assert.That(users.Select(p => p.Login), Is.EqualTo(new[] { "bsmith", "jdoe" })); + AssertEveryRequestCarriesTheToken(); + } + + [Test] + public void SearchUsersWithoutPermissionIsUnavailable() + { + _handler.AnswerJson( + $"{ServiceUrl}api/users?fields=id,login,fullName,email,banned,guest&query=jane&$top=100", + """{"error":"Forbidden","error_description":"invented"}""", + HttpStatusCode.Forbidden + ); + + Assert.ThrowsAsync(() => CreateClient().SearchUsers("jane")); + } + + // Icons and avatars. + + [Test] + public async Task DownloadFileResolvesHostRelativeUrlsAndSendsTheToken() + { + var bytes = new byte[] { 0x89, 0x50, 0x4E, 0x47 }; + + _handler.AnswerBytes( + "https://www.example.com/hub/api/rest/avatar/0b6f1f62-1f5e-4c43-9b0e-6d5c1b1e2a33?s=48", + bytes, + "image/png" + ); + + var (mediaType, content) = await CreateClient("https://www.example.com/youtrack/") + .DownloadFile( + "/hub/api/rest/avatar/0b6f1f62-1f5e-4c43-9b0e-6d5c1b1e2a33?s=48", + async p => (p.Headers.ContentType?.MediaType, await p.ReadAsByteArrayAsync()) + ); + + Assert.That(mediaType, Is.EqualTo("image/png")); + Assert.That(content, Is.EqualTo(bytes)); + AssertEveryRequestCarriesTheToken(); + Assert.That(_observed, Is.EqualTo(new[] { HttpStatusCode.OK })); + } + + [TestCase("https://www.gravatar.com/avatar/5f0e4ea2b5ab4b7f9b3b0f4e2c1d6a77.jpg?d=retro&s=96")] + [TestCase("http://issues.example.com/hub/api/rest/avatar/0b6f1f62?s=48")] + [TestCase("https://issues.example.com:8443/hub/api/rest/avatar/0b6f1f62?s=48")] + [TestCase("https://hub.example.com/hub/api/rest/avatar/0b6f1f62?s=48")] + public async Task DownloadFileKeepsTheTokenOffOtherHosts(string url) + { + _handler.AnswerBytes(url, new byte[] { 1 }, "image/jpeg"); + + await CreateClient().DownloadFile(url, p => p.ReadAsByteArrayAsync()); + + Assert.That(_handler.Requests.Single().Url, Is.EqualTo(url)); + Assert.That(_handler.Requests.Single().Authorization, Is.Null); + Assert.That(_observed, Is.Empty); + } + + [Test] + public void DownloadFileReportsAFailure() + { + var ex = Assert.ThrowsAsync( + () => CreateClient().DownloadFile("/missing.png", p => p.ReadAsByteArrayAsync()) + )!; + + Assert.That(ex.RequestUrl, Is.EqualTo($"{ServiceUrl}missing.png")); + Assert.That((int?)ex.StatusCode, Is.EqualTo(599)); + } +} diff --git a/tests/Tql.Plugins.YouTrack.Test/YouTrackQueriesFixture.cs b/tests/Tql.Plugins.YouTrack.Test/YouTrackQueriesFixture.cs new file mode 100644 index 00000000..8ad5dea5 --- /dev/null +++ b/tests/Tql.Plugins.YouTrack.Test/YouTrackQueriesFixture.cs @@ -0,0 +1,58 @@ +using NUnit.Framework; +using Tql.Plugins.YouTrack.Support; + +namespace Tql.Plugins.YouTrack.Test; + +[TestFixture] +internal class YouTrackQueriesFixture +{ + [TestCase("KC-230", true)] + [TestCase("kc-230", true)] + [TestCase(" KC-230 ", true)] + [TestCase("MY_PROJ2-7", true)] + [TestCase("A-1", true)] + [TestCase("3-6943", false)] + [TestCase("KC-", false)] + [TestCase("KC 230", false)] + [TestCase("KC-230x", false)] + [TestCase("kubecod", false)] + [TestCase("#Unresolved for: me", false)] + public void IsIssueId(string text, bool expected) + { + Assert.That(YouTrackQueries.IsIssueId(text), Is.EqualTo(expected)); + } + + [TestCase("KC", null, "project: KC sort by: updated desc")] + [TestCase("KC", " ", "project: KC sort by: updated desc")] + [TestCase("KC", " kubecod ", "project: KC kubecod")] + [TestCase("KC", "#Unresolved for: me", "project: KC #Unresolved for: me")] + [TestCase("MY_PROJ2", "x", "project: MY_PROJ2 x")] + [TestCase("MY-PROJ", "x", "project: {MY-PROJ} x")] + public void Project(string shortName, string? text, string expected) + { + Assert.That(YouTrackQueries.Project(shortName, text), Is.EqualTo(expected)); + } + + [TestCase("for: me", null, "for: me")] + [TestCase("for: me", " ", "for: me")] + [TestCase("for: me", " kubecod ", "(for: me) and (kubecod)")] + [TestCase( + "tag: {Needs review} sort by: {resolved date} desc", + "kubecod", + "(tag: {Needs review} sort by: {resolved date} desc) and (kubecod)" + )] + [TestCase("State: -Done Type: Bug ", "for: me", "(State: -Done Type: Bug) and (for: me)")] + [TestCase("", "kubecod", "kubecod")] + public void SavedSearch(string savedQuery, string? text, string expected) + { + Assert.That(YouTrackQueries.SavedSearch(savedQuery, text), Is.EqualTo(expected)); + } + + [TestCase("KC", "KC")] + [TestCase("Needs review", "{Needs review}")] + [TestCase("in-progress", "{in-progress}")] + public void Value(string value, string expected) + { + Assert.That(YouTrackQueries.Value(value), Is.EqualTo(expected)); + } +} diff --git a/tests/Tql.Plugins.YouTrack.Test/YouTrackUrlsFixture.cs b/tests/Tql.Plugins.YouTrack.Test/YouTrackUrlsFixture.cs new file mode 100644 index 00000000..ce686b36 --- /dev/null +++ b/tests/Tql.Plugins.YouTrack.Test/YouTrackUrlsFixture.cs @@ -0,0 +1,142 @@ +using System; +using NUnit.Framework; +using Tql.Plugins.YouTrack.Support; + +namespace Tql.Plugins.YouTrack.Test; + +[TestFixture] +internal class YouTrackUrlsFixture +{ + [TestCase("https://issues.example.com", "https://issues.example.com/")] + [TestCase("https://issues.example.com/", "https://issues.example.com/")] + [TestCase("https://www.example.com/youtrack", "https://www.example.com/youtrack/")] + [TestCase("https://www.example.com/youtrack//", "https://www.example.com/youtrack/")] + [TestCase("https://example.youtrack.cloud", "https://example.youtrack.cloud/")] + [TestCase( + "https://example.myjetbrains.com/youtrack/", + "https://example.myjetbrains.com/youtrack/" + )] + [TestCase( + " https://Issues.Example.COM/issues?q=for:%20me#top ", + "https://issues.example.com/issues/" + )] + [TestCase("issues.example.com", "https://issues.example.com/")] + [TestCase("http://localhost:8080", "http://localhost:8080/")] + [TestCase("https://issues.example.com:443/", "https://issues.example.com/")] + public void NormalizeServiceUrl(string url, string expected) + { + Assert.That(YouTrackUrls.NormalizeServiceUrl(url), Is.EqualTo(expected)); + } + + [TestCase("")] + [TestCase("ftp://issues.example.com/")] + [TestCase("file:///c:/temp")] + [TestCase("https://")] + public void NormalizeServiceUrlRejectsWhatIsNotAUrl(string url) + { + Assert.Throws(() => YouTrackUrls.NormalizeServiceUrl(url)); + } + + [Test] + public void ServiceUrlCandidatesStripPathSegmentsDownToTheHost() + { + Assert.That( + YouTrackUrls.GetServiceUrlCandidates("https://www.example.com/youtrack/issue/KC-230"), + Is.EqualTo( + new[] + { + "https://www.example.com/youtrack/issue/KC-230/", + "https://www.example.com/youtrack/issue/", + "https://www.example.com/youtrack/", + "https://www.example.com/" + } + ) + ); + Assert.That( + YouTrackUrls.GetServiceUrlCandidates("https://issues.example.com/"), + Is.EqualTo(new[] { "https://issues.example.com/" }) + ); + } + + [TestCase( + "https://issues.example.com/", + "/hub/api/rest/avatar/0b6f1f62?s=48", + "https://issues.example.com/hub/api/rest/avatar/0b6f1f62?s=48" + )] + [TestCase( + "https://www.example.com/youtrack/", + "/hub/api/rest/avatar/0b6f1f62?s=48", + "https://www.example.com/hub/api/rest/avatar/0b6f1f62?s=48" + )] + [TestCase( + "https://www.example.com/youtrack", + "api/files/74-1?sign=x", + "https://www.example.com/youtrack/api/files/74-1?sign=x" + )] + [TestCase( + "https://www.example.com/youtrack/", + "https://www.gravatar.com/avatar/5f0e.jpg?d=retro&s=96", + "https://www.gravatar.com/avatar/5f0e.jpg?d=retro&s=96" + )] + public void ResolveFollowsTheUriRules(string serviceUrl, string url, string expected) + { + Assert.That(YouTrackUrls.Resolve(serviceUrl, url), Is.EqualTo(expected)); + } + + [TestCase("https://www.example.com/youtrack/hub/api/x", true)] + [TestCase("https://WWW.EXAMPLE.COM/hub/api/x", true)] + [TestCase("https://www.example.com:443/hub/api/x", true)] + [TestCase("http://www.example.com/hub/api/x", false)] + [TestCase("https://www.example.com:8443/hub/api/x", false)] + [TestCase("https://hub.example.com/hub/api/x", false)] + [TestCase("https://www.gravatar.com/avatar/5f0e.jpg", false)] + [TestCase("/hub/api/x", false)] + public void IsSameOriginComparesSchemeHostAndPort(string url, bool expected) + { + Assert.That( + YouTrackUrls.IsSameOrigin("https://www.example.com/youtrack/", url), + Is.EqualTo(expected) + ); + } + + [TestCase("https://issues.example.com/")] + [TestCase("https://issues.example.com")] + public void Links(string serviceUrl) + { + Assert.That( + YouTrackUrls.GetIssueUrl(serviceUrl, "KC-230"), + Is.EqualTo("https://issues.example.com/issue/KC-230") + ); + Assert.That( + YouTrackUrls.GetProjectUrl(serviceUrl, "KC"), + Is.EqualTo("https://issues.example.com/projects/KC") + ); + Assert.That( + YouTrackUrls.GetAgileBoardUrl(serviceUrl, "201-11"), + Is.EqualTo("https://issues.example.com/agiles/201-11/current") + ); + Assert.That( + YouTrackUrls.GetSavedSearchUrl(serviceUrl, "tag: {Needs review} sort by: updated"), + Is.EqualTo( + "https://issues.example.com/issues?q=tag%3A%20%7BNeeds%20review%7D%20sort%20by%3A%20updated" + ) + ); + Assert.That( + YouTrackUrls.GetDashboardUrl(serviceUrl, "173-10"), + Is.EqualTo("https://issues.example.com/dashboard?id=173-10") + ); + Assert.That( + YouTrackUrls.GetNewIssueUrl(serviceUrl, "KC"), + Is.EqualTo("https://issues.example.com/newIssue?project=KC") + ); + } + + [Test] + public void LinksKeepAPathPrefix() + { + Assert.That( + YouTrackUrls.GetIssueUrl("https://www.example.com/youtrack/", "KC-230"), + Is.EqualTo("https://www.example.com/youtrack/issue/KC-230") + ); + } +} diff --git a/tests/Tql.Plugins.YouTrack.Test/packages.lock.json b/tests/Tql.Plugins.YouTrack.Test/packages.lock.json new file mode 100644 index 00000000..771c2212 --- /dev/null +++ b/tests/Tql.Plugins.YouTrack.Test/packages.lock.json @@ -0,0 +1,83 @@ +{ + "version": 1, + "dependencies": { + "net8.0": { + "Microsoft.NET.Test.Sdk": { + "type": "Direct", + "requested": "[17.8.0, )", + "resolved": "17.8.0", + "contentHash": "BmTYGbD/YuDHmApIENdoyN1jCk0Rj1fJB0+B/fVekyTdVidr91IlzhqzytiUgaEAzL1ZJcYCme0MeBMYvJVzvw==", + "dependencies": { + "Microsoft.CodeCoverage": "17.8.0", + "Microsoft.TestPlatform.TestHost": "17.8.0" + } + }, + "NUnit": { + "type": "Direct", + "requested": "[3.14.0, )", + "resolved": "3.14.0", + "contentHash": "R7iPwD7kbOaP3o2zldWJbWeMQAvDKD0uld27QvA3PAALl1unl7x0v2J7eGiJOYjimV/BuGT4VJmr45RjS7z4LA==", + "dependencies": { + "NETStandard.Library": "2.0.0" + } + }, + "NUnit3TestAdapter": { + "type": "Direct", + "requested": "[4.5.0, )", + "resolved": "4.5.0", + "contentHash": "s8JpqTe9bI2f49Pfr3dFRfoVSuFQyraTj68c3XXjIS/MRGvvkLnrg6RLqnTjdShX+AdFUCCU/4Xex58AdUfs6A==" + }, + "Microsoft.CodeCoverage": { + "type": "Transitive", + "resolved": "17.8.0", + "contentHash": "KC8SXWbGIdoFVdlxKk9WHccm0llm9HypcHMLUUFabRiTS3SO2fQXNZfdiF3qkEdTJhbRrxhdRxjL4jbtwPq4Ew==" + }, + "Microsoft.NETCore.Platforms": { + "type": "Transitive", + "resolved": "1.1.0", + "contentHash": "kz0PEW2lhqygehI/d6XsPCQzD7ff7gUJaVGPVETX611eadGsA3A877GdSlU0LRVMCTH/+P3o2iDTak+S08V2+A==" + }, + "Microsoft.TestPlatform.ObjectModel": { + "type": "Transitive", + "resolved": "17.8.0", + "contentHash": "AYy6vlpGMfz5kOFq99L93RGbqftW/8eQTqjT9iGXW6s9MRP3UdtY8idJ8rJcjeSja8A18IhIro5YnH3uv1nz4g==", + "dependencies": { + "NuGet.Frameworks": "6.5.0", + "System.Reflection.Metadata": "1.6.0" + } + }, + "Microsoft.TestPlatform.TestHost": { + "type": "Transitive", + "resolved": "17.8.0", + "contentHash": "9ivcl/7SGRmOT0YYrHQGohWiT5YCpkmy/UEzldfVisLm6QxbLaK3FAJqZXI34rnRLmqqDCeMQxKINwmKwAPiDw==", + "dependencies": { + "Microsoft.TestPlatform.ObjectModel": "17.8.0", + "Newtonsoft.Json": "13.0.1" + } + }, + "NETStandard.Library": { + "type": "Transitive", + "resolved": "2.0.0", + "contentHash": "7jnbRU+L08FXKMxqUflxEXtVymWvNOrS8yHgu9s6EM8Anr6T/wIX4nZ08j/u3Asz+tCufp3YVwFSEvFTPYmBPA==", + "dependencies": { + "Microsoft.NETCore.Platforms": "1.1.0" + } + }, + "Newtonsoft.Json": { + "type": "Transitive", + "resolved": "13.0.1", + "contentHash": "ppPFpBcvxdsfUonNcvITKqLl3bqxWbDCZIzDWHzjpdAHRFfZe0Dw9HmA0+za13IdyrgJwpkDTDA9fHaxOrt20A==" + }, + "NuGet.Frameworks": { + "type": "Transitive", + "resolved": "6.5.0", + "contentHash": "QWINE2x3MbTODsWT1Gh71GaGb5icBz4chS8VYvTgsBnsi8esgN6wtHhydd7fvToWECYGq7T4cgBBDiKD/363fg==" + }, + "System.Reflection.Metadata": { + "type": "Transitive", + "resolved": "1.6.0", + "contentHash": "COC1aiAJjCoA5GBF+QKL2uLqEBew4JsCkQmoHKbN3TlOZKa2fKLz5CpiRQKDz0RsAOEGsVKqOD5bomsXq/4STQ==" + } + } + } +} \ No newline at end of file From c7e7d4056a7d5dd17edf01c65bef5a33b3779c1e Mon Sep 17 00:00:00 2001 From: Pieter van Ginkel Date: Sat, 21 Nov 2026 15:29:06 +0100 Subject: [PATCH 2/9] Run the YouTrack tests as kc project test, the live fixture included. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RGjkV3AFfnNjd6n2D9pwGX --- .kubecoder/config.yaml | 5 +++-- .kubecoder/project.yaml | 22 +++++++++++++++------- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/.kubecoder/config.yaml b/.kubecoder/config.yaml index eb57d864..689d69de 100644 --- a/.kubecoder/config.yaml +++ b/.kubecoder/config.yaml @@ -14,8 +14,9 @@ tools: memory: 4Gi secrets: - # Permanent token for https://issues.webathome.org. Only for checking the - # YouTrack plugin's REST calls with curl; nothing in the repo reads it. + # Permanent token for https://issues.webathome.org, for checking the YouTrack + # plugin's REST calls with curl and for the live fixture `kc project test` + # runs (read-only). YOUTRACK_API_KEY_SECRET: youtrack-api-key preamble: diff --git a/.kubecoder/project.yaml b/.kubecoder/project.yaml index 1c501ee4..980701ce 100644 --- a/.kubecoder/project.yaml +++ b/.kubecoder/project.yaml @@ -1,9 +1,10 @@ # Curated entry points for TQL. Schema: https://kubecoder.home/help/reference/project-yaml/ # -# Every project in Tql.sln targets net8.0-windows (WPF + WinForms). It compiles on Linux -# through EnableWindowsTargeting (Directory.Build.props) with Microsoft's SDK, but nothing -# WPF runs here: not the app, and not the test projects, whose test host needs the -# Microsoft.WindowsDesktop.App runtime that only exists on Windows. +# Every project in Tql.sln but one targets net8.0-windows (WPF + WinForms). They compile +# on Linux through EnableWindowsTargeting (Directory.Build.props) with Microsoft's SDK, but +# nothing WPF runs here: not the app, and not their test projects, whose test host needs +# the Microsoft.WindowsDesktop.App runtime that only exists on Windows. The exception is +# tests/Tql.Plugins.YouTrack.Test, plain net8.0, which the test verb runs. projects: root: @@ -22,9 +23,16 @@ projects: # win-x64 section to each tracked packages.lock.json; NuGetLockFilePath keeps those # lock files in obj/ instead. - cexec dotnet dotnet publish src/Tql.DebugApp -c Debug -r win-x64 --self-contained -o build/DebugApp -p:NuGetLockFilePath=obj/packages.win-x64.lock.json - # test: deliberately unset. No test project can run on Linux (see the header), and CI - # runs none either. A WPF-free test project (plain net8.0) is the plan for the YouTrack - # plugin; see docs/Designs/YouTrack-plugin.md. + # The one test project that runs on Linux: the YouTrack plugin's WPF-free core, compiled + # into plain net8.0 (docs/Designs/YouTrack-plugin.md). The other test projects need + # Windows (see the header), and CI runs none. cexec passes the environment on to the + # dotnet container, so the live fixture runs too: read-only, against + # issues.webathome.org, with the environment's token. + test: + - >- + YOUTRACK_TEST_URL=https://issues.webathome.org + YOUTRACK_TEST_TOKEN="$YOUTRACK_API_KEY_SECRET" + cexec dotnet dotnet test tests/Tql.Plugins.YouTrack.Test lint: - cexec dotnet dotnet csharpier --check . From cd2b9bdf5c20d8fe6f0bdb2ceaf6814ceee22bfc Mon Sep 17 00:00:00 2001 From: Pieter van Ginkel Date: Sat, 21 Nov 2026 15:31:15 +0100 Subject: [PATCH 3/9] Correct the YouTrack design's page-size and invalid-query facts. Phase 1 measured that /api/issues returns 500 items without $top, not 42, and that a half-typed query answers 400 invalid_query. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RGjkV3AFfnNjd6n2D9pwGX --- docs/Designs/YouTrack-plugin.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/docs/Designs/YouTrack-plugin.md b/docs/Designs/YouTrack-plugin.md index 01115ae8..e9fb7c89 100644 --- a/docs/Designs/YouTrack-plugin.md +++ b/docs/Designs/YouTrack-plugin.md @@ -102,8 +102,9 @@ once there is more than one. ## Features -Paged lists use `$skip` and `$top`; every call passes `$top`, because YouTrack -returns 42 items when it is left out. +Paged lists use `$skip` and `$top`; every call passes `$top`, because the +default page size is not documented (measured: `/api/issues` returned 500 items +without it). - **YouTrack Issues**: searched live with `GET /api/issues?query=&$top=100`. The text goes to YouTrack as a query, @@ -126,7 +127,9 @@ returns 42 items when it is left out. Measured on issues.webathome.org: YouTrack matches word prefixes without a wildcard (`kubecod` finds "KubeCoder"), so the plugin never appends `*`. Doing so could also break a query the user typed. `GET /api/issues/` answers 404 -for an issue that doesn't exist, and the search then runs as usual. +for an issue that doesn't exist, and the search then runs as usual. A half-typed +query such as `#Unres` or `state: Op` answers 400 with `invalid_query`; the +plugin shows no results for it rather than an error. The people directory searches `GET /api/users?query=&$top=100`. It leaves out users without an email address, banned users and guests, and hands the rest From f999c448a48d0e0f598e776b3aebd66d43765b47 Mon Sep 17 00:00:00 2001 From: Pieter van Ginkel Date: Sat, 21 Nov 2026 15:31:50 +0100 Subject: [PATCH 4/9] Added the YouTrack plugin manual test script and listed YouTrack in the README. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RGjkV3AFfnNjd6n2D9pwGX --- README.md | 4 +- specs/Plugins - YouTrack/001-Installation.md | 45 ++++++++ specs/Plugins - YouTrack/002-Configuration.md | 96 +++++++++++++++ specs/Plugins - YouTrack/003-Search.md | 109 ++++++++++++++++++ .../004-Second-connection.md | 41 +++++++ .../005-Search-second-connection.md | 47 ++++++++ .../Configuration/Plugins/YouTrack.md | 5 + 7 files changed, 345 insertions(+), 2 deletions(-) create mode 100644 specs/Plugins - YouTrack/001-Installation.md create mode 100644 specs/Plugins - YouTrack/002-Configuration.md create mode 100644 specs/Plugins - YouTrack/003-Search.md create mode 100644 specs/Plugins - YouTrack/004-Second-connection.md create mode 100644 specs/Plugins - YouTrack/005-Search-second-connection.md create mode 100644 specs/_includes/Configuration/Plugins/YouTrack.md diff --git a/README.md b/README.md index 6d45ac1a..04f694a0 100644 --- a/README.md +++ b/README.md @@ -19,8 +19,8 @@ towards the first release. ## Features -- Support for Azure, Azure DevOps, JIRA, Confluence, GitHub, Outlook and - Microsoft Teams. +- Support for Azure, Azure DevOps, JIRA, YouTrack, Confluence, GitHub, Outlook + and Microsoft Teams. - Built in plugin system to be able to add your own plugins. - Quick start tutorial to get you up and running quickly. - Advanced search capabilities. You'll forget how to use the web apps once you diff --git a/specs/Plugins - YouTrack/001-Installation.md b/specs/Plugins - YouTrack/001-Installation.md new file mode 100644 index 00000000..2fff2fdf --- /dev/null +++ b/specs/Plugins - YouTrack/001-Installation.md @@ -0,0 +1,45 @@ +--- +testspace: +title: Plugins - YouTrack / 001 - Installation +description: Install the YouTrack plugin. +--- + +{% if page %}{% assign spec = page %}{% endif %} + +# {{ spec.title }} + +{{ spec.description }} + +{% include Setup/Clean-Setup.md %} + +## Installation + +{% include Setup/Local-package-source.md %} + +Until the plugin is published, run it from the KubeCoder dev build instead. The +plugin is already loaded in that build, so skip the installation table below and +continue with **Verify installation**, which then only checks that the plugin is +present: + +- Run `\\tqlapp-tql-49385e.home\work\TQL\scripts\Run-KubeCoder-Build.bat`. It + copies the build to `%TEMP%\TQL-DebugApp` and starts + `Tql.DebugApp.exe --env Debug` there. + +For the published plugin: + +| Action | Expected result | +| ------------------------------------------- | --------------- | +| Open the **Configuration** window. | | +| Navigate to **Application > Plugins**. | | +| Select the **TQL YouTrack Plugin** plugin. | | +| **Install** the plugin. | | +| **Restart** the application when requested. | | + +## Verify installation + +| Action | Expected result | +| ------------------------------------------------ | ------------------------------------------------------ | +| Open the **Configuration** window. | | +| Navigate to **Application > Plugins**. | | +| Switch to the **Installed** tab. | The **TQL YouTrack Plugin** plugin shows as installed. | +| Navigate to the **YouTrack** configuration page. | The configuration page opens. | diff --git a/specs/Plugins - YouTrack/002-Configuration.md b/specs/Plugins - YouTrack/002-Configuration.md new file mode 100644 index 00000000..41ae567a --- /dev/null +++ b/specs/Plugins - YouTrack/002-Configuration.md @@ -0,0 +1,96 @@ +--- +testspace: +title: Plugins - YouTrack / 002 - Configuration +description: Configure the YouTrack plugin. +--- + +{% if page %}{% assign spec = page %}{% endif %} +{% include Configuration/Plugins/YouTrack.md %} + +# {{ spec.title }} + +{{ spec.description }} + +{% include Setup/Run-App.md %} + +A token is created in YouTrack under Profile, Account Security, New token, with +the YouTrack scope. + +## Validate dialog + +| Action | Expected result | +| ----------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- | +| Open the **Configuration** window. | | +| Navigate to **YouTrack**. | The **YouTrack > General** page is highlighted. | +| **Add** a new connection. | The dialog has the fields **Name**, **URL** and **Token**. | +| Look at the help text of **URL**. | It reads "The address you open YouTrack on, e.g. https://youtrack.example.com or https://example.youtrack.cloud." | +| Look at the help text of **Token**. | It says where a token is made: Profile, Account Security, New token, with the YouTrack scope. The token is shown as a password box. | +| **Cancel** the dialog. | No connection is added. | + +## URL copied from the address bar + +| Action | Expected result | +| ------------------------------------------------- | ---------------------------------------------------------------------------------------- | +| Open the **Configuration** window. | | +| Navigate to **YouTrack**. | | +| **Add** a new connection with the settings below. | | +| Click **Save**. | The dialog asks "Did you mean {{ youtrack_url }}/?". No exception shows. | +| Decline the suggestion. | The connection is not saved with the wrong URL; the dialog stays open or closes cleanly. | +| Click **Save** again and accept the suggestion. | The URL changes to `{{ youtrack_url }}/` and the connection is accepted. | +| **Cancel** the dialog. | | + +- Connection settings: + - Name: `{{ youtrack_name }}` + - URL: `{{ youtrack_bad_url }}` + - Token: `{{ youtrack_token }}` + +## Wrong token + +| Action | Expected result | +| ------------------------------------------------- | --------------------------------------------------------------------------- | +| Open the **Configuration** window. | | +| Navigate to **YouTrack**. | | +| **Add** a new connection with the settings below. | | +| Click **Save**. | A plain message says the token is wrong. No exception or stack trace shows. | +| **Cancel** the dialog. | No connection is added. | + +- Connection settings: + - Name: `{{ youtrack_name }}` + - URL: `{{ youtrack_url }}` + - Token: `wrong-token` + +## Configuration + +| Action | Expected result | +| ------------------------------------------------- | ------------------------------------------------ | +| Open the **Configuration** window. | | +| Navigate to **YouTrack**. | The **YouTrack > General** page is highlighted. | +| **Add** a new connection with the settings below. | | +| Click **Save**. | The connection is accepted without any question. | +| Click **Save**. | | + +- Connection settings: + - Name: `{{ youtrack_name }}` + - URL: `{{ youtrack_url }}` + - Token: `{{ youtrack_token }}` + +## Validate configuration + +| Action | Expected result | +| -------------------------------------------- | --------------------------------------------------------------------------------- | +| Open the **Configuration** window. | | +| Navigate to **YouTrack**. | The **YouTrack > General** page is highlighted. | +| Highlight the connection and click **Edit**. | The settings conform to the settings below. The token is not shown in clear text. | + +- Connection settings: + - Name: `{{ youtrack_name }}` + - URL: `{{ youtrack_url }}/` + - Token: `{{ youtrack_token }}` + +## Validate authentication + +| Action | Expected result | +| --------------------------------------------- | ----------------------------- | +| Open the app. | | +| Type in `youtrack`. | The YouTrack categories show. | +| **Enter** the **YouTrack Projects** category. | A list of projects shows. | diff --git a/specs/Plugins - YouTrack/003-Search.md b/specs/Plugins - YouTrack/003-Search.md new file mode 100644 index 00000000..bd30ce02 --- /dev/null +++ b/specs/Plugins - YouTrack/003-Search.md @@ -0,0 +1,109 @@ +--- +testspace: +title: Plugins - YouTrack / 003 - Search +description: Verify search features. +--- + +{% if page %}{% assign spec = page %}{% endif %} + +# {{ spec.title }} + +{{ spec.description }} + +{% include Setup/Run-App.md %} + +## Find issue + +| Action | Expected result | +| ------------------------------------------- | ----------------------------------------- | +| Open the app. | | +| **Enter** the **YouTrack Issues** category. | No issues show. | +| **Type** a search term. | All issues matching the search term show. | +| **Type** a partial word, like `kubecod`. | Issues with words starting with it show. | +| **Activate** an issue. | The issue opens. | + +## Find issue by ID + +| Action | Expected result | +| ----------------------------------------------------------- | ---------------------------------------------- | +| Open the app. | | +| **Enter** the **YouTrack Issues** category. | | +| **Type** an existing issue ID in upper case, like `KC-230`. | The issue shows first. | +| **Type** the same issue ID in lower case, like `kc-230`. | The issue shows first. | +| **Activate** the issue. | The issue opens directly. | +| **Type** an issue ID that does not exist, like `KC-999999`. | No error shows; the list is searched as usual. | + +## Find issue with a YouTrack query + +| Action | Expected result | +| ------------------------------------------- | -------------------------------------------- | +| Open the app. | | +| **Enter** the **YouTrack Issues** category. | | +| **Type** in `#Unresolved for: me`. | Only unresolved issues assigned to you show. | +| **Activate** an issue. | The issue opens. | + +## Find project + +| Action | Expected result | +| --------------------------------------------- | -------------------------- | +| Open the app. | | +| **Enter** the **YouTrack Projects** category. | A list of projects shows. | +| Verify the list. | No archived projects show. | +| **Activate** a project. | The project page opens. | + +## Find issues in project + +| Action | Expected result | +| --------------------------------------------- | --------------------------------------------------- | +| Open the app. | | +| **Enter** the **YouTrack Projects** category. | A list of projects shows. | +| **Enter** a project. | All issues of the project show, last updated first. | +| **Type** a search term. | Only issues of the project matching the term show. | +| **Activate** an issue. | The issue opens. | + +## Find agile board + +| Action | Expected result | +| ------------------------------------------------- | ------------------------------------------ | +| Open the app. | | +| **Enter** the **YouTrack Agile Boards** category. | A list of boards shows. | +| **Type** a search term. | The list of boards is filtered by name. | +| **Activate** a board. | The board opens, also if it has no sprint. | +| Select a board. | It cannot be entered to search in it. | + +## Find saved search + +| Action | Expected result | +| --------------------------------------------------- | ------------------------------------------------ | +| Open the app. | | +| **Enter** the **YouTrack Saved Searches** category. | A list of saved searches shows. | +| **Activate** a saved search. | The issues of the saved search show in YouTrack. | + +## Find issue in saved search + +| Action | Expected result | +| --------------------------------------------------- | -------------------------------------------------------- | +| Open the app. | | +| **Enter** the **YouTrack Saved Searches** category. | | +| **Enter** a saved search. | All issues matching the saved search show. | +| **Type** a search term. | Only issues matching the saved search and the term show. | +| **Activate** an issue. | The issue opens. | + +## Find dashboard + +| Action | Expected result | +| ----------------------------------------------- | ------------------------------------------- | +| Open the app. | | +| **Enter** the **YouTrack Dashboards** category. | A list of dashboards shows. | +| **Type** a search term. | The list of dashboards is filtered by name. | +| **Activate** a dashboard. | The dashboard opens. | +| Select a dashboard. | It cannot be entered to search in it. | + +## Create issue + +| Action | Expected result | +| ---------------------------------------------- | -------------------------------------------------------- | +| Open the app. | | +| **Enter** the **New YouTrack Issue** category. | One item per project shows. | +| **Type** in the name of a project. | The item of that project shows. | +| **Activate** the item. | The new issue page opens with that project pre-selected. | diff --git a/specs/Plugins - YouTrack/004-Second-connection.md b/specs/Plugins - YouTrack/004-Second-connection.md new file mode 100644 index 00000000..81ad3dd8 --- /dev/null +++ b/specs/Plugins - YouTrack/004-Second-connection.md @@ -0,0 +1,41 @@ +--- +testspace: +title: Plugins - YouTrack / 004 - Second connection +description: Configure a second connection. +--- + +{% if page %}{% assign spec = page %}{% endif %} +{% include Configuration/Plugins/YouTrack.md %} + +# {{ spec.title }} + +{{ spec.description }} + +{% include Setup/Run-App.md %} + +## Create connection + +| Action | Expected result | +| ------------------------------------------------- | ----------------------------------------------- | +| Open the **Configuration** window. | | +| Navigate to **YouTrack**. | The **YouTrack > General** page is highlighted. | +| **Add** a new connection with the settings below. | | +| Click **Save**. | | +| Click **Save**. | | + +- Connection settings: + - Name: `{{ youtrack_alt_name }}` + - URL: `{{ youtrack_url }}` + - Token: `{{ youtrack_token }}` + +## Verify multiple connections + +| Action | Expected result | +| ---------------------------- | ----------------------------------------------------------------------------------------------------------------------- | +| Open the app. | | +| Type in `youtrack projects`. | One **YouTrack Projects ({{ youtrack_name }})** item and one **YouTrack Projects ({{ youtrack_alt_name }})** item show. | +| Type in `youtrack issues`. | Both an **YouTrack Issues ({{ youtrack_name }})** and an **YouTrack Issues ({{ youtrack_alt_name }})** item show. | +| Type in `youtrack agile`. | The agile boards categories carry the connection names too. | +| Type in `youtrack saved`. | The saved searches categories carry the connection names too. | +| Type in `youtrack dash`. | The dashboards categories carry the connection names too. | +| Type in `new youtrack`. | The **New YouTrack Issue** categories carry the connection names too. | diff --git a/specs/Plugins - YouTrack/005-Search-second-connection.md b/specs/Plugins - YouTrack/005-Search-second-connection.md new file mode 100644 index 00000000..c25cccc1 --- /dev/null +++ b/specs/Plugins - YouTrack/005-Search-second-connection.md @@ -0,0 +1,47 @@ +--- +testspace: +title: Plugins - YouTrack / 005 - Search second connection +description: Verify functionality with a second connection. +--- + +{% if page %}{% assign spec = page %}{% endif %} +{% include Configuration/Plugins/YouTrack.md %} + +# {{ spec.title }} + +{{ spec.description }} + +{% include Setup/Run-App.md %} + +## Verify history of the connections + +| Action | Expected result | +| ----------------------------------------------------------------------- | ----------------------------------------------------- | +| Open the app. | | +| **Enter** the **YouTrack Projects ({{ youtrack_name }})** category. | The previously selected project shows in the history. | +| **Enter** the **YouTrack Projects ({{ youtrack_alt_name }})** category. | No history shows. | + +## Search in the second connection + +| Action | Expected result | +| --------------------------------------------------------------------- | ----------------------------------------- | +| Open the app. | | +| **Enter** the **YouTrack Issues ({{ youtrack_alt_name }})** category. | No issues show. | +| **Type** a search term. | All issues matching the search term show. | +| **Activate** an issue. | The issue opens. | + +## Delete connection + +| Action | Expected result | +| -------------------------------------------------------------------------- | ----------------------------------------------- | +| Open the **Configuration** window. | | +| Navigate to **YouTrack**. | The **YouTrack > General** page is highlighted. | +| Highlight the **{{ youtrack_alt_name }}** connection and click **Delete**. | The connection is deleted. | +| Click **Save**. | | + +## Verify single connection + +| Action | Expected result | +| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Open the app. | | +| Type in `youtrack projects`. | Only a **YouTrack Projects** item shows instead of the **YouTrack Projects ({{ youtrack_name }})** and **YouTrack Projects ({{ youtrack_alt_name }})**. | diff --git a/specs/_includes/Configuration/Plugins/YouTrack.md b/specs/_includes/Configuration/Plugins/YouTrack.md new file mode 100644 index 00000000..6506581c --- /dev/null +++ b/specs/_includes/Configuration/Plugins/YouTrack.md @@ -0,0 +1,5 @@ +{% assign youtrack_name = "webathome" -%} +{% assign youtrack_alt_name = "test" -%} +{% assign youtrack_url = "https://issues.webathome.org" -%} +{% assign youtrack_bad_url = "https://issues.webathome.org/issues" -%} +{% assign youtrack_token = "(omitted)" -%} From b1055dd798146f3de86cf2c430f67795fa073e79 Mon Sep 17 00:00:00 2001 From: Pieter van Ginkel Date: Sat, 21 Nov 2026 15:46:08 +0100 Subject: [PATCH 5/9] Added the YouTrack plugin itself, built the way the JIRA plugin is. Issues, projects, agile boards, saved searches, dashboards and new issue per project, cached per connection; a 403 or 404 on an endpoint leaves its category out for that connection. The people directory feeds the Microsoft Teams plugin. The connection dialog checks the URL and the token before it saves, offering "Did you mean ...?" for a URL copied from the address bar. Labels in English and Dutch, Fluent UI category icons and JetBrains' YouTrack icon. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RGjkV3AFfnNjd6n2D9pwGX --- .../Categories/BoardMatch.cs | 37 ++ .../Categories/BoardType.cs | 16 + .../Categories/BoardsMatch.cs | 37 ++ .../Categories/BoardsType.cs | 19 + .../Categories/DashboardMatch.cs | 40 ++ .../Categories/DashboardType.cs | 16 + .../Categories/DashboardsMatch.cs | 37 ++ .../Categories/DashboardsType.cs | 19 + .../Categories/IssueMatch.cs | 37 ++ .../Categories/IssueType.cs | 16 + .../Categories/IssueUtils.cs | 16 + .../Categories/IssuesMatch.cs | 79 +++ .../Categories/IssuesType.cs | 18 + .../Categories/NewMatch.cs | 49 ++ .../Categories/NewType.cs | 16 + .../Categories/NewsMatch.cs | 39 ++ .../Categories/NewsType.cs | 19 + .../Categories/ProjectMatch.cs | 74 +++ .../Categories/ProjectType.cs | 16 + .../Categories/ProjectsMatch.cs | 39 ++ .../Categories/ProjectsType.cs | 19 + .../Categories/RootItemDto.cs | 3 + .../Categories/SavedSearchMatch.cs | 71 +++ .../Categories/SavedSearchType.cs | 16 + .../Categories/SavedSearchesMatch.cs | 44 ++ .../Categories/SavedSearchesType.cs | 19 + .../Categories/TypeIds.cs | 32 ++ src/Tql.Plugins.YouTrack/Configuration.cs | 10 + .../ConfigurationUI/ConfigurationControl.xaml | 82 +++ .../ConfigurationControl.xaml.cs | 90 ++++ .../ConfigurationUI/ConfigurationDto.cs | 82 +++ .../ConfigurationUI/ConnectionEditWindow.xaml | 101 ++++ .../ConnectionEditWindow.xaml.cs | 133 +++++ .../Data/YouTrackCacheManager.cs | 114 +++++ src/Tql.Plugins.YouTrack/Data/YouTrackData.cs | 38 ++ src/Tql.Plugins.YouTrack/GlobalUsings.cs | 20 + src/Tql.Plugins.YouTrack/Images.cs | 31 ++ src/Tql.Plugins.YouTrack/Labels.Designer.cs | 468 ++++++++++++++++++ src/Tql.Plugins.YouTrack/Labels.nl.resx | 241 +++++++++ src/Tql.Plugins.YouTrack/Labels.resx | 255 ++++++++++ src/Tql.Plugins.YouTrack/README.md | 7 + src/Tql.Plugins.YouTrack/Resources/Boards.svg | 3 + .../Resources/Dashboards.svg | 3 + src/Tql.Plugins.YouTrack/Resources/Issues.svg | 3 + .../Resources/Projects.svg | 3 + .../Resources/SavedSearches.svg | 3 + .../Resources/YouTrack.svg | 13 + .../Services/ConfigurationManager.cs | 95 ++++ .../Services/IconCacheManager.cs | 46 ++ .../Services/YouTrackApi.cs | 60 +++ .../Services/YouTrackPeopleDirectory.cs | 59 +++ .../Support/CollectionExtensions.cs | 12 + .../Support/MatchUtils.cs | 18 + .../Support/RootMatchTypeAttribute.cs | 22 + .../Tql.Plugins.YouTrack.csproj | 43 ++ src/Tql.Plugins.YouTrack/YouTrackPlugin.cs | 100 ++++ src/Tql.Plugins.YouTrack/packages.lock.json | 115 +++++ 57 files changed, 3113 insertions(+) create mode 100644 src/Tql.Plugins.YouTrack/Categories/BoardMatch.cs create mode 100644 src/Tql.Plugins.YouTrack/Categories/BoardType.cs create mode 100644 src/Tql.Plugins.YouTrack/Categories/BoardsMatch.cs create mode 100644 src/Tql.Plugins.YouTrack/Categories/BoardsType.cs create mode 100644 src/Tql.Plugins.YouTrack/Categories/DashboardMatch.cs create mode 100644 src/Tql.Plugins.YouTrack/Categories/DashboardType.cs create mode 100644 src/Tql.Plugins.YouTrack/Categories/DashboardsMatch.cs create mode 100644 src/Tql.Plugins.YouTrack/Categories/DashboardsType.cs create mode 100644 src/Tql.Plugins.YouTrack/Categories/IssueMatch.cs create mode 100644 src/Tql.Plugins.YouTrack/Categories/IssueType.cs create mode 100644 src/Tql.Plugins.YouTrack/Categories/IssueUtils.cs create mode 100644 src/Tql.Plugins.YouTrack/Categories/IssuesMatch.cs create mode 100644 src/Tql.Plugins.YouTrack/Categories/IssuesType.cs create mode 100644 src/Tql.Plugins.YouTrack/Categories/NewMatch.cs create mode 100644 src/Tql.Plugins.YouTrack/Categories/NewType.cs create mode 100644 src/Tql.Plugins.YouTrack/Categories/NewsMatch.cs create mode 100644 src/Tql.Plugins.YouTrack/Categories/NewsType.cs create mode 100644 src/Tql.Plugins.YouTrack/Categories/ProjectMatch.cs create mode 100644 src/Tql.Plugins.YouTrack/Categories/ProjectType.cs create mode 100644 src/Tql.Plugins.YouTrack/Categories/ProjectsMatch.cs create mode 100644 src/Tql.Plugins.YouTrack/Categories/ProjectsType.cs create mode 100644 src/Tql.Plugins.YouTrack/Categories/RootItemDto.cs create mode 100644 src/Tql.Plugins.YouTrack/Categories/SavedSearchMatch.cs create mode 100644 src/Tql.Plugins.YouTrack/Categories/SavedSearchType.cs create mode 100644 src/Tql.Plugins.YouTrack/Categories/SavedSearchesMatch.cs create mode 100644 src/Tql.Plugins.YouTrack/Categories/SavedSearchesType.cs create mode 100644 src/Tql.Plugins.YouTrack/Categories/TypeIds.cs create mode 100644 src/Tql.Plugins.YouTrack/Configuration.cs create mode 100644 src/Tql.Plugins.YouTrack/ConfigurationUI/ConfigurationControl.xaml create mode 100644 src/Tql.Plugins.YouTrack/ConfigurationUI/ConfigurationControl.xaml.cs create mode 100644 src/Tql.Plugins.YouTrack/ConfigurationUI/ConfigurationDto.cs create mode 100644 src/Tql.Plugins.YouTrack/ConfigurationUI/ConnectionEditWindow.xaml create mode 100644 src/Tql.Plugins.YouTrack/ConfigurationUI/ConnectionEditWindow.xaml.cs create mode 100644 src/Tql.Plugins.YouTrack/Data/YouTrackCacheManager.cs create mode 100644 src/Tql.Plugins.YouTrack/Data/YouTrackData.cs create mode 100644 src/Tql.Plugins.YouTrack/GlobalUsings.cs create mode 100644 src/Tql.Plugins.YouTrack/Images.cs create mode 100644 src/Tql.Plugins.YouTrack/Labels.Designer.cs create mode 100644 src/Tql.Plugins.YouTrack/Labels.nl.resx create mode 100644 src/Tql.Plugins.YouTrack/Labels.resx create mode 100644 src/Tql.Plugins.YouTrack/README.md create mode 100644 src/Tql.Plugins.YouTrack/Resources/Boards.svg create mode 100644 src/Tql.Plugins.YouTrack/Resources/Dashboards.svg create mode 100644 src/Tql.Plugins.YouTrack/Resources/Issues.svg create mode 100644 src/Tql.Plugins.YouTrack/Resources/Projects.svg create mode 100644 src/Tql.Plugins.YouTrack/Resources/SavedSearches.svg create mode 100644 src/Tql.Plugins.YouTrack/Resources/YouTrack.svg create mode 100644 src/Tql.Plugins.YouTrack/Services/ConfigurationManager.cs create mode 100644 src/Tql.Plugins.YouTrack/Services/IconCacheManager.cs create mode 100644 src/Tql.Plugins.YouTrack/Services/YouTrackApi.cs create mode 100644 src/Tql.Plugins.YouTrack/Services/YouTrackPeopleDirectory.cs create mode 100644 src/Tql.Plugins.YouTrack/Support/CollectionExtensions.cs create mode 100644 src/Tql.Plugins.YouTrack/Support/MatchUtils.cs create mode 100644 src/Tql.Plugins.YouTrack/Support/RootMatchTypeAttribute.cs create mode 100644 src/Tql.Plugins.YouTrack/Tql.Plugins.YouTrack.csproj create mode 100644 src/Tql.Plugins.YouTrack/YouTrackPlugin.cs create mode 100644 src/Tql.Plugins.YouTrack/packages.lock.json diff --git a/src/Tql.Plugins.YouTrack/Categories/BoardMatch.cs b/src/Tql.Plugins.YouTrack/Categories/BoardMatch.cs new file mode 100644 index 00000000..1d86ec55 --- /dev/null +++ b/src/Tql.Plugins.YouTrack/Categories/BoardMatch.cs @@ -0,0 +1,37 @@ +using System.Windows.Forms; +using Microsoft.Extensions.DependencyInjection; +using Tql.Abstractions; +using Tql.Plugins.YouTrack.Support; + +namespace Tql.Plugins.YouTrack.Categories; + +internal class BoardMatch(BoardMatchDto dto) : IRunnableMatch, ISerializableMatch, ICopyableMatch +{ + public string Text => string.Format(Labels.BoardMatch_Label, dto.Name); + public ImageSource Icon => Images.Boards; + public MatchTypeId TypeId => TypeIds.Board; + + public Task Run(IServiceProvider serviceProvider, IWin32Window owner) + { + serviceProvider.GetRequiredService().OpenUrl(dto.GetUrl()); + + return Task.CompletedTask; + } + + public string Serialize() + { + return JsonSerializer.Serialize(dto); + } + + public Task Copy(IServiceProvider serviceProvider) + { + serviceProvider.GetRequiredService().CopyUri(Text, dto.GetUrl()); + + return Task.CompletedTask; + } +} + +internal record BoardMatchDto(string Url, string Id, string Name) +{ + public string GetUrl() => YouTrackUrls.GetAgileBoardUrl(Url, Id); +}; diff --git a/src/Tql.Plugins.YouTrack/Categories/BoardType.cs b/src/Tql.Plugins.YouTrack/Categories/BoardType.cs new file mode 100644 index 00000000..462b6ebd --- /dev/null +++ b/src/Tql.Plugins.YouTrack/Categories/BoardType.cs @@ -0,0 +1,16 @@ +using Tql.Abstractions; +using Tql.Plugins.YouTrack.Services; +using Tql.Utilities; + +namespace Tql.Plugins.YouTrack.Categories; + +internal class BoardType( + IMatchFactory factory, + ConfigurationManager configurationManager +) : MatchType(factory) +{ + public override Guid Id => TypeIds.Board.Id; + + protected override bool IsValid(BoardMatchDto dto) => + configurationManager.Configuration.HasConnection(dto.Url); +} diff --git a/src/Tql.Plugins.YouTrack/Categories/BoardsMatch.cs b/src/Tql.Plugins.YouTrack/Categories/BoardsMatch.cs new file mode 100644 index 00000000..763efdc7 --- /dev/null +++ b/src/Tql.Plugins.YouTrack/Categories/BoardsMatch.cs @@ -0,0 +1,37 @@ +using Tql.Abstractions; +using Tql.Plugins.YouTrack.Data; +using Tql.Plugins.YouTrack.Services; +using Tql.Plugins.YouTrack.Support; +using Tql.Utilities; + +namespace Tql.Plugins.YouTrack.Categories; + +internal class BoardsMatch( + RootItemDto dto, + ICache cache, + ConfigurationManager configurationManager, + IMatchFactory factory +) : CachedMatch(cache), ISerializableMatch +{ + public override string Text => + MatchUtils.GetMatchLabel( + Labels.BoardsMatch_Label, + configurationManager.Configuration, + dto.Url + ); + + public override ImageSource Icon => Images.Boards; + public override MatchTypeId TypeId => TypeIds.Boards; + public override string SearchHint => Labels.BoardsMatch_SearchHint; + + protected override IEnumerable Create(YouTrackData data) + { + return from board in data.GetConnection(dto.Url).AgileBoards + select factory.Create(new BoardMatchDto(dto.Url, board.Id, board.Name)); + } + + public string Serialize() + { + return JsonSerializer.Serialize(dto); + } +} diff --git a/src/Tql.Plugins.YouTrack/Categories/BoardsType.cs b/src/Tql.Plugins.YouTrack/Categories/BoardsType.cs new file mode 100644 index 00000000..b9c2a74b --- /dev/null +++ b/src/Tql.Plugins.YouTrack/Categories/BoardsType.cs @@ -0,0 +1,19 @@ +using Tql.Abstractions; +using Tql.Plugins.YouTrack.Data; +using Tql.Plugins.YouTrack.Services; +using Tql.Plugins.YouTrack.Support; +using Tql.Utilities; + +namespace Tql.Plugins.YouTrack.Categories; + +[RootMatchType(YouTrackEndpoint.AgileBoards)] +internal class BoardsType( + IMatchFactory factory, + ConfigurationManager configurationManager +) : MatchType(factory) +{ + public override Guid Id => TypeIds.Boards.Id; + + protected override bool IsValid(RootItemDto dto) => + configurationManager.Configuration.HasConnection(dto.Url); +} diff --git a/src/Tql.Plugins.YouTrack/Categories/DashboardMatch.cs b/src/Tql.Plugins.YouTrack/Categories/DashboardMatch.cs new file mode 100644 index 00000000..d28e2c54 --- /dev/null +++ b/src/Tql.Plugins.YouTrack/Categories/DashboardMatch.cs @@ -0,0 +1,40 @@ +using System.Windows.Forms; +using Microsoft.Extensions.DependencyInjection; +using Tql.Abstractions; +using Tql.Plugins.YouTrack.Support; + +namespace Tql.Plugins.YouTrack.Categories; + +internal class DashboardMatch(DashboardMatchDto dto) + : IRunnableMatch, + ISerializableMatch, + ICopyableMatch +{ + public string Text => string.Format(Labels.DashboardMatch_Label, dto.Name); + public ImageSource Icon => Images.Dashboards; + public MatchTypeId TypeId => TypeIds.Dashboard; + + public Task Run(IServiceProvider serviceProvider, IWin32Window owner) + { + serviceProvider.GetRequiredService().OpenUrl(dto.GetUrl()); + + return Task.CompletedTask; + } + + public string Serialize() + { + return JsonSerializer.Serialize(dto); + } + + public Task Copy(IServiceProvider serviceProvider) + { + serviceProvider.GetRequiredService().CopyUri(Text, dto.GetUrl()); + + return Task.CompletedTask; + } +} + +internal record DashboardMatchDto(string Url, string Id, string Name) +{ + public string GetUrl() => YouTrackUrls.GetDashboardUrl(Url, Id); +}; diff --git a/src/Tql.Plugins.YouTrack/Categories/DashboardType.cs b/src/Tql.Plugins.YouTrack/Categories/DashboardType.cs new file mode 100644 index 00000000..2d980cc1 --- /dev/null +++ b/src/Tql.Plugins.YouTrack/Categories/DashboardType.cs @@ -0,0 +1,16 @@ +using Tql.Abstractions; +using Tql.Plugins.YouTrack.Services; +using Tql.Utilities; + +namespace Tql.Plugins.YouTrack.Categories; + +internal class DashboardType( + IMatchFactory factory, + ConfigurationManager configurationManager +) : MatchType(factory) +{ + public override Guid Id => TypeIds.Dashboard.Id; + + protected override bool IsValid(DashboardMatchDto dto) => + configurationManager.Configuration.HasConnection(dto.Url); +} diff --git a/src/Tql.Plugins.YouTrack/Categories/DashboardsMatch.cs b/src/Tql.Plugins.YouTrack/Categories/DashboardsMatch.cs new file mode 100644 index 00000000..2cbf9c7e --- /dev/null +++ b/src/Tql.Plugins.YouTrack/Categories/DashboardsMatch.cs @@ -0,0 +1,37 @@ +using Tql.Abstractions; +using Tql.Plugins.YouTrack.Data; +using Tql.Plugins.YouTrack.Services; +using Tql.Plugins.YouTrack.Support; +using Tql.Utilities; + +namespace Tql.Plugins.YouTrack.Categories; + +internal class DashboardsMatch( + RootItemDto dto, + ICache cache, + ConfigurationManager configurationManager, + IMatchFactory factory +) : CachedMatch(cache), ISerializableMatch +{ + public override string Text => + MatchUtils.GetMatchLabel( + Labels.DashboardsMatch_Label, + configurationManager.Configuration, + dto.Url + ); + + public override ImageSource Icon => Images.Dashboards; + public override MatchTypeId TypeId => TypeIds.Dashboards; + public override string SearchHint => Labels.DashboardsMatch_SearchHint; + + protected override IEnumerable Create(YouTrackData data) + { + return from dashboard in data.GetConnection(dto.Url).Dashboards + select factory.Create(new DashboardMatchDto(dto.Url, dashboard.Id, dashboard.Name)); + } + + public string Serialize() + { + return JsonSerializer.Serialize(dto); + } +} diff --git a/src/Tql.Plugins.YouTrack/Categories/DashboardsType.cs b/src/Tql.Plugins.YouTrack/Categories/DashboardsType.cs new file mode 100644 index 00000000..2e5dc2b3 --- /dev/null +++ b/src/Tql.Plugins.YouTrack/Categories/DashboardsType.cs @@ -0,0 +1,19 @@ +using Tql.Abstractions; +using Tql.Plugins.YouTrack.Data; +using Tql.Plugins.YouTrack.Services; +using Tql.Plugins.YouTrack.Support; +using Tql.Utilities; + +namespace Tql.Plugins.YouTrack.Categories; + +[RootMatchType(YouTrackEndpoint.Dashboards)] +internal class DashboardsType( + IMatchFactory factory, + ConfigurationManager configurationManager +) : MatchType(factory) +{ + public override Guid Id => TypeIds.Dashboards.Id; + + protected override bool IsValid(RootItemDto dto) => + configurationManager.Configuration.HasConnection(dto.Url); +} diff --git a/src/Tql.Plugins.YouTrack/Categories/IssueMatch.cs b/src/Tql.Plugins.YouTrack/Categories/IssueMatch.cs new file mode 100644 index 00000000..cdf6791d --- /dev/null +++ b/src/Tql.Plugins.YouTrack/Categories/IssueMatch.cs @@ -0,0 +1,37 @@ +using System.Windows.Forms; +using Microsoft.Extensions.DependencyInjection; +using Tql.Abstractions; +using Tql.Plugins.YouTrack.Support; + +namespace Tql.Plugins.YouTrack.Categories; + +internal class IssueMatch(IssueMatchDto dto) : IRunnableMatch, ISerializableMatch, ICopyableMatch +{ + public string Text => $"{dto.IdReadable} {dto.Summary}"; + public ImageSource Icon => Images.Issues; + public MatchTypeId TypeId => TypeIds.Issue; + + public Task Run(IServiceProvider serviceProvider, IWin32Window owner) + { + serviceProvider.GetRequiredService().OpenUrl(dto.GetUrl()); + + return Task.CompletedTask; + } + + public string Serialize() + { + return JsonSerializer.Serialize(dto); + } + + public Task Copy(IServiceProvider serviceProvider) + { + serviceProvider.GetRequiredService().CopyUri(Text, dto.GetUrl()); + + return Task.CompletedTask; + } +} + +internal record IssueMatchDto(string Url, string IdReadable, string Summary) +{ + public string GetUrl() => YouTrackUrls.GetIssueUrl(Url, IdReadable); +}; diff --git a/src/Tql.Plugins.YouTrack/Categories/IssueType.cs b/src/Tql.Plugins.YouTrack/Categories/IssueType.cs new file mode 100644 index 00000000..64f37283 --- /dev/null +++ b/src/Tql.Plugins.YouTrack/Categories/IssueType.cs @@ -0,0 +1,16 @@ +using Tql.Abstractions; +using Tql.Plugins.YouTrack.Services; +using Tql.Utilities; + +namespace Tql.Plugins.YouTrack.Categories; + +internal class IssueType( + IMatchFactory factory, + ConfigurationManager configurationManager +) : MatchType(factory) +{ + public override Guid Id => TypeIds.Issue.Id; + + protected override bool IsValid(IssueMatchDto dto) => + configurationManager.Configuration.HasConnection(dto.Url); +} diff --git a/src/Tql.Plugins.YouTrack/Categories/IssueUtils.cs b/src/Tql.Plugins.YouTrack/Categories/IssueUtils.cs new file mode 100644 index 00000000..73e5951f --- /dev/null +++ b/src/Tql.Plugins.YouTrack/Categories/IssueUtils.cs @@ -0,0 +1,16 @@ +using Tql.Abstractions; +using Tql.Plugins.YouTrack.Services; + +namespace Tql.Plugins.YouTrack.Categories; + +internal static class IssueUtils +{ + public static IEnumerable CreateMatches( + string url, + IEnumerable issues, + IMatchFactory factory + ) + { + return issues.Select(p => factory.Create(new IssueMatchDto(url, p.IdReadable, p.Summary))); + } +} diff --git a/src/Tql.Plugins.YouTrack/Categories/IssuesMatch.cs b/src/Tql.Plugins.YouTrack/Categories/IssuesMatch.cs new file mode 100644 index 00000000..31c3c8ab --- /dev/null +++ b/src/Tql.Plugins.YouTrack/Categories/IssuesMatch.cs @@ -0,0 +1,79 @@ +using Tql.Abstractions; +using Tql.Plugins.YouTrack.Services; +using Tql.Plugins.YouTrack.Support; +using Tql.Utilities; + +namespace Tql.Plugins.YouTrack.Categories; + +internal class IssuesMatch( + RootItemDto dto, + ConfigurationManager configurationManager, + IMatchFactory factory +) : ISearchableMatch, ISerializableMatch +{ + public string Text => + MatchUtils.GetMatchLabel( + Labels.IssuesMatch_Label, + configurationManager.Configuration, + dto.Url + ); + + public ImageSource Icon => Images.Issues; + public MatchTypeId TypeId => TypeIds.Issues; + public string SearchHint => Labels.IssuesMatch_SearchHint; + + public async Task> Search( + ISearchContext context, + string text, + CancellationToken cancellationToken + ) + { + if (text.IsWhiteSpace()) + return Array.Empty(); + + var maybeId = YouTrackQueries.IsIssueId(text); + if (maybeId) + context.SuppressPreliminaryResults(); + + await context.DebounceDelay(cancellationToken); + + var client = configurationManager.GetClient(dto.Url); + + if (maybeId) + { + try + { + var issue = await client.GetIssue(text, cancellationToken); + if (issue != null) + return IssueUtils.CreateMatches(dto.Url, new[] { issue }, factory); + } + catch (YouTrackException) + { + // Ignore. Fall back to a normal search. + } + } + + // The text goes to YouTrack as a query, so "#Unresolved for: me" + // works. A query that's still being typed, such as "#Unres", doesn't + // parse; that's no results rather than an error. + try + { + var issues = await client.SearchIssues( + text.Trim(), + YouTrackClient.DefaultSearchTop, + cancellationToken + ); + + return IssueUtils.CreateMatches(dto.Url, issues, factory); + } + catch (YouTrackInvalidQueryException) + { + return Array.Empty(); + } + } + + public string Serialize() + { + return JsonSerializer.Serialize(dto); + } +} diff --git a/src/Tql.Plugins.YouTrack/Categories/IssuesType.cs b/src/Tql.Plugins.YouTrack/Categories/IssuesType.cs new file mode 100644 index 00000000..5aacd7a0 --- /dev/null +++ b/src/Tql.Plugins.YouTrack/Categories/IssuesType.cs @@ -0,0 +1,18 @@ +using Tql.Abstractions; +using Tql.Plugins.YouTrack.Services; +using Tql.Plugins.YouTrack.Support; +using Tql.Utilities; + +namespace Tql.Plugins.YouTrack.Categories; + +[RootMatchType] +internal class IssuesType( + IMatchFactory factory, + ConfigurationManager configurationManager +) : MatchType(factory) +{ + public override Guid Id => TypeIds.Issues.Id; + + protected override bool IsValid(RootItemDto dto) => + configurationManager.Configuration.HasConnection(dto.Url); +} diff --git a/src/Tql.Plugins.YouTrack/Categories/NewMatch.cs b/src/Tql.Plugins.YouTrack/Categories/NewMatch.cs new file mode 100644 index 00000000..4aa841bc --- /dev/null +++ b/src/Tql.Plugins.YouTrack/Categories/NewMatch.cs @@ -0,0 +1,49 @@ +using System.Windows.Forms; +using Microsoft.Extensions.DependencyInjection; +using Tql.Abstractions; +using Tql.Plugins.YouTrack.Services; +using Tql.Plugins.YouTrack.Support; +using Tql.Utilities; + +namespace Tql.Plugins.YouTrack.Categories; + +internal class NewMatch(NewMatchDto dto, IconCacheManager iconCacheManager) + : IRunnableMatch, + ISerializableMatch, + ICopyableMatch +{ + public string Text => MatchText.Path(dto.ProjectName, Labels.NewMatch_NewIssue); + public ImageSource Icon { get; } = + (dto.IconUrl != null ? iconCacheManager.GetIcon(new IconKey(dto.Url, dto.IconUrl)) : null) + ?? Images.Issues; + public MatchTypeId TypeId => TypeIds.New; + + public Task Run(IServiceProvider serviceProvider, IWin32Window owner) + { + serviceProvider.GetRequiredService().OpenUrl(dto.GetUrl()); + + return Task.CompletedTask; + } + + public string Serialize() + { + return JsonSerializer.Serialize(dto); + } + + public Task Copy(IServiceProvider serviceProvider) + { + serviceProvider.GetRequiredService().CopyUri(Text, dto.GetUrl()); + + return Task.CompletedTask; + } +} + +internal record NewMatchDto( + string Url, + string ProjectShortName, + string ProjectName, + string? IconUrl +) +{ + public string GetUrl() => YouTrackUrls.GetNewIssueUrl(Url, ProjectShortName); +}; diff --git a/src/Tql.Plugins.YouTrack/Categories/NewType.cs b/src/Tql.Plugins.YouTrack/Categories/NewType.cs new file mode 100644 index 00000000..f5073d49 --- /dev/null +++ b/src/Tql.Plugins.YouTrack/Categories/NewType.cs @@ -0,0 +1,16 @@ +using Tql.Abstractions; +using Tql.Plugins.YouTrack.Services; +using Tql.Utilities; + +namespace Tql.Plugins.YouTrack.Categories; + +internal class NewType( + IMatchFactory factory, + ConfigurationManager configurationManager +) : MatchType(factory) +{ + public override Guid Id => TypeIds.New.Id; + + protected override bool IsValid(NewMatchDto dto) => + configurationManager.Configuration.HasConnection(dto.Url); +} diff --git a/src/Tql.Plugins.YouTrack/Categories/NewsMatch.cs b/src/Tql.Plugins.YouTrack/Categories/NewsMatch.cs new file mode 100644 index 00000000..5cf12e73 --- /dev/null +++ b/src/Tql.Plugins.YouTrack/Categories/NewsMatch.cs @@ -0,0 +1,39 @@ +using Tql.Abstractions; +using Tql.Plugins.YouTrack.Data; +using Tql.Plugins.YouTrack.Services; +using Tql.Plugins.YouTrack.Support; +using Tql.Utilities; + +namespace Tql.Plugins.YouTrack.Categories; + +internal class NewsMatch( + RootItemDto dto, + ICache cache, + ConfigurationManager configurationManager, + IMatchFactory factory +) : CachedMatch(cache), ISerializableMatch +{ + public override string Text => + MatchUtils.GetMatchLabel( + Labels.NewsMatch_Label, + configurationManager.Configuration, + dto.Url + ); + + public override ImageSource Icon => Images.Issues; + public override MatchTypeId TypeId => TypeIds.News; + public override string SearchHint => Labels.NewsMatch_SearchHint; + + protected override IEnumerable Create(YouTrackData data) + { + return from project in data.GetConnection(dto.Url).Projects + select factory.Create( + new NewMatchDto(dto.Url, project.ShortName, project.Name, project.IconUrl) + ); + } + + public string Serialize() + { + return JsonSerializer.Serialize(dto); + } +} diff --git a/src/Tql.Plugins.YouTrack/Categories/NewsType.cs b/src/Tql.Plugins.YouTrack/Categories/NewsType.cs new file mode 100644 index 00000000..f68a41a6 --- /dev/null +++ b/src/Tql.Plugins.YouTrack/Categories/NewsType.cs @@ -0,0 +1,19 @@ +using Tql.Abstractions; +using Tql.Plugins.YouTrack.Data; +using Tql.Plugins.YouTrack.Services; +using Tql.Plugins.YouTrack.Support; +using Tql.Utilities; + +namespace Tql.Plugins.YouTrack.Categories; + +[RootMatchType(YouTrackEndpoint.Projects)] +internal class NewsType( + IMatchFactory factory, + ConfigurationManager configurationManager +) : MatchType(factory) +{ + public override Guid Id => TypeIds.News.Id; + + protected override bool IsValid(RootItemDto dto) => + configurationManager.Configuration.HasConnection(dto.Url); +} diff --git a/src/Tql.Plugins.YouTrack/Categories/ProjectMatch.cs b/src/Tql.Plugins.YouTrack/Categories/ProjectMatch.cs new file mode 100644 index 00000000..080356f1 --- /dev/null +++ b/src/Tql.Plugins.YouTrack/Categories/ProjectMatch.cs @@ -0,0 +1,74 @@ +using System.Windows.Forms; +using Microsoft.Extensions.DependencyInjection; +using Tql.Abstractions; +using Tql.Plugins.YouTrack.Services; +using Tql.Plugins.YouTrack.Support; + +namespace Tql.Plugins.YouTrack.Categories; + +internal class ProjectMatch( + ProjectMatchDto dto, + IconCacheManager iconCacheManager, + ConfigurationManager configurationManager, + IMatchFactory factory +) : IRunnableMatch, ISerializableMatch, ICopyableMatch, ISearchableMatch +{ + public string Text => string.Format(Labels.ProjectMatch_Label, dto.Name); + public ImageSource Icon { get; } = + (dto.IconUrl != null ? iconCacheManager.GetIcon(new IconKey(dto.Url, dto.IconUrl)) : null) + ?? Images.Projects; + public MatchTypeId TypeId => TypeIds.Project; + public string SearchHint => Labels.ProjectMatch_SearchHint; + + public Task Run(IServiceProvider serviceProvider, IWin32Window owner) + { + serviceProvider.GetRequiredService().OpenUrl(dto.GetUrl()); + + return Task.CompletedTask; + } + + public string Serialize() + { + return JsonSerializer.Serialize(dto); + } + + public Task Copy(IServiceProvider serviceProvider) + { + serviceProvider.GetRequiredService().CopyUri(Text, dto.GetUrl()); + + return Task.CompletedTask; + } + + public async Task> Search( + ISearchContext context, + string text, + CancellationToken cancellationToken + ) + { + await context.DebounceDelay(cancellationToken); + + var client = configurationManager.GetClient(dto.Url); + + // "project: KC ", or the most recently updated issues without + // text. A query that's still being typed is no results. + try + { + var issues = await client.SearchIssues( + YouTrackQueries.Project(dto.ShortName, text), + YouTrackClient.DefaultSearchTop, + cancellationToken + ); + + return IssueUtils.CreateMatches(dto.Url, issues, factory); + } + catch (YouTrackInvalidQueryException) + { + return Array.Empty(); + } + } +} + +internal record ProjectMatchDto(string Url, string ShortName, string Name, string? IconUrl) +{ + public string GetUrl() => YouTrackUrls.GetProjectUrl(Url, ShortName); +}; diff --git a/src/Tql.Plugins.YouTrack/Categories/ProjectType.cs b/src/Tql.Plugins.YouTrack/Categories/ProjectType.cs new file mode 100644 index 00000000..485e37d3 --- /dev/null +++ b/src/Tql.Plugins.YouTrack/Categories/ProjectType.cs @@ -0,0 +1,16 @@ +using Tql.Abstractions; +using Tql.Plugins.YouTrack.Services; +using Tql.Utilities; + +namespace Tql.Plugins.YouTrack.Categories; + +internal class ProjectType( + IMatchFactory factory, + ConfigurationManager configurationManager +) : MatchType(factory) +{ + public override Guid Id => TypeIds.Project.Id; + + protected override bool IsValid(ProjectMatchDto dto) => + configurationManager.Configuration.HasConnection(dto.Url); +} diff --git a/src/Tql.Plugins.YouTrack/Categories/ProjectsMatch.cs b/src/Tql.Plugins.YouTrack/Categories/ProjectsMatch.cs new file mode 100644 index 00000000..c1360843 --- /dev/null +++ b/src/Tql.Plugins.YouTrack/Categories/ProjectsMatch.cs @@ -0,0 +1,39 @@ +using Tql.Abstractions; +using Tql.Plugins.YouTrack.Data; +using Tql.Plugins.YouTrack.Services; +using Tql.Plugins.YouTrack.Support; +using Tql.Utilities; + +namespace Tql.Plugins.YouTrack.Categories; + +internal class ProjectsMatch( + RootItemDto dto, + ICache cache, + ConfigurationManager configurationManager, + IMatchFactory factory +) : CachedMatch(cache), ISerializableMatch +{ + public override string Text => + MatchUtils.GetMatchLabel( + Labels.ProjectsMatch_Label, + configurationManager.Configuration, + dto.Url + ); + + public override ImageSource Icon => Images.Projects; + public override MatchTypeId TypeId => TypeIds.Projects; + public override string SearchHint => Labels.ProjectsMatch_SearchHint; + + protected override IEnumerable Create(YouTrackData data) + { + return from project in data.GetConnection(dto.Url).Projects + select factory.Create( + new ProjectMatchDto(dto.Url, project.ShortName, project.Name, project.IconUrl) + ); + } + + public string Serialize() + { + return JsonSerializer.Serialize(dto); + } +} diff --git a/src/Tql.Plugins.YouTrack/Categories/ProjectsType.cs b/src/Tql.Plugins.YouTrack/Categories/ProjectsType.cs new file mode 100644 index 00000000..61944eaa --- /dev/null +++ b/src/Tql.Plugins.YouTrack/Categories/ProjectsType.cs @@ -0,0 +1,19 @@ +using Tql.Abstractions; +using Tql.Plugins.YouTrack.Data; +using Tql.Plugins.YouTrack.Services; +using Tql.Plugins.YouTrack.Support; +using Tql.Utilities; + +namespace Tql.Plugins.YouTrack.Categories; + +[RootMatchType(YouTrackEndpoint.Projects)] +internal class ProjectsType( + IMatchFactory factory, + ConfigurationManager configurationManager +) : MatchType(factory) +{ + public override Guid Id => TypeIds.Projects.Id; + + protected override bool IsValid(RootItemDto dto) => + configurationManager.Configuration.HasConnection(dto.Url); +} diff --git a/src/Tql.Plugins.YouTrack/Categories/RootItemDto.cs b/src/Tql.Plugins.YouTrack/Categories/RootItemDto.cs new file mode 100644 index 00000000..13408376 --- /dev/null +++ b/src/Tql.Plugins.YouTrack/Categories/RootItemDto.cs @@ -0,0 +1,3 @@ +namespace Tql.Plugins.YouTrack.Categories; + +internal record RootItemDto(string Url); diff --git a/src/Tql.Plugins.YouTrack/Categories/SavedSearchMatch.cs b/src/Tql.Plugins.YouTrack/Categories/SavedSearchMatch.cs new file mode 100644 index 00000000..842a68a9 --- /dev/null +++ b/src/Tql.Plugins.YouTrack/Categories/SavedSearchMatch.cs @@ -0,0 +1,71 @@ +using System.Windows.Forms; +using Microsoft.Extensions.DependencyInjection; +using Tql.Abstractions; +using Tql.Plugins.YouTrack.Services; +using Tql.Plugins.YouTrack.Support; + +namespace Tql.Plugins.YouTrack.Categories; + +internal class SavedSearchMatch( + SavedSearchMatchDto dto, + ConfigurationManager configurationManager, + IMatchFactory factory +) : IRunnableMatch, ISerializableMatch, ICopyableMatch, ISearchableMatch +{ + public string Text => dto.Name; + public ImageSource Icon => Images.SavedSearches; + public MatchTypeId TypeId => TypeIds.SavedSearch; + public string SearchHint => Labels.SavedSearchMatch_SearchHint; + + public Task Run(IServiceProvider serviceProvider, IWin32Window owner) + { + serviceProvider.GetRequiredService().OpenUrl(dto.GetUrl()); + + return Task.CompletedTask; + } + + public string Serialize() + { + return JsonSerializer.Serialize(dto); + } + + public Task Copy(IServiceProvider serviceProvider) + { + serviceProvider.GetRequiredService().CopyUri(Text, dto.GetUrl()); + + return Task.CompletedTask; + } + + public async Task> Search( + ISearchContext context, + string text, + CancellationToken cancellationToken + ) + { + await context.DebounceDelay(cancellationToken); + + var client = configurationManager.GetClient(dto.Url); + + // The saved search narrowed with the text: "() and + // ()". A query that's still being typed is no results. + try + { + var issues = await client.SearchIssues( + YouTrackQueries.SavedSearch(dto.Query, text), + YouTrackClient.DefaultSearchTop, + cancellationToken + ); + + return IssueUtils.CreateMatches(dto.Url, issues, factory); + } + catch (YouTrackInvalidQueryException) + { + return Array.Empty(); + } + } +} + +internal record SavedSearchMatchDto(string Url, string Id, string Name, string Query) +{ + public string GetUrl() => YouTrackUrls.GetSavedSearchUrl(Url, Query); +}; diff --git a/src/Tql.Plugins.YouTrack/Categories/SavedSearchType.cs b/src/Tql.Plugins.YouTrack/Categories/SavedSearchType.cs new file mode 100644 index 00000000..063f3a5e --- /dev/null +++ b/src/Tql.Plugins.YouTrack/Categories/SavedSearchType.cs @@ -0,0 +1,16 @@ +using Tql.Abstractions; +using Tql.Plugins.YouTrack.Services; +using Tql.Utilities; + +namespace Tql.Plugins.YouTrack.Categories; + +internal class SavedSearchType( + IMatchFactory factory, + ConfigurationManager configurationManager +) : MatchType(factory) +{ + public override Guid Id => TypeIds.SavedSearch.Id; + + protected override bool IsValid(SavedSearchMatchDto dto) => + configurationManager.Configuration.HasConnection(dto.Url); +} diff --git a/src/Tql.Plugins.YouTrack/Categories/SavedSearchesMatch.cs b/src/Tql.Plugins.YouTrack/Categories/SavedSearchesMatch.cs new file mode 100644 index 00000000..0a5bc21d --- /dev/null +++ b/src/Tql.Plugins.YouTrack/Categories/SavedSearchesMatch.cs @@ -0,0 +1,44 @@ +using Tql.Abstractions; +using Tql.Plugins.YouTrack.Data; +using Tql.Plugins.YouTrack.Services; +using Tql.Plugins.YouTrack.Support; +using Tql.Utilities; + +namespace Tql.Plugins.YouTrack.Categories; + +internal class SavedSearchesMatch( + RootItemDto dto, + ICache cache, + ConfigurationManager configurationManager, + IMatchFactory factory +) : CachedMatch(cache), ISerializableMatch +{ + public override string Text => + MatchUtils.GetMatchLabel( + Labels.SavedSearchesMatch_Label, + configurationManager.Configuration, + dto.Url + ); + + public override ImageSource Icon => Images.SavedSearches; + public override MatchTypeId TypeId => TypeIds.SavedSearches; + public override string SearchHint => Labels.SavedSearchesMatch_SearchHint; + + protected override IEnumerable Create(YouTrackData data) + { + return from savedSearch in data.GetConnection(dto.Url).SavedSearches + select factory.Create( + new SavedSearchMatchDto( + dto.Url, + savedSearch.Id, + savedSearch.Name, + savedSearch.Query + ) + ); + } + + public string Serialize() + { + return JsonSerializer.Serialize(dto); + } +} diff --git a/src/Tql.Plugins.YouTrack/Categories/SavedSearchesType.cs b/src/Tql.Plugins.YouTrack/Categories/SavedSearchesType.cs new file mode 100644 index 00000000..6a280342 --- /dev/null +++ b/src/Tql.Plugins.YouTrack/Categories/SavedSearchesType.cs @@ -0,0 +1,19 @@ +using Tql.Abstractions; +using Tql.Plugins.YouTrack.Data; +using Tql.Plugins.YouTrack.Services; +using Tql.Plugins.YouTrack.Support; +using Tql.Utilities; + +namespace Tql.Plugins.YouTrack.Categories; + +[RootMatchType(YouTrackEndpoint.SavedSearches)] +internal class SavedSearchesType( + IMatchFactory factory, + ConfigurationManager configurationManager +) : MatchType(factory) +{ + public override Guid Id => TypeIds.SavedSearches.Id; + + protected override bool IsValid(RootItemDto dto) => + configurationManager.Configuration.HasConnection(dto.Url); +} diff --git a/src/Tql.Plugins.YouTrack/Categories/TypeIds.cs b/src/Tql.Plugins.YouTrack/Categories/TypeIds.cs new file mode 100644 index 00000000..47235628 --- /dev/null +++ b/src/Tql.Plugins.YouTrack/Categories/TypeIds.cs @@ -0,0 +1,32 @@ +using Tql.Abstractions; + +namespace Tql.Plugins.YouTrack.Categories; + +internal static class TypeIds +{ + private static MatchTypeId CreateId(string id) => new(Guid.Parse(id), YouTrackPlugin.Id); + + public static readonly MatchTypeId Boards = CreateId("836195e8-2fdd-4280-9079-a9541409820a"); + public static readonly MatchTypeId Board = CreateId("05d3125b-4e61-4e65-a8b9-b79ab1f2924a"); + + public static readonly MatchTypeId Dashboards = CreateId( + "ec125bd1-8f26-4ead-90ad-285a31e94719" + ); + public static readonly MatchTypeId Dashboard = CreateId("ec8ffed0-4b1f-4da7-92c2-d26c533ae54e"); + + public static readonly MatchTypeId Issues = CreateId("f0a983c9-e93d-4995-bb36-e4857167cfc1"); + public static readonly MatchTypeId Issue = CreateId("eec71d7f-237f-4120-9dd5-122f53e551fd"); + + public static readonly MatchTypeId News = CreateId("c4780f73-fe57-4b6d-b911-7e0aa1f914a2"); + public static readonly MatchTypeId New = CreateId("4c780a20-d582-40e9-9668-616e07491495"); + + public static readonly MatchTypeId Projects = CreateId("0268f2d0-7c99-46c2-a6f4-7a1379ea7c9e"); + public static readonly MatchTypeId Project = CreateId("dafbacd3-ff99-4de2-bd7f-baa871399aa1"); + + public static readonly MatchTypeId SavedSearches = CreateId( + "c0b268e5-a45c-441a-ab89-42c5171857df" + ); + public static readonly MatchTypeId SavedSearch = CreateId( + "cc06857b-d24a-4d9c-916a-c1e95801fc2e" + ); +} diff --git a/src/Tql.Plugins.YouTrack/Configuration.cs b/src/Tql.Plugins.YouTrack/Configuration.cs new file mode 100644 index 00000000..1ea54e87 --- /dev/null +++ b/src/Tql.Plugins.YouTrack/Configuration.cs @@ -0,0 +1,10 @@ +namespace Tql.Plugins.YouTrack; + +internal record Configuration(ImmutableArray Connections) +{ + public static readonly Configuration Empty = new(ImmutableArray.Empty); + + public bool HasConnection(string url) => Connections.Any(p => p.Url == url); +} + +internal record Connection(Guid Id, string Name, string Url, string ProtectedToken); diff --git a/src/Tql.Plugins.YouTrack/ConfigurationUI/ConfigurationControl.xaml b/src/Tql.Plugins.YouTrack/ConfigurationUI/ConfigurationControl.xaml new file mode 100644 index 00000000..12dc9465 --- /dev/null +++ b/src/Tql.Plugins.YouTrack/ConfigurationUI/ConfigurationControl.xaml @@ -0,0 +1,82 @@ + + + + + + + + + + + + + + + + + + +