Skip to content

Commit

Permalink
feat: kcl dotnet bindings init version
Browse files Browse the repository at this point in the history
Signed-off-by: peefy <xpf6677@163.com>
  • Loading branch information
Peefy committed Jun 30, 2024
1 parent 41cba02 commit 8de7f9c
Show file tree
Hide file tree
Showing 17 changed files with 18,225 additions and 0 deletions.
72 changes: 72 additions & 0 deletions .github/workflows/dotnet-test.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
name: dotnet-test

on:
push:
branches:
- main
- master
tags:
- '*'
pull_request:
branches:
- main
paths:
- "dotnet/**"
workflow_dispatch:

jobs:
build-and-test:
name: Test .NET Library of KCL
runs-on: ${{ matrix.os }}
defaults:
run:
working-directory: "dotnet"
env:
DevBuild: 'false'
strategy:
fail-fast: false
matrix:
build: [linux-debug, linux-release, macos-debug, macos-release, windows-debug, windows-release]
include:
- build: linux-debug
os: ubuntu-latest
config: debug
- build: linux-release
os: ubuntu-latest
config: release
- build: macos-debug
os: macos-latest
config: debug
- build: macos-release
os: macos-latest
config: release
- build: windows-debug
os: windows-2019
config: debug
- build: windows-release
os: windows-2019
config: release
steps:
- uses: actions/checkout@v4
- uses: actions/setup-dotnet@v4
with:
dotnet-version: '8.0.x'
- name: Clear package cache
run: dotnet clean KclLib.sln && dotnet nuget locals all --clear
- name: Enable development builds for the main branch
if: github.ref == 'refs/heads/main' || github.base_ref == 'main'
shell: bash
run: |
echo "DevBuild=true" >> $GITHUB_ENV
- name: Restore packages
run: dotnet restore KclLib.sln
- name: Build
run: dotnet build KclLib.sln -c ${{ matrix.config }} --no-restore
- name: Test
run: dotnet test KclLib.sln -c ${{ matrix.config }}
- name: Create package
run: |
cd KclLib
dotnet pack -c ${{ matrix.config }} /p:Packing=true
11 changes: 11 additions & 0 deletions dotnet/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
*.swp
*.*~
.DS_Store

.vs/
.vscode

bin/
obj/

BenchmarkDotNet.Artifacts/
11 changes: 11 additions & 0 deletions dotnet/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[package]
name = "kcl-lib-dotnet"
publish = false
version = "0.1.0"

[lib]
crate-type = ["cdylib"]
doc = false

[dependencies]
kclvm-api = { git = "https://github.com/kcl-lang/kcl", version = "0.9.0" }
69 changes: 69 additions & 0 deletions dotnet/KclLib.Tests/APITest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
namespace KclLib.Tests;

using KclLib.API;

