Skip to content

Conversation

lstemplinger
Copy link
Contributor

Currently the Powershell completion script generated by Cobra does not work in constrained mode because creating CompletionResult Objects is blocked there.

This adds a check to the script that returns results as plain strings if constrained mode is enabled. Results in FullLanguage mode are unchanged.

So far I've tested with Powershell 5.1 on Windows 10, all three completion modes seem to work as expected even in constrained mode.

@CLAassistant
Copy link

CLAassistant commented Oct 9, 2024

CLA assistant check
All committers have signed the CLA.

@marckhouzam
Copy link
Collaborator

Cool!
@lstemplinger of you could provide steps to test this in the restricted language mode it would be helpful

@lstemplinger
Copy link
Contributor Author

Hi @marckhouzam ,

the test steps I'm using are:

  1. Put Powershell in constrained mode:
$ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage"
  1. Register completion for my program as usual:
my-cobra-program.exe completion powershell | Out-String | Invoke-Expression
  1. Type a partial my-cobra-program command and press tab

If i build my program with unmodified cobra 1.8.1 nothing happens, I don't get any completions (I assume Powershell tries to run the completion scriptblock and aborts once that hits an error). If I use my modified version, I get the expected completions just like in the normal FullLanguage mode.

To confirm that CompletionResult is the problem, I also tried manually creating one in a constrained session ([System.Management.Automation.CompletionResult]::new()), which failed with the error Cannot create type. Only core types are supported in this language mode.

@marckhouzam
Copy link
Collaborator

marckhouzam commented Oct 12, 2024

@lstemplinger Which version of pwsh are you running? I have 7.4.1 and the change does not work for me.

After some debugging I see that there is more code affected by the language restrictions
The line $Values = $Values | Sort-Object -Property Name is failing for me:

PS /Users/kmarc> $ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage"

# Imitate what the script does
PS /Users/kmarc> $Out = "bash zsh fish powershell"
PS /Users/kmarc> [Array]$Values = $Out | ForEach-Object {@{Name="$Name";Description=""}}
PS /Users/kmarc> $Values = $Values | Sort-Object -Property Name
Sort-Object: Cannot convert value "System.Collections.Hashtable" to type "System.Management.Automation.PSObject". Error: "Cannot convert hashtable to an object of the following type: System.Management.Automation.PSObject. Hashtable-to-Object conversion is not supported in restricted language mode or a Data section."

I'm not familiar much with powershell syntax, but maybe this can help you figure how to fix it?

To help you debug you can set the BASH_COMP_DEBUG_FILE environment variable to a file path and then the completion logic will print traces to that file which are triggered from the completion script at lines with __%[1]s_debug

@lstemplinger
Copy link
Contributor Author

I was testing with v5.1 since that's what i expect most of my users will be on, and I didn't see any changes to constrained mode in later versions. It definitely works there, so seems like something changed with sort-object between those version.

I'll do some testing with 7.4 and see if i can figure out a fix.

Creating CompletionResult objects is not allowed in Powershell constrained mode, so return results as strings if constrained mode is enabled

Store results as PsCustomObjects instead of hashtables. This prevents Sort-Object from trying to convert the hashtable to a object, which is blocked in constrained mode.
PsCustomObjects are created using New-Object to work around PowerShell/PowerShell#20767
@lstemplinger lstemplinger force-pushed the powershell-completion-constrained branch from 6ec249b to 04d768e Compare October 22, 2024 15:25
@lstemplinger
Copy link
Contributor Author

Storing results as PSCustomObjects instead of Hashtables fixed the issue for me. Sort-Object doesn't have to do any conversions that get blocked, and for the rest of the script accessing attributes works the same.

Tested using the same method as before on:

  • PS 5.1, FullLanguage: Works as before
  • PS 5.1 ConstrainedLanguage: Works as before
  • PS 7.4.5 FullLanguage: Works as before
  • PS 7.4.5 ConstrainedLanguage: Was broken, now works. I get the same expected completions

