Skip to content

Commit

Permalink
Merge pull request #12 from kelnishi/feature-detect
Browse files Browse the repository at this point in the history
Feature Detect
  • Loading branch information
kelnishi authored Nov 18, 2024
2 parents 0f068ff + 35007d2 commit e5bd05f
Show file tree
Hide file tree
Showing 18 changed files with 688 additions and 4 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,4 @@ jobs:
run: dotnet build --configuration Release --no-restore

- name: Run Tests
run: dotnet test --configuration Release --no-build --verbosity normal
run: dotnet test --configuration Release --no-build --verbosity normal Spec.Test/Spec.Test.csproj
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,6 @@ output/
riderModule.iml
/_ReSharper.Caches/

/Spec.Test/generated-json/**
/Wacs.Console/Data/**

.DS_Store
3 changes: 3 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,6 @@
[submodule "unity"]
path = unity
url = [email protected]:kelnishi/WACS-Unity.git
[submodule "Feature.Detect/wasm-feature-detect"]
path = Feature.Detect/wasm-feature-detect
url = [email protected]:GoogleChromeLabs/wasm-feature-detect.git
40 changes: 40 additions & 0 deletions Feature.Detect/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Node modules
node_modules/
npm-debug.log
yarn-error.log
package-lock.json
yarn.lock

# Build outputs
dist/
build/

# Environment variables
.env
.env.local
.env.*.local

# IDE and editor specific files
.idea/
.vscode/
*.sublime-project
*.sublime-workspace

# OS generated files
.DS_Store
Thumbs.db

# Logs
logs/
*.log

# Temporary files
tmp/
temp/


#generated files
/generated-wasm/**

#test run
/TestResults/**
43 changes: 43 additions & 0 deletions Feature.Detect/DetectFeatures.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using Spec.Test;
using Wacs.Core;
using Wacs.Core.Runtime;
using Wacs.Core.Types;
using Xunit;

namespace Feature.Detect;

public class DetectFeatures
{
[Theory]
[ClassData(typeof(FeatureDetectTestData))]
public void Detect(FeatureJson.FeatureJson file)
{
if (!string.IsNullOrEmpty(file.Module))
{
try
{
var runtime = new WasmRuntime();

//Mutable globals
var mutableGlobal = new GlobalType(ValType.I32, Mutability.Mutable);
runtime.BindHostGlobal(("a", "b"), mutableGlobal, 1);

var filepath = Path.Combine(file.Path, file.Module);

Check warning on line 25 in Feature.Detect/DetectFeatures.cs

View workflow job for this annotation

GitHub Actions / build-and-test

Possible null reference argument for parameter 'path1' in 'string Path.Combine(string path1, string path2)'.

Check warning on line 25 in Feature.Detect/DetectFeatures.cs

View workflow job for this annotation

GitHub Actions / build-and-test

Possible null reference argument for parameter 'path1' in 'string Path.Combine(string path1, string path2)'.
using var fileStream = new FileStream(filepath, FileMode.Open);
var module = BinaryModuleParser.ParseWasm(fileStream);
var modInst = runtime.InstantiateModule(module);
var moduleName = !string.IsNullOrEmpty(file.Name)?file.Name:$"{filepath}";
module.SetName(moduleName);
}
catch (Exception e)
{
Assert.Fail($"{file.Name} support not detected.\n{e}");
}

}
else
{
Assert.Fail($"{file.Name} not supported.");
}
}
}
35 changes: 35 additions & 0 deletions Feature.Detect/Feature.Detect.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<Folder Include="generated-wasm\" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="9.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>

<ItemGroup>
<None Update="testsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Wacs.Core\Wacs.Core.csproj" />
</ItemGroup>

</Project>
73 changes: 73 additions & 0 deletions Feature.Detect/FeatureDetectTestData.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
// /*
// * Copyright 2024 Kelvin Nishikawa
// *
// * Licensed 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.
// */