[TestClass]
public class APITest
{
static string parentDirectory = FindCsprojInParentDirectory(Environment.CurrentDirectory);

[TestMethod]
public void TestExecProgramAPI()
{
var api = new API();
var execArgs = new ExecProgram_Args();
var path = Path.Combine(parentDirectory, "test_data", "schema.k");
execArgs.KFilenameList.Add(path);
var result = api.ExecProgram(execArgs);
Assert.AreEqual("app:\n replicas: 2", result.YamlResult, result.ToString());
}

[TestMethod]
public void TestExecProgramAPIFileNotFound()
{
var api = new API();
var execArgs = new ExecProgram_Args();
var path = Path.Combine(parentDirectory, "test_data", "file_not_found.k");
execArgs.KFilenameList.Add(path);
try
{
var result = api.ExecProgram(execArgs);
Assert.Fail("No exception was thrown for non-existent file path");
}
catch (Exception ex)
{
Assert.AreEqual(true, ex.Message.Contains("ERROR"));
Assert.AreEqual(true, ex.Message.Contains("Cannot find the kcl file"));
}
}

[TestMethod]
public void TestListVariablesAPI()
{
var api = new API();
var args = new ListVariables_Args();
var path = Path.Combine(parentDirectory, "test_data", "schema.k");
args.Files.Add(path);
var result = api.ListVariables(args);
Assert.AreEqual("AppConfig {replicas = 2}", result.Variables["app"].Variables[0].Value, result.ToString());
}

static string FindCsprojInParentDirectory(string directory)
{
string parentDirectory = Directory.GetParent(directory).FullName;

Check warning on line 53 in dotnet/KclLib.Tests/APITest.cs

View workflow job for this annotation

GitHub Actions / Test .NET Library of KCL (macos-debug)

Dereference of a possibly null reference.

Check warning on line 53 in dotnet/KclLib.Tests/APITest.cs

View workflow job for this annotation

GitHub Actions / Test .NET Library of KCL (macos-release)

Dereference of a possibly null reference.

Check warning on line 53 in dotnet/KclLib.Tests/APITest.cs

View workflow job for this annotation

GitHub Actions / Test .NET Library of KCL (linux-release)

Dereference of a possibly null reference.

Check warning on line 53 in dotnet/KclLib.Tests/APITest.cs

View workflow job for this annotation

GitHub Actions / Test .NET Library of KCL (linux-debug)

Dereference of a possibly null reference.

Check warning on line 53 in dotnet/KclLib.Tests/APITest.cs

View workflow job for this annotation

GitHub Actions / Test .NET Library of KCL (windows-release)

Dereference of a possibly null reference.

Check warning on line 53 in dotnet/KclLib.Tests/APITest.cs

View workflow job for this annotation

GitHub Actions / Test .NET Library of KCL (windows-debug)

Dereference of a possibly null reference.
string csprojFilePath = Directory.GetFiles(parentDirectory, "*.csproj").FirstOrDefault();

Check warning on line 54 in dotnet/KclLib.Tests/APITest.cs

View workflow job for this annotation

GitHub Actions / Test .NET Library of KCL (macos-debug)

Converting null literal or possible null value to non-nullable type.

Check warning on line 54 in dotnet/KclLib.Tests/APITest.cs

View workflow job for this annotation

GitHub Actions / Test .NET Library of KCL (macos-release)

Converting null literal or possible null value to non-nullable type.

Check warning on line 54 in dotnet/KclLib.Tests/APITest.cs

View workflow job for this annotation

GitHub Actions / Test .NET Library of KCL (linux-release)

Converting null literal or possible null value to non-nullable type.

Check warning on line 54 in dotnet/KclLib.Tests/APITest.cs

View workflow job for this annotation

GitHub Actions / Test .NET Library of KCL (linux-debug)

Converting null literal or possible null value to non-nullable type.

Check warning on line 54 in dotnet/KclLib.Tests/APITest.cs

View workflow job for this annotation

GitHub Actions / Test .NET Library of KCL (windows-release)

Converting null literal or possible null value to non-nullable type.

Check warning on line 54 in dotnet/KclLib.Tests/APITest.cs

View workflow job for this annotation

GitHub Actions / Test .NET Library of KCL (windows-debug)

Converting null literal or possible null value to non-nullable type.

if (csprojFilePath != null)
{
return parentDirectory;
}
else if (parentDirectory == directory)
{
return null;

Check warning on line 62 in dotnet/KclLib.Tests/APITest.cs

View workflow job for this annotation

GitHub Actions / Test .NET Library of KCL (macos-debug)

Possible null reference return.

Check warning on line 62 in dotnet/KclLib.Tests/APITest.cs

View workflow job for this annotation

GitHub Actions / Test .NET Library of KCL (macos-release)

Possible null reference return.

Check warning on line 62 in dotnet/KclLib.Tests/APITest.cs

View workflow job for this annotation

GitHub Actions / Test .NET Library of KCL (linux-release)

Possible null reference return.

Check warning on line 62 in dotnet/KclLib.Tests/APITest.cs

View workflow job for this annotation

GitHub Actions / Test .NET Library of KCL (linux-debug)

Possible null reference return.

Check warning on line 62 in dotnet/KclLib.Tests/APITest.cs

View workflow job for this annotation

GitHub Actions / Test .NET Library of KCL (windows-release)

Possible null reference return.

Check warning on line 62 in dotnet/KclLib.Tests/APITest.cs

View workflow job for this annotation

GitHub Actions / Test .NET Library of KCL (windows-debug)

Possible null reference return.
}
else
{
return FindCsprojInParentDirectory(parentDirectory);
}
}
}
36 changes: 36 additions & 0 deletions dotnet/KclLib.Tests/KclLib.Tests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="MSTest.TestAdapter" Version="3.1.1" />
<PackageReference Include="MSTest.TestFramework" Version="3.1.1" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="../KclLib/KclLib.csproj" />
</ItemGroup>