Copy link
Collaborator

@marckhouzam marckhouzam left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM
Thanks for this!

@marckhouzam marckhouzam merged commit 5a138f1 into spf13:main Nov 4, 2024
20 checks passed
@marckhouzam marckhouzam modified the milestones: 1.9.0, 1.8.1 Nov 4, 2024
ayax79 pushed a commit to ayax79/cobra that referenced this pull request Nov 28, 2024
Creating CompletionResult objects is not allowed in Powershell constrained mode, so return results as strings if constrained mode is enabled

Store results as PsCustomObjects instead of hashtables. This prevents Sort-Object from trying to convert the hashtable to a object, which is blocked in constrained mode.
PsCustomObjects are created using New-Object to work around PowerShell/PowerShell#20767
Crown0815 pushed a commit to Crown0815/forgejo-runner-windows that referenced this pull request May 21, 2025
This PR contains the following updates:

| Package | Type | Update | Change |
|---|---|---|---|
| [github.com/spf13/cobra](https://github.com/spf13/cobra) | require | minor | `v1.8.1` -> `v1.9.1` |

---

### Release Notes

<details>
<summary>spf13/cobra (github.com/spf13/cobra)</summary>

### [`v1.9.1`](https://github.com/spf13/cobra/releases/tag/v1.9.1)

[Compare Source](spf13/cobra@v1.9.0...v1.9.1)

##### 🐛 Fixes

-   Fix CompletionFunc implementation by [@&#8203;ccoVeille](https://github.com/ccoVeille) in spf13/cobra#2234
-   Revert "Make detection for test-binary more universal ([#&#8203;2173](spf13/cobra#2173))" by [@&#8203;marckhouzam](https://github.com/marckhouzam) in spf13/cobra#2235

**Full Changelog**: spf13/cobra@v1.9.0...v1.9.1

### [`v1.9.0`](https://github.com/spf13/cobra/releases/tag/v1.9.0)

[Compare Source](spf13/cobra@v1.8.1...v1.9.0)

#### ✨ Features

-   Allow linker to perform deadcode elimination for program using Cobra by [@&#8203;aarzilli](https://github.com/aarzilli) in spf13/cobra#1956
-   Add default completion command even if there are no other sub-commands by [@&#8203;marckhouzam](https://github.com/marckhouzam) in spf13/cobra#1559
-   Add CompletionWithDesc helper by [@&#8203;ccoVeille](https://github.com/ccoVeille) in spf13/cobra#2231

#### 🐛 Fixes

-   Fix deprecation comment for Command.SetOutput by [@&#8203;thaJeztah](https://github.com/thaJeztah) in spf13/cobra#2172
-   Replace deprecated ioutil usage by [@&#8203;nirs](https://github.com/nirs) in spf13/cobra#2181
-   Fix --version help and output for plugins by [@&#8203;nirs](https://github.com/nirs) in spf13/cobra#2180
-   Allow to reset the templates to the default by [@&#8203;marckhouzam](https://github.com/marckhouzam) in spf13/cobra#2229

#### 🤖 Completions

-   Make Powershell completion work in constrained mode by [@&#8203;lstemplinger](https://github.com/lstemplinger) in spf13/cobra#2196
-   Improve detection for flags that accept multiple values by [@&#8203;thaJeztah](https://github.com/thaJeztah) in spf13/cobra#2210
-   add CompletionFunc type to help with completions by [@&#8203;ccoVeille](https://github.com/ccoVeille) in spf13/cobra#2220
-   Add similar whitespace escape logic to bash v2 completions than in other completions by [@&#8203;kangasta](https://github.com/kangasta) in spf13/cobra#1743
-   Print ActiveHelp for bash along other completions by [@&#8203;marckhouzam](https://github.com/marckhouzam) in spf13/cobra#2076
-   fix(completions): Complete map flags multiple times by [@&#8203;gabe565](https://github.com/gabe565) in spf13/cobra#2174
-   fix(bash): nounset unbound file filter variable on empty extension by [@&#8203;scop](https://github.com/scop) in spf13/cobra#2228

#### 🧪 Testing

-   Test also with go 1.23 by [@&#8203;nirs](https://github.com/nirs) in spf13/cobra#2182
-   Make detection for test-binary more universal by [@&#8203;thaJeztah](https://github.com/thaJeztah) in spf13/cobra#2173

#### ✍🏼 Documentation

-   docs: update README.md by [@&#8203;eltociear](https://github.com/eltociear) in spf13/cobra#2197
-   Improve site formatting by [@&#8203;nirs](https://github.com/nirs) in spf13/cobra#2183
-   doc: add Conduit by [@&#8203;raulb](https://github.com/raulb) in spf13/cobra#2230
-   doc: azion project added to the list of CLIs that use cobra by [@&#8203;maxwelbm](https://github.com/maxwelbm) in spf13/cobra#2198
-   Fix broken links in active_help.md by [@&#8203;vuil](https://github.com/vuil) in spf13/cobra#2202
-   chore: fix function name in comment by [@&#8203;zhuhaicity](https://github.com/zhuhaicity) in spf13/cobra#2216

#### 🔧 Dependency upgrades

-   build(deps): bump github.com/cpuguy83/go-md2man/v2 from 2.0.5 to 2.0.6 by [@&#8203;thaJeztah](https://github.com/thaJeztah) in spf13/cobra#2206
-   Update to latest go-md2man by [@&#8203;mikelolasagasti](https://github.com/mikelolasagasti) in spf13/cobra#2201
-   Upgrade `pflag` dependencies for v1.9.0 by [@&#8203;jpmcb](https://github.com/jpmcb) in spf13/cobra#2233

***

Thank you to all of our amazing contributors and all the great work that's been going into the completions feature!!

##### 👋🏼 New Contributors

-   [@&#8203;gabe565](https://github.com/gabe565) made their first contribution in spf13/cobra#2174
-   [@&#8203;maxwelbm](https://github.com/maxwelbm) made their first contribution in spf13/cobra#2198
-   [@&#8203;lstemplinger](https://github.com/lstemplinger) made their first contribution in spf13/cobra#2196
-   [@&#8203;vuil](https://github.com/vuil) made their first contribution in spf13/cobra#2202
-   [@&#8203;mikelolasagasti](https://github.com/mikelolasagasti) made their first contribution in spf13/cobra#2201
-   [@&#8203;zhuhaicity](https://github.com/zhuhaicity) made their first contribution in spf13/cobra#2216
-   [@&#8203;ccoVeille](https://github.com/ccoVeille) made their first contribution in spf13/cobra#2220
-   [@&#8203;kangasta](https://github.com/kangasta) made their first contribution in spf13/cobra#1743
-   [@&#8203;aarzilli](https://github.com/aarzilli) made their first contribution in spf13/cobra#1956

**Full Changelog**: spf13/cobra@v1.8.1...v1.9.0

</details>

---

### Configuration

📅 **Schedule**: Branch creation - Between 12:00 AM and 03:59 AM ( * 0-3 * * * ) (UTC), Automerge - Between 12:00 AM and 03:59 AM ( * 0-3 * * * ) (UTC).

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Renovate Bot](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0MC4wLjgiLCJ1cGRhdGVkSW5WZXIiOiI0MC4wLjgiLCJ0YXJnZXRCcmFuY2giOiJtYWluIiwibGFiZWxzIjpbXX0=-->

Reviewed-on: https://code.forgejo.org/forgejo/runner/pulls/557
Reviewed-by: earl-warren <earl-warren@noreply.code.forgejo.org>
Co-authored-by: Renovate Bot <bot@kriese.eu>
Co-committed-by: Renovate Bot <bot@kriese.eu>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants