Skip to content

Instantly share code, notes, and snippets.

@yustier
Last active March 22, 2024 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yustier/182ecb2ec803fa1240a3ce008c6fc43f to your computer and use it in GitHub Desktop.
Save yustier/182ecb2ec803fa1240a3ce008c6fc43f to your computer and use it in GitHub Desktop.
Copilot in the CLI の従来のエイリアスを設定するやつ (1.0.0 対応)
<#
.SYNOPSIS
A PowerShell module to interact with the GitHub Copilot in the CLI.
.DESCRIPTION
This module provides a convenient way to generate and execute code suggestions
from the GitHub Copilot in the CLI in a PowerShell environment.
#>
# echo ". $(Join-Path -Path $(Split-Path -Path $PROFILE -Parent) -ChildPath "copilot-cli-powershell.ps1)" >> $PROFILE
function Invoke-GitAlias {
[CmdletBinding()]
param (
[Parameter(ValueFromRemainingArguments, HelpMessage = "The remaining arguments for the Copilot command.")]
[string[]]$RemainingArguments
)
# Invoke-CopilotCommand @("suggest", "--target", "git") ($RemainingArguments -join " ")
ghcs -t gh ($RemainingArguments -join " ")
if ($LASTEXITCODE -ne 0) {
Write-Host "User cancelled the command."
}
}
function Invoke-GHAlias {
[CmdletBinding()]
param (
[Parameter(ValueFromRemainingArguments, HelpMessage = "The remaining arguments for the Copilot command.")]
[string[]]$RemainingArguments
)
# Invoke-CopilotCommand @("suggest", "--target", "gh") ($RemainingArguments -join " ")
ghcs -t gh ($RemainingArguments -join " ")
if ($LASTEXITCODE -ne 0) {
Write-Host "User cancelled the command."
}
}
function Invoke-GitHubCopilot {
[CmdletBinding()]
param (
[Parameter(ValueFromRemainingArguments, HelpMessage = "The remaining arguments for the Copilot command.")]
[string[]]$RemainingArguments
)
# Invoke-CopilotCommand @("suggest", "--target", "shell") ($RemainingArguments -join " ")
ghcs -t shell ($RemainingArguments -join " ")
if ($LASTEXITCODE -ne 0) {
Write-Host "User cancelled the command."
}
}
function Invoke-CopilotExplain {
[CmdletBinding()]
param (
[Parameter(ValueFromRemainingArguments, HelpMessage = "The remaining arguments for the Copilot command.")]
[string[]]$RemainingArguments
)
# Invoke-CopilotCommand @("explain") ($RemainingArguments -join " ")
ghce ($RemainingArguments -join " ")
if ($LASTEXITCODE -ne 0) {
Write-Host "User cancelled the command."
}
}
# function Invoke-CopilotCommand {
# param (
# [Parameter(Mandatory)][string[]]$SubCommands,
# [Parameter(Mandatory)][string]$Instruction
# )
#
# # $tempFile = Join-Path -Path $Env:TEMP -ChildPath "copilot_$((Get-Date).ToString('yyyyMMddHHmmss'))_$(Get-Random -Maximum 9999).txt"
#
# gh copilot $SubCommands $Instruction
#
# if ($LASTEXITCODE -eq 0) {
# # $fileContentsArray = Get-Content $tempFile
# # $fileContents = [string]::Join("`n", $fileContentsArray)
# # Write-Host $fileContents
# # Invoke-Expression $fileContents
# }
# else {
# Write-Host "User cancelled the command."
# }
# }
function Test-EscapedString {
param (
[Parameter(Mandatory)][string]$String
)
$startChar = $String.Substring(0, 1)
$endChar = $String.Substring($String.Length - 1, 1)
if (($startChar -eq "'") -and ($endChar -eq "'")) {
$unescapedQuotes = $String.Substring(1, $String.Length - 2) -replace "''", ""
if (-not ($unescapedQuotes -like "*'*")) {
return $true
}
}
return $false
}
<#
.SYNOPSIS
Sets aliases '??', 'git?', 'gh?' and 'cmd?'
#>
function Set-PassiveGitHubCopilotAliases {
Set-Alias -Name '??' -Value Invoke-GitHubCopilot -Scope Global
Set-Alias -Name 'gh?' -Value Invoke-GHAlias -Scope Global
Set-Alias -Name 'git?' -Value Invoke-GitAlias -Scope Global
Set-Alias -Name 'cmd?' -Value Invoke-CopilotExplain -Scope Global
}
<#
.SYNOPSIS
Sets aliases '??', 'git?', 'gh?' and 'cmd?' and hooks the Enter key to escape commands.
#>
function Set-GitHubCopilotAliases {
Set-PassiveGitHubCopilotAliases
Set-PSReadLineKeyHandler -Key Enter -ScriptBlock {
param($key, $arg)
$line = $null
$cursor = $null
[Microsoft.PowerShell.PSConsoleReadLine]::GetBufferState([ref]$line, [ref]$cursor)
$elems = $line.Split(' ', 2)
$command = $elems[0]
$question = $elems[1]
if ($command -in "??", "git?", "gh?", "cmd?") {
Write-Output (Test-EscapedString -String $elems[1])
if (-not (Test-EscapedString -String $elems[1])) {
$question = $elems[1].Replace("'", "''")
$question = "'$question'"
}
[Microsoft.PowerShell.PSConsoleReadLine]::Replace(0, $line.Length, "$command $question")
}
[Microsoft.PowerShell.PSConsoleReadLine]::AcceptLine()
}
}
<#
.SYNOPSIS
Command: gh copilot alias pwsh, from GitHub Copilot in the CLI version 1.0.0 (2024-03-18)
#>
function ghcs {
# Debug support provided by common PowerShell function parameters, which is natively aliased as -d or -db
# https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_commonparameters?view=powershell-7.4#-debug
param(
[ValidateSet('gh', 'git', 'shell')]
[Alias('t')]
[String]$Target = 'shell',
[Parameter(Position=0, ValueFromRemainingArguments)]
[string]$Prompt
)
begin {
# Create temporary file to store potential command user wants to execute when exiting
$executeCommandFile = New-TemporaryFile
# Store original value of GH_DEBUG environment variable
$envGhDebug = $Env:GH_DEBUG
}
process {
if ($PSBoundParameters['Debug']) {
$Env:GH_DEBUG = 'api'
}
gh copilot suggest -t $Target -s "$executeCommandFile" $Prompt
}
end {
# Execute command contained within temporary file if it is not empty
if ($executeCommandFile.Length -gt 0) {
# Extract command to execute from temporary file
$executeCommand = (Get-Content -Path $executeCommandFile -Raw).Trim()
# Insert command into PowerShell up/down arrow key history
[Microsoft.PowerShell.PSConsoleReadLine]::AddToHistory($executeCommand)
# Insert command into PowerShell history
$now = Get-Date
$executeCommandHistoryItem = [PSCustomObject]@{
CommandLine = $executeCommand
ExecutionStatus = [Management.Automation.Runspaces.PipelineState]::NotStarted
StartExecutionTime = $now
EndExecutionTime = $now.AddSeconds(1)
}
Add-History -InputObject $executeCommandHistoryItem
# Execute command
Write-Host "`n"
Invoke-Expression $executeCommand
}
}
clean {
# Clean up temporary file used to store potential command user wants to execute when exiting
Remove-Item -Path $executeCommandFile
# Restore GH_DEBUG environment variable to its original value
$Env:GH_DEBUG = $envGhDebug
}
}
function ghce {
# Debug support provided by common PowerShell function parameters, which is natively aliased as -d or -db
# https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_commonparameters?view=powershell-7.4#-debug
param(
[Parameter(Position=0, ValueFromRemainingArguments)]
[string[]]$Prompt
)
begin {
# Store original value of GH_DEBUG environment variable
$envGhDebug = $Env:GH_DEBUG
}
process {
if ($PSBoundParameters['Debug']) {
$Env:GH_DEBUG = 'api'
}
gh copilot explain $Prompt
}
clean {
# Restore GH_DEBUG environment variable to its original value
$Env:GH_DEBUG = $envGhDebug
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment