template/tests/MetaFixers.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# Taken with love from https://github.com/PowerShell/DscResource.Tests/blob/master/MetaFixers.psm1

<#
    This module helps fix problems, found by Meta.Tests.ps1
#>


$ErrorActionPreference = 'stop'
Set-StrictMode -Version latest

function ConvertTo-UTF8() {
    [CmdletBinding()]
    [OutputType([void])]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [System.IO.FileInfo]$FileInfo
    )

    process {
        $content = Get-Content -Raw -Encoding Unicode -Path $FileInfo.FullName
        [System.IO.File]::WriteAllText($FileInfo.FullName, $content, [System.Text.Encoding]::UTF8)
    }
}

function ConvertTo-SpaceIndentation() {
    [CmdletBinding()]
    [OutputType([void])]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [IO.FileInfo]$FileInfo
    )

    process {
        $content = (Get-Content -Raw -Path $FileInfo.FullName) -replace "`t", ' '
        [IO.File]::WriteAllText($FileInfo.FullName, $content)
    }
}

function Get-TextFilesList {
    [CmdletBinding()]
    [OutputType([IO.FileInfo])]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [string]$Root
    )

    begin {
        $txtFileExtentions = @('.gitignore', '.gitattributes', '.ps1', '.psm1', '.psd1', '.json', '.xml', '.cmd', '.mof')
    }

    process {
        Get-ChildItem -Path $Root -File -Recurse |
            Where-Object { $_.Extension -in $txtFileExtentions }
    }
}

function Test-FileUnicode {
    [CmdletBinding()]
    [OutputType([bool])]
    param(
        [Parameter(Mandatory, ValueFromPipeline)]
        [IO.FileInfo]$FileInfo
    )

    process {
        $bytes     = [IO.File]::ReadAllBytes($FileInfo.FullName)
        $zeroBytes = @($bytes -eq 0)
        return [bool]$zeroBytes.Length
    }
}

function Get-UnicodeFilesList() {
    [CmdletBinding()]
    [OutputType([IO.FileInfo])]
    param(
        [Parameter(Mandatory)]
        [string]$Root
    )

    $root | Get-TextFilesList | Where-Object { Test-FileUnicode $_ }
}