Skip to content

Format Code: ensure code formatting guidelines are met #5908

Format Code: ensure code formatting guidelines are met

Format Code: ensure code formatting guidelines are met #5908

Workflow file for this run

name: 'Format Code: ensure code formatting guidelines are met'
on:
workflow_dispatch: null
schedule:
- cron: '45 4 * * 1-5'
permissions:
contents: write
pull-requests: write
concurrency:
group: '${{ github.ref }}-${{ github.workflow }}'
cancel-in-progress: true
jobs:
build:
name: MegaLinter
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 #v4.1.1
with:
token: '${{ secrets.GITHUB_TOKEN }}'
fetch-depth: 0
- name: Prepare Git options
run: bash ./scripts/git-setup.sh
- name: Create new branch
run: |
date=$(date +%Y_%m_%d_%H_%M)
branch_name="code_formatter_$date"
git checkout -b $branch_name
echo "branch_name=$branch_name" >> $GITHUB_ENV
# Push the empty branch to remote
git push -u origin $branch_name
- name: Run linter
id: ml
# You can override MegaLinter flavor used to have faster performances
# More info at https://megalinter.io/flavors/
uses: oxsecurity/megalinter/flavors/terraform@1fc052d03c7a43c78fe0fee19c9d648b749e0c01 #v8.3.0
env:
# All available variables are described in documentation
# https://megalinter.io/configuration/#shared-variables
# ADD YOUR CUSTOM ENV VARIABLES HERE OR DEFINE THEM IN A FILE .mega-linter.yml AT THE ROOT OF YOUR REPOSITORY
APPLY_FIXES: all # When active, APPLY_FIXES must also be defined as environment variable (in github/workflows/mega-linter.yml or other CI tool)
APPLY_FIXES_EVENT: all # Decide which event triggers application of fixes in a commit or a PR (pull_request, push, all)
APPLY_FIXES_MODE: pull_request # If APPLY_FIXES is used, defines if the fixes are directly committed (commit) or posted in a PR (pull_request)
DISABLE_ERRORS: true
EMAIL_REPORTER: false
ENABLE_LINTERS: JSON_PRETTIER,YAML_PRETTIER,TERRAFORM_TERRAFORM_FMT,MARKDOWN_MARKDOWNLINT
GITHUB_TOKEN: '${{ secrets.GITHUB_TOKEN }}'
VALIDATE_ALL_CODEBASE: true
YAML_PRETTIER_FILTER_REGEX_EXCLUDE: (.github/*)
MARKDOWN_MARKDOWNLINT_FILTER_REGEX_EXCLUDE: (terraform/modules/.*/.*.md)
REPORT_OUTPUT_FOLDER: none
- name: Check for changes
run: |
# Show the status and diff before attempting to pull/push
echo "===== Git Status & Diff ====="
git status
git diff
echo "===== Git Add ====="
git add .
changes=$(git diff --staged --name-only)
if [ -z "$changes" ]; then
echo "No changes detected."
echo "Exiting workflow using status 1 without reporting an error"
exit 0
else
echo "Changes detected."
echo "changes=true" >> $GITHUB_ENV
git diff --staged --name-only > changed_files.txt
echo "List Files"
cat changed_files.txt
fi
- name: Prepare the Changes for GraphQL
if: env.changes == 'true'
run: |
commit_oid=$(git rev-parse HEAD)
echo "commit_oid=$commit_oid" >> $GITHUB_ENV
# Initialize an empty JSON object for the additions
files_for_commit='{"additions": []}'
# Read the changed files from changed_files.txt
while IFS= read -r file; do
if [[ -f "$file" ]]; then
# Add a newline to the end of the content
file_content="$(cat "$file")"
# Base64 encode the contents of the file
base64_content=$(base64 -w 0 <<< "$file_content")
# Construct a JSON object for this file and append it to the additions array
files_for_commit=$(echo "$files_for_commit" | jq --arg path "$file" --arg content "$base64_content" \
'.additions += [{ "path": $path, "contents": $content }]')
fi
done < changed_files.txt
# Output the final JSON array
echo "$files_for_commit" > files_for_commit.json
cat files_for_commit.json
# Error handling for `jq` output
if ! jq . files_for_commit.json; then
echo "Error processing files_for_commit.json"
exit 1
fi
- name: Commit changes via GraphQL
if: env.changes == 'true'
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
commit_message="Automated code formatting fixes"
files_for_commit="$(cat files_for_commit.json)"
# Error handling for `jq` output
if ! jq . files_for_commit.json; then
echo "Error reading files_for_commit.json"
exit 1
fi
# Output the final JSON array
echo "$files_for_commit" > files_for_commit.json
cat files_for_commit.json # Check the contents for validity
# Validate the JSON before proceeding
if ! jq empty files_for_commit.json; then
echo "Invalid JSON in files_for_commit.json"
exit 1
fi
# Prepare the mutation payload
mutation_payload=$(jq -n \
--arg branch_name "$branch_name" \
--arg commit_oid "$commit_oid" \
--arg repo_id "$repo_id" \
--arg commit_message "$commit_message" \
--argjson fileChanges "$(jq -c . < files_for_commit.json)" \
'{
query: "mutation($input: CreateCommitOnBranchInput!) { createCommitOnBranch(input: $input) { commit { oid } } }",
variables: {
input: {
branch: {
repositoryNameWithOwner: "ministryofjustice/modernisation-platform",
branchName: $branch_name
},
message: {
headline: $commit_message
},
fileChanges: $fileChanges,
expectedHeadOid: $commit_oid
}
}
}')
echo "Mutation Payload: $mutation_payload"
# Send the mutation request to GitHub's GraphQL API and capture the response
RESPONSE=$(curl -X POST -H "Authorization: bearer $GITHUB_TOKEN" \
-H "Content-Type: application/json" \
-d "$mutation_payload" https://api.github.com/graphql)
# Parse the commit OID from the response
COMMIT_OID=$(echo "$RESPONSE" | jq -r ".data.createCommitOnBranch.commit.oid")
# Check if the commit was successfully created
if [ "$COMMIT_OID" != "null" ]; then
echo "Commit successfully created with OID: $COMMIT_OID"
else
echo "Error creating commit: $RESPONSE"
fi
- name: Create pull request
if: env.changes == 'true'
env:
GH_TOKEN: ${{ github.token }}
run: |
pr_title="GitHub Actions Code Formatter workflow"
pr_body="This pull request includes updates from the GitHub Actions Code Formatter workflow. Please review the changes and merge if everything looks good."
pr_head="${{ github.repository_owner }}:${branch_name}"
pr_base="main"
gh pr create --title "$pr_title" --body "$pr_body" --head "$pr_head" --base "$pr_base" --label "code quality"