using System.Collections;
using System.Text.Json;
using System.Text.Json.Serialization;
using Feature.Detect.FeatureJson;
using Microsoft.Extensions.Configuration;

namespace Spec.Test
{
public class FeatureDetectTestData : IEnumerable<object[]>
{
private static readonly IConfiguration Configuration;

static FeatureDetectTestData()
{
// Use ConfigurationFixture to get the JSON directory path
Configuration = new ConfigurationBuilder()
.SetBasePath(AppContext.BaseDirectory) // Set to current directory
.AddJsonFile("testsettings.json", optional: false, reloadOnChange: true)
.Build();
}

private static string JsonDirectory => Path.Combine(AppContext.BaseDirectory, Configuration["JsonDirectory"] ?? "");

public IEnumerator<object[]> GetEnumerator()
{
var files = Directory.GetFiles(JsonDirectory, "*.json", SearchOption.AllDirectories).OrderBy(path => path);
foreach (var file in files)
{
var testData = LoadFeatureDefinition(file);
yield return new object[] { testData };
}
}

IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();

static FeatureJson LoadFeatureDefinition(string jsonPath)
{
string json = File.ReadAllText(jsonPath);

var options = new JsonSerializerOptions
{
Converters =
{
new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)
},
PropertyNameCaseInsensitive = true
};

var testDefinition = JsonSerializer.Deserialize<FeatureJson>(json, options);
if (testDefinition == null)
throw new JsonException($"Error while parsing {jsonPath}");

testDefinition.Path = Path.GetDirectoryName(jsonPath)!;
return testDefinition;
}
}
}
67 changes: 67 additions & 0 deletions Feature.Detect/FeatureJson/FeatureJson.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// /*
// * Copyright 2024 Kelvin Nishikawa
// *
// * Licensed 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.
// */

using System.Text;
using System.Text.Json.Serialization;
using Microsoft.Extensions.Primitives;

namespace Feature.Detect.FeatureJson;

public class FeatureJson
{
[JsonPropertyName("source")]
public string? Source { get; set; }

public string? Path { get; set; }

[JsonPropertyName("id")]
public string? Id { get; set; }

[JsonPropertyName("module")]
public string? Module { get; set; }

[JsonPropertyName("options")]
public Options? Options { get; set; }

[JsonPropertyName("name")]
public string? Name { get; set; }

[JsonPropertyName("proposal")]
public string? Proposal { get; set; }

[JsonPropertyName("features")]
public List<string>? Features { get; set; } // New property for features list

public override string ToString()
{
var feats = (Features ?? new List<string>()).Select(f => $"\"{f}\"");
var sb = new StringBuilder();
sb.Append("{")
.Append("\"Name\": \"").Append(Name).Append("\",\n")
.Append("\"Proposal\": \"").Append(Proposal).Append("\",\n")
.Append("\"Features\": [").Append(string.Join(", ", feats)).Append("],\n")
.Append("\"Id\": \"").Append(Id).Append("\"\n")
.Append("}");
return sb.ToString();
}

}

public class Options
{
[JsonPropertyName("builtins")]
public List<string>? Builtins { get; set; }
}
24 changes: 24 additions & 0 deletions Feature.Detect/build_feature_detect.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#!/bin/bash

# Set the parent directory
PARENT_DIR="./wasm-feature-detect/src/detectors"

OUTPUT_DIR="./generated-wasm"

mkdir -p "$OUTPUT_DIR"

# Iterate over all directories in the parent directory
for dir in "$PARENT_DIR"/*/; do
# Check if it is indeed a directory
if [ -d "$dir" ]; then
echo "Processing directory: $dir"
# Run the node command with the directory as an argument
node convert_detector.mjs "$dir" "$OUTPUT_DIR"
fi
done

#run detection
dotnet test --logger "trx;LogFileName=TestResults.trx"

#publish support matrix
node trx-to-markdown.js TestResults/TestResults.trx ../features.md
Loading

0 comments on commit e5bd05f

Please sign in to comment.