Skip to content

Commit

Permalink
Remove redundant options and fix switch to default branch when requir…
Browse files Browse the repository at this point in the history
…es origin checkout.
  • Loading branch information
torbacz committed Sep 5, 2024
1 parent 20ab364 commit aa6a2d0
Show file tree
Hide file tree
Showing 5 changed files with 67 additions and 41 deletions.
19 changes: 16 additions & 3 deletions src/DependencyUpdated.Core/Config/Project.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ public sealed class Project : IValidatableObject

public string Name { get; set; } = default!;

public string[] DependencyConfigurations { get; set; } = ["https://api.nuget.org/v3/index.json"];
public string[] DependencyConfigurations { get; set; } = [];

public string[] Directories { get; set; } = ArraySegment<string>.Empty.ToArray();
public string[] Directories { get; set; } = [];

public string[] Groups { get; set; } = ["*"];
public string[] Groups { get; set; } = [];

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
Expand All @@ -38,4 +38,17 @@ public IEnumerable<ValidationResult> Validate(ValidationContext validationContex
yield return new ValidationResult($"Missing ${nameof(Groups)}.");
}
}

public void ApplyDefaultValue()
{
if (DependencyConfigurations.Length == 0 && Type == ProjectType.DotNet)
{
DependencyConfigurations = ["https://api.nuget.org/v3/index.json"];
}

if (Groups.Length == 0)
{
Groups = ["*"];
}
}
}
8 changes: 8 additions & 0 deletions src/DependencyUpdated.Core/Config/UpdaterConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,12 @@ public IEnumerable<ValidationResult> Validate(ValidationContext validationContex
}
}
}

public void ApplyDefaultValues()
{
foreach (var project in Projects)
{
project.ApplyDefaultValue();
}
}
}
71 changes: 41 additions & 30 deletions src/DependencyUpdated.Repositories.AzureDevOps/AzureDevOps.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using DependencyUpdated.Core.Config;
using DependencyUpdated.Repositories.AzureDevOps.Dto;
using LibGit2Sharp;
using LibGit2Sharp.Handlers;
using Microsoft.Extensions.Options;
using Serilog;
using System.Net;
Expand All @@ -15,14 +16,22 @@ internal sealed class AzureDevOps(TimeProvider timeProvider, IOptions<UpdaterCon
: IRepositoryProvider
{
private const string GitCommitMessage = "Bump dependencies";
private const string RemoteName = "origin";

public void SwitchToDefaultBranch(string repositoryPath)
{
var branchName = config.Value.AzureDevOps.TargetBranchName;
logger.Information("Switching {Repository} to branch {Branch}", repositoryPath, branchName);
using var repo = new Repository(repositoryPath);
var branch = repo.Branches[branchName] ??
throw new InvalidOperationException($"Branch {branchName} doesn't exists");

var options = new FetchOptions { CredentialsProvider = CreateGitCredentialsProvider() };
Commands.Fetch(repo, RemoteName, ArraySegment<string>.Empty, options, string.Empty);
var branch = repo.Branches[branchName] ?? repo.Branches[$"{RemoteName}/{branchName}"];

if (branch == null)
{
throw new InvalidOperationException($"Branch {branchName} doesn't exist");
}

Commands.Checkout(repo, branch);
}
Expand Down Expand Up @@ -53,27 +62,14 @@ public void CommitChanges(string repositoryPath, string projectName, string grou
{
var gitBranchName = CreateGitBranchName(projectName, config.Value.AzureDevOps.BranchName, group);
logger.Information("Commiting {Repository} to branch {Branch}", repositoryPath, gitBranchName);
using (var repo = new Repository(repositoryPath))
{
Commands.Stage(repo, "*");
var author = new Signature(config.Value.AzureDevOps.Username, config.Value.AzureDevOps.Email,
timeProvider.GetUtcNow());
repo.Commit(GitCommitMessage, author, author);
var options = new PushOptions();

if (!string.IsNullOrEmpty(config.Value.AzureDevOps.Username) &&
!string.IsNullOrEmpty(config.Value.AzureDevOps.PAT))
{
options.CredentialsProvider = (_, _, _) =>
new UsernamePasswordCredentials()
{
Username = config.Value.AzureDevOps.Username,
Password = config.Value.AzureDevOps.PAT
};
}

repo.Network.Push(repo.Branches[gitBranchName], options);
}
using var repo = new Repository(repositoryPath);
Commands.Stage(repo, "*");
var author = new Signature(config.Value.AzureDevOps.Username, config.Value.AzureDevOps.Email,
timeProvider.GetUtcNow());
repo.Commit(GitCommitMessage, author, author);
var options = new PushOptions();
options.CredentialsProvider = CreateGitCredentialsProvider();
repo.Network.Push(repo.Branches[gitBranchName], options);
}

public async Task SubmitPullRequest(IReadOnlyCollection<UpdateResult> updates, string projectName, string group)
Expand Down Expand Up @@ -106,11 +102,8 @@ public async Task SubmitPullRequest(IReadOnlyCollection<UpdateResult> updates, s
}

var response = await result.Content.ReadAsStringAsync();
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
};
var responseObject = JsonSerializer.Deserialize<PullRequestResponse>(response, options) ??
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true, };
var responseObject = JsonSerializer.Deserialize<PullRequestResponse>(response, options) ??
throw new InvalidOperationException("Missing response from API");

logger.Information("New PR created {Id}", responseObject.PullRequestId);
Expand Down Expand Up @@ -154,10 +147,10 @@ public async Task SubmitPullRequest(IReadOnlyCollection<UpdateResult> updates, s
result.EnsureSuccessStatusCode();
}
}

