/ src / codeAnalysis / format_sources.ps1
format_sources.ps1
 1  param (
 2    [switch]$all = $false
 3  )
 4  
 5  if(!(Get-Command "git" -ErrorAction SilentlyContinue)) {
 6    throw "You need to have a git in path to be able to format only the dirty files!"
 7  }
 8  
 9  $clangFormat = "clang-format.exe"
10  if(!(Get-Command $clangFormat -ErrorAction SilentlyContinue)) {
11      Write-Information "Can't find clang-format.exe in %PATH%, trying to use %VCINSTALLDIR%..."
12      $clangFormat="$env:VCINSTALLDIR\Tools\Llvm\bin\clang-format.exe"
13      if(!(Test-Path -Path $clangFormat -PathType leaf)) {
14        throw "Can't find clang-format.exe executable. Make sure you either have it in %PATH% or run this script from vcvars.bat!"
15      }
16  }
17  
18  $sourceExtensions = New-Object System.Collections.Generic.HashSet[string]
19  $sourceExtensions.Add(".cpp") | Out-Null
20  $sourceExtensions.Add(".h")   | Out-Null
21  
22  function Get-Dirty-Files-From-Git() {
23    $repo_root = & git rev-parse --show-toplevel
24  
25    $staged    = & git diff --name-only --diff-filter=d --cached | % { $repo_root + "/" + $_ }
26    $unstaged  = & git ls-files -m
27    $untracked = & git ls-files --others --exclude-standard
28    $result = New-Object System.Collections.Generic.List[string]
29    $staged, $unstaged, $untracked | % {
30      $_.Split(" ") | 
31        where {Test-Path $_ -PathType Leaf} |
32        where {$sourceExtensions.Contains((Get-Item $_).Extension)} | 
33        foreach {$result.Add($_)}
34    } 
35    return $result
36  }
37  
38  if($all) { 
39    $filesToFormat = 
40      Get-ChildItem -Recurse -File ..\src | 
41      Resolve-Path -Relative |
42      where { (Get-Item $_).Directory -notmatch "(Generated Files)|node_modules" -And 
43        $sourceExtensions.Contains((Get-Item $_).Extension)}
44  }
45  else {
46    $filesToFormat = Get-Dirty-Files-From-Git
47  }
48  
49  $filesToFormat | % {
50    Write-Host "Formatting $_"
51    & $clangFormat -i -style=file -fallback-style=none $_ 2>&1
52  }
53  
54  Write-Host "Done!"