How Can We Help?
Use case: Github Actions
One of the use cases of STweep CLI is automatically formatting commit code with a fixed set of settings.
This article shows an example of a Github repository which automatically formats pushed code with help of Github actions. The demonstration repository can be found here.
Setup
The repository contains a TwinCAT project with unformatted code.
Under .github/workflows/ the Github Actions workflow ‘formatCode’ can be found, containing the logic the automatically format the code and create a pull request with the formatted code.
Workflow
The workflow file is written in yml. General information regarding Github Actions can be found here. Most work in the steps is done with the run command, which by default is a Powershell environment.
First step is downloading STweep CLI and install it on the running agent, in our case a Windows system. The step explicitly adds the STweep install folder as a system environment path. This is needed because path added by the installer is not accepted by the sandboxed Github Actions environment.
- name: Install STweep CLI.
run: |
Invoke-WebRequest -Uri "https://www.stweep.com/wp-content/uploads/STweep.CLI/LatestRelease/STweep.CLI.Installer.msi" -Outfile "$HOME\Downloads\STweep.msi"
$params = '/i',"$HOME\Downloads\STweep.msi",'/quiet'
$p = Start-Process 'msiexec.exe' -ArgumentList $params -NoNewWindow -Wait -PassThru
echo $p.ExitCode
echo "${env:ProgramFiles(x86)}${env:InstallationFolder}" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append
After installing STweep CLI the program can be called using the ‘STweep.CLI’ command in a shell environment, in this case Powershell.
First a license must be activated before formatting can be executed. The license key is added as Github secret in the reposity and can be accessed safely in the action.
- name: Activate STweep CLI.
run: |
&STweep.CLI license-activate -k ${{secrets.STWEEPCLILICENSEKEY}} -a
After licensing the real formatting can be executed. In this example the default settings as delivered with STweep CLI are used. The working folder is assigned as path variable, without filters STweep CLI recursivly searches this folder and child folders for known file extension.
- name: Format code
run: |
&STweep.CLI format --path (Resolve-Path .\).Path --settingsFile "${env:ProgramFiles(x86)}${env:SettingsFilePath}"
We use the ‘Create a pull request‘ action from Peter Evans to create a pull request if any changes to the code are detected.
- name: Formatted code pull request
uses: peter-evans/create-pull-request@v3
with:
commit-message : STweep.CLI formatted code.
title: STweep.CLI formatted code
body: Pull request with the formatted code by STweep CLI.
branch: STweepCLIFormattedCode
Final step is to release the STweep CLI license. Notice that this step is also executed in case of any failures in the previous steps.
- name: Deactivate license
if: always()
run: |
&STweep.CLI license-deactivate