Skip to content
Open
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
6 changes: 6 additions & 0 deletions dotnet/Selenium.sln
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Selenium.WebDriver.Safari.T
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Selenium.WebDriver.Support.Tests", "test\support\Selenium.WebDriver.Support.Tests.csproj", "{2136C695-2526-45E0-AE1D-68FBBC6A9DE2}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Selenium.WebDriver.ResourceUtilitiesGenerator", "private\Selenium.WebDriver.ResourceUtilitiesGenerator\Selenium.WebDriver.ResourceUtilitiesGenerator.csproj", "{C3650129-9310-F297-D3F8-219678D6F433}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down Expand Up @@ -69,6 +71,10 @@ Global
{2136C695-2526-45E0-AE1D-68FBBC6A9DE2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2136C695-2526-45E0-AE1D-68FBBC6A9DE2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2136C695-2526-45E0-AE1D-68FBBC6A9DE2}.Release|Any CPU.Build.0 = Release|Any CPU
{C3650129-9310-F297-D3F8-219678D6F433}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C3650129-9310-F297-D3F8-219678D6F433}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C3650129-9310-F297-D3F8-219678D6F433}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C3650129-9310-F297-D3F8-219678D6F433}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
// <copyright file="ResourceUtilitiesGenerator.cs" company="Selenium Committers">
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://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.
// </copyright>

using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using System;
using System.Collections.Immutable;
using System.IO;
using System.Text;
using System.Threading;

namespace Selenium.WebDriver.ResourceUtilitiesGenerator;