<ItemGroup>
<Using Include="Microsoft.VisualStudio.TestTools.UnitTesting" />
</ItemGroup>

<ItemGroup>
<None Include="../target/release/libkcl_lib_dotnet.*">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="../target/release/kcl_lib_dotnet.*">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>

</Project>
7 changes: 7 additions & 0 deletions dotnet/KclLib.Tests/test_data/schema.k
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@

schema AppConfig:
replicas: int = 1

app: AppConfig {
replicas = 2
}
27 changes: 27 additions & 0 deletions dotnet/KclLib.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.002.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "kcl_lib", "./KclLib/KclLib.csproj", "{925059E1-CFF5-4A12-A293-88344BAF33D9}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "kcl_lib_test", "./KclLib.Tests/KclLib.Tests.csproj", "{925059E1-CFF5-4A12-A293-88344BAF33D9}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{925059E1-CFF5-4A12-A293-88344BAF33D9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{925059E1-CFF5-4A12-A293-88344BAF33D9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{925059E1-CFF5-4A12-A293-88344BAF33D9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{925059E1-CFF5-4A12-A293-88344BAF33D9}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {13F982F0-938D-4D8B-AB03-9D13D0F1D80F}
EndGlobalSection
EndGlobal
23 changes: 23 additions & 0 deletions dotnet/KclLib/KclLib.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Google.Protobuf" Version="3.27.2" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>

<ItemGroup>
<None Include="../target/release/libkcl_lib_dotnet.*">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="../target/release/kcl_lib_dotnet.*">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>

</Project>
118 changes: 118 additions & 0 deletions dotnet/KclLib/api/API.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
namespace KclLib.API;

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Google.Protobuf;

using KclLib.Plugin;

public class API : IService
{
private const string LIB_NAME = "kcl_lib_dotnet";

// Native methods declarations
[DllImport(LIB_NAME, CallingConvention = CallingConvention.Cdecl)]
private static extern int callNative([In] byte[] name, int nameLength, [In] byte[] args, int argsLength, IntPtr buffer);

public API()
{

}

// Implementing IService methods
public ParseProgram_Result ParseProgram(ParseProgram_Args args)
{
return ParseProgram_Result.Parser.ParseFrom(Call("KclvmService.ParseProgram", args.ToByteArray()));
}

public ParseFile_Result ParseFile(ParseFile_Args args)
{
return ParseFile_Result.Parser.ParseFrom(Call("KclvmService.ParseFile", args.ToByteArray()));
}

public LoadPackage_Result LoadPackage(LoadPackage_Args args)
{
return LoadPackage_Result.Parser.ParseFrom(Call("KclvmService.LoadPackage", args.ToByteArray()));
}

public ListVariables_Result ListVariables(ListVariables_Args args)
{
return ListVariables_Result.Parser.ParseFrom(Call("KclvmService.ListVariables", args.ToByteArray()));
}

public ExecProgram_Result ExecProgram(ExecProgram_Args args)
{
return ExecProgram_Result.Parser.ParseFrom(Call("KclvmService.ExecProgram", args.ToByteArray()));
}

public OverrideFile_Result OverrideFile(OverrideFile_Args args)
{
return OverrideFile_Result.Parser.ParseFrom(Call("KclvmService.OverrideFile", args.ToByteArray()));
}

public GetSchemaTypeMapping_Result GetSchemaTypeMapping(GetSchemaTypeMapping_Args args)
{
return GetSchemaTypeMapping_Result.Parser.ParseFrom(Call("KclvmService.GetSchemaTypeMapping", args.ToByteArray()));
}

public FormatCode_Result FormatCode(FormatCode_Args args)
{
return FormatCode_Result.Parser.ParseFrom(Call("KclvmService.FormatCode", args.ToByteArray()));
}

public FormatPath_Result FormatPath(FormatPath_Args args)
{
return FormatPath_Result.Parser.ParseFrom(Call("KclvmService.FormatPath", args.ToByteArray()));
}

public LintPath_Result LintPath(LintPath_Args args)
{
return LintPath_Result.Parser.ParseFrom(Call("KclvmService.LintPath", args.ToByteArray()));
}

public ValidateCode_Result ValidateCode(ValidateCode_Args args)
{
return ValidateCode_Result.Parser.ParseFrom(Call("KclvmService.ValidateCode", args.ToByteArray()));
}

public LoadSettingsFiles_Result LoadSettingsFiles(LoadSettingsFiles_Args args)
{
return LoadSettingsFiles_Result.Parser.ParseFrom(Call("KclvmService.LoadSettingsFiles", args.ToByteArray()));
}

public Rename_Result Rename(Rename_Args args)
{
return Rename_Result.Parser.ParseFrom(Call("KclvmService.Rename", args.ToByteArray()));
}

public RenameCode_Result RenameCode(RenameCode_Args args)
{
return RenameCode_Result.Parser.ParseFrom(Call("KclvmService.RenameCode", args.ToByteArray()));
}

public Test_Result Test(Test_Args args)
{
return Test_Result.Parser.ParseFrom(Call("KclvmService.Test", args.ToByteArray()));
}

public UpdateDependencies_Result UpdateDependencies(UpdateDependencies_Args args)
{
return UpdateDependencies_Result.Parser.ParseFrom(Call("KclvmService.UpdateDependencies", args.ToByteArray()));
}

private byte[] Call(string name, byte[] args)
{
var nameBytes = System.Text.Encoding.UTF8.GetBytes(name);
IntPtr resultBuf = Marshal.AllocHGlobal(2048 * 2048);
int resultLength = callNative(nameBytes, nameBytes.Length, args, args.Length, resultBuf);
var result = new byte[resultLength];
Marshal.Copy(resultBuf, result, 0, resultLength);
Marshal.FreeHGlobal(resultBuf);
if (result == null || !result.AsSpan().StartsWith(System.Text.Encoding.UTF8.GetBytes("ERROR")))
{
return result;

Check warning on line 114 in dotnet/KclLib/api/API.cs

View workflow job for this annotation

GitHub Actions / Test .NET Library of KCL (macos-debug)

Possible null reference return.

Check warning on line 114 in dotnet/KclLib/api/API.cs

View workflow job for this annotation

GitHub Actions / Test .NET Library of KCL (macos-release)

Possible null reference return.

Check warning on line 114 in dotnet/KclLib/api/API.cs

View workflow job for this annotation

GitHub Actions / Test .NET Library of KCL (linux-release)

Possible null reference return.

Check warning on line 114 in dotnet/KclLib/api/API.cs

View workflow job for this annotation

GitHub Actions / Test .NET Library of KCL (linux-debug)

Possible null reference return.

Check warning on line 114 in dotnet/KclLib/api/API.cs

View workflow job for this annotation

GitHub Actions / Test .NET Library of KCL (windows-release)

Possible null reference return.

Check warning on line 114 in dotnet/KclLib/api/API.cs

View workflow job for this annotation

GitHub Actions / Test .NET Library of KCL (windows-debug)

Possible null reference return.
}
throw new Exception(System.Text.Encoding.UTF8.GetString(result));
}
}
Loading

0 comments on commit 8de7f9c

Please sign in to comment.