-
-
Notifications
You must be signed in to change notification settings - Fork 49
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #903 from rsteube/action-invoke-completer
added ActionInvoke
- Loading branch information
Showing
2 changed files
with
70 additions
and
16 deletions.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
// package invoke contains carapace-bin internal actions | ||
package invoke | ||
|
||
import ( | ||
"bytes" | ||
"io" | ||
"os" | ||
|
||
"github.com/rsteube/carapace" | ||
) | ||
|
||
// ActionInvoke invokes an internal carapace-bin completer | ||
// var composeCmd = &cobra.Command{ | ||
// Use: "compose", | ||
// Short: "Define and run multi-container applications with Docker", | ||
// Run: func(cmd *cobra.Command, args []string) {}, | ||
// DisableFlagParsing: true, | ||
// } | ||
// | ||
// func init() { | ||
// carapace.Gen(composeCmd).Standalone() | ||
// | ||
// rootCmd.AddCommand(composeCmd) | ||
// | ||
// carapace.Gen(composeCmd).PositionalAnyCompletion( | ||
// invoke.ActionInvokeCompleter(compose.Execute), | ||
// ) | ||
// } | ||
func ActionInvoke(f func() error) carapace.Action { | ||
return carapace.ActionCallback(func(c carapace.Context) carapace.Action { | ||
// TODO experimental | ||
// TODO beware of carapace.Batch goroutines - is this safe? might need locking | ||
old := os.Args | ||
args := []string{"", "_carapace", "export", "_", ""} | ||
args = append(args, c.Args...) | ||
args = append(args, c.CallbackValue) | ||
os.Args = args | ||
output, err := captureStdout(f) | ||
os.Args = old | ||
if err != nil { | ||
return carapace.ActionMessage(err.Error()) | ||
} | ||
return carapace.ActionImport([]byte(output)) | ||
}) | ||
} | ||
|
||
func captureStdout(f func() error) (string, error) { | ||
old := os.Stdout | ||
r, w, _ := os.Pipe() | ||
os.Stdout = w | ||
|
||
outC := make(chan string) | ||
// copy the output in a separate goroutine so printing can't block indefinitely | ||
go func() { | ||
var buf bytes.Buffer | ||
io.Copy(&buf, r) | ||
outC <- buf.String() | ||
}() | ||
|
||
err := f() | ||
|
||
w.Close() | ||
out := <-outC | ||
os.Stdout = old | ||
|
||
return out, err | ||
} |