'Change .csproj version with GitHub Actions

What command or tools can I use to change version of my .csproj project before build it?

I have next .csproj file in my repository:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
    <Version>1.2.3</Version>
  </PropertyGroup>

  <ItemGroup>
    <Reference Include="UnityEngine">
      <HintPath>Libs\UnityEngine.dll</HintPath>
    </Reference>
  </ItemGroup>

</Project>

And I want replace the minor version(the one that is '3') to the GitHub Actions context github.run_number value.

Now my workflow file looks like this:

name: .NET

on:
  push:
    branches: [ master ]

jobs:
  build:

    runs-on: ubuntu-latest
    environment: CommonEnv

    steps:
    - uses: actions/checkout@v2
    - name: Setup .NET Core SDK 3.1.x
      uses: actions/[email protected]
      with:
        dotnet-version: '3.1.x'
    - name: Set version
      run: |
       echo "Buid version is ${{github.run_number}}"
       # here should be some commands to replace version in the .csproj file
    - name: Restore .Net
      run: dotnet restore
    - name: Test
      run: dotnet test --verbosity normal
    - name: Build
      run: dotnet build UnityAuxiliaryTools/UnityAuxiliaryTools.csproj --no-dependencies --output build


Solution 1:[1]

As I found out the best way to solve this problem is to use SED tool. It allows to edit text files from command line with regex usage. SED is installed on GitHub Actions virtual Ubuntu, so it is not required to download it manually with some package manger.

There are a usefull links that helps me to create correct command for my issue:

Replacing part of pattern with sed

https://www.gnu.org/software/sed/manual/sed.html

As result command looks like this:

sed -i "s/\(<Version>\([0-9]\+\.\)\{2\}\)\([0-9]\+\)/\1${{github.run_number}}/" projectName.csproj

What does it do:

  • -i parameter specify that result of command shoud be rewrite to the read file.
  • "s/\(<Version>\([0-9]\+\.\)\{2\}\)\([0-9]\+\)/\1${{github.run_number}}/" is a SED script. It has three parts separated by /. s/someregex/replacemant/. s is a replacement command key. My regex contains two parts. The first one is \(<Version>\([0-9]\+\.\)\{2\}\) is detecting the <Version>1.1. substring. The second part just detecting a minimum one digit(the version I want to be changed). And the last one is a replacemant pattern \1${{github.run_number}}. The \1 construction tells to SED to take the string that match the first part of the regex(it is <Version>1.1.). And the rest part of mathcing string replaced with ${{github.run_number}}. So as result I receive <Version>1.1.${{github.run_number}}. Profit!
  • projectName.csproj file to read

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nikolay