Functions/Resolve-HgRoot.ps1


filter Resolve-HgRoot
{
    <#
    .SYNOPSIS
    Gets the repository root for a given path.
     
    .DESCRIPTION
    It's very useful for commands to know where the root of a repository is for a given path. This function takes in a path to a directory or file and returns the root of its Mercurial repository. If there isn't one, it returns $null.
     
    ALIASES
      rvhgroot
       
    .EXAMPLE
    Resolve-HgRoot -Path C:\Projects\psHg\Test\Test-GetHgRoot.ps1
     
    Returns C:\Projects\psHg
    #>

    [CmdletBinding()]
    param(
        [Parameter(ValueFromPipeline=$true)]
        [string]
        # The path whose repository root should be returned.
        $Path = (Resolve-Path .)
    )
    
    if( [Uri]::IsWellFormedUriString( $Path, [UriKind]::Absolute ) )
    {
        [object[]]$output = hg id -i -r0 $Path 2>&1
        $output | Write-Verbose 
        if( -not $output -or $output[0] -notmatch '^[0-9a-f]{12}\+?$' )
        {
            Write-Error ('Repository ''{0}'' not found.' -f $Path) -ErrorAction:$ErrorActionPreference
            return $null
        }
        return $Path
    }
    
    if( -not ([IO.Path]::IsPathRooted( $Path )) )
    {
        $Path = Resolve-Path -Path $Path | Select-Object -ExpandProperty ProviderPath
        if( -not $Path )
        {
            return
        }
    }
    
    $originalPath = $Path
    # We don't use the hg root command because under CruiseControl.NET, it returns nothing.
    do 
    {
        if( (Test-Path -Path (Join-Path $Path .hg) -PathType Container) )
        {
            $Path = Resolve-Path -Path $Path | Select-Object -ExpandProperty ProviderPath
            Write-Verbose ('Resolved repository root: {0} -> {1}' -f $originalPath,$Path)
            return $Path
        }
        $Path = Split-Path -Parent -Path $Path
    }
    while( $Path )
    
    Write-Error ('Repository root for {0} not found.' -f $originalPath) -ErrorAction:$ErrorActionPreference
    return $null
}

Set-Alias -Name 'rvhgroot' -Value 'Resolve-HgRoot'