[Generator]
public class ResourceUtilitiesGenerator : IIncrementalGenerator
{
public void Initialize(IncrementalGeneratorInitializationContext context)
{
var jsFiles = context.AdditionalTextsProvider
.Where(static (text) => text.Path.EndsWith(".js") || text.Path.EndsWith(".json"))
.WithTrackingName("ResourceFiles")
.Select(static (data, token) =>
{
var name = Path.GetFileName(data.Path);
var code = GenerateAtom(data, token, out string propertyName, out var diagnostics);

return (name, code, propertyName, diagnostics);
});

context.RegisterSourceOutput(jsFiles, static (context, pair) =>
{
foreach (var diagnostic in pair.diagnostics)
{
context.ReportDiagnostic(diagnostic);
}
if (pair.code is not null)
{
context.AddSource($"ResourceUtilities.{pair.propertyName}.g.cs", SourceText.From(pair.code, Encoding.UTF8));
}
});
}

private static string? GenerateAtom(AdditionalText additionalText, CancellationToken token, out string propertyName, out ImmutableArray<Diagnostic> diagnostics)
{
diagnostics = [];
var sourceText = additionalText.GetText(token);
if (sourceText is null)
{
var d = Diagnostic.Create(new DiagnosticDescriptor("WRG1001", "Failed to read atom", "Atom '{0}' could not be read", "WebDriverResourceGenerator", DiagnosticSeverity.Error, true), Location.None, additionalText.Path);
diagnostics = [d];
propertyName = string.Empty;
return null;
}

propertyName = GetPropertyNameFromFilePath(additionalText.Path, out var lang, out var diag);
if (diag is not null)
{
diagnostics = diagnostics.Add(diag);
}

string contents = $$"""""""
// <auto-generated />

namespace OpenQA.Selenium.Internal;

internal static partial class ResourceUtilities
{
[global::System.Diagnostics.CodeAnalysis.StringSyntaxAttribute("{{lang}}")]
internal const string {{propertyName}} =
"""""

""""""";

var builder = new StringBuilder(contents);

// Normalize line endings for each line
foreach (var line in sourceText.Lines)
{
builder.AppendLine(sourceText.GetSubText(line.Span).ToString());
}

builder.AppendLine("""""""
""""";
}
""""""");

return builder.ToString();
}

private static string GetPropertyNameFromFilePath(string filePath, out string language, out Diagnostic? diagnostic)
{
diagnostic = null;
if (filePath.EndsWith("webdriver.json"))
{
language = "json";
return "WebDriverPrefsJson";
}
else if (filePath.EndsWith("is-displayed.js"))
{
language = "javascript";
return "IsDisplayedAtom";
}
else if (filePath.EndsWith("mutation-listener.js"))
{
language = "javascript";
return "MutationListenerAtom";
}
else if (filePath.EndsWith("get-attribute.js"))
{
language = "javascript";
return "GetAttributeAtom";
}
else if (filePath.EndsWith("find-elements.js"))
{
language = "javascript";
return "FindElementsAtom";
}

diagnostic = Diagnostic.Create(new DiagnosticDescriptor("WRG1002", "Unknown resource file", "Unknown file in the resource generator '{0}'", "WebDriverResourceGenerator", DiagnosticSeverity.Warning, true), Location.None, filePath);

var suffix = filePath.EndsWith(".js") ? "Atom" : "Json";

language = string.Empty;
return KebabCaseToPascalCase(Path.GetFileNameWithoutExtension(filePath)) + suffix;
}

private static string KebabCaseToPascalCase(string v)
{
Span<char> newValues = new char[v.Length];
int newValuesOffset = 0;
for (int i = 0; i < v.Length; i++)
{
if (i == 0)
{
newValues[i - newValuesOffset] = char.ToUpperInvariant(v[i]);
}
else if (char.IsLetter(v[i]))
{
newValues[i - newValuesOffset] = v[i];
}
else
{
i++;
newValuesOffset++;
newValues[i - newValuesOffset] = char.ToUpperInvariant(v[i]);
}
}

return newValues.Slice(0, v.Length - newValuesOffset).ToString();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>preview</LangVersion>
<Nullable>enable</Nullable>
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>

<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<IncludeBuildOutput>false</IncludeBuildOutput>

</PropertyGroup>

<ItemGroup>
<None Include="$(OutputPath)\$(AssemblyName).dll" Pack="true" PackagePath="analyzers/dotnet/cs" Visible="false" />

</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="3.3.4" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.9.2" PrivateAssets="all" />
</ItemGroup>

</Project>
19 changes: 13 additions & 6 deletions dotnet/src/webdriver/Selenium.WebDriver.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -79,13 +79,20 @@
<None Include="..\..\..\common\images\selenium_logo_small.png" Pack="true" PackagePath="logo.png" Visible="false" />
</ItemGroup>

<Target Name="GenerateResources" BeforeTargets="CoreCompile">
<Exec Command="bazel build //dotnet/src/webdriver:resource-utilities" WorkingDirectory="../../.." />
<ItemGroup>
<ProjectReference Include="..\..\private\Selenium.WebDriver.ResourceUtilitiesGenerator\Selenium.WebDriver.ResourceUtilitiesGenerator.csproj"
OutputItemType="Analyzer"
ReferenceOutputAssembly="false" />
</ItemGroup>

<ItemGroup>
<Compile Include="..\..\..\bazel-bin\dotnet\src\webdriver\ResourceUtilities.g.cs" />
</ItemGroup>
</Target>
<ItemGroup>
<AdditionalFiles Include="$(ProjectDir)..\..\..\third_party\js\selenium\webdriver.json" />
<AdditionalFiles Include="$(ProjectDir)..\..\..\bazel-bin\javascript\webdriver\atoms\get-attribute.js" />
<AdditionalFiles Include="$(ProjectDir)..\..\..\bazel-bin\javascript\webdriver\atoms\get-attribute.js" />
<AdditionalFiles Include="$(ProjectDir)..\..\..\bazel-bin\javascript\atoms\fragments\is-displayed.js" />
<AdditionalFiles Include="$(ProjectDir)..\..\..\bazel-bin\javascript\atoms\fragments\find-elements.js" />
<AdditionalFiles Include="$(ProjectDir)..\..\..\javascript\cdp-support\mutation-listener.js" />
</ItemGroup>

<Target Name="GenerateCdp" BeforeTargets="CoreCompile">
<Exec Command="bazel build //dotnet/src/webdriver/cdp/..." WorkingDirectory="../../.." />
Expand Down