Skip to content

Commit

Permalink
Rename ISourceFile.FileUri to ISourceFile.Identifier (#15638)
Browse files Browse the repository at this point in the history
This PR introduces no functional changes and focuses solely on renaming
properties of `ISourceFile` to isolate the change and minimize the scope
of follow-up file I/O refactoring PRs.

The first commit also contains a minor change to add `Query` and
`Fragment` to `Bicep.IO.ResourceIdentifier`, as `Query` may be required
for the remote compilation service in the future.
###### Microsoft Reviewers: [Open in
CodeFlow](https://microsoft.github.io/open-pr/?codeflow=https://github.com/Azure/bicep/pull/15638)
  • Loading branch information
shenglol authored Nov 21, 2024
1 parent 6cf5576 commit e085d02
Show file tree
Hide file tree
Showing 62 changed files with 218 additions and 216 deletions.
2 changes: 1 addition & 1 deletion src/Bicep.Cli.IntegrationTests/TestBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ protected static async Task<IEnumerable<string>> GetAllDiagnostics(string bicepF
{
var (line, character) = TextCoordinateConverter.GetPosition(bicepFile.LineStarts, diagnostic.Span.Position);
var codeDescription = diagnostic.Uri == null ? string.Empty : $" [{diagnostic.Uri.AbsoluteUri}]";
output.Add($"{bicepFile.FileUri.LocalPath}({line + 1},{character + 1}) : {diagnostic.Level} {diagnostic.Code}: {diagnostic.Message}{codeDescription}");
output.Add($"{bicepFile.Identifier.LocalPath}({line + 1},{character + 1}) : {diagnostic.Level} {diagnostic.Code}: {diagnostic.Message}{codeDescription}");
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public static class ExperimentalFeatureWarningProvider
public static string? TryGetEnabledExperimentalFeatureWarningMessage(SourceFileGrouping sourceFileGrouping, IFeatureProviderFactory featureProviderFactory)
{
var experimentalFeaturesEnabled = sourceFileGrouping.SourceFiles
.Select(file => featureProviderFactory.GetFeatureProvider(file.FileUri))
.Select(file => featureProviderFactory.GetFeatureProvider(file.Identifier))
.SelectMany(static features => features.EnabledFeatureMetadata.Where(f => f.impactsCompilation).Select(f => f.name))
.Distinct()
.ToImmutableArray();
Expand Down
2 changes: 1 addition & 1 deletion src/Bicep.Cli/Helpers/ParamsFileHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,6 @@ public static BicepParamFile ApplyParameterOverrides(BicepParamFile sourceFile,
return sourceFile;
}

return SourceFileFactory.CreateBicepParamFile(sourceFile.FileUri, newProgramSyntax.ToString());
return SourceFileFactory.CreateBicepParamFile(sourceFile.Identifier, newProgramSyntax.ToString());
}
}
4 changes: 2 additions & 2 deletions src/Bicep.Cli/Logging/DiagnosticLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ private static void LogDefaultDiagnostics(ILogger logger, ImmutableDictionary<Bi
// build a a code description link if the Uri is assigned
var codeDescription = diagnostic.Uri == null ? string.Empty : $" [{diagnostic.Uri.AbsoluteUri}]";

var message = $"{bicepFile.FileUri.LocalPath}({line + 1},{character + 1}) : {diagnostic.Level} {diagnostic.Code}: {diagnostic.Message}{codeDescription}";
var message = $"{bicepFile.Identifier.LocalPath}({line + 1},{character + 1}) : {diagnostic.Level} {diagnostic.Code}: {diagnostic.Message}{codeDescription}";

logger.Log(ToLogLevel(diagnostic.Level), message);
}
Expand Down Expand Up @@ -136,7 +136,7 @@ private static Result GetSarifDiagnostic(BicepSourceFile sourceFile, IDiagnostic
{
ArtifactLocation = new ArtifactLocation
{
Uri = sourceFile.FileUri,
Uri = sourceFile.Identifier,
},
Region = new Region
{
Expand Down
6 changes: 3 additions & 3 deletions src/Bicep.Cli/Rpc/CliJsonRpcServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public async Task<CompileParamsResponse> CompileParams(CompileParamsRequest requ

var workspace = new Workspace();
workspace.UpsertSourceFile(paramFile);
compilation = await compiler.CreateCompilation(paramFile.FileUri, workspace);
compilation = await compiler.CreateCompilation(paramFile.Identifier, workspace);
var paramsResult = compilation.Emitter.Parameters();

return new(
Expand All @@ -96,7 +96,7 @@ public async Task<GetFileReferencesResponse> GetFileReferences(GetFileReferences
var fileUris = new HashSet<Uri>();
foreach (var otherModel in compilation.GetAllBicepModels())
{
fileUris.Add(otherModel.SourceFile.FileUri);
fileUris.Add(otherModel.SourceFile.Identifier);
fileUris.UnionWith(otherModel.GetAuxiliaryFileReferences());
if (otherModel.Configuration.ConfigFileIdentifier is { } configFileIdentifier)
{
Expand Down Expand Up @@ -235,7 +235,7 @@ private static IEnumerable<DiagnosticDefinition> GetDiagnostics(Compilation comp
{
foreach (var diagnostic in diagnostics)
{
yield return new(bicepFile.FileUri.LocalPath, GetRange(bicepFile, diagnostic), diagnostic.Level.ToString(), diagnostic.Code, diagnostic.Message);
yield return new(bicepFile.Identifier.LocalPath, GetRange(bicepFile, diagnostic), diagnostic.Level.ToString(), diagnostic.Code, diagnostic.Message);
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/Bicep.Core.IntegrationTests/DecoratorTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ param inputb string
};

var compilation = Services.BuildCompilation(files, mainUri);
var diagnosticsByFile = compilation.GetAllDiagnosticsByBicepFile().ToDictionary(kvp => kvp.Key.FileUri, kvp => kvp.Value);
var diagnosticsByFile = compilation.GetAllDiagnosticsByBicepFile().ToDictionary(kvp => kvp.Key.Identifier, kvp => kvp.Value);
var success = diagnosticsByFile.Values.SelectMany(x => x).All(d => !d.IsError());

using (new AssertionScope())
Expand Down Expand Up @@ -215,7 +215,7 @@ param inputb string
};

var compilation = Services.BuildCompilation(files, mainUri);
var diagnosticsByFile = compilation.GetAllDiagnosticsByBicepFile().ToDictionary(kvp => kvp.Key.FileUri, kvp => kvp.Value);
var diagnosticsByFile = compilation.GetAllDiagnosticsByBicepFile().ToDictionary(kvp => kvp.Key.Identifier, kvp => kvp.Value);
var success = diagnosticsByFile.Values.SelectMany(x => x).All(d => !d.IsError());

using (new AssertionScope())
Expand Down
2 changes: 1 addition & 1 deletion src/Bicep.Core.IntegrationTests/ExamplesTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ private async Task RunExampleTest(EmbeddedFile embeddedBicep, FeatureProviderOve
diagnostics.Where(d => !IsPermittedMissingTypeDiagnostic(d)),
diagnostics =>
{
diagnostics.Should().BeEmpty("{0} should not have warnings or errors", file.FileUri.LocalPath);
diagnostics.Should().BeEmpty("{0} should not have warnings or errors", file.Identifier.LocalPath);
});
}

Expand Down
4 changes: 2 additions & 2 deletions src/Bicep.Core.IntegrationTests/ModuleTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -652,7 +652,7 @@ param p resource 'Some.Fake/Type@2019-06-01'
output storage resource 'Another.Fake/Type@2019-06-01' = fake
"));
var diagnosticsMap = result.Compilation.GetAllDiagnosticsByBicepFile().ToDictionary(kvp => kvp.Key.FileUri, kvp => kvp.Value);
var diagnosticsMap = result.Compilation.GetAllDiagnosticsByBicepFile().ToDictionary(kvp => kvp.Key.Identifier, kvp => kvp.Value);
using (new AssertionScope())
{
diagnosticsMap[InMemoryFileResolver.GetFileUri("/path/to/module.bicep")].Should().HaveDiagnostics(new[]
Expand Down Expand Up @@ -769,7 +769,7 @@ private static string GetTemplate(Compilation compilation)

private static (bool success, IDictionary<Uri, ImmutableArray<IDiagnostic>> diagnosticsByFile) GetSuccessAndDiagnosticsByFile(Compilation compilation)
{
var diagnosticsByFile = compilation.GetAllDiagnosticsByBicepFile().ToDictionary(kvp => kvp.Key.FileUri, kvp => kvp.Value);
var diagnosticsByFile = compilation.GetAllDiagnosticsByBicepFile().ToDictionary(kvp => kvp.Key.Identifier, kvp => kvp.Value);
var success = diagnosticsByFile.Values.SelectMany(x => x).All(d => !d.IsError());

return (success, diagnosticsByFile);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,6 @@ public void CompileWithLocalJsonModule_ValidTemplate_Succeeds()
}

private static ImmutableDictionary<string, ImmutableArray<IDiagnostic>> GetDiagnosticsByFileName(Compilation compilation) =>
compilation.GetAllDiagnosticsByBicepFile().ToImmutableDictionary(kvp => Path.GetFileName(kvp.Key.FileUri.LocalPath), kvp => kvp.Value);
compilation.GetAllDiagnosticsByBicepFile().ToImmutableDictionary(kvp => Path.GetFileName(kvp.Key.Identifier.LocalPath), kvp => kvp.Value);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ private static void TestGetFunctionCallInfo(string bicep, string expectedFunctio
bicep);
using (new AssertionScope().WithFullSource(result.BicepFile))
{
UseRecentApiVersionRuleTests.VerifyAllTypesAndDatesAreFake(result.BicepFile.GetOriginalSource());
UseRecentApiVersionRuleTests.VerifyAllTypesAndDatesAreFake(result.BicepFile.Text);

var actual = UseRecentApiVersionRule.GetFunctionCallInfos(result.Compilation.GetEntrypointSemanticModel()).ToArray();
actual.Should().HaveCount(1, "Expecting a single function call per test");
Expand Down
12 changes: 6 additions & 6 deletions src/Bicep.Core.UnitTests/SourceCode/SourceArchiveTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ public void CanPackAndUnpackSourceFiles()


using var stream = SourceArchive.PackSourcesIntoStream(
mainBicep.SourceFile.FileUri,
mainBicep.SourceFile.Identifier,
CacheRoot, mainBicep, mainJson, standaloneJson, templateSpecMainJson, localModuleJson, templateSpecMainJson2, externalModuleJson);
stream.Length.Should().BeGreaterThan(0);

Expand Down Expand Up @@ -252,7 +252,7 @@ public void CanPackAndUnpackDocumentLinks()
}
},
};
using var stream = SourceArchive.PackSourcesIntoStream(mainBicep.SourceFile.FileUri, CacheRoot, linksInput, mainBicep, mainJson, standaloneJson, templateSpecMainJson, localModuleJson, localModuleBicep, externalModuleJson);
using var stream = SourceArchive.PackSourcesIntoStream(mainBicep.SourceFile.Identifier, CacheRoot, linksInput, mainBicep, mainJson, standaloneJson, templateSpecMainJson, localModuleJson, localModuleBicep, externalModuleJson);
stream.Length.Should().BeGreaterThan(0);

SourceArchive? sourceArchive = SourceArchive.UnpackFromStream(stream).TryUnwrap();
Expand Down Expand Up @@ -433,7 +433,7 @@ string[] expectedArchivePaths
}
var files = inputPaths.Select(path => CreateSourceFile(fs, path, SourceArchive.SourceKind.Bicep, $"// {path}")).ToArray();

using var stream = SourceArchive.PackSourcesIntoStream(files[0].SourceFile.FileUri, CacheRoot, files);
using var stream = SourceArchive.PackSourcesIntoStream(files[0].SourceFile.Identifier, CacheRoot, files);
SourceArchive sourceArchive = SourceArchive.UnpackFromStream(stream).UnwrapOrThrow();

sourceArchive.EntrypointRelativePath.Should().Be(expectedPaths[0], "entrypoint path should be correct");
Expand All @@ -447,7 +447,7 @@ string[] expectedArchivePaths

for (int i = 0; i < inputPaths.Length; ++i)
{
var archivedTestFile = sourceArchive.SourceFiles.Single(f => f.Contents.Equals(files[i].SourceFile.GetOriginalSource()));
var archivedTestFile = sourceArchive.SourceFiles.Single(f => f.Contents.Equals(files[i].SourceFile.Text));
archivedTestFile.Path.Should().Be(expectedPaths[i]);
archivedTestFile.ArchivePath.Should().Be(expectedArchivePaths[i]);
}
Expand Down Expand Up @@ -495,8 +495,8 @@ public void DuplicateNamesAfterMunging_ShouldHaveSeparateEntries(
var sutFile3 = inputBicepPath3 is null ? null : CreateSourceFile(fs, rootBicepFolder, inputBicepPath3, SourceArchive.SourceKind.Bicep, SecondaryDotBicepSource);

using var stream = sutFile3 is null ?
SourceArchive.PackSourcesIntoStream(entrypointFile.SourceFile.FileUri, CacheRoot, entrypointFile, sutFile1, sutFile2) :
SourceArchive.PackSourcesIntoStream(entrypointFile.SourceFile.FileUri, CacheRoot, entrypointFile, sutFile1, sutFile2, sutFile3);
SourceArchive.PackSourcesIntoStream(entrypointFile.SourceFile.Identifier, CacheRoot, entrypointFile, sutFile1, sutFile2) :
SourceArchive.PackSourcesIntoStream(entrypointFile.SourceFile.Identifier, CacheRoot, entrypointFile, sutFile1, sutFile2, sutFile3);

SourceArchive sourceArchive = SourceArchive.UnpackFromStream(stream).UnwrapOrThrow();

Expand Down
6 changes: 3 additions & 3 deletions src/Bicep.Core.UnitTests/Utils/CompilationResultExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,11 @@ public static string ApplyCodeFix(this ICompilationResult result, IDiagnostic di
var fix = fixable.Fixes.Single();
var replacement = fix.Replacements.Single();

var originalFile = result.SourceFile.GetOriginalSource();
var sourceText = result.SourceFile.Text;

return string.Concat(
originalFile.AsSpan(0, replacement.Span.Position),
sourceText.AsSpan(0, replacement.Span.Position),
replacement.Text,
originalFile.AsSpan(replacement.Span.GetEndPosition()));
sourceText.AsSpan(replacement.Span.GetEndPosition()));
}
}
2 changes: 1 addition & 1 deletion src/Bicep.Core.UnitTests/Utils/RegistryHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public static async Task PublishModuleToRegistryAsync(
throw new InvalidOperationException($"Module {moduleName} failed to produce a template.");
}

var features = featureProviderFactory.GetFeatureProvider(result.BicepFile.FileUri);
var features = featureProviderFactory.GetFeatureProvider(result.BicepFile.Identifier);
BinaryData? sourcesStream = publishSource ? BinaryData.FromStream(SourceArchive.PackSourcesIntoStream(dispatcher, result.Compilation.SourceFileGrouping, features.CacheRootDirectory)) : null;
await dispatcher.PublishModule(targetReference, BinaryData.FromString(result.Template.ToString()), sourcesStream, documentationUri);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Bicep.Core.UnitTests/Utils/SourceArchiveBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public Stream BuildStream()
SourceFiles[0].Should().BeOfType<BicepFile>("Entrypoint should be a bicep file");

return SourceArchive.PackSourcesIntoStream(
EntrypointFile.FileUri,
EntrypointFile.Identifier,
cacheRoot,
SourceFiles.Select(x => new SourceFileWithArtifactReference(x, null)).ToArray());
}
Expand Down
2 changes: 1 addition & 1 deletion src/Bicep.Core/Emit/CompilationEmitter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public ParametersResult Parameters()
}
case ArmTemplateSemanticModel armTemplateModel:
{
var template = armTemplateModel.SourceFile.GetOriginalSource();
var template = armTemplateModel.SourceFile.Text;
var templateResult = new TemplateResult(true, ImmutableDictionary<BicepSourceFile, ImmutableArray<IDiagnostic>>.Empty, template, null);

return new ParametersResult(true, diagnostics, parametersData, null, templateResult);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ internal ArmReferenceCollector(ArmTemplateFile templateFile)
{
if (templateFile.Template is not { } template)
{
throw new InvalidOperationException($"Source template of {templateFile.FileUri} is not valid");
throw new InvalidOperationException($"Source template of {templateFile.Identifier} is not valid");
}

schemaContext = SchemaValidationContext.ForTemplate(template);
Expand Down
10 changes: 5 additions & 5 deletions src/Bicep.Core/Emit/CompileTimeImports/ImportClosureInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public record ImportClosureInfo(ImmutableArray<DeclaredTypeExpression> ImportedT

public static ImportClosureInfo Calculate(SemanticModel model)
{
IntraTemplateSymbolicReferenceFactory referenceFactory = new(model.SourceFile.FileUri);
IntraTemplateSymbolicReferenceFactory referenceFactory = new(model.SourceFile.Identifier);
var closure = CalculateImportClosure(model, referenceFactory);
var closureMetadata = CalculateImportedSymbolNames(model, closure);

Expand Down Expand Up @@ -205,7 +205,7 @@ private static ImportClosure CalculateImportClosure(
if (!targetModel.Exports.TryGetValue(name, out var exportMetadata))
{
throw new InvalidOperationException($"No export named {name} found in {TemplateIdentifier(
model.SourceFile.FileUri,
model.SourceFile.Identifier,
targetModel,
importedSymbolReference.ImportTarget)}");
}
Expand Down Expand Up @@ -441,9 +441,9 @@ private static string TemplateIdentifier(Uri entryPointUri, ISemanticModel model

private static Uri GetSourceFileUri(ISemanticModel model) => model switch
{
SemanticModel bicepModel => bicepModel.SourceFile.FileUri,
ArmTemplateSemanticModel armTemplate => armTemplate.SourceFile.FileUri,
TemplateSpecSemanticModel templateSpec => templateSpec.SourceFile.FileUri,
SemanticModel bicepModel => bicepModel.SourceFile.Identifier,
ArmTemplateSemanticModel armTemplate => armTemplate.SourceFile.Identifier,
TemplateSpecSemanticModel templateSpec => templateSpec.SourceFile.Identifier,
_ => throw new InvalidOperationException($"Unrecognized module type {model.GetType().Name} encountered"),
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public PlaceholderParametersBicepParamWriter(SemanticModel semanticModel, Includ

public void Write(TextWriter writer, string existingContent)
{
var bicepFileName = Path.GetFileName(semanticModel.SourceFile.FileUri.LocalPath);
var bicepFileName = Path.GetFileName(semanticModel.SourceFile.Identifier.LocalPath);

var allParameterDeclarations = semanticModel.Root.ParameterDeclarations;

Expand Down
4 changes: 2 additions & 2 deletions src/Bicep.Core/Emit/PositionTrackingJsonTextWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -231,11 +231,11 @@ private void AddRawMapping(BicepSourceFile bicepFile, TextSpan bicepPosition, Te
Array.Fill(weights, int.MaxValue);

var sourceMapFileEntries = new List<SourceMapFileEntry>();
var entrypointFileName = System.IO.Path.GetFileName(sourceFile.FileUri.AbsolutePath);
var entrypointFileName = System.IO.Path.GetFileName(sourceFile.Identifier.AbsolutePath);

foreach (var bicepFileEntry in this.rawSourceMap.Entries)
{
var bicepRelativeFilePath = PathHelper.GetRelativePath(sourceFile.FileUri, bicepFileEntry.SourceFile.FileUri);
var bicepRelativeFilePath = PathHelper.GetRelativePath(sourceFile.Identifier, bicepFileEntry.SourceFile.Identifier);
var sourceMapEntries = new List<SourceMapEntry>();

foreach (var sourceMapEntry in bicepFileEntry.SourceMap)
Expand Down
6 changes: 3 additions & 3 deletions src/Bicep.Core/Rewriters/RewriterHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,23 @@ public static class RewriterHelper
{
private static (BicepSourceFile bicepFile, bool hasChanges) Rewrite(BicepCompiler compiler, Workspace workspace, BicepSourceFile bicepFile, Func<SemanticModel, SyntaxRewriteVisitor> rewriteVisitorBuilder)
{
var compilation = compiler.CreateCompilationWithoutRestore(bicepFile.FileUri, workspace);
var compilation = compiler.CreateCompilationWithoutRestore(bicepFile.Identifier, workspace);
var newProgramSyntax = rewriteVisitorBuilder(compilation.GetEntrypointSemanticModel()).Rewrite(bicepFile.ProgramSyntax);

if (object.ReferenceEquals(bicepFile.ProgramSyntax, newProgramSyntax))
{
return (bicepFile, false);
}

bicepFile = SourceFileFactory.CreateBicepFile(bicepFile.FileUri, newProgramSyntax.ToString());
bicepFile = SourceFileFactory.CreateBicepFile(bicepFile.Identifier, newProgramSyntax.ToString());
return (bicepFile, true);
}

public static BicepSourceFile RewriteMultiple(BicepCompiler compiler, Compilation compilation, BicepSourceFile bicepFile, int rewritePasses, params Func<SemanticModel, SyntaxRewriteVisitor>[] rewriteVisitorBuilders)
{
var workspace = new Workspace();
workspace.UpsertSourceFiles(compilation.SourceFileGrouping.SourceFiles);
var fileUri = bicepFile.FileUri;
var fileUri = bicepFile.Identifier;

// Changing the syntax changes the semantic model, so it's possible for rewriters to have dependencies on each other.
// For example, fixing the casing of a type may fix type validation, causing another rewriter to apply.
Expand Down
2 changes: 1 addition & 1 deletion src/Bicep.Core/Semantics/ArmTemplateSemanticModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public class ArmTemplateSemanticModel : ISemanticModel

public ArmTemplateSemanticModel(ArmTemplateFile sourceFile)
{
Trace.WriteLine($"Building semantic model for {sourceFile.FileUri}");
Trace.WriteLine($"Building semantic model for {sourceFile.Identifier}");

this.SourceFile = sourceFile;

Expand Down
Loading

0 comments on commit e085d02

Please sign in to comment.