Skip to content

Instantly share code, notes, and snippets.

@pcrockett-pathway
Last active November 9, 2022 14:23
Show Gist options
  • Select an option

  • Save pcrockett-pathway/cf3e17d36706bea6afbdc6d2c46811a4 to your computer and use it in GitHub Desktop.

Select an option

Save pcrockett-pathway/cf3e17d36706bea6afbdc6d2c46811a4 to your computer and use it in GitHub Desktop.
File encoding pre-commit hook. Just clone this Gist next to all your other repos and run Copy-ToPeerRepos.ps1
<#
.SYNOPSIS
Clone this repo alongside all your other code repos. Then run this script.
It will automatically copy the pre-commit hook scripts to your other repos.
#>
[CmdletBinding()]
param()
$ErrorActionPreference = "Stop"
Set-StrictMode -Version 5.0
$thisDir = Split-Path $MyInvocation.MyCommand.Path -Parent
$repoDir = Split-Path $thisDir
$filesToCopy = "pre-commit", "pre-commit.ps1" `
| ForEach-Object { Join-Path $thisDir $_ }
Get-ChildItem $repoDir | ForEach-Object { Join-Path $_.FullName ".git\hooks" } `
| Where-Object { Test-Path $_ } `
| ForEach-Object {
$destDir = $_
Write-Verbose "$destDir..."
$filesToCopy | ForEach-Object { Copy-Item $_ $destDir }
}
#!/bin/sh
exec c:/Windows/System32/WindowsPowerShell/v1.0/powershell.exe -ExecutionPolicy RemoteSigned -NoProfile -Command '.git\hooks\pre-commit.ps1'
$ErrorActionPreference = "Stop"
Set-StrictMode -Version 5.0
$textExtensions = ".txt", ".md",
".ps1", ".psm1",
".cpp", ".h",
".cs", ".xaml",
".html", ".cshtml", ".ts", ".tsx", ".js", ".jsx",
".sln", ".csproj",
".xml", ".config", ".json"
$filesToCheck = git diff --cached --name-only --diff-filter=ACM `
| ForEach-Object { Get-Item $_ } `
| Where-Object { $textExtensions -contains $_.Extension }
if (!$filesToCheck) {
return
}
function Get-FileEncoding([string]$path) {
$path = (Resolve-Path $path).ProviderPath
$reader = [IO.StreamReader]::new($path)
try {
# Reading a single character from the file will cause the StreamReader
# to do encoding detection
$reader.Read() | Out-Null
$reader.CurrentEncoding.WebName
} finally {
$reader.Close()
$reader.Dispose()
}
}
$wrongEncoding = $filesToCheck | Where-Object {
(Get-FileEncoding $_.FullName) -ne "utf-8"
}
if ($wrongEncoding) {
$fileNames = $wrongEncoding | ForEach-Object { $_.Name }
Write-Error "These files are not using the UTF8 encoding: $fileNames"
}
@perXautomatik
Copy link

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment