Private/Edit-PackageJson.ps1

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
function Edit-PackageJson
{
    [CmdletBinding(ConfirmImpact = "Medium", SupportsShouldProcess)]
    Param(
        [Parameter(Mandatory)]
        $Manifest,

        [Parameter(Mandatory, ValueFromPipeline)]
        $InputObject
    )

    BEGIN
    {
        $path = ConvertTo-Path $Manifest;
        if ((-not [string]::IsNullOrEmpty($path)) -and (Test-Path $path -PathType Leaf)) { $Manifest = Get-Content $path | ConvertFrom-Json; }
    }

    PROCESS
    {
        $temp = Test-PackageJson $InputObject ;
        $path = $temp.Path;
        $package = $temp.Content;

        if ($package -ne $null)
        {
            [string]$name = $Manifest.Name;
            if (-not [string]::IsNullOrEmpty($null)) { $name = $name.ToLowerInvariant(); }

            $tags = @();
            if (-not [string]::IsNullOrEmpty($Manifest.Tags)) { $tags = $Manifest.Tags.Split(' '); }

            [bool]$appliedChanges = $false;
            $version = ConvertTo-NcrementVersionNumber $Manifest | Select-Object -ExpandProperty Version;

            foreach ($token in @{
                "name"=$name;
                "author"=$Manifest.Author;
                "homepage"=$Manifest.Website;
                "description"=$Manifest.Description;
                "keywords"=$tags;
                "repository"=$Manifest.Repository;
                "version"=$version;
            }.GetEnumerator())
            {
                if (($token.Value -ne $null) -and (-not [string]::IsNullOrWhiteSpace($token.Value)))
                {
                    $appliedChanges = $true;
                    if ($token.Name -eq "repository")
                    {
                        $token.Value = @{"type"="git"; "url"=$token.Value; }
                    }

                    if ($package | Get-Member $token.Name) { $package."$($token.Name)" = $token.Value; }
                    else { $package | Add-Member -MemberType NoteProperty -Name $token.Name -Value $token.Value; }
                }
            }

            if ($appliedChanges -and $PSCmdlet.ShouldProcess($InputObject)) { $package | ConvertTo-Json | Out-File $path -Encoding utf8; }
            return $InputObject;
        }
    }
}