Last active
September 6, 2020 20:51
-
-
Save technic/1be2c88a1d8f18475ab4319501545f4b to your computer and use it in GitHub Desktop.
Draft of powershell Tab completion for pydoit
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# doit completion | |
function WriteLog([string] $Message) { | |
$timestamp = Get-Date -Format HH:mm:ss | |
"[$timestamp] $Message" | Out-File -Append "${env:Home}\tablog.txt" | |
} | |
Register-ArgumentCompleter -CommandName doit -Native -ScriptBlock { | |
param( | |
[String] $wordToComplete, | |
[System.Management.Automation.Language.CommandAst] $commandAst, | |
[Int] $cursorPosition | |
) | |
WriteLog "Complete '$wordToComplete' in '$commandAst' cursor at $cursorPosition" | |
$elements = $commandAst.CommandElements; | |
$global:ast = $commandAst | |
$sub_cmds = "auto", "clean", "dumpdb", "forget", "help", "ignore", "info", "list", "reset-dep", "run", "strace", "tabcompletion" | |
for ($i = 1; $i -lt $elements.Count; $i++) { | |
$element = $elements[$i] | |
if ($element.Extent.EndOffset -ge $cursorPosition) { | |
break | |
} | |
} | |
$prev = $elements[$i - 1].ToString() | |
# if ($wordToComplete.Length.Equals(0)) { | |
# $prev = $elements[$i - 1] | |
# } else { | |
# $prev = $elements[$i - 2] | |
# } | |
WriteLog "At $i prev: '$prev'" | |
function completePath([String] $str) { | |
$results = if (Split-Path -Path $str* -IsAbsolute) { | |
$(Resolve-Path $str*) | |
} | |
else { | |
$(Resolve-Path -Relative $str*) | |
} | |
return $results | ForEach-Object { | |
$value = $_.ToString() | |
if ($value.Contains(' ')) { | |
$value = "'$value'" | |
} | |
[System.Management.Automation.CompletionResult]::new($value, $_, 'ParameterValue', $_) | |
} | |
} | |
if ($prev.Equals("-f") -or $prev.Equals("-d") -or $prev.Equals("-o")) { | |
return completePath $wordToComplete | |
} | |
if ($wordToComplete.Contains('=')) { | |
$cmd, $arg = $wordToComplete.Split('=', 2) | |
WriteLog "cmd '$cmd', arg '$arg'" | |
if ($cmd.Equals('--file') -or $cmd.Equals('--dir') -or $cmd.Equals('--output-file')) { | |
return completePath $arg | ForEach-Object { | |
# "--cmd=$_" | |
$value = "$cmd=" + $_.completionText | |
$description = $_.listItemText | |
[System.Management.Automation.CompletionResult]::new($value, $description, 'ParameterValue', $description) | |
} | |
} | |
} | |
if ($wordToComplete.Contains(':')) { | |
$base, $suffix = $wordToComplete.Split(':', 2) | |
return $(doit list -q --all $base | Where-Object { $_.StartsWith($wordToComplete) }) | |
} | |
else { | |
return $(doit list -q | ForEach-Object { $_.Trim() } | Where-Object { $_.StartsWith($wordToComplete) }) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment