Skip to content

Commit

Permalink
Move scripts to separate files
Browse files Browse the repository at this point in the history
  • Loading branch information
mayankpatibandla committed Apr 15, 2024
1 parent 6f03011 commit cc212f9
Show file tree
Hide file tree
Showing 5 changed files with 126 additions and 134 deletions.
22 changes: 22 additions & 0 deletions pros/autocomplete/.pros-complete.bash
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
_pros_completion() {
local IFS=$'\n'
local response
response=$(env COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD _PROS_COMPLETE=bash_complete $1)
for completion in $response; do
IFS=',' read type value <<<"$completion"
if [[ $type == 'dir' ]]; then
COMPREPLY=()
compopt -o dirnames
elif [[ $type == 'file' ]]; then
COMPREPLY=()
compopt -o default
elif [[ $type == 'plain' ]]; then
COMPREPLY+=($value)
fi
done
return 0
}
_pros_completion_setup() {
complete -o nosort -F _pros_completion pros
}
_pros_completion_setup
31 changes: 31 additions & 0 deletions pros/autocomplete/.pros-complete.zsh
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
_pros_completion() {
local -a completions
local -a completions_with_descriptions
local -a response
(( ! $+commands[pros] )) && return 1
response=("${(@f)$(env COMP_WORDS="${words[*]}" COMP_CWORD=$((CURRENT-1)) _PROS_COMPLETE=zsh_complete pros)}")
for type key descr in ${response}; do
if [[ "$type" == "plain" ]]; then
if [[ "$descr" == "_" ]]; then
completions+=("$key")
else
completions_with_descriptions+=("$key":"$descr")
fi
elif [[ "$type" == "dir" ]]; then
_path_files -/
elif [[ "$type" == "file" ]]; then
_path_files -f
fi
done
if [ -n "$completions_with_descriptions" ]; then
_describe -V unsorted completions_with_descriptions -U
fi
if [ -n "$completions" ]; then
compadd -U -V unsorted -a completions
fi
}
if [[ $zsh_eval_context[-1] == loadautofunc ]]; then
_pros_completion "$@"
else
compdef _pros_completion pros
fi
45 changes: 45 additions & 0 deletions pros/autocomplete/pros-complete.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Modified from https://github.com/StephLin/click-pwsh/blob/main/click_pwsh/shell_completion.py#L11
Register-ArgumentCompleter -Native -CommandName pros -ScriptBlock {
param($wordToComplete, $commandAst, $cursorPosition)
$env:COMP_WORDS = $commandAst
$env:COMP_WORDS = $env:COMP_WORDS.replace('\\', '/')
$incompleteCommand = $commandAst.ToString()
$myCursorPosition = $cursorPosition
if ($myCursorPosition -gt $incompleteCommand.Length) {
$myCursorPosition = $incompleteCommand.Length
}
$env:COMP_CWORD = @($incompleteCommand.substring(0, $myCursorPosition).Split(" ") | Where-Object { $_ -ne "" }).Length
if ( $wordToComplete.Length -gt 0) { $env:COMP_CWORD -= 1 }
$env:_PROS_COMPLETE = "powershell_complete"
pros | ForEach-Object {
$type, $value, $help = $_.Split(",", 3)
if ( ($type -eq "plain") -and ![string]::IsNullOrEmpty($value) ) {
[System.Management.Automation.CompletionResult]::new($value, $value, "ParameterValue", $value)
}
elseif ( ($type -eq "file") -or ($type -eq "dir") ) {
if ([string]::IsNullOrEmpty($wordToComplete)) {
$dir = "./"
}
else {
$dir = $wordToComplete.replace('\\', '/')
}
if ( (Test-Path -Path $dir) -and ((Get-Item $dir) -is [System.IO.DirectoryInfo]) ) {
[System.Management.Automation.CompletionResult]::new($dir, $dir, "ParameterValue", $dir)
}
Get-ChildItem -Path $dir | Resolve-Path -Relative | ForEach-Object {
$path = $_.ToString().replace('\\', '/').replace('Microsoft.PowerShell.Core/FileSystem::', '')
$isDir = $false
if ((Get-Item $path) -is [System.IO.DirectoryInfo]) {
$path = $path + "/"
$isDir = $true
}
if ( ($type -eq "file") -or ( ($type -eq "dir") -and $isDir ) ) {
[System.Management.Automation.CompletionResult]::new($path, $path, "ParameterValue", $path)
}
}
}
}
$env:COMP_WORDS = $null | Out-Null
$env:COMP_CWORD = $null | Out-Null
$env:_PROS_COMPLETE = $null | Out-Null
}
14 changes: 14 additions & 0 deletions pros/autocomplete/pros.fish
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
function _pros_completion;
set -l response (env _PROS_COMPLETE=fish_complete COMP_WORDS=(commandline -cp) COMP_CWORD=(commandline -t) pros);
for completion in $response;
set -l metadata (string split "," $completion);
if test $metadata[1] = "dir";
__fish_complete_directories $metadata[2];
else if test $metadata[1] = "file";
__fish_complete_path $metadata[2];
else if test $metadata[1] = "plain";
echo $metadata[2];
end;
end;
end;
complete --no-files --command pros --arguments "(_pros_completion)";
148 changes: 14 additions & 134 deletions pros/cli/misc_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,133 +47,26 @@ def upgrade(force_check, no_install):
ui.finalize('upgradeComplete', manager.perform_upgrade())


_SOURCE_BASH = r"""_pros_completion() {
local IFS=$'\n'
local response
response=$(env COMP_WORDS="${COMP_WORDS[*]}" COMP_CWORD=$COMP_CWORD _PROS_COMPLETE=bash_complete $1)
for completion in $response; do
IFS=',' read type value <<< "$completion"
if [[ $type == 'dir' ]]; then
COMPREPLY=()
compopt -o dirnames
elif [[ $type == 'file' ]]; then
COMPREPLY=()
compopt -o default
elif [[ $type == 'plain' ]]; then
COMPREPLY+=($value)
fi
done
return 0
_SCRIPT_FILES = {
'bash': '.pros-complete.bash',
'zsh': '.pros-complete.zsh',
'fish': 'pros.fish',
'pwsh': 'pros-complete.ps1',
'powershell': 'pros-complete.ps1',
}
_pros_completion_setup() {
complete -o nosort -F _pros_completion pros
}
_pros_completion_setup;
"""

_SOURCE_ZSH = r"""_pros_completion() {
local -a completions
local -a completions_with_descriptions
local -a response
(( ! $+commands[pros] )) && return 1
response=("${(@f)$(env COMP_WORDS="${words[*]}" COMP_CWORD=$((CURRENT-1)) _PROS_COMPLETE=zsh_complete pros)}")
for type key descr in ${response}; do
if [[ "$type" == "plain" ]]; then
if [[ "$descr" == "_" ]]; then
completions+=("$key")
else
completions_with_descriptions+=("$key":"$descr")
fi
elif [[ "$type" == "dir" ]]; then
_path_files -/
elif [[ "$type" == "file" ]]; then
_path_files -f
fi
done
if [ -n "$completions_with_descriptions" ]; then
_describe -V unsorted completions_with_descriptions -U
fi
if [ -n "$completions" ]; then
compadd -U -V unsorted -a completions
fi
}
if [[ $zsh_eval_context[-1] == loadautofunc ]]; then
_pros_completion "$@"
else
compdef _pros_completion pros
fi
"""

_SOURCE_FISH = r"""function _pros_completion;
set -l response (env _PROS_COMPLETE=fish_complete COMP_WORDS=(commandline -cp) COMP_CWORD=(commandline -t) pros);
for completion in $response;
set -l metadata (string split "," $completion);
if test $metadata[1] = "dir";
__fish_complete_directories $metadata[2];
else if test $metadata[1] = "file";
__fish_complete_path $metadata[2];
else if test $metadata[1] = "plain";
echo $metadata[2];
end;
end;
end;
complete --no-files --command pros --arguments "(_pros_completion)";
"""

