编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

在 Github Action 中执行 C# 脚本

wxchong 2024-10-28 20:19:35 开源技术 52 ℃ 0 评论

在 Github Action 中执行 C# 脚本

Intro

dotnet-exec 是一个命令行小工具,可以用来执行 C# 程序/脚本,我们在前面一篇文章中 基于 C# 编写构建脚本 介绍了使用基于 C# 编写构建脚本,在有 .NET SDK 的环境中我们直接安装 dotnet-execute 这个 dotnet tool 即可

在没有 .NET SDK 的环境中我们也可以基于 docker 来执行 C# 脚本,为了方便在 Github Action 中使用发布了一个简单的 Github Action 来方便使用

Implement

Github Action 的类型分为三种

  • JavaScript/TypeScript Action,通过 nodejs 来完成一些 task
  • Docker Action,基于 Dockerfile 或者 docker image 来实现 task 逻辑
  • Composite Action,将多个 step 组合成一个步骤的 action

目前 dotnet-exec 的 action 是 docker action 基于 docker 来实现的,基于 docker 创建 Github action 可以参考文档:https://docs.github.com/en/actions/creating-actions/creating-a-docker-container-action

实现源码:https://github.com/WeihanLi/dotnet-exec-action

Usage Sample

基本使用如下:

- name: dotnet-exec script
uses: WeihanLi/dotnet-exec-action@0.16.0
with:
script: "./build/build.cs" # script text or script path
arguments: "target=test" # optional

目前有两个参数,一个是 script,一个是 arguments

  • Script 是必选参数,要执行的 script 路径或者 url 或者 script 源代码
  • arguments 是一个可选参数,要传给 script 的命令行参数,就是 C# 程序里的 args

来看一个实际的示例,使用如下:

 - name: dotnet-exec
uses: WeihanLi/dotnet-exec-action@0.16.0
with:
script: "./scripts/build.cs"
env:
DingBotWebhookUrl: ${{ secrets.DINGBOTWEBHOOKURL }}

完整的 github workflow 可以参考:https://github.com/WeihanLi/markdown-nice/blob/master/.github/workflows/docker.yaml

如果查看完整的 workflow yaml 的会发现,没有 setup .NET SDK 的地方,这就是为什么要使用这个 action 了

这里的示例指定了 script 的路径是 ./scripts/build.cs,并且设置了环境变量以供我们 C# 代码里使用

script 代码如下 https://github.com/WeihanLi/markdown-nice/blob/master/scripts/build.cs:

using System.Net.Http.Json;

var message = """
The `weihanli/mdnice` docker image has been updated
[Amazing]
"
"";

var webhookUrl = Environment.GetEnvironmentVariable("DingBotWebhookUrl");
if (string.IsOrEmpty(webhookUrl))
{
Console.WriteLine("WebhookUrl not found");
return;
}

using var response = await HttpHelper.HttpClient.PostAsJsonAsync(webhookUrl, new
{
msgtype = "text",
text = new
{
content = message
}
});
response.EnsureSuccessStatusCode();

这个示例是一个纯前端的项目打包 docker 镜像成功之后发一个钉钉消息推送,这个 script 就是用来推送钉钉消息的,推送消息效果如下:

action build

dingding-notification

Let C# power everywhere~~

References

  • https://github.com/WeihanLi/dotnet-exec
  • https://github.com/WeihanLi/dotnet-exec-action
  • https://github.com/marketplace/actions/dotnet-exec
  • https://github.com/WeihanLi/markdown-nice/blob/master/scripts/build.cs
  • https://github.com/WeihanLi/markdown-nice/blob/master/.github/workflows/docker.yaml#L34
  • https://docs.github.com/en/actions/creating-actions/metadata-syntax-for-github-actions
  • https://docs.github.com/en/actions/creating-actions/creating-a-docker-container-action


Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表