private static string CreateGitBranchName(string projectName, string branchName, string group)
{
return $"{projectName.ToLower()}/{branchName.ToLower()}/{group.ToLower().Replace("*", "-asterix-")}";
return $"{projectName.ToLower()}/{branchName.ToLower()}/{group.ToLower().Replace("*", "asterix")}";
}

private string CreatePrDescription(IReadOnlyCollection<UpdateResult> updates)
Expand All @@ -173,4 +166,22 @@ private string CreatePrDescription(IReadOnlyCollection<UpdateResult> updates)

return stringBuilder.ToString();
}

private CredentialsHandler? CreateGitCredentialsProvider()
{
if (string.IsNullOrEmpty(config.Value.AzureDevOps.Username))
{
return null;
}

if (string.IsNullOrEmpty(config.Value.AzureDevOps.PAT))
{
return null;
}

return (_, _, _) => new UsernamePasswordCredentials()
{
Username = config.Value.AzureDevOps.Username, Password = config.Value.AzureDevOps.PAT
};
}
}
3 changes: 0 additions & 3 deletions src/DependencyUpdated/Options.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,4 @@ public class Options
{
[Option('c', "configPath", Required = false, HelpText = "Path for the configuration file.")]
public string? ConfigPath { get; set; }

[Option('r', "repoPath", Required = false, HelpText = "Path for the repository folder.")]
public string? RepositoryPath { get; set; }
}
7 changes: 2 additions & 5 deletions src/DependencyUpdated/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ private static async Task RunApplication(Options options)
ConfigureServices();

var config = _serviceProvider.GetRequiredService<IOptions<UpdaterConfig>>();
config.Value.ApplyDefaultValues();
var validationResult = config.Value.Validate(new ValidationContext(config.Value)).ToList();
if (validationResult.Count != 0)
{
Expand All @@ -39,11 +40,7 @@ private static async Task RunApplication(Options options)

var repositoryProvider =
_serviceProvider.GetRequiredKeyedService<IRepositoryProvider>(config.Value.RepositoryType);
var repositoryPath = string.IsNullOrEmpty(options.RepositoryPath)
? Environment.CurrentDirectory
: options.RepositoryPath;

Directory.SetCurrentDirectory(repositoryPath);
var repositoryPath = Environment.CurrentDirectory;

foreach (var configEntry in config.Value.Projects)
{
Expand Down

0 comments on commit aa6a2d0

Please sign in to comment.