# Modified from https://github.com/StephLin/click-pwsh/blob/main/click_pwsh/shell_completion.py#L11
_SOURCE_POWERSHELL = r"""Register-ArgumentCompleter -Native -CommandName pros -ScriptBlock {
param($wordToComplete, $commandAst, $cursorPosition)
$env:COMP_WORDS = $commandAst
$env:COMP_WORDS = $env:COMP_WORDS.replace('\\', '/')
$incompleteCommand = $commandAst.ToString()
$myCursorPosition = $cursorPosition
if ($myCursorPosition -gt $incompleteCommand.Length) {
$myCursorPosition = $incompleteCommand.Length
}
$env:COMP_CWORD = @($incompleteCommand.substring(0, $myCursorPosition).Split(" ") | Where-Object { $_ -ne "" }).Length
if ( $wordToComplete.Length -gt 0) { $env:COMP_CWORD -= 1 }
$env:_PROS_COMPLETE = "powershell_complete"
pros | ForEach-Object {
$type, $value, $help = $_.Split(",", 3)
if ( ($type -eq "plain") -and ![string]::IsNullOrEmpty($value) ) {
[System.Management.Automation.CompletionResult]::new($value, $value, "ParameterValue", $value)
}
elseif ( ($type -eq "file") -or ($type -eq "dir") ) {
if ([string]::IsNullOrEmpty($wordToComplete)) {
$dir = "./"
}
else {
$dir = $wordToComplete.replace('\\', '/')
}
if ( (Test-Path -Path $dir) -and ((Get-Item $dir) -is [System.IO.DirectoryInfo]) ) {
[System.Management.Automation.CompletionResult]::new($dir, $dir, "ParameterValue", $dir)
}
Get-ChildItem -Path $dir | Resolve-Path -Relative | ForEach-Object {
$path = $_.ToString().replace('\\', '/').replace('Microsoft.PowerShell.Core/FileSystem::', '')
$isDir = $false
if ((Get-Item $path) -is [System.IO.DirectoryInfo]) {
$path = $path + "/"
$isDir = $true
}
if ( ($type -eq "file") -or ( ($type -eq "dir") -and $isDir ) ) {
[System.Management.Automation.CompletionResult]::new($path, $path, "ParameterValue", $path)
}
}
}
}
$env:COMP_WORDS = $null | Out-Null
$env:COMP_CWORD = $null | Out-Null
$env:_PROS_COMPLETE = $null | Out-Null
}
"""
def _get_shell_script(shell: str) -> str:
with open(f'pros/autocomplete/{_SCRIPT_FILES[shell]}', 'r') as f:
return f.read()


@add_completion_class
class PowerShellComplete(ZshComplete):
"""Shell completion for PowerShell and Windows PowerShell."""

name = "powershell"
source_template = _SOURCE_POWERSHELL
source_template = _get_shell_script("powershell")

def format_completion(self, item: CompletionItem) -> str:
return super().format_completion(item).replace("\n", ",")
Expand Down Expand Up @@ -204,14 +97,6 @@ def setup_autocomplete(shell, config_file, force):
'powershell': None,
}

script_files = {
'bash': '.pros-complete.bash',
'zsh': '.pros-complete.zsh',
'fish': 'pros.fish',
'pwsh': 'pros-complete.ps1',
'powershell': 'pros-complete.ps1',
}

if shell in ('pwsh', 'powershell') and config_file is None:
try:
profile_command = f'{shell} -NoLogo -NoProfile -Command "Write-Output $PROFILE"' if os.name == 'nt' else f"{shell} -NoLogo -NoProfile -Command 'Write-Output $PROFILE'"
Expand All @@ -230,14 +115,9 @@ def setup_autocomplete(shell, config_file, force):
raise click.UsageError(f"Config directory {config_dir} does not exist. Please specify a valid config file.")

# Write the autocomplete script to a shell script file
script_file = os.path.join(config_dir, script_files[shell]).replace('\\', '/')
script_file = os.path.join(config_dir, _SCRIPT_FILES[shell]).replace('\\', '/')
with open(script_file, 'w') as f:
if shell == "bash":
f.write(_SOURCE_BASH)
elif shell == "zsh":
f.write(_SOURCE_ZSH)
elif shell in ('pwsh', 'powershell'):
f.write(_SOURCE_POWERSHELL)
f.write(_get_shell_script(shell))

if shell in ('bash', 'zsh'):
source_autocomplete = f". {script_file}\n"
Expand All @@ -260,8 +140,8 @@ def setup_autocomplete(shell, config_file, force):
raise click.UsageError(f"Completions directory {config_dir} does not exist. Please specify a valid completion file.")

# Write the autocomplete script to a shell script file
script_file = os.path.join(config_dir, script_files[shell]).replace('\\', '/')
script_file = os.path.join(config_dir, _SCRIPT_FILES[shell]).replace('\\', '/')
with open(script_file, 'w') as f:
f.write(_SOURCE_FISH)
f.write(_get_shell_script(shell))

ui.echo(f"Succesfully set up autocomplete for {shell} in {config_file}. Restart your shell to apply changes.")

0 comments on commit cc212f9

Please sign in to comment.