Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: use a subdirectory of the output path to reduce the chances of c… #6038

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions it/compare-generation.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -79,11 +79,11 @@ if ($firstGenerationProcess.ExitCode -ne 0 -or $secondGenerationProcess.ExitCode
}

# Remove variable output files
Remove-Item (Join-Path -Path $tmpFolder1 -ChildPath "kiota-lock.json")
Remove-Item (Join-Path -Path $tmpFolder1 -ChildPath "*/kiota-lock.json")
if (Test-Path (Join-Path -Path $tmpFolder1 -ChildPath ".kiota.log")) {
Remove-Item -Force (Join-Path -Path $tmpFolder1 -ChildPath ".kiota.log")
}
Remove-Item (Join-Path -Path $tmpFolder2 -ChildPath "kiota-lock.json")
Remove-Item (Join-Path -Path $tmpFolder2 -ChildPath "*/kiota-lock.json")
if (Test-Path (Join-Path -Path $tmpFolder2 -ChildPath ".kiota.log")) {
Remove-Item -Force (Join-Path -Path $tmpFolder2 -ChildPath ".kiota.log")
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ public ConsumerOperation? Operation
public string OpenAPIFilePath { get; set; } = "openapi.yaml";
public string ApiManifestPath { get; set; } = "apimanifest.json";
public string OutputPath { get; set; } = "./output";
public string ClientOutputPath => Path.Combine(OutputPath, ClientClassName);
public string ClientClassName { get; set; } = "ApiClient";
public AccessModifier TypeAccessModifier { get; set; } = AccessModifier.Public;
public string ClientNamespaceName { get; set; } = "ApiSdk";
Expand Down
24 changes: 13 additions & 11 deletions src/Kiota.Builder/KiotaBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ public partial class KiotaBuilder
private readonly ParallelOptions parallelOptions;
private readonly HttpClient httpClient;
private OpenApiDocument? openApiDocument;
private readonly string outputPath;
internal void SetOpenApiDocument(OpenApiDocument document) => openApiDocument = document ?? throw new ArgumentNullException(nameof(document));

public KiotaBuilder(ILogger<KiotaBuilder> logger, GenerationConfiguration config, HttpClient client, bool useKiotaConfig = false)
Expand All @@ -64,19 +65,20 @@ public KiotaBuilder(ILogger<KiotaBuilder> logger, GenerationConfiguration config
workspaceManagementService = new WorkspaceManagementService(logger, client, useKiotaConfig, workingDirectory);
this.useKiotaConfig = useKiotaConfig;
openApiDocumentDownloadService = new OpenApiDocumentDownloadService(client, logger);
outputPath = this.config.ClientOutputPath;
}
private readonly OpenApiDocumentDownloadService openApiDocumentDownloadService;
private readonly bool useKiotaConfig;
private async Task CleanOutputDirectoryAsync(CancellationToken cancellationToken)
{
if (config.CleanOutput && Directory.Exists(config.OutputPath))
if (config.CleanOutput && Directory.Exists(outputPath))
{
logger.LogInformation("Cleaning output directory {Path}", config.OutputPath);
logger.LogInformation("Cleaning output directory {Path}", outputPath);
// not using Directory.Delete on the main directory because it's locked when mapped in a container
foreach (var subDir in Directory.EnumerateDirectories(config.OutputPath))
foreach (var subDir in Directory.EnumerateDirectories(outputPath))
Directory.Delete(subDir, true);
await workspaceManagementService.BackupStateAsync(config.OutputPath, cancellationToken).ConfigureAwait(false);
foreach (var subFile in Directory.EnumerateFiles(config.OutputPath)
await workspaceManagementService.BackupStateAsync(outputPath, cancellationToken).ConfigureAwait(false);
foreach (var subFile in Directory.EnumerateFiles(outputPath)
.Where(static x => !x.EndsWith(FileLogLogger.LogFileName, StringComparison.OrdinalIgnoreCase)))
File.Delete(subFile);
}
Expand Down Expand Up @@ -273,7 +275,7 @@ public async Task<bool> GenerateClientAsync(CancellationToken cancellationToken)
{
// Generate public API export
sw.Start();
var fileStream = File.Create(Path.Combine(config.OutputPath, PublicApiExportService.DomExportFileName));
var fileStream = File.Create(Path.Combine(outputPath, PublicApiExportService.DomExportFileName));
await using (fileStream.ConfigureAwait(false))
{
await new PublicApiExportService(config).SerializeDomAsync(fileStream, generatedCode, cancellationToken).ConfigureAwait(false);
Expand Down Expand Up @@ -301,11 +303,11 @@ private async Task<bool> GenerateConsumerAsync(Func<Stopwatch, int, OpenApiUrlTr
{
await CleanOutputDirectoryAsync(cancellationToken).ConfigureAwait(false);
// doing this verification at the beginning to give immediate feedback to the user
Directory.CreateDirectory(config.OutputPath);
Directory.CreateDirectory(outputPath);
}
catch (Exception ex)
{
throw new InvalidOperationException($"Could not open/create output directory {config.OutputPath}, reason: {ex.Message}", ex);
throw new InvalidOperationException($"Could not open/create output directory {outputPath}, reason: {ex.Message}", ex);
}
try
{
Expand All @@ -329,7 +331,7 @@ private async Task<bool> GenerateConsumerAsync(Func<Stopwatch, int, OpenApiUrlTr
}
catch
{
await workspaceManagementService.RestoreStateAsync(config.OutputPath, cancellationToken).ConfigureAwait(false);
await workspaceManagementService.RestoreStateAsync(outputPath, cancellationToken).ConfigureAwait(false);
throw;
}
return true;
Expand Down Expand Up @@ -579,13 +581,13 @@ public async Task ApplyLanguageRefinementAsync(GenerationConfiguration config, C

public async Task CreateLanguageSourceFilesAsync(GenerationLanguage language, CodeNamespace generatedCode, CancellationToken cancellationToken)
{
var languageWriter = LanguageWriter.GetLanguageWriter(language, config.OutputPath, config.ClientNamespaceName, config.UsesBackingStore, config.ExcludeBackwardCompatible);
var languageWriter = LanguageWriter.GetLanguageWriter(language, outputPath, config.ClientNamespaceName, config.UsesBackingStore, config.ExcludeBackwardCompatible);
var stopwatch = new Stopwatch();
stopwatch.Start();
var codeRenderer = CodeRenderer.GetCodeRender(config);
await codeRenderer.RenderCodeNamespaceToFilePerClassAsync(languageWriter, generatedCode, cancellationToken).ConfigureAwait(false);
stopwatch.Stop();
logger.LogTrace("{Timestamp}ms: Files written to {Path}", stopwatch.ElapsedMilliseconds, config.OutputPath);
logger.LogTrace("{Timestamp}ms: Files written to {Path}", stopwatch.ElapsedMilliseconds, outputPath);
}
private const string RequestBuilderSuffix = "RequestBuilder";
private const string ItemRequestBuilderSuffix = "ItemRequestBuilder";
Expand Down
10 changes: 10 additions & 0 deletions src/Kiota.Builder/Lock/LockManagementService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,15 @@ public IEnumerable<string> GetDirectoriesContainingLockFile(string searchDirecto
private static async Task<KiotaLock?> GetLockFromDirectoryInternalAsync(string directoryPath, CancellationToken cancellationToken)
{
var lockFilePath = Path.Combine(directoryPath, LockFileName);
// If the lock file does not exist in the provided directory, try checking in the parent directory. This handles
// clients generated by older versions without this fix
if (!File.Exists(lockFilePath))
{
// We could use Directory.GetParent, but that involves a syscall which seems unnecessary given '..' is
// supported by File APIs.
// TODO: Check if there are scenarios where using '..' would fail.
lockFilePath = Path.Combine(directoryPath, "..", LockFileName);
}
if (File.Exists(lockFilePath))
{
#pragma warning disable CA2007
Expand Down Expand Up @@ -73,6 +82,7 @@ public Task WriteLockFileAsync(string directoryPath, KiotaLock lockInfo, Cancell
private static async Task WriteLockFileInternalAsync(string directoryPath, KiotaLock lockInfo, CancellationToken cancellationToken)
{
var lockFilePath = Path.Combine(directoryPath, LockFileName);
Directory.CreateDirectory(directoryPath);
#pragma warning disable CA2007
await using var fileStream = File.Open(lockFilePath, FileMode.Create);
#pragma warning restore CA2007
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ public async Task UpdateStateFromConfigurationAsync(GenerationConfiguration gene
{
DescriptionHash = descriptionHash ?? string.Empty,
};
await lockManagementService.WriteLockFileAsync(generationConfiguration.OutputPath, configurationLock, cancellationToken).ConfigureAwait(false);
await lockManagementService.WriteLockFileAsync(generationConfiguration.ClientOutputPath, configurationLock, cancellationToken).ConfigureAwait(false);
}
}
public async Task RestoreStateAsync(string outputPath, CancellationToken cancellationToken = default)
Expand Down Expand Up @@ -139,7 +139,7 @@ public async Task<bool> ShouldGenerateAsync(GenerationConfiguration inputConfig,
}
else
{
var existingLock = await lockManagementService.GetLockFromDirectoryAsync(inputConfig.OutputPath, cancellationToken).ConfigureAwait(false);
var existingLock = await lockManagementService.GetLockFromDirectoryAsync(inputConfig.ClientOutputPath, cancellationToken).ConfigureAwait(false);
var configurationLock = new KiotaLock(inputConfig)
{
DescriptionHash = descriptionHash,
Expand Down
Loading