diff --git a/.gitattributes b/.gitattributes index df74544..4017e83 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,5 @@ # linguist overrides *.sql linguist-language=TSQL + +# converts to native line endings on checkout for all SQL files +*.sql text=auto diff --git a/.github/workflows/AutoFormatSQL.yml b/.github/workflows/AutoFormatSQL.yml new file mode 100644 index 0000000..06ecbe5 --- /dev/null +++ b/.github/workflows/AutoFormatSQL.yml @@ -0,0 +1,61 @@ +name: AutoFormatSQL + +on: + push: + branches: + - main + paths: + - "**.sql" +permissions: + contents: write +jobs: + trim_whitespace: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v3 + with: + fetch-depth: "20" + + - name: git log + shell: pwsh + run: | + git log --pretty=format:%H --max-count=10 + + - name: Trim trailing whitespace and replace Tabs + shell: pwsh + run: | + $changedFiles = git --no-pager diff --name-only --relative --diff-filter=AM "${{ github.event.before }}" "${{ github.sha }}" -- '***.sql' + $tabSize = 4 + $outputString = "" + $changedFiles | ForEach-Object { + $fullPath = $_ + $Content = Get-Content $fullPath + foreach ($Ctnt in $Content) { + $CharArray = $Ctnt.ToCharArray() + $lineOutput = "" + $slidingOffset = 0 + for ($charIdx = 0; $charIdx -lt $CharArray.Length; $charIdx++) { + if ($CharArray[$charIdx] -eq "`t") { + $currentTab = $tabSize - (($charIdx + $slidingOffset) % $tabSize) + $slidingOffset += $currentTab - 1 + $lineOutput += (" " * $currentTab) + } + else { + $lineOutput += $CharArray[$charIdx] + } + } + $outputString += $lineOutput.TrimEnd() + "`n" # Add line output with trailing spaces removed to the output string, and add newline + } + Set-Content -Path $fullPath -Value ($outputString.TrimEnd()) + } + - name: Commit changes + run: | + if [ -n "$(git status --porcelain)" ]; then + git config user.name "GitHub Actions" + git config user.email "actions@github.com" + git add . + git commit -m "Automation: Replace tabs and remove trailing spaces" + git push + fi \ No newline at end of file