Generate an interactive, autocompleting shell for any Cobra CLI

Overview

cobra-shell

logo

Description

Leverages the Cobra completion API to generate an interactive shell for any Cobra CLI, powered by go-prompt.

  • On-the-fly autocompletion for all commands
  • Static and dynamic autocompletion for args and flags, as described here
  • Full prompt customizability

Usage

Download

go get github.com/brianstrauch/cobra-shell

Example

package main

import (
    shell "github.com/brianstrauch/cobra-shell"
    "github.com/spf13/cobra"
)

func main() {
	cmd := &cobra.Command{Use: "example"}
	cmd.AddCommand(shell.New())
	_ = cmd.Execute()
}
Comments
  • Alt + Backspace to delete complete words

    Alt + Backspace to delete complete words

    Hey Brian,

    Can't believe I'm the first person creating an issue here. This project is such a great idea! I missed this automation in other projects like ishell or promptui.

    Bug / Feature Request

    I just noticed that alt + backspace behaves strangely. It will insert question marks instead of deleting complete words as I would expect it in an interactive shell.

    As it messes with the cli-ui it might be a bug to address but also a nice feature implementation that I'd love to see!

    Edit: Also ctrl+right and ctrl+left would be a great idea in order to skip through longer commands as I just noticed :D

    Thanks in advance!

    opened by cmprmsd 3
  • [Bug] Flags are permanently removed from the autocompletion

    [Bug] Flags are permanently removed from the autocompletion

    Bug

    When I have e.g. two flags like the following: image

    I can use them one time. Afterwards they will be removed. This is expected and good. image

    However, when I now press up or rewrite the commands the used completion flags are gone. image

    Fix

    The flags should be re-enabled after each execution.

    Edit: I saw you already tried to fix this issue in https://github.com/brianstrauch/cobra-shell/commit/db07c08a0692da8f1c0d8400fdce7fb81be5fd15. However, I'm on 0.2.4 so maybe the fix is not complete.

    opened by cmprmsd 2
  • Autocomplete Flag Parsing Order

    Autocomplete Flag Parsing Order

    Currently flags do show up like this: image

    However, it might be a good idea to display all --flags first and after them the -f(lags). Another solution would be to show only the long version or both in one line as the description has to be the same and on autocomplete insert the long one as this is the most descriptive. This might need some conditional logic I guess if there are cases with short but no long flags or the other way round.

    opened by cmprmsd 2
  • Hide shorthand flags and sort suggestions

    Hide shorthand flags and sort suggestions

    Hide shorthand flags from the suggestion list, since they are guaranteed to have regular-length equivalents (which can just as easily be completed with ). Sort the flags so that persistent flags (like --help) aren't stuck at the top. Closes #2.

    opened by brianstrauch 0
  • Persistent History

    Persistent History

    Hey!

    I'm trying to get a persistent history working. However, the struggle is real :D Maybe you have an idea and better understanding of cobra.

    The command has the following additional argument

    ...
    PreRun:            WriteHistory,
    

    The following function does write the history line and append it to the file:

    func WriteHistory(cmd *cobra.Command, args []string) {
    	enabledFlags = nil
    
    	// Open history file
    	f, err := os.OpenFile(".fry_history",
    		os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
    	if err != nil {
    		log.Println(err)
    	}
    	defer f.Close()
    
    	// Parse flags
    	cmd.Flags().SortFlags = false
    	cmd.Flags().Visit(checkFlags)
    	log.Print()
    	// Join flags and arguments
    	cmdLine := cmd.Parent().Use + " " + cmd.Use + " " + strings.Join(enabledFlags, " ") + " " + strings.Join(args, " ")
    	if _, err := f.WriteString(cmdLine + "\n"); err != nil {
    		log.Println(err)
    	}
    }
    

    Reading the history does happen at the start of the program execution:

    func init...
    hist := prompt.OptionHistory(readHistory())
    	myShell := shell.New(rootCmd, keyBinds, codeBinds, number, hist)
    
    func readHistory() []string {
    	data, err := os.ReadFile(".fry_history")
    	if err != nil {
    		log.Println("No history yet. Nothing to parse")
    	}
    	history := strings.Split(string(data), "\n")
    	return history
    }
    

    Build the flag strings (this is super weird and I look for a better solution).

    func checkFlags(f *pflag.Flag) {
    	if f.Value.Type() == "bool" {
    		//fmt.Println(f.Value.String())
    		enabledFlags = append(enabledFlags, "--"+f.Name)
    	} else {
    		enabledFlags = append(enabledFlags, "--"+f.Name+" \""+f.Value.String()+"\"")
    	}
    	fmt.Printf("Flags: %v\n", enabledFlags)
    }
    

    This approach works fine for the first execution of a command. However, the flags do not reset after each command execution. Thus the flags add up when running multiple times in one shell.

    image

    By any chance. Do you have experience how to parse the flags correctly in order to write them to a file?

    opened by cmprmsd 2
  • Fuzzy Suggestions for Autocomplete

    Fuzzy Suggestions for Autocomplete

    Hey!

    I implemented a directory walker that outputs e.g. ps1 files recursively in nested folders.

    Is it possible to do fuzzy searching on this parameter? I saw fuzzy suggestions are implemented in go-prompt (https://github.com/c-bata/go-prompt/blob/82a912274504477990ecf7c852eebb7c85291772/CHANGELOG.md and https://github.com/c-bata/go-prompt/pull/92).

    However, I'm unsure where to set this option and if it is configurable also in cobra-shell. You showed already a nice way to add keybindings. So I thought there may be an easy solution for this as well. :smile:

    opened by cmprmsd 2
Owner
Brian Strauch
Brian Strauch
Cobra CLI tool to generate applications and commands

Cobra Generator Cobra provides its own program that will create your application and add any commands you want. It's the easiest way to incorporate Co

Steve Francia 263 Jan 3, 2023
A simple CLI based rock-paper-scissors game created in GO with interactive shell prompt.

rock-paper-scissors A simple CLI (Command Line Interface) based rock-paper-scissors game with interactive shell prompt. Language Download Grab a binar

Saif Shahriar 0 Oct 9, 2022
painless task queue manager for shell commands with an intuitive cli interface (execute shell commands in distributed cloud-native queue manager).

EXEQ DOCS STILL IN PROGRESS. Execute shell commands in queues via cli or http interface. Features Simple intuitive tiny cli app. Modular queue backend

Mohammed Al Ashaal 13 Dec 14, 2022
CLI to run a docker image with R. CLI built using cobra library in go.

BlueBeak Installation Guide Task 1: Building the CLI The directory structure looks like Fastest process: 1)cd into bbtools 2)cd into bbtools/bin 3)I h

