Functions/Resolve-HgPath.ps1


filter Resolve-HgPath
{
    <#
    .SYNOPSIS
    Converts a file system path/item into that item's path in a Mercurial repository.
     
    .DESCRIPTION
    Files paths in a Mercurial repository are stored as paths relative to the repository's root directory. This function takes a path or file system item and converts it to the relative path used by Mercurial.
     
    If the item doesn't exist in a Mercurial repository, and error is written and nothing is returned.
     
    ALIASES
      rvhgp
       
    .EXAMPLE
    > dir file.txt | Resolve-HgPath
    file.txt
     
    Gets the path to an item in the root of a Mercurial repository.
     
    .EXAMPLE
    > dir .\Website\web.config | Resolve-HgPath
    Website/web.config
     
    Gets the path to the Website\web.config file in the current Mercurial repository.
     
    .EXAMPLE
    > Resolve-HgPath 'C:\Projects\psHg\Tools'
    Tools
     
    Returns the path to the Tools directory in the repository at C:\Projects\psHg.
    #>

    [CmdletBinding()]
    param(
        [Alias("Path")]
        [Alias("FullName")]
        [Parameter(Mandatory=$true,ValueFromPipeline=$true,ValueFromPipelineByPropertyName=$true,Position=0)]
        [string]
        # The path to convert.
        $InputObject
    )

    Set-StrictMode -Version 'Latest'
    
    $InputObject | 
        Where-Object {
            if( -not (Test-Path -Path $_) )
            {
                Write-Error "$_`: not found."
                return $false
            }
            return $true
        } |
        Resolve-Path | 
        Select-Object -ExpandProperty 'ProviderPath' | 
        Where-Object { 
            $repoRoot = Resolve-HgRoot -Path $_
            return ($repoRoot -and $repoRoot -ne $_)
        } |
        ForEach-Object { $_ -replace [Text.RegularExpressions.Regex]::Escape($repoRoot + "\"),'' } |
        ForEach-Object { $_ -replace '\\','/' }
}

Set-Alias -Name 'rvhgp' -Value 'Resolve-HgPath'