Skip to content

Commit

Permalink
chore: adjust process execution
Browse files Browse the repository at this point in the history
  • Loading branch information
Phil91 committed Jan 29, 2024
1 parent 4cf7571 commit d3bb125
Show file tree
Hide file tree
Showing 5 changed files with 61 additions and 80 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ public static IServiceCollection AddGithubService(this IServiceCollection servic
{
services.AddOptions<GithubServiceSettings>()
.Bind(section)
.ValidateDataAnnotations()
.ValidateOnStart();

var sp = services.BuildServiceProvider();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ public static IServiceCollection AddJiraService(this IServiceCollection services
{
services.AddOptions<JiraServiceSettings>()
.Bind(section)
.ValidateDataAnnotations()
.ValidateOnStart();

var sp = services.BuildServiceProvider();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ public static IServiceCollection AddParsers(this IServiceCollection services, IC
{
services.AddOptions<ParserSettings>()
.Bind(section)
.ValidateDataAnnotations()
.ValidateOnStart();

services
Expand Down
74 changes: 22 additions & 52 deletions jihub.Worker/Program.cs
Original file line number Diff line number Diff line change
@@ -1,24 +1,4 @@
/********************************************************************************
* Copyright (c) 2021, 2023 BMW Group AG
* Copyright (c) 2021, 2023 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
********************************************************************************/

using CommandLine;
using CommandLine;
using jihub;
using jihub.Base;
using jihub.Github.DependencyInjection;
Expand All @@ -29,48 +9,38 @@

try
{
var options = Parser.Default.ParseArguments<JihubOptions>(args)
.MapResult(opts =>
{
opts.Validate();
return opts;
},
err =>
{
foreach (var error in err)
Console.WriteLine(error.Tag.ToString());
throw new ArgumentException("failed to parse options");
});

Console.WriteLine("Building worker");
var host = Host
await Host
.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
Console.WriteLine("Building services");
services
.AddTransient<Worker>()
.AddJiraService(hostContext.Configuration.GetSection("Jira"))
.AddGithubService(hostContext.Configuration.GetSection("Github"))
.AddParsers(hostContext.Configuration.GetSection("Parsers"))
.AddLogging();
})
.Build();
Console.WriteLine("Building importer completed");

var cts = new CancellationTokenSource();
Console.CancelKeyPress += (s, e) =>
{
Console.WriteLine("Canceling...");
cts.Cancel();
e.Cancel = true;
};
Console.WriteLine("Starting...");
var workerInstance = host.Services.GetRequiredService<Worker>();
await Parser.Default.ParseArguments<JihubOptions>(args)
.MapResult(async opts =>
{
opts.Validate();
services.AddSingleton(options);
services
.AddHostedService<Worker>();
})
.RunConsoleAsync();

try
{
// We have the parsed arguments, so let's just pass them down
return await workerInstance.ExecuteAsync(opts, cts.Token);
}
catch
{
Console.WriteLine("Error!");
return -3; // Unhandled error
}
},
_ => Task.FromResult(-1));
Console.WriteLine("Execution finished shutting down");
}
catch (Exception ex)
Expand Down
64 changes: 36 additions & 28 deletions jihub.Worker/Worker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,79 +5,81 @@
using jihub.Jira.Models;
using jihub.Parsers.Jira;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace jihub;

/// <summary>
/// Worker to process the jql query.
/// </summary>
public class Worker
public class Worker : IHostedService
{
private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly IJiraService _jiraService;
private readonly IGithubService _githubService;
private readonly IJiraParser _jiraParser;
private readonly JihubOptions _jihubOptions;
private readonly ILogger<Worker> _logger;

/// <summary>
/// Creates a new instance of <see cref="Worker"/>
/// </summary>
/// <param name="serviceScopeFactory">access to the services</param>
/// <param name="jiraParser"></param>
/// <param name="jihubOptions"></param>
/// <param name="logger">the logger</param>
/// <param name="jiraService"></param>
/// <param name="githubService"></param>
public Worker(
IServiceScopeFactory serviceScopeFactory,
IJiraService jiraService,
IGithubService githubService,
IJiraParser jiraParser,
JihubOptions jihubOptions,
ILogger<Worker> logger)
{
_serviceScopeFactory = serviceScopeFactory;
_jiraService = jiraService;
_githubService = githubService;
_jiraParser = jiraParser;
_jihubOptions = jihubOptions;
_logger = logger;
}

/// <summary>
/// Handles the conversion from jira to github issues and the import to github
/// </summary>
/// <param name="options">the options given by the user</param>
/// <param name="cts">Cancellation Token</param>
public async Task<int> ExecuteAsync(JihubOptions options, CancellationToken cts)
/// <inheritdoc />
public async Task StartAsync(CancellationToken cts)
{
try
{
using var scope = _serviceScopeFactory.CreateScope();
var jiraService = scope.ServiceProvider.GetRequiredService<IJiraService>();
var githubService = scope.ServiceProvider.GetRequiredService<IGithubService>();
var parser = scope.ServiceProvider.GetRequiredService<IJiraParser>();

var jiraIssues = await jiraService.GetAsync(options.SearchQuery, options.MaxResults, cts).ConfigureAwait(false);
var jiraIssues = await _jiraService.GetAsync(_jihubOptions.SearchQuery, _jihubOptions.MaxResults, cts).ConfigureAwait(false);
var content = Enumerable.Empty<GithubContent>();
if (options.Export)
if (_jihubOptions.Export)
{
content = await githubService.GetRepoContent(options.ImportOwner!, options.UploadRepo!, "contents", cts).ConfigureAwait(false);
content = await _githubService.GetRepoContent(_jihubOptions.ImportOwner!, _jihubOptions.UploadRepo!, "contents", cts).ConfigureAwait(false);
}

var githubInformation = await githubService.GetRepositoryData(options.Owner, options.Repo, cts).ConfigureAwait(false);
var githubInformation = await _githubService.GetRepositoryData(_jihubOptions.Owner, _jihubOptions.Repo, cts).ConfigureAwait(false);

var excludedJiraIssues = jiraIssues.Where(x => githubInformation.Issues.Any(i => i.Title.Contains($"(ext: {x.Key})")));
_logger.LogInformation("The following issues were not imported because they are already available in Github {Issues}", string.Join(",", excludedJiraIssues.Select(x => x.Key)));

var convertedIssues = await parser.ConvertIssues(jiraIssues.Except(excludedJiraIssues), options, content, githubInformation.Labels.ToList(), githubInformation.Milestones.ToList(), cts).ConfigureAwait(false);
var createdIssues = await githubService.CreateIssuesAsync(options.Owner, options.Repo, convertedIssues, cts).ConfigureAwait(false);
var convertedIssues = await _jiraParser.ConvertIssues(jiraIssues.Except(excludedJiraIssues), _jihubOptions, content, githubInformation.Labels.ToList(), githubInformation.Milestones.ToList(), cts).ConfigureAwait(false);
var createdIssues = await _githubService.CreateIssuesAsync(_jihubOptions.Owner, _jihubOptions.Repo, convertedIssues, cts).ConfigureAwait(false);

if (options.LinkChildren)
if (_jihubOptions.LinkChildren)
{
var childIssues = GetLinks(jiraIssues, "Parent of");
await githubService.LinkChildren(options.Owner, options.Repo, childIssues, githubInformation.Issues, createdIssues, cts).ConfigureAwait(false);
await _githubService.LinkChildren(_jihubOptions.Owner, _jihubOptions.Repo, childIssues, githubInformation.Issues, createdIssues, cts).ConfigureAwait(false);
}

if (options.LinkRelated)
if (_jihubOptions.LinkRelated)
{
var relatedIssues = GetLinks(jiraIssues, "relates to");
await githubService.AddRelatesComment(options.Owner, options.Repo, relatedIssues, githubInformation.Issues, createdIssues, cts).ConfigureAwait(false);
await _githubService.AddRelatesComment(_jihubOptions.Owner, _jihubOptions.Repo, relatedIssues, githubInformation.Issues, createdIssues, cts).ConfigureAwait(false);
}
}
catch (Exception ex)
{
Environment.ExitCode = 1;
_logger.LogError(ex, "processing failed with following Exception {ExceptionMessage}", ex.Message);
}

return 0;
}

private static Dictionary<string, List<string>> GetLinks(IEnumerable<JiraIssue> jiraIssues, string linkType)
Expand Down Expand Up @@ -105,4 +107,10 @@ private static Dictionary<string, List<string>> GetLinks(IEnumerable<JiraIssue>

return dict;
}

/// <inheritdoc />
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}

0 comments on commit d3bb125

Please sign in to comment.