Monday, September 14, 2020

Saving personal Git snippets

I had a need this week to save all my personal Git Snippets.  Obviously, viewing and saving each Snippet would have been extremely time consuming and simply not necessary given Git has an API.  The PowerShell 7 script below will enumerate each of your Snippets and save them to the folder specified.  This will also save a file with the same name as the Snippet, but with a .info extension which includes all pertinent information about the Snippet itself. Quick and dirty, but works :-)

$git_token  = @{ "PRIVATE-TOKEN" = "<your_git_api_token" }
$git_url    = "https://git.some_domain.io/api/v4/snippets"
$snip_count = 100
$export_loc = "E:\Snippets"

# Enumerate each snippet
foreach ($snip in (Invoke-RestMethod -Uri ("{0}?per_page={1}" -f $git_url, $snip_count) -Headers $git_token)) {
    
    Write-Verbose ("Processing snippet: {0} [Id: {1}]" -f $snip.title, $snip.id) -Verbose
    
    # Determine file path based on file_name or title if file_name does not exist
    $out_file = if(!$snip.file_name){
        ("{0}.snip" -f ($snip.title.Split([IO.Path]::GetInvalidFileNameChars()) -join '_' -replace ' ', '_'))
    }else{
        $snip.file_name
    }
    
    Write-Verbose (" Out file: {0}" -f $out_file) -Verbose
    
    # Save snippet code
    Invoke-RestMethod -Uri ("{0}/{1}/raw" -f $git_url, $snip.id) -Headers $git_token -OutFile (Join-Path -Path $export_loc -ChildPath $out_file)

    # Save info file
    $snip | Out-File -FilePath (Join-Path -Path $export_loc -ChildPath ("{0}.info" -f (Split-Path -Path $out_file -LeafBase)))
}

No comments:

Post a Comment