Aniruddha Chattopadhyay 0 Dec 20, 2021
Go-file-downloader-ftctl - A file downloader cli built using golang. Makes use of cobra for building the cli and go concurrent feature to download files.

ftctl This is a file downloader cli written in Golang which uses the concurrent feature of go to download files. The cli is built using cobra. How to

Dipto Chakrabarty 2 Jan 2, 2022
An interactive shell for go application

goshell An interactive shell for go application in normal mode ctrl-c break exec

null 1 Dec 15, 2022
ap 是一个 shell 工具,可以让其它 shell 命令的输出能够自动进入交互翻页模式

ap -- auto-pager ap 是一个 shell 工具,可以让其它 shell 命令的输出能够自动进入交互翻页模式。 ap 由两部分组成,一个 Go 语言编写的二进制程序,负责捕获命令的输出并支持翻页, 和一组 shell 脚本,负责为用户指定的命令清单创建与之同名的 wrapper。 经

flw 12 Apr 12, 2022
Simple CLI using spf13/cobra and Flink REST API

Flinkctl Flinkctl is a simple CLI written on Go using Cobra created to facilitate my team's daily basis work with multiple Flink clusters at Azion Tec

Tiago Krebs 3 Aug 16, 2022
Prompts users to enter values for required flags in Cobra CLI applications

Cobra Flag Prompt Cobra Flag Prompt prompts users to enter values for required flags. It is an extension of Cobra, and requires that you use Cobra to

null 1 Nov 13, 2021
A cli client-server app with cobra

cli-client-server-calculator a cli client-server app with cobra overview this project is a cli client-server app in which client gives a bunch of numb

mohammad-hossein zeynal zadeh 5 Dec 7, 2021
Cobra CLI challenge Segsalerty

Banking app done using Cobra CLI - Segsalerty challenge c/o Segun Mustafa It uses a database.json file as datastore for queries - createCustomer, Upda

Oladapo Olawale Sunday 0 Dec 14, 2021
This project is used to get familiar with GoLang cli apps, along with cobra generator.

SecretCTL SecretCTL About the project Status Getting started Layout Notes About the project This project is used to get familiar with GoLang cli apps,

Milos Folic 0 Jan 11, 2022
Run any shell command in a temporary proxy environment.

Run any shell command in a temporary proxy environment.

Wonder 4 Jun 2, 2022
Abacus is a simple interactive calculator CLI

Abacus is a simple interactive calculator CLI with support for variables, comparison checks, and math functions abacus -

Viktor Danov 33 Sep 15, 2022
Interactive CLI helper for creating git branches with JIRA Links and some text

bb (better-branch) Interactive CLI helper for creating git branches with JIRA Links and some text Still in development? Yes How it works? This tiny ut

Eugene Uvarov 3 Aug 18, 2022
Interactive cli tool for HTTP inspection

Wuzz command line arguments are similar to cURL's arguments, so it can be used to inspect/modify requests copied from the browser's network inspector with the "copy as cURL" feature.

Adam Tauber 10.2k Dec 27, 2022
This tool is a CLI-interactive tool for TA who use eeclass platform

NTHU eeclass TA helper. This tool is a CLI-interactive tool for TA who use eeclass platform. It helps TA to download all the submitted homework, and use CSV to record the score and comment, and upload CSV score directly to the eeclass platform with just 2 Enter key!

Bo-Wei Chen 1 Dec 11, 2021
🧨 Interactive Process Killer CLI made with Go!

proc-manager is an interactive CLI to kill processes made with Go, currently supports Linux, Mac OS X, Solaris, and Windows.

Aykut 24 Dec 2, 2022